answer
stringlengths
17
10.2M
package org.ccnx.ccn.utils; import java.io.File; import java.io.IOException; import java.security.InvalidKeyException; import java.util.HashMap; import java.util.Set; import java.util.SortedSet; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.config.ConfigurationException; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.config.UserConfiguration; import org.ccnx.ccn.impl.security.keys.BasicKeyManager; import org.ccnx.ccn.impl.security.keys.NetworkKeyManager; import org.ccnx.ccn.impl.security.keys.RepositoryKeyManager; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.impl.support.Tuple; import org.ccnx.ccn.io.content.PublicKeyObject; import org.ccnx.ccn.profiles.nameenum.EnumeratedNameList; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.test.Flosser; /** * The standard CCNx mechanisms try to generate a keystore for each user that uses * them. This tool allows you to make keys for additional users, on the command line * or programmatically. It is primarily useful for tests, and for generating credentials * that will be prepared offline and then given to their intended users. * * Creates and loads a set of simulated users. Will store them into * a repository if asked, or to files and then will reload them from there the next time. * * As long as you are careful to create your CCNHandle objects pointing at these * users' keystores, you can create data as any of these users. */ public class CreateUserData { /** * Our users are named, in order, from this list, with 1 attached the first time, and 2 the * second, and so on. This allows them to be enumerated without requiring them to be stored * in a repo. */ public static final String [] USER_NAMES = {"Alice", "Bob", "Carol", "Dave", "Oswald", "Binky", "Spot", "Fred", "Eve", "Harold", "Barack", "Newt", "Allison", "Zed", "Walter", "Gizmo", "Nick", "Michael", "Nathan", "Rebecca", "Diana", "Jim", "Van", "Teresa", "Russ", "Tim", "Sharon", "Jessica", "Elaine", "Mark", "Weasel", "Ralph", "Junior", "Beki", "Darth", "Cauliflower", "Pico", "Eric", "Eric", "Eric", "Erik", "Richard"}; protected HashMap<String, ContentName> _userContentNames = new HashMap<String,ContentName>(); protected HashMap<String, File> _userKeystoreDirectories = new HashMap<String,File>(); protected HashMap<String,KeyManager> _userKeyManagers = new HashMap<String, KeyManager>(); protected HashMap<String,CCNHandle> _userHandles = new HashMap<String, CCNHandle>(); /** * Read/write constructor to write keystores as CCN data. * Makes extra new users if necessary. Expects names to come as above. * Will incur timeouts the first time, as it checks for data first, and will take time * to generate keys. * TODO eventually use this "for real" with real passwords. * @param userKeyStorePrefix * @param userNames list of user names to use, if null uses built-in list * @param userCount * @param storeInRepo * @param password * @param handle * @throws IOException * @throws ConfigurationException * @throws InvalidKeyException */ public CreateUserData(ContentName userKeyStorePrefix, String [] userNames, int userCount, boolean storeInRepo, char [] password, CCNHandle handle) throws ConfigurationException, IOException, InvalidKeyException { ContentName childName = null; String friendlyName = null; KeyManager userKeyManager = null; if (null == userNames) { userNames = USER_NAMES; } for (int i=0; i < userCount; ++i) { friendlyName = userNames[i % userNames.length]; if (i >= userNames.length) { friendlyName += Integer.toString(1 + i/userNames.length); } childName = ContentName.fromNative(userKeyStorePrefix, friendlyName); Log.info("Loading user: " + friendlyName + " from " + childName); if (storeInRepo) { // This only matters the first time through, when we save the user's data. // but it makes no difference in other cases anyway. userKeyManager = new RepositoryKeyManager(friendlyName, childName, null, password, handle); } else { userKeyManager = new NetworkKeyManager(friendlyName, childName, null, password, handle); } userKeyManager.initialize(); _userContentNames.put(friendlyName, childName); _userKeyManagers.put(friendlyName, userKeyManager); } } /** * Backwards compatibility constructor */ public CreateUserData(ContentName userKeyStorePrefix, int userCount, boolean storeInRepo, char [] password, CCNHandle handle) throws ConfigurationException, IOException, InvalidKeyException { this(userKeyStorePrefix, null, userCount, storeInRepo, password, handle); } /** * General read constructor. Expects names to be available in repo, and so enumerable. * i.e. something must be there. Uses NetworkKeyManager to read them out, though. * @throws IOException * @throws ConfigurationException * @throws InvalidKeyException */ public CreateUserData(ContentName userKeystoreDataPrefix, char [] password, CCNHandle handle) throws IOException, ConfigurationException, InvalidKeyException { EnumeratedNameList userDirectory = new EnumeratedNameList(userKeystoreDataPrefix, handle); userDirectory.waitForChildren(); // will block SortedSet<ContentName> availableChildren = userDirectory.getChildren(); if ((null == availableChildren) || (availableChildren.size() == 0)) { Log.warning("No available user keystore data in directory " + userKeystoreDataPrefix + ", giving up."); throw new IOException("No available user keystore data in directory " + userKeystoreDataPrefix + ", giving up."); } String friendlyName; ContentName childName; KeyManager userKeyManager; while (null != availableChildren) { for (ContentName child : availableChildren) { friendlyName = ContentName.componentPrintNative(child.lastComponent()); if (null != getUser(friendlyName)) { Log.info("Already loaded data for user: " + friendlyName + " from name: " + _userContentNames.get(friendlyName)); continue; } childName = new ContentName(userKeystoreDataPrefix, child.lastComponent()); Log.info("Loading user: " + friendlyName + " from " + childName); userKeyManager = new NetworkKeyManager(friendlyName, childName, null, password, handle); userKeyManager.initialize(); _userContentNames.put(friendlyName, childName); _userKeyManagers.put(friendlyName, userKeyManager); } availableChildren = null; if (userDirectory.hasNewData()) { // go around opportunistically availableChildren = userDirectory.getNewData(); } } } /** * Read/write constructor to write keystores as files. * Makes extra new users if necessary. Expects names to come as above. * Will incur timeouts the first time, as it checks for data first, and will take time * to generate keys. * TODO eventually use this "for real" with real passwords. * @param userKeystoreDirectory a directory under which to put each user's information; * segregated into subdirectories by user name, e.g. <userKeystoreDirectory>/<userName>. * @param userNames list of user names to use, if null uses built-in list * @param userCount * @param storeInRepo * @param password * @param handle * @throws IOException * @throws ConfigurationException * @throws IOException * @throws ConfigurationException * @throws InvalidKeyException * @throws InvalidKeyException */ public CreateUserData(File userKeystoreDirectory, String [] userNames, int userCount, char [] password, boolean clearSavedState) throws ConfigurationException, IOException, InvalidKeyException { String friendlyName = null; KeyManager userKeyManager = null; File userDirectory = null; File userKeystoreFile = null; if (!userKeystoreDirectory.exists()) { userKeystoreDirectory.mkdirs(); } else if (!userKeystoreDirectory.isDirectory()) { Log.severe("Specified path {0} must be a directory!", userKeystoreDirectory); throw new IllegalArgumentException("Specified path " + userKeystoreDirectory + " must be a directory!"); } for (int i=0; i < userCount; ++i) { friendlyName = userNames[i % userNames.length]; if (i >= userNames.length) { friendlyName += Integer.toString(1 + i/userNames.length); } userDirectory = new File(userKeystoreDirectory, friendlyName); if (!userDirectory.exists()) { userDirectory.mkdirs(); } userKeystoreFile = new File(userDirectory, UserConfiguration.keystoreFileName()); if (userKeystoreFile.exists()) { Log.info("Loading user: " + friendlyName + " from " + userKeystoreFile.getAbsolutePath()); } else { Log.info("Creating user's: " + friendlyName + " keystore in file " + userKeystoreFile.getAbsolutePath()); } userKeyManager = new BasicKeyManager(friendlyName, userDirectory.getAbsolutePath(), null, null, null, null, password); if (clearSavedState) { userKeyManager.clearSavedConfigurationState(); } userKeyManager.initialize(); _userKeyManagers.put(friendlyName, userKeyManager); _userKeystoreDirectories.put(friendlyName, userDirectory.getAbsoluteFile()); } } public CreateUserData(File userKeystoreDirectory, String [] userNames, int userCount, char [] password) throws ConfigurationException, IOException, InvalidKeyException { this(userKeystoreDirectory, userNames, userCount, password, false); } /** * For writing apps that run "as" a particular user. * @param userKeystoreDirectory This is the path to this particular user's keystore directory, * not the path above it where a bunch of users might have been generated. Assumes keystore * file has default name in that directory. If you give it a path that doesn't exist, it * takes it as a directory and makes a keystore there making the parent directories if necessary. * @return * @throws IOException * @throws ConfigurationException * @throws InvalidKeyException */ public static KeyManager loadKeystoreFile(File userKeystoreFileOrDirectory, String friendlyName, char [] password) throws ConfigurationException, IOException, InvalidKeyException { // Could actually easily generate this... probably should do that instead. if (!userKeystoreFileOrDirectory.exists()) { userKeystoreFileOrDirectory.mkdirs(); } File userKeystoreFile = userKeystoreFileOrDirectory.isDirectory() ? new File(userKeystoreFileOrDirectory, UserConfiguration.keystoreFileName()) : userKeystoreFileOrDirectory; if (userKeystoreFile.exists()) { Log.info("Loading user: from " + userKeystoreFile.getAbsolutePath()); } else { Log.info("Creating user's: keystore in file " + userKeystoreFile.getAbsolutePath()); } KeyManager userKeyManager = new BasicKeyManager(friendlyName, userKeystoreFile.getParent(), null, null, null, null, password); userKeyManager.initialize(); return userKeyManager; } /** * Load a set of user data from an existing generated set of file directories. Don't * force user to know names or count, enumerate them. * @throws IOException * @throws ConfigurationException * @throws InvalidKeyException */ public static CreateUserData readUserDataDirectory(File userDirectory, char [] keystorePassword) throws ConfigurationException, IOException, InvalidKeyException { if (!userDirectory.exists()) { Log.warning("Asked to read data from user directory {0}, but it does not exist!", userDirectory); return null; } if (!userDirectory.isDirectory()) { Log.warning("Asked to read data from user directory {0}, but it isn't a directory!", userDirectory); return null; } // Right now assume everything below here is a directory. String [] children = userDirectory.list(); return new CreateUserData(userDirectory, children, children.length, keystorePassword); } public void closeAll() { for (String user : _userKeyManagers.keySet()) { CCNHandle handle = _userHandles.get(user); if (null != handle) { handle.close(); } KeyManager km = _userKeyManagers.get(user); if (null != km) { km.close(); } } } public void publishUserKeysToRepository() throws IOException{ for (String friendlyName: _userKeyManagers.keySet()) { System.out.println(friendlyName); CCNHandle userHandle = getHandleForUser(friendlyName); try { userHandle.keyManager().publishKeyToRepository(); ContentName keyName = userHandle.keyManager().getDefaultKeyNamePrefix(); keyName = keyName.cut(keyName.count()-1); // Won't publish if it's already there. userHandle.keyManager().publishKeyToRepository(keyName, null); } catch (Exception e) { e.printStackTrace(); } } } /** * Publishes self-referential key objects under user namespace prefix. * @param userNamespace * @return * @throws IOException * @throws InvalidKeyException */ public PublicKeyObject [] publishUserKeysToRepository(ContentName userNamespace) throws IOException, InvalidKeyException{ PublicKeyObject [] results = new PublicKeyObject[_userKeyManagers.size()]; int i=0; for (String friendlyName: _userKeyManagers.keySet()) { CCNHandle userHandle = getHandleForUser(friendlyName); ContentName keyName = ContentName.fromNative(userNamespace, friendlyName); results[i++] = userHandle.keyManager().publishSelfSignedKeyToRepository( keyName, userHandle.keyManager().getDefaultPublicKey(), userHandle.keyManager().getDefaultKeyID(), SystemConfiguration.getDefaultTimeout()); } return results; } public void publishUserKeysToRepositorySetLocators(ContentName userNamespace) throws InvalidKeyException, IOException { PublicKeyObject [] results = publishUserKeysToRepository(userNamespace); int i=0; for (String friendlyName: _userKeyManagers.keySet()) { CCNHandle userHandle = getHandleForUser(friendlyName); userHandle.keyManager().setKeyLocator(null, results[i].getPublisherKeyLocator()); i++; } } public boolean hasUser(String friendlyName) { return _userKeyManagers.containsKey(friendlyName); } public KeyManager getUser(String friendlyName) { return _userKeyManagers.get(friendlyName); } public File getUserDirectory(String friendlyName) { return _userKeystoreDirectories.get(friendlyName); } public CCNHandle getHandleForUser(String friendlyName) throws IOException { synchronized (_userHandles) { CCNHandle userHandle = _userHandles.get(friendlyName); if (null == userHandle) { KeyManager km = getUser(friendlyName); if (null == km) return null; userHandle = CCNHandle.open(km); _userHandles.put(friendlyName, userHandle); } return userHandle; } } public Set<String> friendlyNames() { return _userKeyManagers.keySet(); } public int count() { return _userKeyManagers.size(); } /** * Helper method for other programs that want to use TestUserData. Takes an args * array, and an offset int it, at which it expects to find (optionally) * [-as keystoreDirectoryorFilePath [-name friendlyName]]. If the latter refers to * a file, it takes it as the keystore file. If it refers to a directory, it looks * for the default keystore file name under that directory. If the friendly name * argument is given, it uses that as the friendly name, otherwise it uses the last * component of the keystoreDirectoryOrFilePath. It returns a Tuple of a handle * opened under that user, and the count of arguments read, or null if the argument * at offset was not -as. */ public static Tuple<Integer, CCNHandle> handleAs(String [] args, int offset) throws ConfigurationException, IOException, InvalidKeyException { Tuple<Integer, KeyManager> t = keyManagerAs(args, offset); if (null == t) return null; return new Tuple<Integer, CCNHandle>(t.first(), CCNHandle.open(t.second())); } public static Tuple<Integer, KeyManager> keyManagerAs(String [] args, int offset) throws ConfigurationException, IOException, InvalidKeyException { String friendlyName = null; String keystoreFileOrDirectoryPath = null; int argsUsed = 0; if (args.length < offset + 2) return null; // no as if (args.length >= offset+2) { if (!args[offset].equals("-as")) { return null; // caller must print usage() } else { keystoreFileOrDirectoryPath = args[offset+1]; argsUsed += 2; } } if (args.length >= offset+5) { if (args[offset+2].equals("-name")) { friendlyName = args[offset+3]; argsUsed += 2; } } File keystoreFileOrDirectory = new File(keystoreFileOrDirectoryPath); if ((null == friendlyName) && ((keystoreFileOrDirectory.exists() && (keystoreFileOrDirectory.isDirectory())) || (!keystoreFileOrDirectory.exists()))) { // if its a directory, or it doesn't exist yet and we're going to make it as one, // use last component as user name friendlyName = keystoreFileOrDirectory.getName(); } Log.info("handleAs: loading data for user {0} from location {1}", friendlyName, keystoreFileOrDirectory); KeyManager manager = CreateUserData.loadKeystoreFile(keystoreFileOrDirectory, friendlyName, UserConfiguration.keystorePassword().toCharArray()); return new Tuple<Integer, KeyManager>(argsUsed, manager); } public static KeyManager keyManagerAs(String keystoreFileOrDirectoryPath, String friendlyName) throws InvalidKeyException, ConfigurationException, IOException { File keystoreFileOrDirectory = new File(keystoreFileOrDirectoryPath); if ((null == friendlyName) && ((keystoreFileOrDirectory.exists() && (keystoreFileOrDirectory.isDirectory())) || (!keystoreFileOrDirectory.exists()))) { // if its a directory, or it doesn't exist yet and we're going to make it as one, // use last component as user name friendlyName = keystoreFileOrDirectory.getName(); } Log.info("keyManagerAs: loading data for user {0} from location {1}", friendlyName, keystoreFileOrDirectory); KeyManager manager = CreateUserData.loadKeystoreFile(keystoreFileOrDirectory, friendlyName, UserConfiguration.keystorePassword().toCharArray()); return manager; } public static void usage() { System.out.println("usage: CreateUserData [[-f <file directory for keystores>] | [-r] <ccn uri for keystores>] [\"comma-separated user names\"] <user count> [<password>] [-p] (-r == use repo, -f == use files)"); } /** * Command-line driver to generate key data. */ public static void main(String [] args) { boolean useRepo = false; File directory = null; ContentName userNamespace = null; boolean publishKeysToRepo = true; Flosser flosser = null; String [] userNames = null; CreateUserData td = null; int arg = 0; if (args.length < 2) { usage(); return; } if (args[arg].equals("-f")) { arg++; if (args.length < 3) { usage(); return; } directory = new File(args[arg++]); } else { if (args[arg].equals("-r")) { arg++; useRepo = true; if (args.length < 3) { usage(); return; } } // Generate and write to repo try { userNamespace = ContentName.fromURI(args[arg]); if (!useRepo) { flosser = new Flosser(userNamespace); } } catch (Exception e) { System.out.println("Exception parsing user namespace " + args[arg]); e.printStackTrace(); return; } arg++; } if ((args.length - arg) >= 2) { String userNamesString = args[arg++]; userNames = userNamesString.split(","); } else userNames = USER_NAMES; int count = Integer.valueOf(args[arg++]); String password = UserConfiguration.keystorePassword(); if (arg < args.length) { password = args[arg++]; } try { if (null != directory) { td = new CreateUserData(directory, userNames, count, password.toCharArray()); if (publishKeysToRepo) { td.publishUserKeysToRepository(); } } else { td = new CreateUserData(userNamespace, userNames, count, useRepo, password.toCharArray(), CCNHandle.open()); if (publishKeysToRepo) { td.publishUserKeysToRepository(); } } System.out.println("Generated/retrieved " + td.count() + " user keystores, for users : " + td.friendlyNames()); } catch (Exception e) { System.out.println("Exception generating/reading user data: " + e); e.printStackTrace(); } finally { if (null != flosser) flosser.stop(); } if (null != td) { td.closeAll(); } System.out.println("Finished."); System.exit(0); } }
package io.ddf.jdbc; import com.google.common.base.Strings; import io.ddf.content.Schema; import io.ddf.datasource.DataSourceDescriptor; import io.ddf.datasource.JDBCDataSourceDescriptor; import io.ddf.DDF; import io.ddf.DDFManager; import io.ddf.exception.DDFException; import io.ddf.misc.Config.ConfigConstant; import io.ddf.util.ConfigHandler; import io.ddf.util.IHandleConfig; import java.net.URI; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * The DDF manager for JDBC connector * * DDF can be created directly on each table on the JDBC connector. We call these DDFs: <b>direct DDF</b>. * <br><br> * * If <code>autocreate = true</code>, a DDF will be generated automatically for each table, * else DDF will be created through <code>createDDF(String tableName)</code>.<br><br> * * Note that <code>ddf@jdbc</code> still follow the general rules of DDF on using SqlHandler. * That is a sql query that does not specify source will by default only apply to DDFs not * the underlying JDBC database. <br><br> * * <i>Creating (temporary) DDFs</i>: to avoid polluting the original database, newly <b>created DDF</b> will be stored in a separate * database, which is specified by <code>ddf.jdbc.created.ddf.database</code>. This database is hidden from users of DDF. * Note that, from user point of view, the <b>created DDF</b> are the same as the direct DDF in the sense * that they can query both of them in the same query (e.g. join, where clause etc.)<br><br> * * TODO (by priority): * 1. create direct DDF (automatically or not) * 2. */ public class JDBCDDFManager extends DDFManager { private JDBCDataSourceDescriptor mJdbcDataSource; private Connection conn; private static IHandleConfig sConfigHandler; static { String configFileName = System.getenv(ConfigConstant.DDF_INI_ENV_VAR.toString()); if (Strings.isNullOrEmpty(configFileName)) configFileName = ConfigConstant.DDF_INI_FILE_NAME.toString(); sConfigHandler = new ConfigHandler(ConfigConstant.DDF_CONFIG_DIR.toString(), configFileName); } @Override public DDF transfer(String fromEngine, String ddfuri) throws DDFException { throw new DDFException("Currently jdbc engine doesn't support transfer"); } public JDBCDDFManager() { } public JDBCDDFManager(DataSourceDescriptor dataSourceDescriptor, String engineType) throws Exception { /* * Register driver for the JDBC connector */ // TODO: check the correctness here. super(dataSourceDescriptor); this.setEngineType(engineType); mLog.info(">>> Initializing JDBCDDFManager"); String driver = sConfigHandler.getValue(this.getEngine(), ConfigConstant.JDBC_DRIVER.toString()); Class.forName(driver); mJdbcDataSource = (JDBCDataSourceDescriptor) dataSourceDescriptor; if (engineType.equals("sfdc")) { // Special handler for sfdc connection string, add RTK (for cdata driver) String rtkString = System.getenv("SFDC_RTK"); String uriString = mJdbcDataSource.getDataSourceUri().getUri().toString(); if (!Strings.isNullOrEmpty(rtkString)) { uriString += "RTK='" + rtkString + "';"; } mJdbcDataSource.getDataSourceUri().setUri(new URI(uriString)); } this.setDataSourceDescriptor(dataSourceDescriptor); if (mJdbcDataSource == null) { throw new Exception("JDBCDataSourceDescriptor is null when initializing " + "JDBCDDFManager"); } conn = DriverManager.getConnection(mJdbcDataSource.getDataSourceUri().toString(), mJdbcDataSource.getCredentials().getUsername(), mJdbcDataSource.getCredentials().getPassword()); mLog.info(">>> Set up connection with jdbc : " + mJdbcDataSource .getDataSourceUri().toString()); boolean isDDFAutoCreate = Boolean.parseBoolean(sConfigHandler.getValue(ConfigConstant.ENGINE_NAME_JDBC.toString(), ConfigConstant.JDBC_DDF_AUTOCREATE.toString())); this.showTables(); mLog.info(">>> Connection is set up"); if (isDDFAutoCreate){ } else { } } /** * @brief Close the jdbc connection. * @throws Throwable */ protected void finalize() throws Throwable { this.conn.close(); } public JDBCDataSourceDescriptor getJdbcDataSource() { return mJdbcDataSource; } public Connection getConn() { return conn; } public void setConn(Connection conn) { this.conn = conn; } public static IHandleConfig getConfigHandler() { return sConfigHandler; } public static void setConfigHandler(IHandleConfig sConfigHandler) { JDBCDDFManager.sConfigHandler = sConfigHandler; } /** * Class representing column metadata of a JDBC source * @TODO: refactor to make it reusable on any JDBC connector */ public class ColumnSchema { private String name; private Integer colType; /* Since atm the following variables are not used programmatically, I keep it as string to avoid multiple type conversions between layers. Note: the output from the JDBC connector is string */ private String isNullable; private String isAutoIncrement; private String isGenerated; public ColumnSchema(String name, Integer colType, String isNullable, String isAutoIncrement, String isGenerated) { this.name = name; this.colType = colType; this.isNullable = isNullable; this.isAutoIncrement = isAutoIncrement; this.isGenerated = isGenerated; } public ColumnSchema(String name, Integer colType, String isNullable, String isAutoIncrement) { this(name, colType, isNullable, isAutoIncrement, null); } public String getName() { return name; } /** * @Getter and Setter. * @return */ public Integer getColType() { return colType; } public void setColType(Integer colType) { this.colType = colType; } @Override public String toString() { return String.format("[name: %s, type: %s, isNullable: %s, isAutoIncrement: %s, isGenerated: %s]", name, colType, isNullable, isAutoIncrement, isGenerated); } } public class TableSchema extends ArrayList<ColumnSchema> {} @Override public DDF loadTable(String fileURL, String fieldSeparator) throws DDFException { throw new DDFException("Load DDF from file is not supported!"); } public DDF DDF(String tableName) throws DDFException { return null; } @Override public DDF getOrRestoreDDFUri(String ddfURI) throws DDFException { return null; } @Override public DDF getOrRestoreDDF(UUID uuid) throws DDFException { return null; } /** * * @param * @return * * @TODO: refactor to make it reusable on any JDBC connector */ public List<String> showTables() throws SQLException { //assert(conn != null, ""); DatabaseMetaData dbMetaData = conn.getMetaData(); ResultSet tbls = dbMetaData.getTables(null, null, null, null); List<String> tableList = new ArrayList<String>(); while(tbls.next()){ tableList.add(tbls.getString("TABLE_NAME")); } return tableList; } public List<String> listColumns(String tablename) throws SQLException { DatabaseMetaData dbmd = conn.getMetaData(); ResultSet columns = dbmd.getColumns(null, null, tablename, null); List<String> columnNames = new ArrayList<String>(); while (columns.next()) { columnNames.add(columns.getString("COLUMN_NAME")); } return columnNames; } /** * @param * @param tableName * @return * @throws SQLException * @TODO: refactor to make it reusable on any JDBC connector */ public TableSchema getTableSchema(String tableName) throws SQLException { //assert(conn != null, ""); DatabaseMetaData dbMetaData = conn.getMetaData(); //assert(tableName != null, "Table name cannot be null"); ResultSet tblSchemaResult = dbMetaData.getColumns(null, null, tableName, null); TableSchema tblSchema = new TableSchema(); while(tblSchemaResult.next()) { ColumnSchema colSchema = new ColumnSchema(tblSchemaResult.getString("COLUMN_NAME"), tblSchemaResult.getInt("DATA_TYPE"), tblSchemaResult.getString("IS_NULLABLE"), tblSchemaResult.getString("IS_AUTOINCREMENT") //tblSchemaResult.getString("IS_GENERATEDCOLUMN") ); tblSchema.add(colSchema); } return tblSchema; } @Override public String getEngine() { // return ConfigConstant.ENGINE_NAME_JDBC.toString(); return this.getEngineType(); } /** * @param jdbcDataSource * @TODO: refactor to make it reusable on any JDBC connector */ public void setJdbcDataSource(JDBCDataSourceDescriptor jdbcDataSource) { this.mJdbcDataSource = jdbcDataSource; } /** * Get metadata of the table <code>tableName</code> * @param query SQL query string * @param conn Connection object * @return an array where each element is a list of every row in a column * @TODO: refactor to make it reusable on any JDBC connector */ public void runQuery(String query, Connection conn) throws SQLException { // Statement stm = conn.createStatement(); // ResultSet rs = stm.executeQuery(query); // ResultSetMetaData rsMetaData = rs.getMetaData(); /* Read data into array of list, each list is a column */ // val colCnt = rsMetaData.getColumnCount(); // var colList: Array[ListBuffer[Object]] = new Array[ListBuffer[Object]](colCnt); // while(rs.next()){ // for (i <- 0 to colCnt-1){ // if (colList(i) == null) { // colList(i) = new ListBuffer[Object](); // colList(i).append(rs.getObject(i+1)); // colList } }
package org.jpos.iso; import java.io.EOFException; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.ref.WeakReference; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Collection; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.Random; import java.util.Stack; import java.util.Vector; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.core.ReConfigurable; import org.jpos.util.LogEvent; import org.jpos.util.LogSource; import org.jpos.util.Logger; import org.jpos.util.NameRegistrar; import org.jpos.util.ThreadPool; /** * Accept ServerChannel sessions and forwards them to ISORequestListeners * @author Alejandro P. Revilla * @author Bharavi Gade * @version $Revision$ $Date$ */ public class ISOServer extends Observable implements LogSource, Runnable, Observer, ISOServerMBean, ReConfigurable { int port; ISOChannel clientSideChannel; Class clientSideChannelClass; ISOPackager clientPackager; Collection clientOutgoingFilters, clientIncomingFilters, listeners; ThreadPool pool; public static final int DEFAULT_MAX_THREADS = 100; String name; protected Logger logger; protected String realm; protected String realmChannel; protected ISOServerSocketFactory socketFactory = null; public static final int CONNECT = 0; public static final int SIZEOF_CNT = 1; private int[] cnt; private String[] allow; protected Configuration cfg; private boolean shutdown = false; private ServerSocket serverSocket; private Stack channels; /** * @param port port to listen * @param clientSide client side ISOChannel (where we accept connections) * @param pool ThreadPool (created if null) */ public ISOServer(int port, ServerChannel clientSide, ThreadPool pool) { super(); this.port = port; this.clientSideChannel = clientSide; this.clientSideChannelClass = clientSide.getClass(); this.clientPackager = clientSide.getPackager(); if (clientSide instanceof FilteredChannel) { FilteredChannel fc = (FilteredChannel) clientSide; this.clientOutgoingFilters = fc.getOutgoingFilters(); this.clientIncomingFilters = fc.getIncomingFilters(); } this.pool = (pool == null) ? new ThreadPool (1, DEFAULT_MAX_THREADS) : pool; listeners = new Vector(); name = ""; channels = new Stack(); cnt = new int[SIZEOF_CNT]; } protected Session createSession (ServerChannel channel) { return new Session (channel); } protected class Session implements Runnable, LogSource { ServerChannel channel; String realm; protected Session(ServerChannel channel) { this.channel = channel; realm = ISOServer.this.getRealm() + ".session"; } public void run() { if (channel instanceof BaseChannel) { LogEvent ev = new LogEvent (this, "session-start"); Socket socket = ((BaseChannel)channel).getSocket (); realm = realm + socket.getInetAddress(); try { checkPermission (socket, ev); } catch (ISOException e) { try { int delay = 1000 + new Random().nextInt (4000); ev.addMessage (e.getMessage()); ev.addMessage ("delay=" + delay); ISOUtil.sleep (delay); socket.close (); } catch (IOException ioe) { ev.addMessage (ioe); } return; } finally { Logger.log (ev); } } try { for (;;) { try { ISOMsg m = channel.receive(); Iterator iter = listeners.iterator(); while (iter.hasNext()) if (((ISORequestListener)iter.next()).process (channel, m)) break; } catch (ISOFilter.VetoException e) { Logger.log (new LogEvent (this, "VetoException", e.getMessage())); } } } catch (EOFException e) { Logger.log (new LogEvent (this, "session-warning", "<eof/>")); } catch (SocketException e) { if (!shutdown) Logger.log (new LogEvent (this, "session-warning", e)); } catch (InterruptedIOException e) { // nothing to log } catch (Throwable e) { Logger.log (new LogEvent (this, "session-error", e)); } try { channel.disconnect(); } catch (IOException ex) { Logger.log (new LogEvent (this, "session-error", ex)); } Logger.log (new LogEvent (this, "session-end")); } public void setLogger (Logger logger, String realm) { } public String getRealm () { return realm; } public Logger getLogger() { return ISOServer.this.getLogger(); } public void checkPermission (Socket socket, LogEvent evt) throws ISOException { if (allow != null && allow.length > 0) { String ip = socket.getInetAddress().getHostAddress (); for (int i=0; i<allow.length; i++) { if (ip.equals (allow[i])) { evt.addMessage ("access granted, ip=" + ip); return; } } throw new ISOException ("access denied, ip=" + ip); } } } /** * add an ISORequestListener * @param l request listener to be added * @see ISORequestListener */ public void addISORequestListener(ISORequestListener l) { listeners.add (l); } /** * remove an ISORequestListener * @param l a request listener to be removed * @see ISORequestListener */ public void removeISORequestListener(ISORequestListener l) { listeners.remove (l); } /** * Shutdown this server */ public void shutdown () { shutdown = true; new Thread ("ISOServer-shutdown") { public void run () { shutdownServer (); shutdownChannels (); } }.start(); } private void shutdownServer () { try { if (serverSocket != null) serverSocket.close (); } catch (IOException e) { Logger.log (new LogEvent (this, "shutdown", e)); } } private void shutdownChannels () { Iterator iter = channels.iterator(); while (iter.hasNext()) { ISOChannel c = (ISOChannel) ((WeakReference) iter.next()).get (); if (c != null) { try { c.disconnect (); } catch (IOException e) { Logger.log (new LogEvent (this, "shutdown", e)); } } } } private void purgeChannels () { Iterator iter = channels.iterator(); while (iter.hasNext()) { WeakReference ref = (WeakReference) iter.next(); ISOChannel c = (ISOChannel) ref.get (); if (c == null || (!c.isConnected())) iter.remove (); } } public void run() { ServerChannel channel; while (!shutdown) { try { serverSocket = socketFactory != null ? socketFactory.createServerSocket(port) : (new ServerSocket (port)); Logger.log (new LogEvent (this, "iso-server", "listening on port "+port)); while (!shutdown) { try { channel = (ServerChannel) clientSideChannelClass.newInstance(); channel.setPackager (clientPackager); if (channel instanceof LogSource) { ((LogSource)channel) . setLogger (getLogger(), realmChannel); } if (clientSideChannel instanceof BaseChannel) { ((BaseChannel)channel).setHeader ( ((BaseChannel)clientSideChannel).getHeader()); ((BaseChannel)channel).setTimeout ( ((BaseChannel)clientSideChannel).getTimeout()); } setFilters (channel); if (channel instanceof Observable) ((Observable)channel).addObserver (this); for (int i=0; pool.getAvailableCount() <= 0; i++) { ISOUtil.sleep (250); if (i % 240 == 0) { LogEvent evt = new LogEvent (this, "warn"); evt.addMessage ( "pool exahusted " + serverSocket.toString() ); evt.addMessage (pool); Logger.log (evt); } } channel.accept (serverSocket); if ((cnt[CONNECT]++) % 100 == 0) purgeChannels (); channels.push (new WeakReference (channel)); setChanged (); notifyObservers (channel); pool.execute (createSession(channel)); } catch (SocketException e) { if (!shutdown) Logger.log (new LogEvent (this, "iso-server", e)); } catch (IOException e) { Logger.log (new LogEvent (this, "iso-server", e)); relax(); } catch (InstantiationException e) { Logger.log (new LogEvent (this, "iso-server", e)); relax(); } catch (IllegalAccessException e) { Logger.log (new LogEvent (this, "iso-server", e)); relax(); } } } catch (Throwable e) { Logger.log (new LogEvent (this, "iso-server", e)); relax(); } } } private void setFilters (ISOChannel channel) { if (clientOutgoingFilters != null) ((FilteredChannel)channel) . setOutgoingFilters (clientOutgoingFilters); if (clientIncomingFilters != null) ((FilteredChannel)channel) . setIncomingFilters (clientIncomingFilters); } private void relax() { try { Thread.sleep (5000); } catch (InterruptedException e) { } } /** * associates this ISOServer with a name using NameRegistrar * @param name name to register * @see NameRegistrar */ public void setName (String name) { this.name = name; NameRegistrar.register ("server."+name, this); } /** * @return ISOMUX instance with given name. * @throws NameRegistrar.NotFoundException; * @see NameRegistrar */ public static ISOServer getServer (String name) throws NameRegistrar.NotFoundException { return (ISOServer) NameRegistrar.get ("server."+name); } /** * @return this ISOServer's name ("" if no name was set) */ public String getName() { return this.name; } public void setLogger (Logger logger, String realm) { this.logger = logger; this.realm = realm; this.realmChannel = realm + ".channel"; } public String getRealm () { return realm; } public Logger getLogger() { return logger; } public void update(Observable o, Object arg) { setChanged (); notifyObservers (arg); } /** * Gets the ISOClientSocketFactory (may be null) * @see ISOClientSocketFactory * @since 1.3.3 */ public ISOServerSocketFactory getSocketFactory() { return socketFactory; } /** * Sets the specified Socket Factory to create sockets * @param socketFactory the ISOClientSocketFactory * @see ISOClientSocketFactory * @since 1.3.3 */ public void setSocketFactory(ISOServerSocketFactory socketFactory) { this.socketFactory = socketFactory; } public int getPort () { return port; } public void resetCounters () { cnt = new int[SIZEOF_CNT]; } /** * @return number of connections accepted by this server */ public int getConnectionCount () { return cnt[CONNECT]; } // ThreadPoolMBean implementation (delegate calls to pool) public int getJobCount () { return pool.getJobCount(); } public int getPoolSize () { return pool.getPoolSize(); } public int getMaxPoolSize () { return pool.getMaxPoolSize(); } public int getIdleCount() { return pool.getIdleCount(); } public int getPendingCount () { return pool.getPendingCount(); } /** * @return most recently connected ISOChannel or null */ public ISOChannel getLastConnectedISOChannel () { if (!channels.empty()) { WeakReference ref = (WeakReference) channels.peek (); if (ref != null) return (ISOChannel) ref.get (); } return null; } public void setConfiguration (Configuration cfg) throws ConfigurationException { this.cfg = cfg; allow = cfg.getAll ("allow"); if (socketFactory != this && socketFactory instanceof Configurable) { ((Configurable)socketFactory).setConfiguration (cfg); } } }
package com.feedback.app; import com.feedback.resources.DatasetResource; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.eclipse.jetty.util.resource.Resource; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import javax.servlet.DispatcherType; import java.util.EnumSet; /** * Main class. */ public class Main { private static final int PORT = 9999; public static void main( String[] args ) throws Exception { int serverPort = PORT; // Workaround for resources from JAR files Resource.setDefaultUseCaches( false ); // Holds handlers final HandlerList handlers = new HandlerList(); // Handler for Reviews Service and Swagger handlers.addHandler( enableCors( buildContext() ) ); // Start server Server server = new Server( serverPort ); server.setHandler( handlers ); server.start(); server.join(); } private static ContextHandler buildContext() { ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig.register( JacksonFeature.class ); // Replace EntityBrowser with your resource class // com.wordnik.swagger.jaxrs.listing loads up Swagger resources resourceConfig.packages( DatasetResource.class.getPackage().getName(), "com.wordnik.swagger.jaxrs.listing" ); ServletContainer servletContainer = new ServletContainer( resourceConfig ); ServletHolder entityBrowser = new ServletHolder( servletContainer ); ServletContextHandler entityBrowserContext = new ServletContextHandler( ServletContextHandler.SESSIONS ); entityBrowserContext.setContextPath( "/" );
package edu.umd.cs.findbugs; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import org.apache.bcel.Constants; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.JavaClassAndMethod; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.bcp.FieldVariable; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; /** * An instance of a bug pattern. * A BugInstance consists of several parts: * <p/> * <ul> * <li> the type, which is a string indicating what kind of bug it is; * used as a key for the FindBugsMessages resource bundle * <li> the priority; how likely this instance is to actually be a bug * <li> a list of <em>annotations</em> * </ul> * <p/> * The annotations describe classes, methods, fields, source locations, * and other relevant context information about the bug instance. * Every BugInstance must have at least one ClassAnnotation, which * describes the class in which the instance was found. This is the * "primary class annotation". * <p/> * <p> BugInstance objects are built up by calling a string of <code>add</code> * methods. (These methods all "return this", so they can be chained). * Some of the add methods are specialized to get information automatically from * a BetterVisitor or DismantleBytecode object. * * @author David Hovemeyer * @see BugAnnotation */ public class BugInstance implements Comparable<BugInstance>, XMLWriteableWithMessages, Serializable, Cloneable { private static final long serialVersionUID = 1L; private String type; private int priority; private ArrayList<BugAnnotation> annotationList; private int cachedHashCode; @NonNull private String annotationText; private BugProperty propertyListHead, propertyListTail; private String uniqueId; /* * The following fields are used for tracking Bug instances across multiple versions of software. * They are meaningless in a BugCollection for just one version of software. */ private long firstVersion = 0; private long lastVersion = -1; private boolean introducedByChangeOfExistingClass; private boolean removedByChangeOfPersistingClass; /** * This value is used to indicate that the cached hashcode * is invalid, and should be recomputed. */ private static final int INVALID_HASH_CODE = 0; /** * This value is used to indicate whether BugInstances should be reprioritized very low, * when the BugPattern is marked as experimental */ private static boolean adjustExperimental = false; /** * Constructor. * * @param type the bug type * @param priority the bug priority */ public BugInstance(String type, int priority) { this.type = type; this.priority = priority < Detector.HIGH_PRIORITY ? Detector.HIGH_PRIORITY : priority; annotationList = new ArrayList<BugAnnotation>(4); cachedHashCode = INVALID_HASH_CODE; annotationText = ""; if (adjustExperimental && isExperimental()) this.priority = Detector.EXP_PRIORITY; } //@Override public Object clone() { BugInstance dup; try { dup = (BugInstance) super.clone(); // Do deep copying of mutable objects for (int i = 0; i < dup.annotationList.size(); ++i) { dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone()); } dup.propertyListHead = dup.propertyListTail = null; for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) { dup.addProperty((BugProperty) i.next().clone()); } return dup; } catch (CloneNotSupportedException e) { throw new IllegalStateException("impossible", e); } } /** * Create a new BugInstance. * This is the constructor that should be used by Detectors. * * @param detector the Detector that is reporting the BugInstance * @param type the bug type * @param priority the bug priority */ public BugInstance(Detector detector, String type, int priority) { this(type, priority); if (detector != null) { // Adjust priority if required DetectorFactory factory = DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName()); if (factory != null) { this.priority += factory.getPriorityAdjustment(); if (this.priority < 0) this.priority = 0; } } if (adjustExperimental && isExperimental()) this.priority = Detector.EXP_PRIORITY; } public static void setAdjustExperimental(boolean adjust) { adjustExperimental = adjust; } /** * Get the bug type. */ public String getType() { return type; } /** * Get the BugPattern. */ public BugPattern getBugPattern() { return I18N.instance().lookupBugPattern(getType()); } /** * Get the bug priority. */ public int getPriority() { return priority; } /** * Set the bug priority. */ public void setPriority(int p) { priority = p < Detector.HIGH_PRIORITY ? Detector.HIGH_PRIORITY : p; } /** * Is this bug instance the result of an experimental detector? */ public boolean isExperimental() { BugPattern pattern = I18N.instance().lookupBugPattern(type); return (pattern != null) && pattern.isExperimental(); } /** * Get the primary class annotation, which indicates where the bug occurs. */ public ClassAnnotation getPrimaryClass() { return (ClassAnnotation) findAnnotationOfType(ClassAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public MethodAnnotation getPrimaryMethod() { return (MethodAnnotation) findAnnotationOfType(MethodAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public FieldAnnotation getPrimaryField() { return (FieldAnnotation) findAnnotationOfType(FieldAnnotation.class); } /** * Find the first BugAnnotation in the list of annotations * that is the same type or a subtype as the given Class parameter. * * @param cls the Class parameter * @return the first matching BugAnnotation of the given type, * or null if there is no such BugAnnotation */ private BugAnnotation findAnnotationOfType(Class<? extends BugAnnotation> cls) { for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) { BugAnnotation annotation = i.next(); if (cls.isAssignableFrom(annotation.getClass())) return annotation; } return null; } /** * Get the primary source line annotation. * * @return the source line annotation, or null if there is * no source line annotation */ public SourceLineAnnotation getPrimarySourceLineAnnotation() { // Highest priority: return the first top level source line annotation for (BugAnnotation annotation : annotationList) { if (annotation instanceof SourceLineAnnotation) return (SourceLineAnnotation) annotation; } // Second priority: return the source line annotation describing the // primary method MethodAnnotation primaryMethodAnnotation = getPrimaryMethod(); if (primaryMethodAnnotation != null) return primaryMethodAnnotation.getSourceLines(); else return null; } /** * Get an Iterator over all bug annotations. */ public Iterator<BugAnnotation> annotationIterator() { return annotationList.iterator(); } /** * Get the abbreviation of this bug instance's BugPattern. * This is the same abbreviation used by the BugCode which * the BugPattern is a particular species of. */ public String getAbbrev() { BugPattern pattern = I18N.instance().lookupBugPattern(getType()); return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>"; } /** * Set the user annotation text. * * @param annotationText the user annotation text */ public void setAnnotationText(@NonNull String annotationText) { this.annotationText = annotationText; } /** * Get the user annotation text. * * @return the user annotation text */ @NonNull public String getAnnotationText() { return annotationText; } /** * Determine whether or not the annotation text contains * the given word. * * @param word the word * @return true if the annotation text contains the word, false otherwise */ public boolean annotationTextContainsWord(String word) { return getTextAnnotationWords().contains(word); } /** * Get set of words in the text annotation. */ public Set<String> getTextAnnotationWords() { HashSet<String> result = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(annotationText, " \t\r\n\f.,:;-"); while (tok.hasMoreTokens()) { result.add(tok.nextToken()); } return result; } /** * Get the BugInstance's unique id. * * @return the unique id, or null if no unique id has been assigned */ public String getUniqueId() { return uniqueId; } /** * Set the unique id of the BugInstance. * * @param uniqueId the unique id */ public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } private class BugPropertyIterator implements Iterator<BugProperty> { private BugProperty prev, cur; private boolean removed; /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return findNext() != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public BugProperty next() { BugProperty next = findNext(); if (next == null) throw new NoSuchElementException(); prev = cur; cur = next; removed = false; return cur; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { if (cur == null || removed) throw new IllegalStateException(); if (prev == null) { propertyListHead = cur.getNext(); } else { prev.setNext(cur.getNext()); } if (cur == propertyListTail) { propertyListTail = prev; } removed = true; } private BugProperty findNext() { return cur == null ? propertyListHead : cur.getNext(); } } /** * Get value of given property. * * @param name name of the property to get * @return the value of the named property, or null if * the property has not been set */ public String getProperty(String name) { BugProperty prop = lookupProperty(name); return prop != null ? prop.getValue() : null; } /** * Get value of given property, returning given default * value if the property has not been set. * * @param name name of the property to get * @param defaultValue default value to return if propery is not set * @return the value of the named property, or the default * value if the property has not been set */ public String getProperty(String name, String defaultValue) { String value = getProperty(name); return value != null ? value : defaultValue; } /** * Get an Iterator over the properties defined in this BugInstance. * * @return Iterator over properties */ public Iterator<BugProperty> propertyIterator() { return new BugPropertyIterator(); } /** * Set value of given property. * * @param name name of the property to set * @param value the value of the property * @return this object, so calls can be chained */ public BugInstance setProperty(String name, String value) { BugProperty prop = lookupProperty(name); if (prop != null) { prop.setValue(value); } else { prop = new BugProperty(name, value); addProperty(prop); } return this; } /** * Look up a property by name. * * @param name name of the property to look for * @return the BugProperty with the given name, * or null if the property has not been set */ public BugProperty lookupProperty(String name) { BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prop = prop.getNext(); } return prop; } /** * Delete property with given name. * * @param name name of the property to delete * @return true if a property with that name was deleted, * or false if there is no such property */ public boolean deleteProperty(String name) { BugProperty prev = null; BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prev = prop; prop = prop.getNext(); } if (prop != null) { if (prev != null) { // Deleted node in interior or at tail of list prev.setNext(prop.getNext()); } else { // Deleted node at head of list propertyListHead = prop.getNext(); } if (prop.getNext() == null) { // Deleted node at end of list propertyListTail = prev; } return true; } else { // No such property return false; } } private void addProperty(BugProperty prop) { if (propertyListTail != null) { propertyListTail.setNext(prop); propertyListTail = prop; } else { propertyListHead = propertyListTail = prop; } prop.setNext(null); } /** * Add a Collection of BugAnnotations. * * @param annotationCollection Collection of BugAnnotations */ public void addAnnotations(Collection<BugAnnotation> annotationCollection) { for (BugAnnotation annotation : annotationCollection) { add(annotation); } } /** * Add a class annotation and a method annotation for the class and method * which the given visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClassAndMethod(PreorderVisitor visitor) { addClass(visitor); addMethod(visitor); return this; } /** * Add class and method annotations for given method. * * @param methodAnnotation the method * @return this object */ public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) { addClass(methodAnnotation.getClassName()); addMethod(methodAnnotation); return this; } /** * Add class and method annotations for given method. * * @param methodGen the method * @param sourceFile source file the method is defined in * @return this object */ public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) { addClass(methodGen.getClassName()); addMethod(methodGen, sourceFile); return this; } /** * Add class and method annotations for given class and method. * * @param javaClass the class * @param method the method * @return this object */ public BugInstance addClassAndMethod(JavaClass javaClass, Method method) { addClass(javaClass.getClassName()); addMethod(javaClass, method); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param className the name of the class * @return this object */ public BugInstance addClass(String className) { ClassAnnotation classAnnotation = new ClassAnnotation(className); add(classAnnotation); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param jclass the JavaClass object for the class * @return this object */ public BugInstance addClass(JavaClass jclass) { addClass(jclass.getClassName()); return this; } /** * Add a class annotation for the class that the visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClass(PreorderVisitor visitor) { String className = visitor.getDottedClassName(); addClass(className); return this; } /** * Add a class annotation for the superclass of the class the visitor * is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addSuperclass(PreorderVisitor visitor) { String className = visitor.getSuperclassName(); addClass(className); return this; } /** * Add a field annotation. * * @param className name of the class containing the field * @param fieldName the name of the field * @param fieldSig type signature of the field * @param isStatic whether or not the field is static * @return this object */ public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) { addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic)); return this; } /** * Add a field annotation * * @param fieldAnnotation the field annotation * @return this object */ public BugInstance addField(FieldAnnotation fieldAnnotation) { add(fieldAnnotation); return this; } /** * Add a field annotation for a FieldVariable matched in a ByteCodePattern. * * @param field the FieldVariable * @return this object */ public BugInstance addField(FieldVariable field) { return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic()); } /** * Add a field annotation for an XField. * * @param xfield the XField * @return this object */ public BugInstance addField(XField xfield) { return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic()); } /** * Add a field annotation for the field which has just been accessed * by the method currently being visited by given visitor. * Assumes that a getfield/putfield or getstatic/putstatic * has just been seen. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addReferencedField(DismantleBytecode visitor) { FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor); addField(f); return this; } /** * Add a field annotation for the field referenced by the FieldAnnotation parameter */ public BugInstance addReferencedField(FieldAnnotation fa) { addField(fa); return this; } /** * Add a field annotation for the field which is being visited by * given visitor. * * @param visitor the visitor * @return this object */ public BugInstance addVisitedField(PreorderVisitor visitor) { FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor); addField(f); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param className name of the class containing the method * @param methodName name of the method * @param methodSig type signature of the method * @param isStatic true if the method is static, false otherwise * @return this object */ public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) { addMethod(new MethodAnnotation(className, methodName, methodSig, isStatic)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param methodGen the MethodGen object for the method * @param sourceFile source file method is defined in * @return this object */ public BugInstance addMethod(MethodGen methodGen, String sourceFile) { MethodAnnotation methodAnnotation = new MethodAnnotation(methodGen.getClassName(), methodGen.getName(), methodGen.getSignature(), methodGen.isStatic()); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param javaClass the class the method is defined in * @param method the method * @return this object */ public BugInstance addMethod(JavaClass javaClass, Method method) { MethodAnnotation methodAnnotation = new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature(), method.isStatic()); SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod( javaClass, method); methodAnnotation.setSourceLines(methodSourceLines); addMethod(methodAnnotation); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param classAndMethod JavaClassAndMethod identifying the method to add * @return this object */ public BugInstance addMethod(JavaClassAndMethod classAndMethod) { return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod()); } /** * Add a method annotation for the method which the given visitor is currently visiting. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addMethod(PreorderVisitor visitor) { MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor)); return this; } /** * Add a method annotation for the method which has been called * by the method currently being visited by given visitor. * Assumes that the visitor has just looked at an invoke instruction * of some kind. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addCalledMethod(DismantleBytecode visitor) { String className = visitor.getDottedClassConstantOperand(); String methodName = visitor.getNameConstantOperand(); String methodSig = visitor.getDottedSigConstantOperand(); addMethod(className, methodName, methodSig, visitor.getMethod().isStatic()); describe("METHOD_CALLED"); return this; } /** * Add a method annotation. * * @param className name of class containing called method * @param methodName name of called method * @param methodSig signature of called method * @param isStatic true if called method is static, false if not * @return this object */ public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) { addMethod(className, methodName, methodSig, isStatic); describe("METHOD_CALLED"); return this; } /** * Add a method annotation for the method which is called by given * instruction. * * @param methodGen the method containing the call * @param inv the InvokeInstruction * @return this object */ public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) { ConstantPoolGen cpg = methodGen.getConstantPool(); String className = inv.getClassName(cpg); String methodName = inv.getMethodName(cpg); String methodSig = inv.getSignature(cpg); addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC); describe("METHOD_CALLED"); return this; } /** * Add a MethodAnnotation from an XMethod. * * @param xmethod the XMethod * @return this object */ public BugInstance addMethod(XMethod xmethod) { addMethod(MethodAnnotation.fromXMethod(xmethod)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param methodAnnotation the method annotation * @return this object */ public BugInstance addMethod(MethodAnnotation methodAnnotation) { add(methodAnnotation); return this; } /** * Add an integer annotation. * * @param value the integer value * @return this object */ public BugInstance addInt(int value) { add(new IntAnnotation(value)); return this; } /** * Add a String annotation. * * @param value the String value * @return this object */ public BugInstance addString(String value) { add(new StringAnnotation(value)); return this; } /** * Add a source line annotation. * * @param sourceLine the source line annotation * @return this object */ public BugInstance addSourceLine(SourceLineAnnotation sourceLine) { add(sourceLine); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BytecodeScanningDetector that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(), visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a PreorderVisitor that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for the given instruction in the given method. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param methodGen the method being visited * @param sourceFile source file the method is defined in * @param handle the InstructionHandle containing the visited instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing a range of instructions. * * @param classContext the ClassContext * @param methodGen the method * @param sourceFile source file the method is defined in * @param start the start instruction in the range * @param end the end instruction in the range (inclusive) * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) { // Make sure start and end are really in the right order. if (start.getPosition() > end.getPosition()) { InstructionHandle tmp = start; start = end; end = tmp; } SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen, sourceFile, start, end); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(), visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction currently being visited * by given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BytecodeScanningDetector visitor that is currently visiting the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a non-specific source line annotation. * This will result in the entire source file being displayed. * * @param className the class name * @param sourceFile the source file name * @return this object */ public BugInstance addUnknownSourceLine(String className, String sourceFile) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Format a string describing this bug instance. * * @return the description */ public String getMessage() { String pattern = I18N.instance().getMessage(type); FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()])); } /** * Add a description to the most recently added bug annotation. * * @param description the description to add * @return this object */ public BugInstance describe(String description) { annotationList.get(annotationList.size() - 1).setDescription(description); return this; } /** * Convert to String. * This method returns the "short" message describing the bug, * as opposed to the longer format returned by getMessage(). * The short format is appropriate for the tree view in a GUI, * where the annotations are listed separately as part of the overall * bug instance. */ public String toString() { return I18N.instance().getShortMessage(type); } public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, false); } public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException { XMLAttributeList attributeList = new XMLAttributeList() .addAttribute("type", type) .addAttribute("priority", String.valueOf(priority)); BugPattern pattern = getBugPattern(); if (pattern != null) { // The bug abbreviation and pattern category are // emitted into the XML for informational purposes only. // (The information is redundant, but might be useful // for processing tools that want to make sense of // bug instances without looking at the plugin descriptor.) attributeList.addAttribute("abbrev", pattern.getAbbrev()); attributeList.addAttribute("category", pattern.getCategory()); } // Add a uid attribute, if we have a unique id. if (getUniqueId() != null) { attributeList.addAttribute("uid", getUniqueId()); } if (firstVersion > 0) attributeList.addAttribute("first", Long.toString(firstVersion)); if (lastVersion >= 0) attributeList.addAttribute("last", Long.toString(lastVersion)); if (introducedByChangeOfExistingClass) attributeList.addAttribute("introducedByChange", "true"); if (removedByChangeOfPersistingClass) attributeList.addAttribute("removedByChange", "true"); xmlOutput.openTag(ELEMENT_NAME, attributeList); if (!annotationText.equals("")) { xmlOutput.openTag("UserAnnotation"); xmlOutput.writeCDATA(annotationText); xmlOutput.closeTag("UserAnnotation"); } if (addMessages) { BugPattern bugPattern = getBugPattern(); xmlOutput.openTag("ShortMessage"); xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString()); xmlOutput.closeTag("ShortMessage"); xmlOutput.openTag("LongMessage"); xmlOutput.writeText(this.getMessage()); xmlOutput.closeTag("LongMessage"); } for (BugAnnotation annotation : annotationList) { annotation.writeXML(xmlOutput, addMessages); } if (propertyListHead != null) { BugProperty prop = propertyListHead; while (prop != null) { prop.writeXML(xmlOutput); prop = prop.getNext(); } } xmlOutput.closeTag(ELEMENT_NAME); } private static final String ELEMENT_NAME = "BugInstance"; private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation"; public BugInstance add(BugAnnotation annotation) { if (annotation == null) throw new IllegalStateException("Missing BugAnnotation!"); // Add to list annotationList.add(annotation); // This object is being modified, so the cached hashcode // must be invalidated cachedHashCode = INVALID_HASH_CODE; return this; } private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) { if (sourceLineAnnotation != null) { // Note: we don't add the source line annotation directly to // the bug instance. Instead, we stash it in the MethodAnnotation. // It is much more useful there, and it would just be distracting // if it were displayed in the UI, since it would compete for attention // with the actual bug location source line annotation (which is much // more important and interesting). methodAnnotation.setSourceLines(sourceLineAnnotation); } } public int hashCode() { if (cachedHashCode == INVALID_HASH_CODE) { int hashcode = type.hashCode() + priority; Iterator<BugAnnotation> i = annotationIterator(); while (i.hasNext()) hashcode += i.next().hashCode(); if (hashcode == INVALID_HASH_CODE) hashcode = INVALID_HASH_CODE+1; cachedHashCode = hashcode; } return cachedHashCode; } public boolean equals(Object o) { if (!(o instanceof BugInstance)) return false; BugInstance other = (BugInstance) o; if (!type.equals(other.type) || priority != other.priority) return false; if (annotationList.size() != other.annotationList.size()) return false; int numAnnotations = annotationList.size(); for (int i = 0; i < numAnnotations; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); if (!lhs.equals(rhs)) return false; } return true; } public int compareTo(BugInstance other) { int cmp; cmp = type.compareTo(other.type); if (cmp != 0) return cmp; cmp = priority - other.priority; if (cmp != 0) return cmp; // Compare BugAnnotations lexicographically int pfxLen = Math.min(annotationList.size(), other.annotationList.size()); for (int i = 0; i < pfxLen; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); cmp = lhs.compareTo(rhs); if (cmp != 0) return cmp; } // All elements in prefix were the same, // so use number of elements to decide return annotationList.size() - other.annotationList.size(); } /** * @param firstVersion The firstVersion to set. */ public void setFirstVersion(long firstVersion) { this.firstVersion = firstVersion; if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); } /** * @return Returns the firstVersion. */ public long getFirstVersion() { return firstVersion; } /** * @param lastVersion The lastVersion to set. */ public void setLastVersion(long lastVersion) { if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); this.lastVersion = lastVersion; } /** * @return Returns the lastVersion. */ public long getLastVersion() { return lastVersion; } /** * @param introducedByChangeOfExistingClass The introducedByChangeOfExistingClass to set. */ public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) { this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass; } /** * @return Returns the introducedByChangeOfExistingClass. */ public boolean isIntroducedByChangeOfExistingClass() { return introducedByChangeOfExistingClass; } /** * @param removedByChangeOfPersistingClass The removedByChangeOfPersistingClass to set. */ public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) { this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass; } /** * @return Returns the removedByChangeOfPersistingClass. */ public boolean isRemovedByChangeOfPersistingClass() { return removedByChangeOfPersistingClass; } } // vim:ts=4
package edu.umd.cs.findbugs; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.meta.TypeQualifier; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantDouble; import org.apache.bcel.classfile.ConstantFloat; import org.apache.bcel.classfile.ConstantInteger; import org.apache.bcel.classfile.ConstantLong; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.AnalysisFeatures; import edu.umd.cs.findbugs.ba.ClassMember; import edu.umd.cs.findbugs.ba.FieldSummary; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.classfile.engine.bcel.AnalysisFactory; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.visitclass.Constants2; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.LVTHelper; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * tracks the types and numbers of objects that are currently on the operand stack * throughout the execution of method. To use, a detector should instantiate one for * each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method. * at any point you can then inspect the stack and see what the types of objects are on * the stack, including constant values if they were pushed. The types described are of * course, only the static types. * There are some outstanding opcodes that have yet to be implemented, I couldn't * find any code that actually generated these, so i didn't put them in because * I couldn't test them: * <ul> * <li>dup2_x2</li> * <li>jsr_w</li> * <li>wide</li> * </ul> */ public class OpcodeStack implements Constants2 { private static final String JAVA_UTIL_ARRAYS_ARRAY_LIST = "Ljava/util/Arrays$ArrayList;"; private static final boolean DEBUG = SystemProperties.getBoolean("ocstack.debug"); private static final boolean DEBUG2 = DEBUG; private List<Item> stack; private List<Item> lvValues; private List<Integer> lastUpdate; private boolean top; static class HttpParameterInjection { HttpParameterInjection(String parameterName, int pc) { this.parameterName = parameterName; this.pc = pc; } String parameterName; int pc; } private boolean seenTransferOfControl = false; private boolean useIterativeAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS); public static class Item { @Documented @TypeQualifier(applicableTo=Integer.class) @Retention(RetentionPolicy.RUNTIME) public @interface SpecialKind {} public static final @SpecialKind int NOT_SPECIAL = 0; public static final @SpecialKind int SIGNED_BYTE = 1; public static final @SpecialKind int RANDOM_INT = 2; public static final @SpecialKind int LOW_8_BITS_CLEAR = 3; public static final @SpecialKind int HASHCODE_INT = 4; public static final @SpecialKind int INTEGER_SUM = 5; public static final @SpecialKind int AVERAGE_COMPUTED_USING_DIVISION = 6; public static final @SpecialKind int FLOAT_MATH = 7; public static final @SpecialKind int RANDOM_INT_REMAINDER = 8; public static final @SpecialKind int HASHCODE_INT_REMAINDER = 9; public static final @SpecialKind int FILE_SEPARATOR_STRING = 10; public static final @SpecialKind int MATH_ABS = 11; public static final @SpecialKind int NON_NEGATIVE = 12; public static final @SpecialKind int NASTY_FLOAT_MATH = 13; public static final @SpecialKind int FILE_OPENED_IN_APPEND_MODE = 14; public static final @SpecialKind int SERVLET_REQUEST_TAINTED = 15; public static final @SpecialKind int NEWLY_ALLOCATED = 16; public static final @SpecialKind int ZERO_MEANS_NULL = 17; public static final @SpecialKind int NONZERO_MEANS_NULL = 18; private static final int IS_INITIAL_PARAMETER_FLAG=1; private static final int COULD_BE_ZERO_FLAG = 2; private static final int IS_NULL_FLAG = 4; public static final Object UNKNOWN = null; private @SpecialKind int specialKind = NOT_SPECIAL; private String signature; private Object constValue = UNKNOWN; private @CheckForNull ClassMember source; private int pc = -1; private int flags; private int registerNumber = -1; private Object userValue = null; private HttpParameterInjection injection = null; private int fieldLoadedFromRegister = -1; public void makeCrossMethod() { pc = -1; registerNumber = -1; fieldLoadedFromRegister = -1; } public int getSize() { if (signature.equals("J") || signature.equals("D")) return 2; return 1; } public int getPC() { return pc; } public void setPC(int pc) { this.pc = pc; } public boolean isWide() { return getSize() == 2; } @Override public int hashCode() { int r = 42 + specialKind; if (signature != null) r+= signature.hashCode(); r *= 31; if (constValue != null) r+= constValue.hashCode(); r *= 31; if (source != null) r+= source.hashCode(); r *= 31; r += flags; r *= 31; r += registerNumber; return r; } @Override public boolean equals(Object o) { if (!(o instanceof Item)) return false; Item that = (Item) o; return Util.nullSafeEquals(this.signature, that.signature) && Util.nullSafeEquals(this.constValue, that.constValue) && Util.nullSafeEquals(this.source, that.source) && Util.nullSafeEquals(this.userValue, that.userValue) && Util.nullSafeEquals(this.injection, that.injection) && this.specialKind == that.specialKind && this.registerNumber == that.registerNumber && this.flags == that.flags && this.fieldLoadedFromRegister == that.fieldLoadedFromRegister; } @Override public String toString() { StringBuilder buf = new StringBuilder("< "); buf.append(signature); switch(specialKind) { case SIGNED_BYTE: buf.append(", byte_array_load"); break; case RANDOM_INT: buf.append(", random_int"); break; case LOW_8_BITS_CLEAR: buf.append(", low8clear"); break; case HASHCODE_INT: buf.append(", hashcode_int"); break; case INTEGER_SUM: buf.append(", int_sum"); break; case AVERAGE_COMPUTED_USING_DIVISION: buf.append(", averageComputingUsingDivision"); break; case FLOAT_MATH: buf.append(", floatMath"); break; case NASTY_FLOAT_MATH: buf.append(", nastyFloatMath"); break; case HASHCODE_INT_REMAINDER: buf.append(", hashcode_int_rem"); break; case RANDOM_INT_REMAINDER: buf.append(", random_int_rem"); break; case FILE_SEPARATOR_STRING: buf.append(", file_separator_string"); break; case MATH_ABS: buf.append(", Math.abs"); break; case NON_NEGATIVE: buf.append(", non_negative"); break; case FILE_OPENED_IN_APPEND_MODE: buf.append(", file opened in append mode"); break; case SERVLET_REQUEST_TAINTED: buf.append(", servlet request tainted"); break; case NEWLY_ALLOCATED: buf.append(", new"); break; case ZERO_MEANS_NULL: buf.append(", zero means null"); break; case NONZERO_MEANS_NULL: buf.append(", nonzero means null"); break; case NOT_SPECIAL : break; default: buf.append(", #" + specialKind); break; } if (constValue != UNKNOWN) { if (constValue instanceof String) { buf.append(", \""); buf.append(constValue); buf.append("\""); } else { buf.append(", "); buf.append(constValue); } } if (source instanceof XField) { buf.append(", "); if (fieldLoadedFromRegister != -1) buf.append(fieldLoadedFromRegister).append(':'); buf.append(source); } if (source instanceof XMethod) { buf.append(", return value from "); buf.append(source); } if (isInitialParameter()) { buf.append(", IP"); } if (isNull()) { buf.append(", isNull"); } if (registerNumber != -1) { buf.append(", r"); buf.append(registerNumber); } if (isCouldBeZero()) buf.append(", cbz"); buf.append(" >"); return buf.toString(); } public static Item merge(Item i1, Item i2) { if (i1 == null) return i2; if (i2 == null) return i1; if (i1.equals(i2)) return i1; Item m = new Item(); m.flags = i1.flags & i2.flags; m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero()); if (i1.pc == i2.pc) m.pc = i1.pc; if (Util.nullSafeEquals(i1.signature, i2.signature)) m.signature = i1.signature; else if (i1.isNull()) m.signature = i2.signature; else if (i2.isNull()) m.signature = i1.signature; if (Util.nullSafeEquals(i1.constValue, i2.constValue)) m.constValue = i1.constValue; if (Util.nullSafeEquals(i1.source, i2.source)) { m.source = i1.source; } else if ("".equals(i1.constValue)) m.source = i2.source; else if ("".equals(i2.constValue)) m.source = i1.source; if (Util.nullSafeEquals(i1.userValue, i2.userValue)) m.userValue = i1.userValue; if (i1.registerNumber == i2.registerNumber) m.registerNumber = i1.registerNumber; if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister) m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister; if (i1.specialKind == SERVLET_REQUEST_TAINTED) { m.specialKind = SERVLET_REQUEST_TAINTED; m.injection = i1.injection; } else if (i2.specialKind == SERVLET_REQUEST_TAINTED) { m.specialKind = SERVLET_REQUEST_TAINTED; m.injection = i2.injection; } else if (i1.specialKind == i2.specialKind) m.specialKind = i1.specialKind; else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH) m.specialKind = NASTY_FLOAT_MATH; else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH) m.specialKind = FLOAT_MATH; if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m); return m; } public Item(String signature, int constValue) { this(signature, Integer.valueOf(constValue)); } public Item(String signature) { this(signature, UNKNOWN); } public Item(Item it) { this.signature = it.signature; this.constValue = it.constValue; this.source = it.source; this.registerNumber = it.registerNumber; this.userValue = it.userValue; this.injection = it.injection; this.flags = it.flags; this.specialKind = it.specialKind; this.pc = it.pc; } public Item(Item it, int reg) { this(it); this.registerNumber = reg; } public Item(String signature, FieldAnnotation f) { this.signature = signature; if (f != null) source = XFactory.createXField(f); fieldLoadedFromRegister = -1; } public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) { this.signature = signature; if (f != null) source = XFactory.createXField(f); this.fieldLoadedFromRegister = fieldLoadedFromRegister; } public int getFieldLoadedFromRegister() { return fieldLoadedFromRegister; } public void setLoadedFromField(XField f, int fieldLoadedFromRegister) { source = f; this.fieldLoadedFromRegister = fieldLoadedFromRegister; this.registerNumber = -1; } public @CheckForNull String getHttpParameterName() { if (!isServletParameterTainted()) throw new IllegalStateException(); if (injection == null) return null; return injection.parameterName; } public int getInjectionPC() { if (!isServletParameterTainted()) throw new IllegalStateException(); if (injection == null) return -1; return injection.pc; } public Item(String signature, Object constantValue) { this.signature = signature; constValue = constantValue; if (constantValue instanceof Integer) { int value = ((Integer) constantValue).intValue(); if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } else if (constantValue instanceof Long) { long value = ((Long) constantValue).longValue(); if (value != 0 && (value & 0xff) == 0) specialKind = LOW_8_BITS_CLEAR; if (value == 0) setCouldBeZero(true); } } public Item() { signature = "Ljava/lang/Object;"; constValue = null; setNull(true); } public static Item nullItem(String signature) { Item item = new Item(signature); item.constValue = null; item.setNull(true); return item; } /** Returns null for primitive and arrays */ public @CheckForNull JavaClass getJavaClass() throws ClassNotFoundException { String baseSig; if (isPrimitive() || isArray()) return null; baseSig = signature; if (baseSig.length() == 0) return null; baseSig = baseSig.substring(1, baseSig.length() - 1); baseSig = baseSig.replace('/', '.'); return Repository.lookupClass(baseSig); } public boolean isArray() { return signature.startsWith("["); } @Deprecated public String getElementSignature() { if (!isArray()) return signature; else { int pos = 0; int len = signature.length(); while (pos < len) { if (signature.charAt(pos) != '[') break; pos++; } return signature.substring(pos); } } public boolean isNonNegative() { if (specialKind == NON_NEGATIVE) return true; if (constValue instanceof Number) { double value = ((Number) constValue).doubleValue(); return value >= 0; } return false; } public boolean isPrimitive() { return !signature.startsWith("L") && !signature.startsWith("["); } public int getRegisterNumber() { return registerNumber; } public String getSignature() { return signature; } /** * Returns a constant value for this Item, if known. * NOTE: if the value is a constant Class object, the constant value returned is the name of the class. */ public Object getConstant() { return constValue; } /** Use getXField instead */ @Deprecated public FieldAnnotation getFieldAnnotation() { return FieldAnnotation.fromXField(getXField()); } public XField getXField() { if (source instanceof XField) return (XField) source; return null; } /** * @param specialKind The specialKind to set. */ public void setSpecialKind(@SpecialKind int specialKind) { this.specialKind = specialKind; } public Item cloneAndSetSpecialKind(@SpecialKind int specialKind) { Item that = new Item(this); that.specialKind = specialKind; return that; } /** * @return Returns the specialKind. */ public @SpecialKind int getSpecialKind() { return specialKind; } /** * @return Returns the specialKind. */ public boolean isBooleanNullnessValue() { return specialKind == ZERO_MEANS_NULL || specialKind == NONZERO_MEANS_NULL; } /** * attaches a detector specified value to this item * * @param value the custom value to set */ public void setUserValue(Object value) { userValue = value; } /** * * @return if this value is the return value of a method, give the method * invoked */ public @CheckForNull XMethod getReturnValueOf() { if (source instanceof XMethod) return (XMethod) source; return null; } public boolean couldBeZero() { return isCouldBeZero(); } public boolean mustBeZero() { Object value = getConstant(); return value instanceof Number && ((Number)value).intValue() == 0; } /** * gets the detector specified value for this item * * @return the custom value */ public Object getUserValue() { return userValue; } public boolean isServletParameterTainted() { return getSpecialKind() == Item.SERVLET_REQUEST_TAINTED; } public void setServletParameterTainted() { setSpecialKind(Item.SERVLET_REQUEST_TAINTED); } public boolean valueCouldBeNegative() { return !isNonNegative() && (getSpecialKind() == Item.RANDOM_INT || getSpecialKind() == Item.SIGNED_BYTE || getSpecialKind() == Item.HASHCODE_INT || getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER); } public boolean checkForIntegerMinValue() { return !isNonNegative() && (getSpecialKind() == Item.RANDOM_INT || getSpecialKind() == Item.HASHCODE_INT ); } /** * @param isInitialParameter The isInitialParameter to set. */ private void setInitialParameter(boolean isInitialParameter) { setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG); } /** * @return Returns the isInitialParameter. */ public boolean isInitialParameter() { return (flags & IS_INITIAL_PARAMETER_FLAG) != 0; } /** * @param couldBeZero The couldBeZero to set. */ private void setCouldBeZero(boolean couldBeZero) { setFlag(couldBeZero, COULD_BE_ZERO_FLAG); } /** * @return Returns the couldBeZero. */ private boolean isCouldBeZero() { return (flags & COULD_BE_ZERO_FLAG) != 0; } /** * @param isNull The isNull to set. */ private void setNull(boolean isNull) { setFlag(isNull, IS_NULL_FLAG); } private void setFlag(boolean value, int flagBit) { if (value) flags |= flagBit; else flags &= ~flagBit; } /** * @return Returns the isNull. */ public boolean isNull() { return (flags & IS_NULL_FLAG) != 0; } public void clearNewlyAllocated() { if (specialKind == NEWLY_ALLOCATED) { if (signature.startsWith("Ljava/lang/StringB")) constValue = null; specialKind = NOT_SPECIAL; } } public boolean isNewlyAllocated() { return specialKind == NEWLY_ALLOCATED; } /** * @param i * @return */ public boolean hasConstantValue(int value) { if (constValue instanceof Number) return ((Number) constValue).intValue() == value; return false; } public boolean hasConstantValue(long value) { if (constValue instanceof Number) return ((Number) constValue).longValue() == value; return false; } } @Override public String toString() { if (isTop()) return "TOP"; return stack.toString() + "::" + lvValues.toString(); } public OpcodeStack() { stack = new ArrayList<Item>(); lvValues = new ArrayList<Item>(); lastUpdate = new ArrayList<Integer>(); } public boolean hasIncomingBranches(int pc) { return jumpEntryLocations.get(pc) && jumpEntries.get(pc) != null; } boolean needToMerge = true; private boolean reachOnlyByBranch = false; public static String getExceptionSig(DismantleBytecode dbc, CodeException e) { if (e.getCatchType() == 0) return "Ljava/lang/Throwable;"; Constant c = dbc.getConstantPool().getConstant(e.getCatchType()); if (c instanceof ConstantClass) return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";"; return "Ljava/lang/Throwable;"; } public void mergeJumps(DismantleBytecode dbc) { if (!needToMerge) return; needToMerge = false; if (dbc.getPC() == zeroOneComing) { pop(); top = false; OpcodeStack.Item item = new Item("I"); if (oneMeansNull) item.setSpecialKind(Item.NONZERO_MEANS_NULL); else item.setSpecialKind(Item.ZERO_MEANS_NULL); item.setPC(dbc.getPC() - 8); item.setCouldBeZero(true); push(item); zeroOneComing= -1; if (DEBUG) System.out.println("Updated to " + this); return; } boolean stackUpdated = false; if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) { pop(); Item topItem = new Item("I"); topItem.setCouldBeZero(true); push(topItem); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; stackUpdated = true; } List<Item> jumpEntry = null; if (jumpEntryLocations.get(dbc.getPC())) jumpEntry = jumpEntries.get(Integer.valueOf(dbc.getPC())); if (jumpEntry != null) { setReachOnlyByBranch(false); List<Item> jumpStackEntry = jumpStackEntries.get(Integer.valueOf(dbc.getPC())); if (DEBUG2) { System.out.println("XXXXXXX " + isReachOnlyByBranch()); System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + jumpEntry); System.out.println(" current lvValues " + lvValues); System.out.println(" merging stack entry " + jumpStackEntry); System.out.println(" current stack values " + stack); } if (isTop()) { lvValues = new ArrayList<Item>(jumpEntry); if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); setTop(false); return; } if (isReachOnlyByBranch()) { setTop(false); lvValues = new ArrayList<Item>(jumpEntry); if (!stackUpdated) { if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry); else stack.clear(); } } else { setTop(false); mergeLists(lvValues, jumpEntry, false); if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false); } if (DEBUG) System.out.println(" merged lvValues " + lvValues); } else if (isReachOnlyByBranch() && !stackUpdated) { stack.clear(); for(CodeException e : dbc.getCode().getExceptionTable()) { if (e.getHandlerPC() == dbc.getPC()) { push(new Item(getExceptionSig(dbc, e))); setReachOnlyByBranch(false); setTop(false); return; } } setTop(true); } } int convertJumpToOneZeroState = 0; int convertJumpToZeroOneState = 0; int registerTestedFoundToBeNonnegative = -1; private void setLastUpdate(int reg, int pc) { while (lastUpdate.size() <= reg) lastUpdate.add(Integer.valueOf(0)); lastUpdate.set(reg, Integer.valueOf(pc)); } public int getLastUpdate(int reg) { if (lastUpdate.size() <= reg) return 0; return lastUpdate.get(reg).intValue(); } public int getNumLastUpdates() { return lastUpdate.size(); } int zeroOneComing = -1; boolean oneMeansNull; public void sawOpcode(DismantleBytecode dbc, int seen) { int register; String signature; Item it, it2; Constant cons; // System.out.printf("%3d %3d %s\n", dbc.getPC(), registerTestedFoundToBeNonnegative, OPCODE_NAMES[seen]); if (dbc.isRegisterStore()) setLastUpdate(dbc.getRegisterOperand(), dbc.getPC()); precomputation(dbc); needToMerge = true; try { if (isTop()) { encountedTop = true; return; } if (seen == GOTO) { int nextPC = dbc.getPC() + 3; if (nextPC <= dbc.getMaxPC()) { int prevOpcode1 = dbc.getPrevOpcode(1); int prevOpcode2 = dbc.getPrevOpcode(2); try { int nextOpcode = dbc.getCodeByte(dbc.getPC() + 3); if ((prevOpcode1 == ICONST_0 || prevOpcode1 == ICONST_1) && (prevOpcode2 == IFNULL || prevOpcode2 == IFNONNULL) && (nextOpcode == ICONST_0 || nextOpcode == ICONST_1) && prevOpcode1 != nextOpcode) { oneMeansNull = prevOpcode1 == ICONST_0; if (prevOpcode2 != IFNULL) oneMeansNull = !oneMeansNull; zeroOneComing = nextPC+1; convertJumpToOneZeroState = convertJumpToZeroOneState = 0; } } catch(ArrayIndexOutOfBoundsException e) { throw e; // throw new ArrayIndexOutOfBoundsException(nextPC + " " + dbc.getMaxPC()); } } } switch (seen) { case ICONST_1: convertJumpToOneZeroState = 1; break; case GOTO: if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4) convertJumpToOneZeroState = 2; else convertJumpToOneZeroState = 0; break; case ICONST_0: if (convertJumpToOneZeroState == 2) convertJumpToOneZeroState = 3; else convertJumpToOneZeroState = 0; break; default:convertJumpToOneZeroState = 0; } switch (seen) { case ICONST_0: convertJumpToZeroOneState = 1; break; case GOTO: if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4) convertJumpToZeroOneState = 2; else convertJumpToZeroOneState = 0; break; case ICONST_1: if (convertJumpToZeroOneState == 2) convertJumpToZeroOneState = 3; else convertJumpToZeroOneState = 0; break; default:convertJumpToZeroOneState = 0; } switch (seen) { case ALOAD: pushByLocalObjectLoad(dbc, dbc.getRegisterOperand()); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: pushByLocalObjectLoad(dbc, seen - ALOAD_0); break; case DLOAD: pushByLocalLoad("D", dbc.getRegisterOperand()); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: pushByLocalLoad("D", seen - DLOAD_0); break; case FLOAD: pushByLocalLoad("F", dbc.getRegisterOperand()); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: pushByLocalLoad("F", seen - FLOAD_0); break; case ILOAD: pushByLocalLoad("I", dbc.getRegisterOperand()); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: pushByLocalLoad("I", seen - ILOAD_0); break; case LLOAD: pushByLocalLoad("J", dbc.getRegisterOperand()); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: pushByLocalLoad("J", seen - LLOAD_0); break; case GETSTATIC: { FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary(); XField fieldOperand = dbc.getXFieldOperand(); if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) { OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand); if (item != null) { Item itm = new Item(item); itm.setLoadedFromField(fieldOperand, Integer.MAX_VALUE); push(itm); break; } } FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc); Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE); if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) { i.setSpecialKind(Item.FILE_SEPARATOR_STRING); } push(i); break; } case LDC: case LDC_W: case LDC2_W: cons = dbc.getConstantRefOperand(); pushByConstant(dbc, cons); break; case INSTANCEOF: pop(); push(new Item("I")); break; case IFEQ: case IFNE: case IFLT: case IFLE: case IFGT: case IFGE: case IFNONNULL: case IFNULL: seenTransferOfControl = true; { Item topItem = pop(); if (seen == IFLT || seen == IFLE ) { registerTestedFoundToBeNonnegative = topItem.registerNumber; } // if we see a test comparing a special negative value with 0, // reset all other such values on the opcode stack if (topItem.valueCouldBeNegative() && (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) { int specialKind = topItem.getSpecialKind(); for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0); } } addJumpValue(dbc.getPC(), dbc.getBranchTarget()); break; case LOOKUPSWITCH: case TABLESWITCH: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); int pc = dbc.getBranchTarget() - dbc.getBranchOffset(); for(int offset : dbc.getSwitchOffsets()) addJumpValue(dbc.getPC(), offset+pc); break; case ARETURN: case DRETURN: case FRETURN: case IRETURN: case LRETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); pop(); break; case MONITORENTER: case MONITOREXIT: case POP: case PUTSTATIC: pop(); break; case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGT: case IF_ICMPGE: { seenTransferOfControl = true; Item right = pop(); Item left = pop(); if (right.hasConstantValue(Integer.MIN_VALUE) && left.checkForIntegerMinValue() || left.hasConstantValue(Integer.MIN_VALUE) && right.checkForIntegerMinValue() ) { for(Item i : stack) if (i != null && i.checkForIntegerMinValue()) i.setSpecialKind(Item.NOT_SPECIAL); for(Item i : lvValues) if (i != null && i.checkForIntegerMinValue()) i.setSpecialKind(Item.NOT_SPECIAL); } int branchTarget = dbc.getBranchTarget(); addJumpValue(dbc.getPC(), branchTarget); break; } case POP2: it = pop(); if (it.getSize() == 1) pop(); break; case PUTFIELD: pop(2); break; case IALOAD: case SALOAD: pop(2); push(new Item("I")); break; case DUP: handleDup(); break; case DUP2: handleDup2(); break; case DUP_X1: handleDupX1(); break; case DUP_X2: handleDupX2(); break; case DUP2_X1: handleDup2X1(); break; case DUP2_X2: handleDup2X2(); break; case IINC: register = dbc.getRegisterOperand(); it = getLVValue( register ); it2 = new Item("I", dbc.getIntConstant()); pushByIntMath(dbc, IADD, it2, it); pushByLocalStore(register); break; case ATHROW: pop(); seenTransferOfControl = true; setReachOnlyByBranch(true); setTop(true); break; case CHECKCAST: { String castTo = dbc.getClassConstantOperand(); if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";"; it = pop(); if (!it.signature.equals(castTo)) { it = new Item(it); it.signature = castTo; } push(it); break; } case NOP: break; case RET: case RETURN: seenTransferOfControl = true; setReachOnlyByBranch(true); break; case GOTO: case GOTO_W: seenTransferOfControl = true; setReachOnlyByBranch(true); addJumpValue(dbc.getPC(), dbc.getBranchTarget()); stack.clear(); setTop(true); break; case SWAP: handleSwap(); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: push(new Item("I", (seen-ICONST_0))); break; case LCONST_0: case LCONST_1: push(new Item("J", Long.valueOf(seen-LCONST_0))); break; case DCONST_0: case DCONST_1: push(new Item("D", Double.valueOf(seen-DCONST_0))); break; case FCONST_0: case FCONST_1: case FCONST_2: push(new Item("F", Float.valueOf(seen-FCONST_0))); break; case ACONST_NULL: push(new Item()); break; case ASTORE: case DSTORE: case FSTORE: case ISTORE: case LSTORE: pushByLocalStore(dbc.getRegisterOperand()); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: pushByLocalStore(seen - ASTORE_0); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: pushByLocalStore(seen - DSTORE_0); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: pushByLocalStore(seen - FSTORE_0); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: pushByLocalStore(seen - ISTORE_0); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: pushByLocalStore(seen - LSTORE_0); break; case GETFIELD: { FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary(); XField fieldOperand = dbc.getXFieldOperand(); if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) { OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand); if (item != null) { Item addr = pop(); Item itm = new Item(item); itm.setLoadedFromField(fieldOperand, addr.getRegisterNumber()); push(itm); break; } } Item item = pop(); int reg = item.getRegisterNumber(); push(new Item(dbc.getSigConstantOperand(), FieldAnnotation.fromReferencedField(dbc), reg)); } break; case ARRAYLENGTH: { pop(); Item newItem = new Item("I"); newItem.setSpecialKind(Item.NON_NEGATIVE); push(newItem); } break; case BALOAD: { pop(2); Item newItem = new Item("I"); newItem.setSpecialKind(Item.SIGNED_BYTE); push(newItem); break; } case CALOAD: pop(2); push(new Item("I")); break; case DALOAD: pop(2); push(new Item("D")); break; case FALOAD: pop(2); push(new Item("F")); break; case LALOAD: pop(2); push(new Item("J")); break; case AASTORE: case BASTORE: case CASTORE: case DASTORE: case FASTORE: case IASTORE: case LASTORE: case SASTORE: pop(3); break; case BIPUSH: case SIPUSH: push(new Item("I", Integer.valueOf(dbc.getIntConstant()))); break; case IADD: case ISUB: case IMUL: case IDIV: case IAND: case IOR: case IXOR: case ISHL: case ISHR: case IREM: case IUSHR: it = pop(); it2 = pop(); pushByIntMath(dbc, seen, it2, it); break; case INEG: it = pop(); if (it.getConstant() instanceof Integer) { push(new Item("I", Integer.valueOf(-constantToInt(it)))); } else { push(new Item("I")); } break; case LNEG: it = pop(); if (it.getConstant() instanceof Long) { push(new Item("J", Long.valueOf(-constantToLong(it)))); } else { push(new Item("J")); } break; case FNEG: it = pop(); if (it.getConstant() instanceof Float) { push(new Item("F", Float.valueOf(-constantToFloat(it)))); } else { push(new Item("F")); } break; case DNEG: it = pop(); if (it.getConstant() instanceof Double) { push(new Item("D", Double.valueOf(-constantToDouble(it)))); } else { push(new Item("D")); } break; case LADD: case LSUB: case LMUL: case LDIV: case LAND: case LOR: case LXOR: case LSHL: case LSHR: case LREM: case LUSHR: it = pop(); it2 = pop(); pushByLongMath(seen, it2, it); break; case LCMP: handleLcmp(); break; case FCMPG: case FCMPL: handleFcmp(seen); break; case DCMPG: case DCMPL: handleDcmp(seen); break; case FADD: case FSUB: case FMUL: case FDIV: case FREM: it = pop(); it2 = pop(); pushByFloatMath(seen, it, it2); break; case DADD: case DSUB: case DMUL: case DDIV: case DREM: it = pop(); it2 = pop(); pushByDoubleMath(seen, it, it2); break; case I2B: it = pop(); if (it.getConstant() != null) { it =new Item("I", (byte)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.SIGNED_BYTE); push(it); break; case I2C: it = pop(); if (it.getConstant() != null) { it = new Item("I", (char)constantToInt(it)); } else { it = new Item("I"); } it.setSpecialKind(Item.NON_NEGATIVE); push(it); break; case I2L: case D2L: case F2L:{ it = pop(); Item newValue; if (it.getConstant() != null) { newValue = new Item("J", Long.valueOf(constantToLong(it))); } else { newValue = new Item("J"); } newValue.setSpecialKind(it.getSpecialKind()); push(newValue); } break; case I2S: it = pop(); if (it.getConstant() != null) { push(new Item("I", (short)constantToInt(it))); } else { push(new Item("I")); } break; case L2I: case D2I: case F2I: it = pop(); if (it.getConstant() != null) { push(new Item("I",constantToInt(it))); } else { push(new Item("I")); } break; case L2F: case D2F: case I2F: it = pop(); if (it.getConstant() != null) { push(new Item("F", Float.valueOf(constantToFloat(it)))); } else { push(new Item("F")); } break; case F2D: case I2D: case L2D: it = pop(); if (it.getConstant() != null) { push(new Item("D", Double.valueOf(constantToDouble(it)))); } else { push(new Item("D")); } break; case NEW: { Item item = new Item("L" + dbc.getClassConstantOperand() + ";", (Object) null); item.setSpecialKind(Item.NEWLY_ALLOCATED); push(item); } break; case NEWARRAY: pop(); signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature(); pushBySignature(signature, dbc); break; // According to the VM Spec 4.4.1, anewarray and multianewarray // can refer to normal class/interface types (encoded in // "internal form"), or array classes (encoded as signatures // beginning with "["). case ANEWARRAY: pop(); signature = dbc.getClassConstantOperand(); if (signature.charAt(0) == '[') signature = "[" + signature; else signature = "[L" + signature + ";"; pushBySignature(signature, dbc); break; case MULTIANEWARRAY: int dims = dbc.getIntConstant(); for(int i = 0; i < dims; i++) pop(); signature = dbc.getClassConstantOperand(); pushBySignature(signature, dbc); break; case AALOAD: { pop(); it = pop(); String arraySig = it.getSignature(); if ( arraySig.charAt(0) == '[') pushBySignature(arraySig.substring(1), dbc); else push(new Item()); } break; case JSR: seenTransferOfControl = true; setReachOnlyByBranch(false); push(new Item("")); // push return address on stack addJumpValue(dbc.getPC(), dbc.getBranchTarget()); pop(); if (dbc.getBranchOffset() < 0) { // OK, backwards JSRs are weird; reset the stack. int stackSize = stack.size(); stack.clear(); for(int i = 0; i < stackSize; i++) stack.add(new Item()); } setTop(false); break; case INVOKEINTERFACE: case INVOKESPECIAL: case INVOKESTATIC: case INVOKEVIRTUAL: processMethodCall(dbc, seen); break; default: throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " ); } } catch (RuntimeException e) { //If an error occurs, we clear the stack and locals. one of two things will occur. //Either the client will expect more stack items than really exist, and so they're condition check will fail, //or the stack will resync with the code. But hopefully not false positives String msg = "Error processing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); if (DEBUG) e.printStackTrace(); clear(); } finally { if (DEBUG) { System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth()); System.out.println(this); } } } public void precomputation(DismantleBytecode dbc) { if (registerTestedFoundToBeNonnegative >= 0) { for(int i = 0; i < stack.size(); i++) { Item item = stack.get(i); if (item != null && item.registerNumber == registerTestedFoundToBeNonnegative) stack.set(i, item.cloneAndSetSpecialKind(Item.NON_NEGATIVE)); } for(int i = 0; i < lvValues.size(); i++) { Item item = lvValues.get(i); if (item != null && item.registerNumber == registerTestedFoundToBeNonnegative) lvValues.set(i, item.cloneAndSetSpecialKind(Item.NON_NEGATIVE)); } } registerTestedFoundToBeNonnegative = -1; mergeJumps(dbc); } /** * @param it * @return */ private int constantToInt(Item it) { return ((Number)it.getConstant()).intValue(); } /** * @param it * @return */ private float constantToFloat(Item it) { return ((Number)it.getConstant()).floatValue(); } /** * @param it * @return */ private double constantToDouble(Item it) { return ((Number)it.getConstant()).doubleValue(); } /** * @param it * @return */ private long constantToLong(Item it) { return ((Number)it.getConstant()).longValue(); } /** * handle dcmp * */ private void handleDcmp(int opcode) { Item it = pop(); Item it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { double d = constantToDouble(it); double d2 = constantToDouble(it2); if (Double.isNaN(d) || Double.isNaN(d2)) { if (opcode == DCMPG) push(new Item("I", Integer.valueOf(1))); else push(new Item("I", Integer.valueOf(-1))); } if (d2 < d) push(new Item("I", Integer.valueOf(-1) )); else if (d2 > d) push(new Item("I", Integer.valueOf(1))); else push(new Item("I", Integer.valueOf(0))); } else { push(new Item("I")); } } /** * handle fcmp * */ private void handleFcmp(int opcode) { Item it = pop(); Item it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { float f = constantToFloat(it); float f2 = constantToFloat(it2); if (Float.isNaN(f) || Float.isNaN(f2)) { if (opcode == FCMPG) push(new Item("I", Integer.valueOf(1))); else push(new Item("I", Integer.valueOf(-1))); } if (f2 < f) push(new Item("I", Integer.valueOf(-1))); else if (f2 > f) push(new Item("I", Integer.valueOf(1))); else push(new Item("I", Integer.valueOf(0))); } else { push(new Item("I")); } } /** * handle lcmp */ private void handleLcmp() { Item it = pop(); Item it2 = pop(); if ((it.getConstant() != null) && it2.getConstant() != null) { long l = constantToLong(it); long l2 = constantToLong(it2); if (l2 < l) push(new Item("I", Integer.valueOf(-1))); else if (l2 > l) push(new Item("I", Integer.valueOf(1))); else push(new Item("I", Integer.valueOf(0))); } else { push(new Item("I")); } } /** * handle swap */ private void handleSwap() { Item i1 = pop(); Item i2 = pop(); push(i1); push(i2); } /** * handleDup */ private void handleDup() { Item it; it = pop(); push(it); push(it); } /** * handle dupX1 */ private void handleDupX1() { Item it; Item it2; it = pop(); it2 = pop(); push(it); push(it2); push(it); } /** * handle dup2 */ private void handleDup2() { Item it, it2; it = pop(); if (it.getSize() == 2) { push(it); push(it); } else { it2 = pop(); push(it2); push(it); push(it2); push(it); } } /** * handle Dup2x1 */ private void handleDup2X1() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it2); push(it); push(it3); push(it2); push(it); } } private void handleDup2X2() { Item it = pop(); Item it2 = pop(); if (it.isWide()) { if (it2.isWide()) { push(it); push(it2); push(it); } else { Item it3 = pop(); push(it); push(it3); push(it2); push(it); } } else { Item it3 = pop(); if (it3.isWide()) { push(it2); push(it); push(it3); push(it2); push(it); } else { Item it4 = pop(); push(it2); push(it); push(it4); push(it3); push(it2); push(it); } } } /** * Handle DupX2 */ private void handleDupX2() { String signature; Item it; Item it2; Item it3; it = pop(); it2 = pop(); signature = it2.getSignature(); if (signature.equals("J") || signature.equals("D")) { push(it); push(it2); push(it); } else { it3 = pop(); push(it); push(it3); push(it2); push(it); } } private void processMethodCall(DismantleBytecode dbc, int seen) { String clsName = dbc.getClassConstantOperand(); String methodName = dbc.getNameConstantOperand(); String signature = dbc.getSigConstantOperand(); String appenderValue = null; boolean servletRequestParameterTainted = false; boolean sawUnknownAppend = false; Item sbItem = null; Item topItem = null; if (getStackDepth() > 0) topItem = getStackItem(0); boolean topIsTainted = topItem!= null && topItem.isServletParameterTainted(); HttpParameterInjection injection = null; if (topIsTainted) injection = topItem.injection; //TODO: stack merging for trinaries kills the constant.. would be nice to maintain. if ("java/lang/StringBuffer".equals(clsName) || "java/lang/StringBuilder".equals(clsName)) { if ("<init>".equals(methodName)) { if ("(Ljava/lang/String;)V".equals(signature)) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("()V".equals(signature)) { appenderValue = ""; } } else if ("toString".equals(methodName) && getStackDepth() >= 1) { Item i = getStackItem(0); appenderValue = (String)i.getConstant(); if (i.isServletParameterTainted()) servletRequestParameterTainted = true; } else if ("append".equals(methodName)) { if (signature.indexOf("II)") == -1 && getStackDepth() >= 2) { sbItem = getStackItem(1); Item i = getStackItem(0); if (i.isServletParameterTainted() || sbItem.isServletParameterTainted()) servletRequestParameterTainted = true; Object sbVal = sbItem.getConstant(); Object sVal = i.getConstant(); if ((sbVal != null) && (sVal != null)) { appenderValue = sbVal + sVal.toString(); } else if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else if (signature.startsWith("([CII)")) { sawUnknownAppend = true; sbItem = getStackItem(3); if (sbItem.registerNumber >= 0) { OpcodeStack.Item item = getLVValue(sbItem.registerNumber); if (item != null) item.constValue = null; } } else { sawUnknownAppend = true; } } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/FileOutputStream") && methodName.equals("<init>") && (signature.equals("(Ljava/io/File;Z)V") || signature.equals("(Ljava/lang/String;Z)V")) && stack.size() > 3) { OpcodeStack.Item item = getStackItem(0); Object value = item.getConstant(); if ( value instanceof Integer && ((Integer)value).intValue() == 1) { pop(3); Item newTop = getStackItem(0); if (newTop.signature.equals("Ljava/io/FileOutputStream;")) { newTop.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); newTop.source = XFactory.createReferencedXMethod(dbc); newTop.setPC(dbc.getPC()); } return; } } else if (seen == INVOKESPECIAL && clsName.equals("java/io/BufferedOutputStream") && methodName.equals("<init>") && signature.equals("(Ljava/io/OutputStream;)V")) { if (getStackItem(0).getSpecialKind() == Item.FILE_OPENED_IN_APPEND_MODE && getStackItem(2).signature.equals("Ljava/io/BufferedOutputStream;")) { pop(2); Item newTop = getStackItem(0); newTop.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE); newTop.source = XFactory.createReferencedXMethod(dbc); newTop.setPC(dbc.getPC()); return; } } else if (seen == INVOKEINTERFACE && methodName.equals("getParameter") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { Item requestParameter = pop(); pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); String parameterName = null; if (requestParameter.getConstant() instanceof String) parameterName = (String) requestParameter.getConstant(); result.injection = new HttpParameterInjection(parameterName, dbc.getPC()); result.setPC(dbc.getPC()); push(result); return; } else if (seen == INVOKEINTERFACE && methodName.equals("getQueryString") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); result.setPC(dbc.getPC()); push(result); return; } else if (seen == INVOKEINTERFACE && methodName.equals("getHeader") && clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) { /*Item requestParameter = */pop(); pop(); Item result = new Item("Ljava/lang/String;"); result.setServletParameterTainted(); result.source = XFactory.createReferencedXMethod(dbc); result.setPC(dbc.getPC()); push(result); return; } else if (seen == INVOKESTATIC && methodName.equals("asList") && clsName.equals("java/util/Arrays")) { /*Item requestParameter = */pop(); Item result = new Item(JAVA_UTIL_ARRAYS_ARRAY_LIST); push(result); return; }else if (seen == INVOKESTATIC && signature.equals("(Ljava/util/List;)Ljava/util/List;") && clsName.equals("java/util/Collections")) { Item requestParameter = pop(); if (requestParameter.getSignature().equals(JAVA_UTIL_ARRAYS_ARRAY_LIST)) { Item result = new Item(JAVA_UTIL_ARRAYS_ARRAY_LIST); push(result); return; } push(requestParameter); // fall back to standard logic } pushByInvoke(dbc, seen != INVOKESTATIC); if ((sawUnknownAppend || appenderValue != null || servletRequestParameterTainted) && getStackDepth() > 0) { Item i = this.getStackItem(0); i.constValue = appenderValue; if (!sawUnknownAppend && servletRequestParameterTainted) { i.injection = topItem.injection; i.setServletParameterTainted(); } if (sbItem != null) { i.registerNumber = sbItem.registerNumber; i.source = sbItem.source; if (i.injection == null) i.injection = sbItem.injection; if (sbItem.registerNumber >= 0) setLVValue(sbItem.registerNumber, i ); } return; } if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) { Item i = pop(); i.setSpecialKind(Item.RANDOM_INT); push(i); } else if (clsName.equals("java/lang/Math") && methodName.equals("abs")) { Item i = pop(); i.setSpecialKind(Item.MATH_ABS); push(i); } else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I") || seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) { Item i = pop(); i.setSpecialKind(Item.HASHCODE_INT); push(i); } else if (topIsTainted && ( methodName.startsWith("encode") && clsName.equals("javax/servlet/http/HttpServletResponse") || methodName.equals("trim") && clsName.equals("java/lang/String")) ) { Item i = pop(); i.setSpecialKind(Item.SERVLET_REQUEST_TAINTED); i.injection = injection; push(i); } if (!signature.endsWith(")V")) { Item i = pop(); i.source = XFactory.createReferencedXMethod(dbc); push(i); } } private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) { // merge stacks int intoSize = mergeInto.size(); int fromSize = mergeFrom.size(); if (errorIfSizesDoNotMatch && intoSize != fromSize) { if (DEBUG2) { System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } } else { if (DEBUG2) { if (intoSize == fromSize) System.out.println("Merging items"); else System.out.println("Bad merging items"); System.out.println("current items: " + mergeInto); System.out.println("jump items: " + mergeFrom); } for (int i = 0; i < Math.min(intoSize, fromSize); i++) mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i))); if (DEBUG2) { System.out.println("merged items: " + mergeInto); } } } public void clear() { stack.clear(); lvValues.clear(); } boolean encountedTop; boolean backwardsBranch; BitSet exceptionHandlers = new BitSet(); private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>(); private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>(); private BitSet jumpEntryLocations = new BitSet(); static class JumpInfo { final Map<Integer, List<Item>> jumpEntries; final Map<Integer, List<Item>> jumpStackEntries; final BitSet jumpEntryLocations; JumpInfo(Map<Integer, List<Item>> jumpEntries, Map<Integer, List<Item>> jumpStackEntries, BitSet jumpEntryLocations) { this.jumpEntries = jumpEntries; this.jumpStackEntries = jumpStackEntries; this.jumpEntryLocations = jumpEntryLocations; } } public static class JumpInfoFactory extends AnalysisFactory<JumpInfo> { public JumpInfoFactory() { super("Jump info for opcode stack", JumpInfo.class); } public JumpInfo analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException { Method method = analysisCache.getMethodAnalysis(Method.class, descriptor); JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor()); Code code = method.getCode(); final OpcodeStack stack = new OpcodeStack(); if (code == null) { return null; } DismantleBytecode branchAnalysis = new DismantleBytecode() { @Override public void sawOpcode(int seen) { stack.sawOpcode(this, seen); } }; branchAnalysis.setupVisitorForClass(jclass); int oldCount = 0; while (true) { stack.resetForMethodEntry0(ClassName.toSlashedClassName(jclass.getClassName()), method); branchAnalysis.doVisitMethod(method); int newCount = stack.jumpEntries.size(); if (newCount == oldCount || !stack.encountedTop || !stack.backwardsBranch) break; oldCount = newCount; } return new JumpInfo(stack.jumpEntries, stack.jumpStackEntries, stack.jumpEntryLocations); }} public boolean isJumpTarget(int pc) { return jumpEntryLocations.get(pc); } private void addJumpValue(int from, int target) { if (DEBUG) System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues ); if (from >= target) backwardsBranch = true; List<Item> atTarget = jumpEntries.get(Integer.valueOf(target)); if (atTarget == null) { if (DEBUG) System.out.println("Was null"); jumpEntries.put(Integer.valueOf(target), new ArrayList<Item>(lvValues)); jumpEntryLocations.set(target); if (stack.size() > 0) { jumpStackEntries.put(Integer.valueOf(target), new ArrayList<Item>(stack)); } return; } mergeLists(atTarget, lvValues, false); List<Item> stackAtTarget = jumpStackEntries.get(Integer.valueOf(target)); if (stack.size() > 0 && stackAtTarget != null) mergeLists(stackAtTarget, stack, false); if (DEBUG) System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget); } private String methodName; DismantleBytecode v; public void learnFrom(JumpInfo info) { jumpEntries = new HashMap<Integer, List<Item>>(info.jumpEntries); jumpStackEntries = new HashMap<Integer, List<Item>>(info.jumpStackEntries); jumpEntryLocations = (BitSet) info.jumpEntryLocations.clone(); } public void initialize() { setTop(false); jumpEntries.clear(); jumpStackEntries.clear(); jumpEntryLocations.clear(); encountedTop = false; backwardsBranch = false; lastUpdate.clear(); convertJumpToOneZeroState = convertJumpToZeroOneState = 0; zeroOneComing = -1; registerTestedFoundToBeNonnegative = -1; setReachOnlyByBranch(false); } public int resetForMethodEntry(final DismantleBytecode visitor) { this.v = visitor; initialize(); int result = resetForMethodEntry0(v); Code code = v.getMethod().getCode(); if (code == null) return result; if (useIterativeAnalysis) { IAnalysisCache analysisCache = Global.getAnalysisCache(); XMethod xMethod = XFactory.createXMethod(v.getThisClass(), v.getMethod()); try { JumpInfo jump = analysisCache.getMethodAnalysis(JumpInfo.class, xMethod.getMethodDescriptor()); if (jump != null) { learnFrom(jump); } } catch (CheckedAnalysisException e) { AnalysisContext.logError("Error getting jump information", e); } } return result; } private int resetForMethodEntry0(PreorderVisitor visitor) { return resetForMethodEntry0(visitor.getClassName(), visitor.getMethod()); } private int resetForMethodEntry0(@SlashedClassName String className, Method m) { methodName = m.getName(); if (DEBUG) System.out.println(" String signature = m.getSignature(); stack.clear(); lvValues.clear(); top = false; encountedTop = false; backwardsBranch = false; setReachOnlyByBranch(false); seenTransferOfControl = false; exceptionHandlers.clear(); Code code = m.getCode(); if (code != null) { CodeException[] exceptionTable = code.getExceptionTable(); if (exceptionTable != null) for(CodeException ex : exceptionTable) exceptionHandlers.set(ex.getHandlerPC()); } if (DEBUG) System.out.println(" --- " + className + " " + m.getName() + " " + signature); Type[] argTypes = Type.getArgumentTypes(signature); int reg = 0; if (!m.isStatic()) { Item it = new Item("L" + className+";"); it.setInitialParameter(true); it.registerNumber = reg; setLVValue( reg, it); reg += it.getSize(); } for (Type argType : argTypes) { Item it = new Item(argType.getSignature()); it.registerNumber = reg; it.setInitialParameter(true); setLVValue(reg, it); reg += it.getSize(); } return reg; } public int getStackDepth() { return stack.size(); } public Item getStackItem(int stackOffset) { if (stackOffset < 0 || stackOffset >= stack.size()) { AnalysisContext.logError("Can't get stack offset " + stackOffset + " from " + stack.toString() +" @ " + v.getPC() + " in " + v.getFullyQualifiedMethodName(), new IllegalArgumentException(stackOffset + " is not a value stack offset")); return new Item("Lfindbugs/OpcodeStackError;"); } int tos = stack.size() - 1; int pos = tos - stackOffset; try { return stack.get(pos); } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException( "Requested item at offset " + stackOffset + " in a stack of size " + stack.size() +", made request for position " + pos); } } private Item pop() { return stack.remove(stack.size()-1); } public void replaceTop(Item newTop) { pop(); push(newTop); } private void pop(int count) { while ((count pop(); } private void push(Item i) { stack.add(i); } private void pushByConstant(DismantleBytecode dbc, Constant c) { if (c instanceof ConstantClass) push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool()))); else if (c instanceof ConstantInteger) push(new Item("I", Integer.valueOf(((ConstantInteger) c).getBytes()))); else if (c instanceof ConstantString) { int s = ((ConstantString) c).getStringIndex(); push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s))); } else if (c instanceof ConstantFloat) push(new Item("F", Float.valueOf(((ConstantFloat) c).getBytes()))); else if (c instanceof ConstantDouble) push(new Item("D", Double.valueOf(((ConstantDouble) c).getBytes()))); else if (c instanceof ConstantLong) push(new Item("J", Long.valueOf(((ConstantLong) c).getBytes()))); else throw new UnsupportedOperationException("Constant type not expected" ); } private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) { Method m = dbc.getMethod(); LocalVariableTable lvt = m.getLocalVariableTable(); if (lvt != null) { LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC()); if (lv != null) { String signature = lv.getSignature(); pushByLocalLoad(signature, register); return; } } pushByLocalLoad("Ljava/lang/Object;", register); } private void pushByIntMath(DismantleBytecode dbc, int seen, Item lhs, Item rhs) { Item newValue = new Item("I"); if (lhs == null || rhs == null) { push(newValue); return; } try { if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() ); if (rhs.getConstant() != null && lhs.getConstant() != null) { int lhsValue = constantToInt(lhs); int rhsValue = constantToInt(rhs); if (seen == IADD) newValue = new Item("I",lhsValue + rhsValue); else if (seen == ISUB) newValue = new Item("I",lhsValue - rhsValue); else if (seen == IMUL) newValue = new Item("I", lhsValue * rhsValue); else if (seen == IDIV) newValue = new Item("I", lhsValue / rhsValue); else if (seen == IAND) { newValue = new Item("I", lhsValue & rhsValue); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); } else if (seen == IOR) newValue = new Item("I",lhsValue | rhsValue); else if (seen == IXOR) newValue = new Item("I",lhsValue ^ rhsValue); else if (seen == ISHL) { newValue = new Item("I",lhsValue << rhsValue); if (rhsValue >= 8) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); } else if (seen == ISHR) newValue = new Item("I",lhsValue >> rhsValue); else if (seen == IREM) newValue = new Item("I", lhsValue % rhsValue); else if (seen == IUSHR) newValue = new Item("I", lhsValue >>> rhsValue); } else if ((seen == ISHL || seen == ISHR || seen == IUSHR)) { if (rhs.getConstant() != null) { int constant = constantToInt(rhs); if ((constant & 0x1f) == 0) newValue = new Item(lhs); else if (seen == ISHL && (constant & 0x1f) >= 8) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); } else if (lhs.getConstant() != null) { int constant = constantToInt(lhs); if (constant == 0) newValue = new Item("I", 0); } } else if (lhs.getConstant() != null && seen == IAND) { int value = constantToInt(lhs); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); else if (value >= 0) newValue.setSpecialKind(Item.NON_NEGATIVE); } else if (rhs.getConstant() != null && seen == IAND) { int value = constantToInt(rhs); if (value == 0) newValue = new Item("I", 0); else if ((value & 0xff) == 0) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); else if (value >= 0) newValue.setSpecialKind(Item.NON_NEGATIVE); } else if (seen == IAND && lhs.getSpecialKind() == Item.ZERO_MEANS_NULL) { newValue.setSpecialKind(Item.ZERO_MEANS_NULL); newValue.setPC(lhs.getPC()); } else if (seen == IAND && rhs.getSpecialKind() == Item.ZERO_MEANS_NULL) { newValue.setSpecialKind(Item.ZERO_MEANS_NULL); newValue.setPC(rhs.getPC()); } else if (seen == IOR && lhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) { newValue.setSpecialKind(Item.NONZERO_MEANS_NULL); newValue.setPC(lhs.getPC()); } else if (seen == IOR && rhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) { newValue.setSpecialKind(Item.NONZERO_MEANS_NULL); newValue.setPC(rhs.getPC()); } } catch (ArithmeticException e) { assert true; // ignore it } catch (RuntimeException e) { String msg = "Error processing2 " + lhs + OPCODE_NAMES[seen] + rhs + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName(); AnalysisContext.logError(msg , e); } if (lhs.getSpecialKind() == Item.INTEGER_SUM && rhs.getConstant() != null ) { int rhsValue = constantToInt(rhs); if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1) newValue.setSpecialKind(Item.AVERAGE_COMPUTED_USING_DIVISION); } if (seen == IADD && newValue.getSpecialKind() == Item.NOT_SPECIAL && lhs.getConstant() == null && rhs.getConstant() == null ) newValue.setSpecialKind(Item.INTEGER_SUM); if (seen == IREM && lhs.getSpecialKind() == Item.HASHCODE_INT) newValue.setSpecialKind(Item.HASHCODE_INT_REMAINDER); if (seen == IREM && lhs.getSpecialKind() == Item.RANDOM_INT) newValue.setSpecialKind(Item.RANDOM_INT_REMAINDER); if (DEBUG) System.out.println("push: " + newValue); newValue.setPC(dbc.getPC()); push(newValue); } private void pushByLongMath(int seen, Item lhs, Item rhs) { Item newValue = new Item("J"); try { if ((rhs.getConstant() != null) && lhs.getConstant() != null) { long lhsValue = constantToLong(lhs); if (seen == LSHL) { newValue =new Item("J", Long.valueOf(lhsValue << constantToInt(rhs))); if (constantToInt(rhs) >= 8) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); } else if (seen == LSHR) newValue =new Item("J", Long.valueOf(lhsValue >> constantToInt(rhs))); else if (seen == LUSHR) newValue =new Item("J", Long.valueOf(lhsValue >>> constantToInt(rhs))); else { long rhsValue = constantToLong(rhs); if (seen == LADD) newValue = new Item("J", Long.valueOf(lhsValue + rhsValue)); else if (seen == LSUB) newValue = new Item("J", Long.valueOf(lhsValue - rhsValue)); else if (seen == LMUL) newValue = new Item("J", Long.valueOf(lhsValue * rhsValue)); else if (seen == LDIV) newValue =new Item("J", Long.valueOf(lhsValue / rhsValue)); else if (seen == LAND) { newValue = new Item("J", Long.valueOf(lhsValue & rhsValue)); if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 ) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); } else if (seen == LOR) newValue = new Item("J", Long.valueOf(lhsValue | rhsValue)); else if (seen == LXOR) newValue =new Item("J", Long.valueOf(lhsValue ^ rhsValue)); else if (seen == LREM) newValue =new Item("J", Long.valueOf(lhsValue % rhsValue)); } } else if (rhs.getConstant() != null && seen == LSHL && constantToInt(rhs) >= 8) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); else if (lhs.getConstant() != null && seen == LAND && (constantToLong(lhs) & 0xff) == 0) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); else if (rhs.getConstant() != null && seen == LAND && (constantToLong(rhs) & 0xff) == 0) newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR); } catch (RuntimeException e) { // ignore it } push(newValue); } private void pushByFloatMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) { if (seen == FADD) result =new Item("F", Float.valueOf(constantToFloat(it2) + constantToFloat(it))); else if (seen == FSUB) result =new Item("F", Float.valueOf(constantToFloat(it2) - constantToFloat(it))); else if (seen == FMUL) result =new Item("F", Float.valueOf(constantToFloat(it2) * constantToFloat(it))); else if (seen == FDIV) result =new Item("F", Float.valueOf(constantToFloat(it2) / constantToFloat(it))); else if (seen == FREM) result =new Item("F", Float.valueOf(constantToFloat(it2) % constantToFloat(it))); else result =new Item("F"); } else { result =new Item("F"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByDoubleMath(int seen, Item it, Item it2) { Item result; int specialKind = Item.FLOAT_MATH; if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) { if (seen == DADD) result = new Item("D", Double.valueOf(constantToDouble(it2) + constantToDouble(it))); else if (seen == DSUB) result = new Item("D", Double.valueOf(constantToDouble(it2) - constantToDouble(it))); else if (seen == DMUL) result = new Item("D", Double.valueOf(constantToDouble(it2) * constantToDouble(it))); else if (seen == DDIV) result = new Item("D", Double.valueOf(constantToDouble(it2) / constantToDouble(it))); else if (seen == DREM) result = new Item("D", Double.valueOf(constantToDouble(it2) % constantToDouble(it))); else result = new Item("D"); } else { result = new Item("D"); if (seen == DDIV) specialKind = Item.NASTY_FLOAT_MATH; } result.setSpecialKind(specialKind); push(result); } private void pushByInvoke(DismantleBytecode dbc, boolean popThis) { String signature = dbc.getSigConstantOperand(); if (dbc.getNameConstantOperand().equals("<init>") && signature.endsWith(")V") && popThis) { pop(PreorderVisitor.getNumberArguments(signature)); Item constructed = pop(); if (getStackDepth() > 0) { Item next = getStackItem(0); if (constructed.equals(next)) next.source = XFactory.createReferencedXMethod(dbc); } return; } pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0)); pushBySignature(Type.getReturnType(signature).getSignature(), dbc); } public Item getItemMethodInvokedOn(DismantleBytecode dbc) { int opcode = dbc.getOpcode(); switch (opcode) { case INVOKEVIRTUAL: case INVOKEINTERFACE: case INVOKESPECIAL: String signature = dbc.getSigConstantOperand(); int stackOffset = PreorderVisitor.getNumberArguments(signature); return getStackItem(stackOffset); } throw new IllegalArgumentException("Not visiting an instance method call"); } private String getStringFromIndex(DismantleBytecode dbc, int i) { ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i); return name.getBytes(); } private void pushBySignature(String s, DismantleBytecode dbc) { if ("V".equals(s)) return; Item item = new Item(s, (Object) null); if (dbc != null) item.setPC(dbc.getPC()); push(item); } private void pushByLocalStore(int register) { Item it = pop(); if (it.getRegisterNumber() != register) { for(Item i : lvValues) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } for(Item i : stack) if (i != null) { if (i.registerNumber == register) i.registerNumber = -1; if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1; } } setLVValue( register, it ); } private void pushByLocalLoad(String signature, int register) { Item oldItem = getLVValue(register); Item newItem; if (oldItem == null) { newItem = new Item(signature); newItem.registerNumber = register; } else { newItem = oldItem; if (newItem.signature.equals("Ljava/lang/Object;") && !signature.equals("Ljava/lang/Object;")) { newItem = new Item(oldItem); newItem.signature = signature; } if (newItem.getRegisterNumber() < 0) { if (newItem == oldItem) newItem = new Item(oldItem); newItem.registerNumber = register; } } push(newItem); } private void setLVValue(int index, Item value ) { int addCount = index - lvValues.size() + 1; while ((addCount lvValues.add(null); if (!useIterativeAnalysis && seenTransferOfControl) value = Item.merge(value, lvValues.get(index) ); lvValues.set(index, value); } public Item getLVValue(int index) { if (index >= lvValues.size()) return new Item(); return lvValues.get(index); } public int getNumLocalValues() { return lvValues.size(); } /** * @param top The top to set. */ private void setTop(boolean top) { if (top) { if (!this.top) this.top = true; } else if (this.top) this.top = false; } /** * @return Returns the top. */ public boolean isTop() { if (top) return true; return false; } /** * @param reachOnlyByBranch The reachOnlyByBranch to set. */ void setReachOnlyByBranch(boolean reachOnlyByBranch) { if (reachOnlyByBranch) setTop(true); this.reachOnlyByBranch = reachOnlyByBranch; } /** * @return Returns the reachOnlyByBranch. */ boolean isReachOnlyByBranch() { return reachOnlyByBranch; } } // vim:ts=4
package net.sf.jaer.eventio; import java.beans.PropertyChangeSupport; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.aemonitor.EventRaw; import net.sf.jaer.aemonitor.EventRaw.EventType; import net.sf.jaer.chip.AEChip; import net.sf.jaer.chip.EventExtractor2D; import net.sf.jaer.util.EngineeringFormat; /** * Class to stream in packets of events from binary input stream from a file * recorded by AEViewer. * <p> * The file format is simple, it consists of an arbitrary number of timestamped * AEs: * * <pre> * int32 address *int32 timestamp * * int32 address *int32 timestamp * </pre> * <p> * (Prior to version 2.0 data files, the address was a 16 bit short value.) * <p> * An optional ASCII header consisting of lines starting with '#' is skipped * when opening the file and may be retrieved. No later comment lines are * allowed because the rest ot the file must be pure binary data. * <p> * The first line of the header specifies the file format (for later versions). * Files lacking a header are assumed to be of int16 address form. * <p> * The first line of the header has a value like "#!AER-DAT2.0". The 2.0 is the * version number. * <p> * <strong>PropertyChangeEvents.</strong> * AEFileInputStream has PropertyChangeSupport via getSupport(). * PropertyChangeListeners will be informed of the following events * <ul> * <li>"position" - on any new packet of events, either by time chunk or fixed * number of events chunk. * <li>"rewind" - on file rewind. * <li>"eof" - on end of file. * <li>"wrappedTime" - on wrap of time timestamps. This happens every int32 us, * which is about 4295 seconds which is 71 minutes. Time is negative, then * positive, then negative again. * <li>"init" - on initial read of a file (after creating this with a file input * stream). This init event is called on the initial packet read because * listeners can't be added until the object is created. * <li>"markset" - on setting mark, old and new mark positions. * <li>"markcleared" - on clearing mark, old mark position and zero. * </ul> * * <strong>Timestamp resets.</strong> AEFileInputStream also supports a special * "zero timestamps" operation on reading a file. A bit mask which is normally * zero can be set; if set to a non zero value, then if ORing the bitmask with * the raw address results in a nonzero value, then the timestamps are reset to * zero at this point. (A timestamp offset is memorized and subtracted from * subsequent timestamps read from the file.) This allow synchronization using, * e.g. bit 15 of the address space. * * @author tobi * @see net.sf.jaer.eventio.AEDataFile */ public class AEFileInputStream extends DataInputStream implements AEFileInputStreamInterface { // TODO extend // AEInputStream // public final static long MAX_FILE_SIZE=200000000; private static final int NUMBER_LINE_SEPARATORS = 2; // number of line separators which AEFileOutputStream // (writeHeaderLine) is writing to ae data files. // important for calculation of header offset public static int NUM_HEADER_LINES_TO_PRINT = 15; /** * The offset of the marked position in events, to allow users to mark a * position before they hit the mark button */ public int MARK_OFFSET_EVENTS = 100000; private PropertyChangeSupport support = new PropertyChangeSupport(this); static Logger log = Logger.getLogger("net.sf.jaer.eventio"); private FileInputStream fileInputStream = null; long fileSize = 0; // size of file in bytes private File file = null; private Class addressType = Short.TYPE; // default address type, unless file header specifies otherwise public final int MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT = 1000; private int numNonMonotonicTimeExceptionsPrinted = 0; private int numHeaderLines = 0; /** * Marking positions */ private long markPosition = 0; // a single MARK position for rewinding to private long markIn = 0, markOut = Long.MAX_VALUE; private int eventSizeBytes = AEFileInputStream.EVENT16_SIZE; // size of event in bytes, set finally after reading // file header private boolean firstReadCompleted = false; private boolean repeat; private long absoluteStartingTimeMs = 0; // parsed from filename if possible private boolean enableTimeWrappingExceptionsChecking = true; // private int numEvents,currentEventNumber; // mostRecentTimestamp is the last event sucessfully read // firstTimestamp, lastTimestamp are the first and last timestamps in the file (at least the memory mapped part of // the file) private int mostRecentTimestamp, firstTimestamp, lastTimestamp; // this marks the present read time for packets private int currentStartTimestamp; private FileChannel fileChannel = null; /** * Maximum size of raw packet in events. */ public static final int MAX_BUFFER_SIZE_EVENTS = 1 << 20; /** * Size of old style event in bytes. With new 32bits addresses, use * EVENT32_SIZE, but use EVENT16_SIZE for backward compatibility with 16 bit * addresses */ public static final int EVENT16_SIZE = (Short.SIZE / 8) + (Integer.SIZE / 8); /** * Size of new style event in bytes; int addr, int timestamp */ public static final int EVENT32_SIZE = (Integer.SIZE / 8) + (Integer.SIZE / 8); /** * the size of the memory mapped part of the input file. This window is * centered over the file position except at the start and end of the file. */ private long CHUNK_SIZE_EVENTS = Integer.MAX_VALUE/EVENT32_SIZE; private long chunkSizeBytes = CHUNK_SIZE_EVENTS * EVENT32_SIZE; // size of memory mapped file chunk, depends on event // size and number of events to map, initialized as /** * the packet used for reading events. */ private AEPacketRaw packet = new AEPacketRaw(MAX_BUFFER_SIZE_EVENTS); private EventRaw tmpEvent = new EventRaw(); /** * The memory-mapped byte buffer pointing to the file. */ private MappedByteBuffer byteBuffer = null; /** * absolute position in file in events, points to next event number, 0 based * (1 means 2nd event) */ private long position = 0; private ArrayList<String> header = new ArrayList<>(); private int headerOffset = 0; // this is starting position in file for rewind or to add to positioning via slider private int chunkNumber = 0; // current memory mapped file chunk, starts with 0 past header private int numChunks = 1; // set by parseFileFormatVersion, this is at least 1 and includes the last portion which // may be smaller than chunkSizeBytes private final String lineSeparator = System.getProperty("line.separator"); private int timestampResetBitmask = 0; // used to memorize timestamp offset. private int timestampOffset = 0; // set by nonzero bitmask result on address to that events timestamp, subtracted // from all timestamps /** * The AEChip object associated with this stream. This field was added for * supported jAER 3.0 format files to support translating bit locations in * events. */ private AEChip chip = null; // jaer3 files // private Jaer3FileInputStream jaer3fileinputstream = null; // if non-null, then we have a jaer 3 file // jaer3 parse private Jaer3BufferParser jaer3BufferParser = null; // if non-null, then we have a jaer 3 file private boolean jaer3EnableFlg = false; // jaer3 parse enable flag private static AEChip LAST_CHIP = null; // It's a static value, so it will always store the last AEFileInputStream's chip private static EventExtractor2D LAST_EVENT_EXTRACTOR = null; // This value saves the last chip's extractor, it's always associated with the last chip /** * Creates a new instance of AEInputStream * * @param f the file to open * @throws FileNotFoundException if file doesn't exist or can't be read */ public AEFileInputStream(File f, AEChip chip) throws IOException { super(new FileInputStream(f)); this.chip = chip; /* Here is the logic: * The chip and extractor will be updated unless the chip changed such as by the user. * It makes the chip and the extractor are alwayse associated with each other. */ if (this.chip != LAST_CHIP) { LAST_CHIP = this.chip; LAST_EVENT_EXTRACTOR = this.chip.getEventExtractor(); } this.chip.setEventExtractor(LAST_EVENT_EXTRACTOR); // Restore the extractor, because jaer3BufferParser might change it. init(new FileInputStream(f)); setFile(f); } @Override public String toString() { EngineeringFormat fmt = new EngineeringFormat(); String s = "AEInputStream with size=" + fmt.format(size()) + " events, firstTimestamp=" + getFirstTimestamp() + " lastTimestamp=" + getLastTimestamp() + " duration=" + fmt.format(getDurationUs() / 1e6f) + " s" + " event rate=" + fmt.format(size() / (getDurationUs() / 1e6f)) + " eps"; return s; } /** * fires property change "position". * * @throws IOException if file is empty or there is some other error. */ private void init(FileInputStream fileInputStreamP) throws IOException { fileInputStream = fileInputStreamP; if (fileInputStream == null) { log.warning("File input stream is NULL"); return; } readHeader(fileInputStream); // parses header, sets eventSize, chunkSize, throws 0-size IOException mostRecentTimestamp = Integer.MIN_VALUE; currentStartTimestamp = Integer.MIN_VALUE; // make sure these are initialized correctly so that an event is // always read when file is opened setupChunks(); clearMarks(); setRepeat(true); // long totalMemory=Runtime.getRuntime().totalMemory(); // long maxMemory=Runtime.getRuntime().maxMemory(); // long maxSize=3*(maxMemory-totalMemory)/4; // EngineeringFormat fmt=new EngineeringFormat(); // log.info("AEInputStream.init(): trying to open file using memory mapped file of size="+fmt.format(fileSize)+" // using memory-limited max size="+fmt.format(maxSize)); // try{ // fileChannel.position(0); // long size=fileChannel.size(); // if(size>maxSize){ // log.warning("opening file using byteBuffer with size="+maxSize+" but file size="+size); // size=maxSize; // byteBuffer=fileChannel.map(FileChannel.MapMode.READ_ONLY,0,size); // openok=true; // }catch(IOException e){ // System.gc(); // long newMaxSize=3*maxSize/4; // log.warning("AEInputStream.init(): cannot open file "+fileInputStream+" with maxSize="+maxSize+" trying again // with size="+newMaxSize); // maxSize=newMaxSize; // }while(openok==false && maxSize>20000000); // if(!openok){ // throw new RuntimeException("cannot open preview, not enough memory"); try { EventRaw ev = readEventForwards(); // init timestamp firstTimestamp = ev.timestamp; if (true == jaer3EnableFlg) { if (fileSize <= chunkSizeBytes) { lastTimestamp = jaer3BufferParser.getLastTimeStamp(); } else { //TODO, add the code to find the last time stamp of the big files // this.mapChunk((int)fileSize/chunkSizeBytes); // lastTimestamp = jaer3BufferParser.getLastTimeStamp(); // mapChunk(0); position(size() - 2); ev = readEventForwards(); lastTimestamp = ev.timestamp; } } else { position(size() - 2); ev = readEventForwards(); lastTimestamp = ev.timestamp; } if (true == jaer3EnableFlg) { jaer3BufferParser.setInFrameEvent(false); } currentStartTimestamp = firstTimestamp; mostRecentTimestamp = firstTimestamp; } catch (IOException e) { log.warning("couldn't read first event to set starting timestamp - maybe the file is empty?"); } catch (NonMonotonicTimeException e2) { log.warning("On AEInputStream.init() caught " + e2.toString()); } finally { position(0); } log.info("initialized " + this.toString()); } /** * Reads the next event from the stream setting no limit on how far ahead in * time it is. * * @return the event. * @throws IOException on reading the file. * @throws net.sf.jaer.eventio.AEFileInputStream.NonMonotonicTimeException * if the timestamp is earlier than the one last read. */ private EventRaw readEventForwards() throws IOException, NonMonotonicTimeException { return readEventForwards(Integer.MAX_VALUE); } private int zeroTimestampWarningCount = 0; private final int ZERO_TIMESTAMP_MAX_WARNINGS = 10; /** * Reads the next event forward, sets mostRecentTimestamp, returns null if * the next timestamp is later than maxTimestamp. * * @param maxTimestamp the latest timestamp that should be read. * @throws EOFException at end of file * @throws NonMonotonicTimeException - the event that has wrapped will be * returned on the next readEventForwards * @throws WrappedTimeException - the event that has wrapped will be * returned on the next readEventForwards */ private EventRaw readEventForwards(int maxTimestamp) throws IOException, NonMonotonicTimeException { int ts = firstTimestamp; int addr = 0; int pixelData = 0; // For jAER 3.0, no influence on jAER 2.0 EventType etype = EventType.PolarityEvent; // For jAER 3.0, no influence on jAER 2.0 int lastTs = mostRecentTimestamp; int lastBufferPosition = 0; ByteBuffer tmpEventBuffer = ByteBuffer.allocate(16); // TODO why allocate every time? // if(jaer3fileinputstream!=null){ // return jaer3fileinputstream.readEventForwards(); try { if (position == markOut) { // TODO check exceptions here for markOut set before markIn getSupport().firePropertyChange(AEInputStream.EVENT_EOF, null, position()); if (repeat) { rewind(); return readEventForwards(); } else { return null; } } // eventByteBuffer.rewind(); // fileChannel.read(eventByteBuffer); // eventByteBuffer.rewind(); // addr=eventByteBuffer.getShort(); // ts=eventByteBuffer.getInt(); if (jaer3EnableFlg) { lastBufferPosition = byteBuffer.position(); tmpEventBuffer = jaer3BufferParser.getJaer2EventBuf(); int etypeValue = tmpEventBuffer.getInt(); etype = EventType.values()[etypeValue]; addr = tmpEventBuffer.getInt(); ts = tmpEventBuffer.getInt(); pixelData = tmpEventBuffer.getInt(); } else { if (addressType == Integer.TYPE) { addr = byteBuffer.getInt(); } else { addr = (byteBuffer.getShort() & 0xffff); // TODO reads addr as negative number if msb is set } ts = byteBuffer.getInt(); } if (ts == 0) { if (zeroTimestampWarningCount++ < ZERO_TIMESTAMP_MAX_WARNINGS) { log.warning("zero timestamp: position=" + position + " ts=" + ts); } if (zeroTimestampWarningCount == ZERO_TIMESTAMP_MAX_WARNINGS) { log.warning("suppressing further messages about zero timestamps"); } if (jaer3EnableFlg) { tmpEventBuffer = jaer3BufferParser.getJaer2EventBuf(); tmpEventBuffer = jaer3BufferParser.getJaer2EventBuf(); int etypeValue = tmpEventBuffer.getInt(); etype = EventType.values()[etypeValue]; addr = tmpEventBuffer.getInt(); ts = tmpEventBuffer.getInt(); pixelData = tmpEventBuffer.getInt(); } else { if (addressType == Integer.TYPE) { addr = byteBuffer.getInt(); } else { addr = (byteBuffer.getShort() & 0xffff); // TODO reads addr as negative number if msb is set } ts = byteBuffer.getInt(); } } // for marking sync in a recording using the result of bitmask with input if ((addr & timestampResetBitmask) != 0) { log.log(Level.INFO, "found timestamp reset event addr={0} position={1} timstamp={2}", new Object[]{addr, position, ts}); timestampOffset = ts; } ts -= timestampOffset; // TODO fix extra event no matter what dt if (ts > maxTimestamp) { // handle bigwrap this way // push back event onto byteBuffer. // we've already read the event, but have not updated the position field. // therefore we just set position back to its value now (the event we are reading) if (jaer3EnableFlg == false) { position(position); // we haven't updated our position field yet } else { byteBuffer.position(lastBufferPosition); } ts = lastTs; // this is the one last read successfully mostRecentTimestamp = ts; return null; } // check for non-monotonic increasing timestamps, if we get one, reset our notion of the starting time if (isWrappedTime(ts, mostRecentTimestamp, 1)) { if (jaer3EnableFlg) { log.log(Level.INFO, "The current packet file position is {0} and current file position is {1}", new Object[]{jaer3BufferParser.getCurrentPktPos(), byteBuffer.position()}); } throw new WrappedTimeException(ts, mostRecentTimestamp, position); // WrappedTimeException e = new WrappedTimeException(ts, mostRecentTimestamp, position); // log.info(e.toString()); // getSupport().firePropertyChange(AEInputStream.EVENT_WRAPPED_TIME,e.getPreviousTimestamp(),e.getCurrentTimestamp()); } if (enableTimeWrappingExceptionsChecking && (ts < mostRecentTimestamp) && (etype != EventType.FrameEvent) && (etype != EventType.SpecialEvent)) { // FrameEvent and SpecialEvent // usually // have // the // nonMonotonicTs, // don't // check // them if (jaer3EnableFlg) { log.log(Level.INFO, "The current packet file position is {0} and current file position is {1}", new Object[]{jaer3BufferParser.getCurrentPktPos(), byteBuffer.position()}); } // log.warning("AEInputStream.readEventForwards returned ts="+ts+" which goes backwards in time // (mostRecentTimestamp="+mostRecentTimestamp+")"); throw new NonMonotonicTimeException(ts, mostRecentTimestamp, position); } tmpEvent.address = addr; tmpEvent.timestamp = ts; tmpEvent.eventtype = etype; // For jAER 3.0, no influence on jAER 2.0 tmpEvent.pixelData = pixelData; // For jAER 3.0, no influence on jAER 2.0 position++; return tmpEvent; } catch (BufferUnderflowException e) { try { mapNextChunk(); return readEventForwards(maxTimestamp); } catch (IOException eof) { byteBuffer = null; System.gc(); // all the byteBuffers have referred to mapped files and use up all memory, now free them // since we're at end of file anyhow getSupport().firePropertyChange(AEInputStream.EVENT_EOF, null, position()); throw new EOFException("reached end of file"); } } catch (NullPointerException npe) { rewind(); return readEventForwards(maxTimestamp); } finally { mostRecentTimestamp = ts; } } /** * Reads the next event backwards and leaves the position and byte buffer * pointing to event one earlier than the one we just read. I.e., we back * up, read the event, then back up again to leave us in state to either * read forwards the event we just read, or to repeat backing up and reading * if we read backwards * * @throws EOFException at end of file * @throws NonMonotonicTimeException * @throws WrappedTimeException */ private EventRaw readEventBackwards() throws IOException, NonMonotonicTimeException { // we enter this with position pointing to next event *to read forwards* and byteBuffer also in this state. // therefore we need to decrement the byteBuffer pointer and the position, and read the event. // update the position first to leave us afterwards pointing one before current position long newPos = position - 1; // this is new absolute position if (newPos < 0) { // reached start of file newPos = 0; // System.out.println("readEventBackwards: reached start"); throw new EOFException("reached start of file"); } // normally we just update the postiion to be one less, then move the byteBuffer pointer back by // one event and read that new event. But if we have reached start of byte buffer, we // need to load a new chunk and set the buffer pointer to point to one event before the end long newBufPos; newBufPos = byteBuffer.position() - eventSizeBytes; if (newBufPos < 0) { // check if we need to map a new earlier chunk of the file int newChunkNumber = getChunkNumber(newPos); if (newChunkNumber != chunkNumber) { mapPreviousChunk(); // will throw EOFException when reaches start of file newBufPos = (eventSizeBytes * newPos) % chunkSizeBytes; byteBuffer.position((int) newBufPos); // put the buffer pointer at the end of the buffer } } else { // this is usual situation byteBuffer.position((int) newBufPos); } // short addr=byteBuffer.getShort(); int addr; // with new 32bits adressses, use getInt, but use getShort for backward compatibility with 16bits if (addressType == Integer.TYPE) { addr = byteBuffer.getInt(); } else { addr = (byteBuffer.getShort() & 0xffff); // TODO reads addr as negative number if msb is set if we don't AND // with 0xFFFF } int ts = byteBuffer.getInt() - timestampOffset; byteBuffer.position((int) newBufPos); tmpEvent.address = addr; tmpEvent.timestamp = ts; mostRecentTimestamp = ts; position--; // decrement position before exception to make sure we skip over a bad timestamp if (enableTimeWrappingExceptionsChecking && isWrappedTime(ts, mostRecentTimestamp, -1)) { throw new WrappedTimeException(ts, mostRecentTimestamp, position); } if (enableTimeWrappingExceptionsChecking && (ts > mostRecentTimestamp)) { throw new NonMonotonicTimeException(ts, mostRecentTimestamp, position); } return tmpEvent; } /** * Used to read fixed size packets either forwards or backwards. Behavior in * case of non-monotonic timestamps depends on setting of time wrapping * exception checking. If exception checking is enabled, then the read will * terminate on the first non-monotonic timestamp. * * @param n the number of events to read * @return a raw packet of events of a specified number of events fires a * property change "position" on every call, and a property change * "wrappedTime" if time wraps around. */ @Override synchronized public AEPacketRaw readPacketByNumber(int n) throws IOException { if (!firstReadCompleted) { fireInitPropertyChange(); } int an = Math.abs(n); int cap = packet.getCapacity(); if (an > cap) { an = cap; if (n > 0) { n = cap; } else { n = -cap; } } int[] addr = packet.getAddresses(); int[] ts = packet.getTimestamps(); long oldPosition = position(); EventRaw ev; int count = 0; try { if (n > 0) { for (int i = 0; i < n; i++) { ev = readEventForwards(); // TODO since repeat is always true in existing code, then can never get null event right now TODO; fix this count++; addr[i] = ev.address; // could get null pointer exception here if repeat was false ts[i] = ev.timestamp; currentStartTimestamp = ts[i]; } } else { // backwards n = -n; for (int i = 0; i < n; i++) { ev = readEventBackwards(); // TODO fix for repeat = false count++; addr[i] = ev.address; ts[i] = ev.timestamp; currentStartTimestamp = ts[i]; } } } catch (WrappedTimeException e) { log.info(e.toString()); getSupport().firePropertyChange(AEInputStream.EVENT_WRAPPED_TIME, e.getPreviousTimestamp(), e.getCurrentTimestamp()); } catch (NonMonotonicTimeException e) { getSupport().firePropertyChange(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, e.getPreviousTimestamp(), e.getCurrentTimestamp()); // log.info(e.getMessage()); } packet.setNumEvents(count); getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, position()); return packet; // return new AEPacketRaw(addr,ts); } /** * Returns an AEPacketRaw at most {@literal dt} long up to the max size of * the buffer or until end-of-file. Events are read as long as the timestamp * does not exceed {@literal currentStartTimestamp+dt}. If there are no * events in this period then the very last event from the previous packet * is returned again. The currentStartTimestamp is incremented after the * call by dt, unless there is an exception like * EVENT_NON_MONOTONIC_TIMESTAMP, in which case the currentStartTimestamp is * set to the most recently read timestamp {@literal mostRecentTimestamp}. * <p> * The following property changes are fired: * <ol> * <li>Fires a property change AEInputStream.EVENT_POSITION at end of * reading each packet. * <li>Fires property change AEInputStream.EVENT_WRAPPED_TIME when time * wraps from positive to negative or vice versa (when playing backwards). * These events are fired on "big wraps" when the 32 bit 1-us timestamp * wraps around, which occurs every 4295 seconds or 72 minutes. This event * signifies that on the next packet read the absolute time should be * advanced or retarded (for backwards reading) by the big wrap. * <li>Fires property change AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP if * a non-monotonically increasing timestamp is detected that is not a * wrapped time non-monotonic event. * <li>Fires property change AEInputStream.EVENT_EOF on end of the file. * </ol> * <p> * Non-monotonic timestamps cause warning messages to be printed (up to * MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT) and packet reading is aborted * when the non-monotonic timestamp or wrapped timestamp is encountered and * the non-monotonic timestamp is NOT included in the packet. Normally this * does not cause problems except that the packet is shorter in duration * that called for. But when synchronized playback is enabled it causes the * different threads to desynchronize. Therefore the data files should not * contain non-monotonic timestamps when synchronized playback is desired. * * @param dt the timestamp different in units of the timestamp (usually us) * @see #MAX_BUFFER_SIZE_EVENTS */ @Override synchronized public AEPacketRaw readPacketByTime(int dt) throws IOException { if (!firstReadCompleted) { fireInitPropertyChange(); } int endTimestamp = currentStartTimestamp + dt; // check to see if this read will wrap the int32 timestamp around e.g. from >0 to <0 for dt>0 boolean bigWrap = isWrappedTime(endTimestamp, currentStartTimestamp, dt); if (bigWrap) { log.info("bigwrap is true - read should wrap around"); } // if( (dt>0 && mostRecentTimestamp>endTimestamp ) || (dt<0 && mostRecentTimestamp<endTimestamp)){ // boolean lt1=endTimestamp<0, lt2=mostRecentTimestamp<0; // boolean changedSign= ( (lt1 && !lt2) || (!lt1 && lt2) ); // if( !changedSign ){ currentStartTimestamp = endTimestamp; // always set currentStartTimestamp to the endTimestamp unless there is // some exception. // log.info(this+" returning empty packet because mostRecentTimestamp="+mostRecentTimestamp+" is already later // than endTimestamp="+endTimestamp); // return new AEPacketRaw(0); int startTimestamp = mostRecentTimestamp; int[] addr = packet.getAddresses(); int[] ts = packet.getTimestamps(); EventType[] etypes = packet.getEventtypes(); // For jAER 3.0, no influence on jAER 2.0 int[] pixelDataArray = packet.getPixelDataArray(); long oldPosition = position(); EventRaw ae; int i = 0; // System.out.println("endTimestamp-startTimestamp="+(endTimestamp-startTimestamp)+" // mostRecentTimestamp="+mostRecentTimestamp+" startTimestamp="+startTimestamp); try { if (dt > 0) { // read forwards if (!bigWrap) { // normal situation do { ae = readEventForwards(endTimestamp); if (ae == null) { break; } addr[i] = ae.address; ts[i] = ae.timestamp; etypes[i] = ae.eventtype; pixelDataArray[i] = ae.pixelData; i++; } while ((mostRecentTimestamp < endTimestamp) && (i < addr.length) && (mostRecentTimestamp >= startTimestamp)); // time // jumps // backwards // timestamp // reset // during // recording) // then // will // read // huge // number // events. } else { // read should wrap around log.info("bigwrap started"); do { ae = readEventForwards(); if (ae == null) { break; } addr[i] = ae.address; ts[i] = ae.timestamp; etypes[i] = ae.eventtype; pixelDataArray[i] = ae.pixelData; i++; } while ((mostRecentTimestamp > 0) && (i < addr.length)); // read to where bigwrap occurs, then // terminate - but wrapped time exception // will happen first // never gets here because of wrap exception // System.out.println("reading one more event after bigwrap"); // ae = readEventForwards(); // addr[i] = ae.address; // ts[i] = ae.timestamp; } } else // read backwards { if (!bigWrap) { do { ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ((mostRecentTimestamp > endTimestamp) && (i < addr.length) && (mostRecentTimestamp <= startTimestamp)); } else { do { ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } while ((mostRecentTimestamp < 0) && (i < (addr.length - 1))); ae = readEventBackwards(); addr[i] = ae.address; ts[i] = ae.timestamp; i++; } } } catch (WrappedTimeException w) { log.info(w.toString()); System.out.println(w.toString()); currentStartTimestamp = w.getCurrentTimestamp(); mostRecentTimestamp = w.getCurrentTimestamp(); getSupport().firePropertyChange(AEInputStream.EVENT_WRAPPED_TIME, w.getPreviousTimestamp(), w.getCurrentTimestamp()); } catch (NonMonotonicTimeException e) { // e.printStackTrace(); if (numNonMonotonicTimeExceptionsPrinted++ < MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT) { log.log(Level.INFO, "{0} resetting currentStartTimestamp from {1} to {2} and setting mostRecentTimestamp to same value", new Object[]{e, currentStartTimestamp, e.getCurrentTimestamp()}); if (numNonMonotonicTimeExceptionsPrinted == MAX_NONMONOTONIC_TIME_EXCEPTIONS_TO_PRINT) { log.warning("suppressing further warnings about NonMonotonicTimeException"); } } currentStartTimestamp = e.getCurrentTimestamp(); mostRecentTimestamp = e.getCurrentTimestamp(); getSupport().firePropertyChange(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, lastTimestamp, mostRecentTimestamp); } finally { // currentStartTimestamp = mostRecentTimestamp; } packet.setNumEvents(i); // if(i<1){ // log.info(packet.toString()); getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, position()); // System.out.println("bigwrap="+bigWrap+" read "+packet.getNumEvents()+" // mostRecentTimestamp="+mostRecentTimestamp+" currentStartTimestamp="+currentStartTimestamp); return packet; } /** * rewind to the start, or to the marked position, if it has been set. Fires * a property change "position" followed by "rewind". */ @Override synchronized public void rewind() throws IOException { long oldPosition = position(); position(markIn); try { if (markIn == 0) { mostRecentTimestamp = firstTimestamp; // skipHeader(); } else { readEventForwards(); // to set the mostRecentTimestamp } } catch (NonMonotonicTimeException e) { log.log(Level.INFO, "rewind from timestamp={0} to timestamp={1}", new Object[]{e.getPreviousTimestamp(), e.getCurrentTimestamp()}); } if (this.jaer3EnableFlg == true) { jaer3BufferParser.setInFrameEvent(false); } currentStartTimestamp = mostRecentTimestamp; // System.out.println("AEInputStream.rewind(): set position="+byteBuffer.position()+" // mostRecentTimestamp="+mostRecentTimestamp); getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, position()); getSupport().firePropertyChange(AEInputStream.EVENT_REWIND, oldPosition, position()); // String s=ListPropertyChangeListeners.listListeners(getSupport()); // log.info("Listeners for EVENT_REWIND of "+this+" are \n"+s); } /** * gets the size of the stream in events * * @return size in events */ @Override public long size() { if (jaer3EnableFlg) { return jaer3BufferParser.size(); } else { return (fileSize - headerOffset) / eventSizeBytes; } } /** * set position in events from start of file * * @param event the number of the event, starting with 0 */ @Override synchronized public void position(long event) { // if(event==size()) event=event-1; int newChunkNumber; try { if ((newChunkNumber = getChunkNumber(event)) != chunkNumber) { mapChunk(newChunkNumber); } byteBuffer.position((int) ((event * eventSizeBytes) % chunkSizeBytes)); position = event; } catch (ClosedByInterruptException e3) { log.info("caught interrupt, probably from single stepping this file"); } catch (ClosedChannelException cce) { log.warning("caught exception " + cce); cce.printStackTrace(); } catch (IOException e) { log.warning("caught exception " + e); e.printStackTrace(); } catch (IllegalArgumentException e2) { log.warning("caught " + e2); e2.printStackTrace(); } } /** * gets the current position (in events) for reading forwards, i.e., * readEventForwards will read this event number. * * @return position in events. */ @Override synchronized public long position() { return this.position; } /** * Returns the position as a fraction of the total number of events * * @return fractional position in total events */ @Override synchronized public float getFractionalPosition() { return (float) position() / size(); } /** * Sets fractional position in events * * @param frac 0-1 float range, 0 at start, 1 at end */ @Override synchronized public void setFractionalPosition(float frac) { position((int) (frac * size())); try { readEventForwards(); } catch (Exception e) { e.printStackTrace(); } } /** * AEFileInputStream has PropertyChangeSupport. This support fires events on * certain events such as "rewind". */ public PropertyChangeSupport getSupport() { return support; } /** * Sets or clears the marked IN position. Does nothing if trying to set * markIn > markOut. * * @return the markIn position. */ @Override public long setMarkIn() { long here = position(); if (here > markOut) { return markIn; } here -= MARK_OFFSET_EVENTS; if (here < 0) { here = 0; } long old = markIn; markIn = here; markIn = (markIn / eventSizeBytes) * eventSizeBytes; // to avoid marking inside an event getSupport().firePropertyChange(AEInputStream.EVENT_MARK_IN_SET, old, markIn); return markIn; } /** * Sets or clears the marked OUT position. Does nothing if trying to set * markOut <= markIn. * * @return the markIn position. */ @Override public long setMarkOut() { long here = position(); if (here <= markIn) { return markOut; } long old = markOut; markOut = position(); markOut = (markOut / eventSizeBytes) * eventSizeBytes; // to avoid marking inside an event getSupport().firePropertyChange(AEInputStream.EVENT_MARK_OUT_SET, old, markOut); return markIn; } /** * clear any marked position */ @Override synchronized public void clearMarks() { long oldIn = markIn; long oldOut = markOut; long[] oldMarks = {oldIn, oldOut}; markOut = size() - 1; markIn = 0; long[] newMarks = {markIn, markOut}; markPosition = 0; getSupport().firePropertyChange(AEInputStream.EVENT_MARKS_CLEARED, oldMarks, newMarks); } /** * Returns true if mark has been set to nonzero position. * * @return true if set. * @deprecated */ @Deprecated public boolean isMarkSet() { return markPosition != 0; } @Override public long getMarkInPosition() { return markIn; } @Override public long getMarkOutPosition() { return markOut; } @Override public boolean isMarkInSet() { return markIn != 0; } @Override public boolean isMarkOutSet() { return markOut != size(); } @Override public void close() throws IOException { super.close(); fileChannel.close(); System.gc(); System.runFinalization(); // try to free memory mapped file buffers so file can be deleted.... } /** * returns the first timestamp in the stream * * @return the timestamp */ public int getFirstTimestamp() { return firstTimestamp; } /** * returns the last timestamp in the stream * * @return last timestamp in file */ public int getLastTimestamp() { return lastTimestamp; } /** * @return the duration of the file in us. * <p> * Assumes data file is timestamped in us. This method fails to provide a * sensible value if the timestamp wwaps. */ public int getDurationUs() { return lastTimestamp - firstTimestamp; } /** * @return the present value of the startTimestamp for reading data */ synchronized public int getCurrentStartTimestamp() { return currentStartTimestamp; } public void setCurrentStartTimestamp(int currentStartTimestamp) { this.currentStartTimestamp = currentStartTimestamp; } /** * @return returns the most recent timestamp */ public int getMostRecentTimestamp() { return mostRecentTimestamp; } public void setMostRecentTimestamp(int mostRecentTimestamp) { this.mostRecentTimestamp = mostRecentTimestamp; } /** * Determines whether reaching EOF results in rewind or just no more data at * end of file or mark. * * @return the repeat */ @Override public boolean isRepeat() { return repeat; } /** * Determines whether reaching EOF results in rewind or just no more data at * end of file or mark. * * @param rep true to repeat, false to return null packets after mark out or * EOF */ @Override public synchronized void setRepeat(boolean rep) { repeat = rep; } /** * @return the byteBuffer */ public MappedByteBuffer getByteBuffer() { return byteBuffer; } /** * class used to signal a backwards read from input stream */ public class NonMonotonicTimeException extends Exception { protected int timestamp, lastTimestamp; protected long position; public NonMonotonicTimeException() { super(); } public NonMonotonicTimeException(String s) { super(s); } public NonMonotonicTimeException(int ts) { this.timestamp = ts; } /** * Constructs a new NonMonotonicTimeException * * @param readTs the timestamp just read * @param lastTs the previous timestamp */ public NonMonotonicTimeException(int readTs, int lastTs) { this.timestamp = readTs; this.lastTimestamp = lastTs; } /** * Constructs a new NonMonotonicTimeException * * @param readTs the timestamp just read * @param lastTs the previous timestamp * @param position the current position in the stream */ public NonMonotonicTimeException(int readTs, int lastTs, long position) { this.timestamp = readTs; this.lastTimestamp = lastTs; this.position = position; } public int getCurrentTimestamp() { return timestamp; } public int getPreviousTimestamp() { return lastTimestamp; } @Override public String toString() { return "NonMonotonicTimeException: position=" + position + " timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + (timestamp - lastTimestamp); } } /** * Indicates that this timestamp has wrapped around from most positive to * most negative signed value. The de-facto timestamp tick is us and * timestamps are represented as int32 in jAER. Therefore the largest * possible positive timestamp is 2^31-1 ticks which equals 2147.4836 * seconds (35.7914 minutes). This wraps to -2147 seconds. The actual total * time can be computed taking account of these "big wraps" if the time is * increased by 4294.9673 seconds on each WrappedTimeException (when reading * file forwards). * * @param readTs the current (just read) timestamp * @param lastTs the previous timestamp */ public class WrappedTimeException extends NonMonotonicTimeException { public WrappedTimeException(int readTs, int lastTs) { super(readTs, lastTs); } public WrappedTimeException(int readTs, int lastTs, long position) { super(readTs, lastTs, position); } @Override public String toString() { return "WrappedTimeException: position=" + position + " timestamp=" + timestamp + " lastTimestamp=" + lastTimestamp + " jumps backwards by " + (timestamp - lastTimestamp); } } // checks for wrap (if reading forwards, this timestamp <0 and previous timestamp >0) private boolean isWrappedTime(int read, int prevRead, int dt) { if ((dt > 0) && (read <= 0) && (prevRead > 0)) { return true; } if ((dt < 0) && (read >= 0) && (prevRead < 0)) { return true; } return false; } /** * cuts out the part of the stream from IN to OUT and returns it as a new * AEInputStream * * @return the new stream */ public AEFileInputStream cut() { AEFileInputStream out = null; return out; } /** * copies out the part of the stream from IN to OUT markers and returns it * as a new AEInputStream * * @return the new stream */ public AEFileInputStream copy() { AEFileInputStream out = null; return out; } /** * pastes the in stream at the IN marker into this stream * * @param in the stream to paste */ public void paste(AEFileInputStream in) { } /** * returns the chunk number which starts with 0. For * position<CHUNK32_SIZE_BYTES returns 0 */ private int getChunkNumber(long position) { int chunk; chunk = (int) ((position * eventSizeBytes) / chunkSizeBytes); return chunk; } private long positionFromChunk(int chunkNumber) { long pos = chunkNumber * (chunkSizeBytes / eventSizeBytes); return pos; } /** * Maps in the next chunk of the file. */ public void mapNextChunk() throws IOException { chunkNumber++; // increment the chunk number if (chunkNumber >= numChunks) { // if we try now to map a chunk past the last one then throw an EOF throw new EOFException("end of file; tried to map chunkNumber=" + chunkNumber + " but file only has numChunks=" + numChunks); } long start = getChunkStartPosition(chunkNumber); if ((start >= fileSize) || (start < 0)) { chunkNumber = 0; // overflow will wrap<0 } mapChunk(chunkNumber); } /** * Maps back in the previous file chunk. */ protected void mapPreviousChunk() throws IOException { chunkNumber if (chunkNumber < 0) { chunkNumber = 0; } long start = getChunkStartPosition(chunkNumber); if ((start >= fileSize) || (start < 0)) { chunkNumber = 0; // overflow will wrap<0 } mapChunk(chunkNumber); } private int chunksMapped = 0; private final int GC_EVERY_THIS_MANY_CHUNKS = 8; /** * memory-maps a chunk of the input file. * * @param chunkNumber the number of the chunk, starting with 0 */ private void mapChunk(int chunkNumber) throws IOException { this.chunkNumber = chunkNumber; long start = getChunkStartPosition(chunkNumber); if (start >= fileSize) { throw new EOFException("start of chunk=" + start + " but file has fileSize=" + fileSize); } long numBytesToMap = chunkSizeBytes; if ((start + numBytesToMap) >= fileSize) { numBytesToMap = fileSize - start; } if (!fileChannel.isOpen()) { fileChannel = fileInputStream.getChannel(); if (!fileChannel.isOpen()) { log.warning("fileChannel unexpectedly was closed"); throw new IOException("fileChannel unexpectedly was closed"); } log.info("had to reopen fileChannel from fileInputStream"); } byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, start, numBytesToMap); if (byteBuffer == null) { log.severe("got null byteBuffer from fileChannel.map(FileChannel.MapMode.READ_ONLY,start,numBytesToMap) with start=" + start + " numBytesToMap=" + numBytesToMap); } this.position = positionFromChunk(chunkNumber); // log.info("mapped chunk "+chunkNumber+" of "+(numBytesToMap>>10)+"kB"); if (++chunksMapped > GC_EVERY_THIS_MANY_CHUNKS) { chunksMapped = 0; System.gc(); // System.runFinalization(); // caused deadlock on rewind where AEViewer.viewLoop was wating for // finalization thread to run (which waited for Thread to join), while holding AEFileInputStream, while AWT // thread was waiting for same AEFileInputStream // log.info("ran garbage collection after mapping chunk " + chunkNumber); } // log.info("mapped chunk # "+chunkNumber+" of "+numChunks); if (jaer3EnableFlg) { if (jaer3BufferParser == null) { jaer3BufferParser = new Jaer3BufferParser(byteBuffer, chip); // jaer3ParseBuffer.setInBuffer(byteBuffer); // jaer3ByteBuffer = jaer3ParseBuffer.extractAddrAndTs(); } else { // Update in buffer at the same time, just for jAER 3.0 format file jaer3BufferParser.setInBuffer(byteBuffer); jaer3BufferParser.setInBufferOrder(ByteOrder.LITTLE_ENDIAN); jaer3BufferParser.setInFrameEvent(false); } } else { jaer3BufferParser = null; // should call finalize method to restore the extractor } } /** * @return start of chunk in bytes * @param chunk the chunk number */ private long getChunkStartPosition(long chunk) { if (chunk <= 0) { return headerOffset; } return (chunk * chunkSizeBytes) + headerOffset; } private long getChunkEndPosition(long chunk) { return headerOffset + ((chunk + 1) * chunkSizeBytes); } /** * skips the header lines (if any) */ protected void skipHeader() throws IOException { position(headerOffset); } /** * reads the header comment lines. Must have eventSize and chunkSizeBytes * set for backwards compatiblity for files without headers to short address * sizes. */ protected void readHeader(FileInputStream fileInputStream) throws IOException { if (fileInputStream == null) { throw new IOException("null fileInputStream"); } if (fileInputStream.available() == 0) { throw new IOException("empty file (0 bytes available)"); } BufferedReader bufferedHeaderReader = new BufferedReader(new InputStreamReader(fileInputStream)); headerOffset = 0; // start from 0 if (!bufferedHeaderReader.markSupported()) { throw new IOException("no mark supported while reading file header, is this a normal file?"); } String s; // System.out.println("File header:"); while ((s = readHeaderLine(bufferedHeaderReader)) != null) { header.add(s); parseFileFormatVersion(s); } // we don't map yet until we know eventSize StringBuilder sb = new StringBuilder(); sb.append("File header (clipped to " + NUM_HEADER_LINES_TO_PRINT + " lines: \n"); int nLines = 0; for (String str : header) { sb.append(str); sb.append(lineSeparator); if (nLines++ > NUM_HEADER_LINES_TO_PRINT) { break; } } log.info(sb.toString()); bufferedHeaderReader = null; // mark for GC, but don't close or underlying channel breaks! } /** * parses the file format version given a string with the header comment * character stripped off. * * @see net.sf.jaer.eventio.AEDataFile */ protected void parseFileFormatVersion(String s) { float version = 1f; if (s.startsWith(AEDataFile.DATA_FILE_FORMAT_HEADER)) { // # stripped off by readHeaderLine try { version = Float.parseFloat(s.substring(AEDataFile.DATA_FILE_FORMAT_HEADER.length())); } catch (NumberFormatException numberFormatException) { log.warning("While parsing header line " + s + " got " + numberFormatException.toString()); } if (Math.floor(version) == 1) { // #!AER-DAT-1.0 addressType = Short.TYPE; eventSizeBytes = (Integer.SIZE / 8) + (Short.SIZE / 8); jaer3EnableFlg = false; log.info("File format AER-DAT-1.0"); } else if (Math.floor(version) == 2) { // #!AER-DAT-2.0 addressType = Integer.TYPE; eventSizeBytes = (Integer.SIZE / 8) + (Integer.SIZE / 8); jaer3EnableFlg = false; log.info("File format AER-DAT-2.0"); } else if (Math.floor(version) == 3) { // #!AER-DAT-3.x // TODO: need to change this code's affect to the cAER network steam data parsing. if (Math.round((version - 3.0) * 10) == 1) { Jaer3BufferParser.JAER3XSHIFT = 17; Jaer3BufferParser.JAER3XMASK = 0x7fff << Jaer3BufferParser.JAER3XSHIFT; Jaer3BufferParser.JAER3YSHIFT = 2; Jaer3BufferParser.JAER3YMASK = 0x7fff << Jaer3BufferParser.JAER3YSHIFT; Jaer3BufferParser.JAER3POLSHIFT = 1; Jaer3BufferParser.JAER3POLMASK = 1 << Jaer3BufferParser.JAER3POLSHIFT; log.info("File format AER-DAT-3.1"); } else if (Math.round((version - 3.0) * 10) == 0){ Jaer3BufferParser.JAER3XSHIFT = 18; Jaer3BufferParser.JAER3XMASK = 0x3fff << Jaer3BufferParser.JAER3XSHIFT; Jaer3BufferParser.JAER3YSHIFT = 4; Jaer3BufferParser.JAER3YMASK = 0x3fff << Jaer3BufferParser.JAER3YSHIFT;; Jaer3BufferParser.JAER3POLSHIFT = 1; Jaer3BufferParser.JAER3POLMASK = 1 << Jaer3BufferParser.JAER3POLSHIFT; log.info("File format AER-DAT-3.0"); } else { log.warning("unknown AER-DAT-3.x file format version detected, definitions of JAER3YSHIFT etc "); } addressType = Integer.TYPE; eventSizeBytes = (Integer.SIZE / 8) + (Integer.SIZE / 8); jaer3EnableFlg = true; } log.info("Data file version=" + version + " and has addressType=" + addressType); } } void setupChunks() throws IOException { fileChannel = fileInputStream.getChannel(); fileSize = fileChannel.size(); chunkSizeBytes = eventSizeBytes * CHUNK_SIZE_EVENTS; numChunks = (int) ((fileSize / chunkSizeBytes) + 1); // used to limit chunkNumber to prevent overflow of // position and for EOF log.info("fileSize=" + fileSize + " chunkSizeBytes=" + chunkSizeBytes + " numChunks=" + numChunks); mapChunk(0); } /** * assumes we are positioned at start of line and that we may either read a * comment char '#' or something else leaves us after the line at start of * next line or of raw data. Assumes header lines are written using the * AEOutputStream.writeHeaderLine(). * * @return header line */ private String readHeaderLine(BufferedReader reader) throws IOException { // StringBuffer s = new StringBuffer(); // read header lines from fileInputStream, not byteBuffer, since we have not mapped file yet // reader.mark(1); // max header line length in chars int c = reader.read(); // read single char String s = reader.readLine(); boolean flag = true; // code below is wrong because it means that any header line with non alpha char // (such as device with binary serial number) will terminate header // and cause header to be treated as data (tobi) // header non alpha are converted to alpha below in any case. // for (int i = 0; i < s.length(); i++) { // char b = s.charAt(i); // if ((b < 32) || (b > 126)) { // flag = false; // break; if (s.equals(AEDataFile.END_OF_HEADER_STRING)) { numHeaderLines++; log.info("On line " + numHeaderLines + " detected end of header section string \"" + AEDataFile.END_OF_HEADER_STRING + "\""); headerOffset += s.length() + NUMBER_LINE_SEPARATORS + 1; // adds comment char and trailing CRLF newline, return null; } if (c != AEDataFile.COMMENT_CHAR || flag == false) { // if it's not a comment char log.info("On line " + numHeaderLines + " detected line not starting with comment character, ending header read"); return null; // return a null header line } // reader.reset(); // reset to start of header/comment line // we don't push back comment char because we want to parse the file format sans this //String s = reader.readLine(); StringBuilder sb = new StringBuilder(s); // Log and replace unprintable chars. for (int i = 0; i < s.length(); i++) { char b = s.charAt(i); if ((b < 32) || (b > 126)) { log.warning("On line " + numHeaderLines + " non printable ASCII character (char value=" + b + ") which is (<32 || >126) detected in header line"); sb.setCharAt(i, '-'); } } headerOffset += sb.length() + NUMBER_LINE_SEPARATORS + 1; // adds comment char and trailing CRLF newline, numHeaderLines++; // assumes CRLF EOL // TODO fix this assumption return sb.toString(); } /** * Gets the header strings from the file * * @return list of strings, one per line */ public ArrayList<String> getHeader() { return header; } /** * Called to signal first read from file. Fires PropertyChange * AEInputStream.EVENT_INIT, with new value this. */ protected void fireInitPropertyChange() { getSupport().firePropertyChange(AEInputStream.EVENT_INIT, null, this); firstReadCompleted = true; } /** * Returns the File that is being read, or null if the instance is * constructed from a FileInputStream */ public File getFile() { return file; } /** * Sets the File reference but doesn't open the file */ public void setFile(File f) { this.file = f; absoluteStartingTimeMs = getAbsoluteStartingTimeMsFromFile(getFile()); } /** * When the file is opened, the filename is parsed to try to extract the * date and time the file was created from the filename. * * @return the time logging was started in ms since 1970 */ public long getAbsoluteStartingTimeMs() { return absoluteStartingTimeMs; } public void setAbsoluteStartingTimeMs(long absoluteStartingTimeMs) { this.absoluteStartingTimeMs = absoluteStartingTimeMs; } /** * Parses the filename to extract the file logging date from the name of the * file. * * @return start of logging time in ms, i.e., in "java" time, since 1970 */ private long getAbsoluteStartingTimeMsFromFile(File f) { if (f == null) { return 0; } try { String fn = f.getName(); String dateStr = fn.substring(fn.indexOf('-') + 1); // guess that datestamp is right after first - which // follows Chip classname Date date = AEDataFile.DATE_FORMAT.parse(dateStr); log.info(f.getName() + " has from file name the absolute starting date of " + date.toString()); return date.getTime(); } catch (Exception e) { log.warning(e.toString()); return 0; } } @Override public boolean isNonMonotonicTimeExceptionsChecked() { return enableTimeWrappingExceptionsChecking; } @Override public void setNonMonotonicTimeExceptionsChecked(boolean yes) { enableTimeWrappingExceptionsChecking = yes; } /** * * Returns the bitmask that is OR'ed with raw addresses; if result is * nonzero then a new timestamp offset is memorized and subtracted from * * @return the timestampResetBitmask */ public int getTimestampResetBitmask() { return timestampResetBitmask; } /** * Sets the bitmask that is OR'ed with raw addresses; if result is nonzero * then a new timestamp offset is memorized and subtracted from all * subsequent timestamps. * * @param timestampResetBitmask the timestampResetBitmask to set */ public void setTimestampResetBitmask(int timestampResetBitmask) { this.timestampResetBitmask = timestampResetBitmask; } }
package nl.mpi.arbil.clarin; import java.io.File; import java.util.ArrayList; import javax.swing.JProgressBar; import nl.mpi.arbil.LinorgSessionStorage; import org.apache.commons.digester.Digester; public class CmdiProfileReader { public ArrayList<CmdiProfile> cmdiProfileArray = null; // todo: move this url into the config file String profilesUrlString = "http://catalog.clarin.eu/ds/ComponentRegistry/rest/registry/profiles"; public static void main(String args[]) { new CmdiProfileReader(); } public static boolean pathIsProfile(String pathString) { // TODO: make this smarter return (pathString.startsWith("http") && pathString.contains("clarin")); } public String getProfileName(String XsdHref) { for (CmdiProfile currentProfile : cmdiProfileArray) { if (currentProfile.getXsdHref().equals(XsdHref)) { return currentProfile.name; } } return "unknown Clarin profile"; } public class CmdiProfile { public String id; public String description; public String name; public String registrationDate; public String creatorName; public String href; public String getXsdHref() { return href + "/xsd"; } } public CmdiProfileReader() { loadProfiles(); // get all the xsd files from the profile listing and store them on disk for offline use for (CmdiProfileReader.CmdiProfile currentCmdiProfile : cmdiProfileArray) { System.out.println("checking profile exists on disk: " + currentCmdiProfile.getXsdHref()); LinorgSessionStorage.getSingleInstance().updateCache(currentCmdiProfile.getXsdHref(), 90); } } public void refreshProfiles(JProgressBar progressBar) { progressBar.setIndeterminate(true); progressBar.setString(""); LinorgSessionStorage.getSingleInstance().updateCache(profilesUrlString, 0); loadProfiles(); progressBar.setIndeterminate(false); progressBar.setMinimum(0); progressBar.setMaximum(cmdiProfileArray.size() + 1); progressBar.setValue(1); // get all the xsd files from the profile listing and store them on disk for offline use for (CmdiProfileReader.CmdiProfile currentCmdiProfile : cmdiProfileArray) { progressBar.setString(currentCmdiProfile.name); System.out.println("resaving profile to disk: " + currentCmdiProfile.getXsdHref()); LinorgSessionStorage.getSingleInstance().updateCache(currentCmdiProfile.getXsdHref(), 0); progressBar.setValue(progressBar.getValue() + 1); } progressBar.setString(""); progressBar.setValue(0); } public void loadProfiles() { File profileXmlFile = LinorgSessionStorage.getSingleInstance().updateCache(profilesUrlString, 10); try { Digester digester = new Digester(); // This method pushes this (SampleDigester) class to the Digesters // object stack making its methods available to processing rules. digester.push(this); // This set of rules calls the addProfile method and passes // in five parameters to the method. digester.addCallMethod("profileDescriptions/profileDescription", "addProfile", 6); digester.addCallParam("profileDescriptions/profileDescription/id", 0); digester.addCallParam("profileDescriptions/profileDescription/description", 1); digester.addCallParam("profileDescriptions/profileDescription/name", 2); digester.addCallParam("profileDescriptions/profileDescription/registrationDate", 3); digester.addCallParam("profileDescriptions/profileDescription/creatorName", 4); digester.addCallParam("profileDescriptions/profileDescription/ns2:href", 5); cmdiProfileArray = new ArrayList<CmdiProfile>(); digester.parse(profileXmlFile); } catch (Exception e) { e.printStackTrace(); } } public void addProfile(String id, String description, String name, String registrationDate, String creatorName, String href) { // System.out.println(id + " : " + description + " : " + name + " : " + registrationDate + " : " + creatorName + " : " + href); CmdiProfile cmdiProfile = new CmdiProfile(); cmdiProfile.id = id; cmdiProfile.description = description; cmdiProfile.name = name; cmdiProfile.registrationDate = registrationDate; cmdiProfile.creatorName = creatorName; cmdiProfile.href = href; cmdiProfileArray.add(cmdiProfile); } }
package org.anddev.andengine.util.color; public class Color { // Constants public static final Color WHITE = new Color(1, 1, 1, 1); public static final Color BLACK = new Color(0, 0, 0, 1); public static final Color RED = new Color(1, 0, 0, 1); public static final Color YELLOW = new Color(1, 1, 0, 1); public static final Color GREEN = new Color(0, 1, 0, 1); public static final Color CYAN = new Color(0, 1, 1, 1); public static final Color BLUE = new Color(0, 0, 1, 1); public static final Color PINK = new Color(1, 0, 1, 1); public static final Color TRANSPARENT = new Color(1, 1, 1, 0); public static final float WHITE_PACKED = Color.WHITE.getPacked(); public static final float BLACK_PACKED = Color.BLACK.getPacked(); public static final float RED_PACKED = Color.RED.getPacked(); public static final float YELLOW_PACKED = Color.YELLOW.getPacked(); public static final float GREEN_PACKED = Color.GREEN.getPacked(); public static final float CYAN_PACKED = Color.CYAN.getPacked(); public static final float BLUE_PACKED = Color.BLUE.getPacked(); public static final float PINK_PACKED = Color.PINK.getPacked(); public static final float TRANSPARENT_PACKED = Color.TRANSPARENT.getPacked(); // Fields private float mRed; private float mGreen; private float mBlue; private float mAlpha; private float mPacked; // Constructors public Color(final float pRed, final float pGreen, final float pBlue) { this(pRed, pGreen, pBlue, 1); } public Color(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.set(pRed, pGreen, pBlue, pAlpha); } // Getter & Setter public float getRed() { return this.mRed; } public float getGreen() { return this.mGreen; } public float getBlue() { return this.mBlue; } public float getAlpha() { return this.mAlpha; } public void setRed(final float pRed) { this.mRed = pRed; this.pack(); } public boolean setRedChecking(final float pRed) { if(this.mRed != pRed) { this.mRed = pRed; this.pack(); return true; } return false; } public void setGreen(final float pGreen) { this.mGreen = pGreen; this.pack(); } public boolean setGreenChecking(final float pGreen) { if(this.mGreen != pGreen) { this.mGreen = pGreen; this.pack(); return true; } return false; } public void setBlue(final float pBlue) { this.mBlue = pBlue; this.pack(); } public boolean setBlueChecking(final float pBlue) { if(this.mBlue != pBlue) { this.mBlue = pBlue; this.pack(); return true; } return false; } public void setAlpha(final float pAlpha) { this.mAlpha = pAlpha; this.pack(); } public boolean setAlphaChecking(final float pAlpha) { if(this.mAlpha != pAlpha) { this.mAlpha = pAlpha; this.pack(); return true; } return false; } public void set(final float pRed, final float pGreen, final float pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.pack(); } public boolean setChanging(final float pRed, final float pGreen, final float pBlue) { if(this.mRed != pRed || this.mGreen != pGreen || this.mBlue != pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.pack(); return true; } return false; } public void set(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.mAlpha = pAlpha; this.pack(); } public boolean setChanging(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { if(this.mAlpha != pAlpha || this.mRed != pRed || this.mGreen != pGreen || this.mBlue != pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.pack(); return true; } return false; } public void set(final Color pColor) { this.mRed = pColor.mRed; this.mGreen = pColor.mGreen; this.mBlue = pColor.mBlue; this.mAlpha = pColor.mAlpha; this.mPacked = pColor.mPacked; } public boolean setChecking(final Color pColor) { if(this.mAlpha != pColor.mAlpha || this.mRed != pColor.mRed || this.mGreen != pColor.mGreen || this.mBlue != pColor.mBlue) { this.mRed = pColor.mRed; this.mGreen = pColor.mGreen; this.mBlue = pColor.mBlue; this.mAlpha = pColor.mAlpha; this.mPacked = pColor.mPacked; return true; } return false; } public float getPacked() { return this.mPacked; } public void reset() { this.set(1, 1, 1, 1); } // Methods for/from SuperClass/Interfaces // Methods private void pack() { final int packed = ((int)(255 * this.mAlpha) << 24) | ((int)(255 * this.mBlue) << 16) | ((int)(255 * this.mGreen) << 8) | ((int)(255 * this.mRed)); this.mPacked = Float.intBitsToFloat(packed & 0XFEFFFFFF); } public static float pack(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { final int packed = ((int)(255 * pAlpha) << 24) | ((int)(255 * pBlue) << 16) | ((int)(255 * pGreen) << 8) | ((int)(255 * pRed)); return Float.intBitsToFloat(packed & 0XFEFFFFFF); } public void mix(final Color pColorA, final float pPercentageA, final Color pColorB, final float pPercentageB) { final float red = pColorA.mRed * pPercentageA + pColorB.mRed * pPercentageB; final float green = pColorA.mGreen * pPercentageA + pColorB.mGreen * pPercentageB; final float blue = pColorA.mBlue * pPercentageA + pColorB.mBlue * pPercentageB; final float alpha = pColorA.mAlpha * pPercentageA + pColorB.mAlpha * pPercentageB; this.set(red, green, blue, alpha); } // Inner and Anonymous Classes }
package org.exist.util; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.pool.BasePoolableObjectFactory; import org.exist.EXistException; import org.exist.Namespaces; import org.exist.storage.BrokerPool; import org.exist.validation.GrammarPool; import org.exist.validation.resolver.eXistXMLCatalogResolver; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; /** * Factory to create new XMLReader objects on demand. The factory is used * by {@link org.exist.util.XMLReaderPool}. * * @author wolf */ public class XMLReaderObjectFactory extends BasePoolableObjectFactory { public final static int VALIDATION_ENABLED = 0; public final static int VALIDATION_AUTO = 1; public final static int VALIDATION_DISABLED = 2; public final static String CONFIGURATION_ENTITY_RESOLVER_ELEMENT_NAME = "entity-resolver"; public final static String CONFIGURATION_CATALOG_ELEMENT_NAME = "catalog"; public final static String CONFIGURATION_ELEMENT_NAME = "validation"; //TOO : move elsewhere ? public final static String VALIDATION_MODE_ATTRIBUTE = "mode"; public final static String PROPERTY_VALIDATION_MODE = "validation.mode"; public final static String CATALOG_RESOLVER = "validation.resolver"; public final static String CATALOG_URIS = "validation.catalog_uris"; public final static String GRAMMER_POOL = "validation.grammar_pool"; // Xerces feature and property names public final static String FEATURES_VALIDATION_SCHEMA ="http://apache.org/xml/features/validation/schema"; public final static String PROPERTIES_INTERNAL_GRAMMARPOOL ="http://apache.org/xml/properties/internal/grammar-pool"; public final static String PROPERTIES_LOAD_EXT_DTD ="http://apache.org/xml/features/nonvalidating/load-external-dtd"; public final static String PROPERTIES_ENTITYRESOLVER ="http://apache.org/xml/properties/internal/entity-resolver"; private BrokerPool pool; public XMLReaderObjectFactory(BrokerPool pool) { super(); this.pool = pool; } /** * @see org.apache.commons.pool.BasePoolableObjectFactory#makeObject() */ public Object makeObject() throws Exception { Configuration config = pool.getConfiguration(); // Get validation settings int validation = VALIDATION_AUTO; String option = (String) config.getProperty(PROPERTY_VALIDATION_MODE); if (option != null) { if (option.equals("true") || option.equals("yes")) validation = VALIDATION_ENABLED; else if (option.equals("auto")) validation = VALIDATION_AUTO; else validation = VALIDATION_DISABLED; } // Create a xmlreader SAXParserFactory saxFactory = SAXParserFactory.newInstance(); if (validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED){ saxFactory.setValidating(true); } else { saxFactory.setValidating(false); } saxFactory.setNamespaceAware(true); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, true); try { xmlReader.setFeature(Namespaces.SAX_VALIDATION, validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED); xmlReader.setFeature(Namespaces.SAX_VALIDATION_DYNAMIC, validation == VALIDATION_AUTO); xmlReader.setFeature(FEATURES_VALIDATION_SCHEMA, validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED); xmlReader.setFeature(PROPERTIES_LOAD_EXT_DTD, validation == VALIDATION_AUTO || validation == VALIDATION_ENABLED); // Attempt to make validation function equal to insert mode //saxFactory.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, true); } catch (SAXNotRecognizedException e1) { // Ignore: feature only recognized by xerces } catch (SAXNotSupportedException e1) { // Ignore: feature only recognized by xerces } // Setup grammar cache GrammarPool grammarPool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMER_POOL); if(grammarPool!=null){ xmlReader.setProperty(PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool); } // Setup xml catalog resolver eXistXMLCatalogResolver resolver = (eXistXMLCatalogResolver) config.getProperty(CATALOG_RESOLVER); if(resolver!=null){ xmlReader.setProperty(PROPERTIES_ENTITYRESOLVER, resolver); } return xmlReader; } }
package net.mm2d.upnp; import net.mm2d.log.Log; import net.mm2d.util.IoUtils; import net.mm2d.util.TextUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URL; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * HTTP * * <p>UPnP * * * * * <p>keep-alive * keep-alive * * <p>keep-alivepost * * * @author <a href="mailto:ryo@mm2d.net">(OHMAE Ryosuke)</a> */ public class HttpClient { private static final int REDIRECT_MAX = 2; @Nullable private Socket mSocket; private boolean mKeepAlive; @Nullable private InputStream mInputStream; @Nullable private OutputStream mOutputStream; /** * * * @see #setKeepAlive(boolean) */ public HttpClient() { setKeepAlive(true); } /** * * * @param keepAlive keep-alivetrue * @see #setKeepAlive(boolean) */ public HttpClient(final boolean keepAlive) { setKeepAlive(keepAlive); } /** * keep-alive * * @return keep-alivetrue */ public boolean isKeepAlive() { return mKeepAlive; } /** * keep-alive * * <p>true * truekeep-alive * truekeep-alive * false * * <p>true/false * post{@link HttpRequest} * keep-alivepost * {@link HttpRequest} * * @param keepAlive keep-alivetrue */ public void setKeepAlive(final boolean keepAlive) { mKeepAlive = keepAlive; } /** * * * <p>HTTP * * @param request * @return * @throws IOException */ @Nonnull public HttpResponse post(@Nonnull final HttpRequest request) throws IOException { return post(request, 0); } /** * * * <p>HTTP * * @param request * @param redirectDepth * @return * @throws IOException */ @Nonnull private HttpResponse post( @Nonnull final HttpRequest request, final int redirectDepth) throws IOException { confirmReuseSocket(request); final HttpResponse response; try { response = doRequest(request); } catch (final IOException e) { closeSocket(); throw e; } if (!isKeepAlive() || !response.isKeepAlive()) { closeSocket(); } return redirectIfNeeded(request, response, redirectDepth); } private void confirmReuseSocket(@Nonnull final HttpRequest request) { if (!canReuse(request)) { closeSocket(); } } private HttpResponse doRequest(@Nonnull final HttpRequest request) throws IOException { if (mSocket == null) { openSocket(request); return writeAndRead(request); } else { try { return writeAndRead(request); } catch (final IOException e) { // peer // KeepAliveKeepAlive Log.w("retry:" + e.getMessage()); setKeepAlive(false); closeSocket(); openSocket(request); return writeAndRead(request); } } } @Nonnull private HttpResponse writeAndRead(@Nonnull final HttpRequest request) throws IOException { request.writeData(mOutputStream); final HttpResponse response = new HttpResponse(mSocket); response.readData(mInputStream); return response; } @Nonnull private HttpResponse redirectIfNeeded( @Nonnull final HttpRequest request, @Nonnull final HttpResponse response, final int redirectDepth) throws IOException { if (needToRedirect(response) && redirectDepth < REDIRECT_MAX) { final String location = response.getHeader(Http.LOCATION); if (!TextUtils.isEmpty(location)) { return redirect(request, location, redirectDepth); } } return response; } // VisibleForTesting boolean needToRedirect(@Nonnull final HttpResponse response) { final Http.Status status = response.getStatus(); switch (status) { case HTTP_MOVED_PERM: case HTTP_FOUND: case HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: return true; default: return false; } } @Nonnull private HttpResponse redirect( @Nonnull final HttpRequest request, @Nonnull final String location, final int redirectDepth) throws IOException { final HttpRequest newRequest = new HttpRequest(request) .setUrl(new URL(location), true) .setHeader(Http.CONNECTION, Http.CLOSE); return new HttpClient(false).post(newRequest, redirectDepth + 1); } // VisibleForTesting boolean canReuse(@Nonnull final HttpRequest request) { return mSocket != null && mSocket.isConnected() && mSocket.getInetAddress().equals(request.getAddress()) && mSocket.getPort() == request.getPort(); } private void openSocket(@Nonnull final HttpRequest request) throws IOException { mSocket = new Socket(); mSocket.connect(request.getSocketAddress(), Property.DEFAULT_TIMEOUT); mSocket.setSoTimeout(Property.DEFAULT_TIMEOUT); mInputStream = new BufferedInputStream(mSocket.getInputStream()); mOutputStream = new BufferedOutputStream(mSocket.getOutputStream()); } private void closeSocket() { IoUtils.closeQuietly(mInputStream); IoUtils.closeQuietly(mOutputStream); IoUtils.closeQuietly(mSocket); mInputStream = null; mOutputStream = null; mSocket = null; } public void close() { closeSocket(); } /** * HTTP GET * * @param url URL * @return * @throws IOException */ @Nonnull public String downloadString(@Nonnull final URL url) throws IOException { return download(url).getBody(); } /** * HTTP GET * * @param url URL * @return * @throws IOException */ @Nonnull public byte[] downloadBinary(@Nonnull final URL url) throws IOException { return download(url).getBodyBinary(); } /** * HTTP GET * * @param url URL * @return HTTP * @throws IOException */ @Nonnull public HttpResponse download(@Nonnull final URL url) throws IOException { final HttpRequest request = makeHttpRequest(url); final HttpResponse response = post(request); // response bodyempty if (response.getStatus() != Http.Status.HTTP_OK || response.getBody() == null) { Log.i("request:" + request.toString() + "\nresponse:" + response.toString()); throw new IOException(response.getStartLine()); } return response; } @Nonnull private HttpRequest makeHttpRequest(@Nonnull final URL url) throws IOException { return new HttpRequest() .setMethod(Http.GET) .setUrl(url, true) .setHeader(Http.USER_AGENT, Property.USER_AGENT_VALUE) .setHeader(Http.CONNECTION, isKeepAlive() ? Http.KEEP_ALIVE : Http.CLOSE); } }
package org.radargun; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.radargun.config.ConfigParser; import org.radargun.config.MasterConfig; import java.io.File; /** * @author Mircea.Markus@jboss.com */ public class LaunchMaster { private static Log log = LogFactory.getLog(LaunchMaster.class); public static void main(String[] args) throws Exception { File currentDir = new File("."); String message = "Running in directory: " + currentDir.getAbsolutePath(); out(message); String config = getConfigOrExit(args); out("Configuration file is: " + config); ConfigParser configParser = ConfigParser.getConfigParser(); MasterConfig masterConfig = configParser.parseConfig(config); Master server = new Master(masterConfig); server.start(); } private static String getConfigOrExit(String[] args) { String config = null; for (int i = 0; i < args.length - 1; i++) { if (args[i].equals("-config")) { config = args[i + 1]; } } if (config == null) { printUsageAndExit(); } return config; } private static void printUsageAndExit() { System.out.println("Usage: master.sh -config <config-file.xml>"); System.out.println(" -config : xml file containing benchmark's configuration"); ShutDownHook.exit(1); } private static void launchOld(String config) throws Exception { File configFile = new File(config); if (!configFile.exists()) { System.err.println("No such file: " + configFile.getAbsolutePath()); printUsageAndExit(); } } private static void out(String message) { System.out.println(message); log.info(message); } }
package org.metawatch.manager.apps; import java.util.ArrayList; import java.util.List; import org.metawatch.manager.FontCache; import org.metawatch.manager.Notification; import org.metawatch.manager.Protocol; import org.metawatch.manager.Notification.NotificationType; import org.metawatch.manager.Utils; import org.metawatch.manager.MetaWatchService.WatchType; import org.metawatch.manager.Monitors.WeatherData; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PixelXorXfermode; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; public class ActionsApp implements InternalApp { public interface Action { public String getName(); public String bulletIcon(); public void performAction(Context context); } static AppData appData = new AppData() {{ id = "org.metawatch.manager.apps.ActionsApp"; name = "Actions"; supportsAnalog = true; supportsDigital = true; }}; public final static byte ACTION_NEXT = 30; public final static byte ACTION_PERFORM = 31; public AppData getInfo() { return appData; } List<Action> internalActions = new ArrayList<Action>(); List<Action> actions; int currentSelection = 0; public ActionsApp() { internalActions.add(new Action() { int count = 0; public String getName() { return "Clicker: "+count; } public String bulletIcon() { return "bullet_circle.bmp"; } public void performAction(Context context) { count++; } }); internalActions.add(new Action() { String name = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"; public String getName() { return name; } public String bulletIcon() { return "bullet_square.bmp"; } public void performAction(Context context) { name = "A woodchuck could chuck no amount of wood, since a woodchuck can't chuck wood."; } }); } public void activate(int watchType) { if (watchType == WatchType.DIGITAL) { Protocol.enableButton(1, 1, ACTION_NEXT, 1); // right middle - press Protocol.enableButton(2, 1, ACTION_PERFORM, 1); // right middle - press } else if (watchType == WatchType.ANALOG) { Protocol.enableButton(0, 1, ACTION_NEXT, 1); // top - press Protocol.enableButton(2, 1, ACTION_PERFORM, 1); // bottom - press } } public void deactivate(int watchType) { if (watchType == WatchType.DIGITAL) { Protocol.disableButton(1, 1, 1); Protocol.disableButton(2, 1, 1); } else if (watchType == WatchType.ANALOG) { Protocol.disableButton(0, 1, 1); Protocol.disableButton(2, 1, 1); } } public Bitmap update(final Context context, int watchType) { TextPaint paint = new TextPaint(); paint.setColor(Color.BLACK); paint.setTextSize(FontCache.instance(context).Get().size); paint.setTypeface(FontCache.instance(context).Get().face); int textHeight = FontCache.instance(context).Get().realSize; Paint paintXor = new Paint(); paintXor.setXfermode(new PixelXorXfermode(Color.WHITE)); actions = new ArrayList<Action>(); final ArrayList<NotificationType> notificationHistory = Notification.history(); for(final NotificationType n : notificationHistory) { actions.add(new Action() { NotificationType notification = n; public String getName() { return notification.description; } public String bulletIcon() { return "bullet_triangle.bmp"; } public void performAction(Context context) { Notification.replay(context, notification); } }); } actions.addAll(internalActions); if (watchType == WatchType.DIGITAL) { Bitmap bitmap = Bitmap.createBitmap(96, 96, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); canvas.drawColor(Color.WHITE); int y=1; int index = 0; for(Action a : actions) { canvas.drawBitmap(Utils.loadBitmapFromAssets(context, a.bulletIcon()), 1, y, null); if(index==currentSelection) { // Draw full multi-line text final StaticLayout layout = new StaticLayout(a.getName(), paint, 79, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false); final int height = layout.getHeight(); canvas.save(); canvas.translate(7, y); layout.draw(canvas); canvas.restore(); canvas.drawRect(0, y-1, 96, y+height, paintXor); y+= height; } else { //draw elipsized text canvas.drawText((String) TextUtils.ellipsize(a.getName(), paint, 79, TruncateAt.END), 7, y+textHeight, paint); y+= textHeight+1; } index++; } canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "switch_app.png"), 87, 0, null); canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "action_down.bmp"), 87, 43, null); canvas.drawBitmap(Utils.loadBitmapFromAssets(context, "action_right.bmp"), 87, 87, null); return bitmap; } else if (watchType == WatchType.ANALOG) { Bitmap bitmap = Bitmap.createBitmap(80, 32, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); canvas.drawColor(Color.WHITE); return bitmap; } return null; } public boolean buttonPressed(Context context, int id) { if(actions==null) { return false; } switch (id) { case ACTION_NEXT: currentSelection = (currentSelection+1)%actions.size(); return true; case ACTION_PERFORM: actions.get(currentSelection).performAction(context); return true; } return false; } }
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.CompatibilityFixer; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; import gcm2sbml.util.GlobalConstants; import graph.Graph; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTabbedPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.plaf.basic.BasicTabbedPaneUI; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import learn.Learn; import synthesis.Synthesis; import verification.Verification; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; /** * This class creates a GUI for the Tstubd program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * are selected. * * @author Curtis Madsen */ public class BioSim implements MouseListener, ActionListener { private JFrame frame; // Frame where components of the GUI are displayed private JMenu file; // The file menu private JMenuItem newProj; // The new menu item private JMenuItem newModel; // The new menu item private JMenuItem newCircuit; // The new menu item private JMenuItem newVhdl; // The new vhdl menu item private JMenuItem newLhpn; // The new lhpn menu item private JMenuItem newCsp; // The new csp menu item private JMenuItem newHse; // The new handshaking extension menu item private JMenuItem newUnc; // The new extended burst mode menu item private JMenuItem newRsg; // The new rsg menu item private JMenuItem exit; // The exit menu item private JMenuItem importSbml; // The import sbml menu item private JMenuItem importDot; // The import dot menu item private JMenuItem importVhdl; // The import vhdl menu item private JMenuItem importLhpn; // The import lhpn menu item private JMenuItem importCsp; // The import csp menu item private JMenuItem importHse; // The import handshaking extension menu item private JMenuItem importUnc; // The import extended burst mode menu item private JMenuItem importRsg; // The import rsg menu item private JMenuItem manual; // The manual menu item private JMenuItem about; // The about menu item private JMenuItem openProj; // The open menu item private JMenuItem pref; // The preferences menu item private JMenuItem graph; // The graph menu item private JMenuItem probGraph; private String root; // The root directory private FileTree tree; // FileTree private JTabbedPane tab; // JTabbedPane for different tools private JPanel mainPanel; // the main panel private Log log; // the log private JPopupMenu popup; // popup menu private String separator; private KeyEventDispatcher dispatcher; private JMenuItem recentProjects[]; private String recentProjectPaths[]; private int numberRecentProj; private int ShortCutKey; public boolean checkUndeclared, checkUnits; private JCheckBox Undeclared, Units; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean lema; private JMenuItem copy, rename, delete; public class MacOSAboutHandler extends Application { public MacOSAboutHandler() { addApplicationListener(new AboutBoxHandler()); } class AboutBoxHandler extends ApplicationAdapter { public void handleAbout(ApplicationEvent event) { about(); event.setHandled(true); } } } public class MacOSPreferencesHandler extends Application { public MacOSPreferencesHandler() { addApplicationListener(new PreferencesHandler()); } class PreferencesHandler extends ApplicationAdapter { public void handlePreferences(ApplicationEvent event) { preferences(); event.setHandled(true); } } } public class MacOSQuitHandler extends Application { public MacOSQuitHandler() { addApplicationListener(new QuitHandler()); } class QuitHandler extends ApplicationAdapter { public void handleQuit(ApplicationEvent event) { exit(); event.setHandled(true); } } } /** * This is the constructor for the Proj class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. * * @throws Exception */ public BioSim(boolean lema) { this.lema = lema; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Creates a new frame if (!lema) { frame = new JFrame("iBioSim"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } else { frame = new JFrame("ATACS"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } // Makes it so that clicking the x in the corner closes the program WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { exit.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; frame.addWindowListener(w); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); popup = new JPopupMenu(); // Creates a menu for the frame JMenuBar menuBar = new JMenuBar(); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); JMenu help = new JMenu("Help"); help.setMnemonic(KeyEvent.VK_H); JMenu edit = new JMenu("Edit"); edit.setMnemonic(KeyEvent.VK_E); JMenu importMenu = new JMenu("Import"); JMenu newMenu = new JMenu("New"); menuBar.add(file); menuBar.add(edit); menuBar.add(help); copy = new JMenuItem("Copy"); rename = new JMenuItem("Rename"); delete = new JMenuItem("Delete"); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); pref = new JMenuItem("Preferences"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); newVhdl = new JMenuItem("VHDL Model"); newLhpn = new JMenuItem("Labeled Hybrid Petri Net"); newCsp = new JMenuItem("CSP Model"); newHse = new JMenuItem("Handshaking Expansion"); newUnc = new JMenuItem("Extended Burst Mode Machine"); newRsg = new JMenuItem("Reduced State Graph"); graph = new JMenuItem("TSD Graph"); probGraph = new JMenuItem("Probability Graph"); importSbml = new JMenuItem("SBML Model"); importDot = new JMenuItem("Genetic Circuit Model"); importVhdl = new JMenuItem("VHDL Model"); importLhpn = new JMenuItem("Labeled Hybrid Petri Net"); importCsp = new JMenuItem("CSP Model"); importHse = new JMenuItem("Handshaking Expansion"); importUnc = new JMenuItem("Extended Burst Mode Machine"); importRsg = new JMenuItem("Reduced State Graph"); exit = new JMenuItem("Exit"); copy.addActionListener(this); rename.addActionListener(this); delete.addActionListener(this); openProj.addActionListener(this); pref.addActionListener(this); manual.addActionListener(this); newProj.addActionListener(this); newCircuit.addActionListener(this); newModel.addActionListener(this); newVhdl.addActionListener(this); newLhpn.addActionListener(this); newCsp.addActionListener(this); newHse.addActionListener(this); newUnc.addActionListener(this); newRsg.addActionListener(this); exit.addActionListener(this); about.addActionListener(this); importSbml.addActionListener(this); importDot.addActionListener(this); importVhdl.addActionListener(this); importLhpn.addActionListener(this); importCsp.addActionListener(this); importHse.addActionListener(this); importUnc.addActionListener(this); importRsg.addActionListener(this); graph.addActionListener(this); probGraph.addActionListener(this); ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey)); rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ShortCutKey)); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ShortCutKey)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey)); newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ShortCutKey)); newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ShortCutKey)); newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey)); about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ShortCutKey)); probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ShortCutKey)); if (!lema) { importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey)); } else { importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey)); } importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, ShortCutKey)); importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ShortCutKey)); copy.setMnemonic(KeyEvent.VK_C); rename.setMnemonic(KeyEvent.VK_R); delete.setMnemonic(KeyEvent.VK_D); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); newCircuit.setMnemonic(KeyEvent.VK_G); newModel.setMnemonic(KeyEvent.VK_S); newVhdl.setMnemonic(KeyEvent.VK_V); newLhpn.setMnemonic(KeyEvent.VK_L); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_Y); if (!lema) { importDot.setMnemonic(KeyEvent.VK_N); } else { importLhpn.setMnemonic(KeyEvent.VK_N); } importSbml.setMnemonic(KeyEvent.VK_B); importVhdl.setMnemonic(KeyEvent.VK_H); importDot.setEnabled(false); importSbml.setEnabled(false); importVhdl.setEnabled(false); importLhpn.setEnabled(false); importCsp.setEnabled(false); importHse.setEnabled(false); importUnc.setEnabled(false); importRsg.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); newVhdl.setEnabled(false); newLhpn.setEnabled(false); newCsp.setEnabled(false); newHse.setEnabled(false); newUnc.setEnabled(false); newRsg.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); edit.add(copy); edit.add(rename); edit.add(delete); file.add(newMenu); newMenu.add(newProj); if (!lema) { newMenu.add(newCircuit); newMenu.add(newModel); } else { newMenu.add(newVhdl); newMenu.add(newLhpn); newMenu.add(newCsp); newMenu.add(newHse); newMenu.add(newUnc); newMenu.add(newRsg); } newMenu.add(graph); newMenu.add(probGraph); file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(importMenu); if (!lema) { importMenu.add(importDot); importMenu.add(importSbml); } else { importMenu.add(importVhdl); importMenu.add(importLhpn); importMenu.add(importCsp); importMenu.add(importHse); importMenu.add(importUnc); importMenu.add(importRsg); } file.addSeparator(); help.add(manual); if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { file.add(pref); file.add(exit); file.addSeparator(); help.add(about); } root = null; // Create recent project menu items numberRecentProj = 0; recentProjects = new JMenuItem[5]; recentProjectPaths = new String[5]; for (int i = 0; i < 5; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_5); Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < 5; i++) { recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } if (biosimrc.get("biosim.check.undeclared", "").equals("false")) { checkUndeclared = false; } else { checkUndeclared = true; } if (biosimrc.get("biosim.check.units", "").equals("false")) { checkUnits = false; } else { checkUnits = true; } if (biosimrc.get("biosim.general.file_browser", "").equals("")) { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KREP_VALUE", ".5"); } if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KACT_VALUE", ".0033"); } if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBIO_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2"); } if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001"); } if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.OCR_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075"); } if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_VALUE", "30"); } if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2"); } if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25"); } if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1"); } if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.INITIAL_VALUE", "0"); } if (biosimrc.get("biosim.sim.abs", "").equals("")) { biosimrc.put("biosim.sim.abs", "None"); } if (biosimrc.get("biosim.sim.type", "").equals("")) { biosimrc.put("biosim.sim.type", "ODE"); } if (biosimrc.get("biosim.sim.sim", "").equals("")) { biosimrc.put("biosim.sim.sim", "rkf45"); } if (biosimrc.get("biosim.sim.limit", "").equals("")) { biosimrc.put("biosim.sim.limit", "100.0"); } if (biosimrc.get("biosim.sim.interval", "").equals("")) { biosimrc.put("biosim.sim.interval", "1.0"); } if (biosimrc.get("biosim.sim.step", "").equals("")) { biosimrc.put("biosim.sim.step", "inf"); } if (biosimrc.get("biosim.sim.error", "").equals("")) { biosimrc.put("biosim.sim.error", "1.0E-9"); } if (biosimrc.get("biosim.sim.seed", "").equals("")) { biosimrc.put("biosim.sim.seed", "314159"); } if (biosimrc.get("biosim.sim.runs", "").equals("")) { biosimrc.put("biosim.sim.runs", "1"); } if (biosimrc.get("biosim.sim.rapid1", "").equals("")) { biosimrc.put("biosim.sim.rapid1", "0.1"); } if (biosimrc.get("biosim.sim.rapid2", "").equals("")) { biosimrc.put("biosim.sim.rapid2", "0.1"); } if (biosimrc.get("biosim.sim.qssa", "").equals("")) { biosimrc.put("biosim.sim.qssa", "0.1"); } if (biosimrc.get("biosim.sim.concentration", "").equals("")) { biosimrc.put("biosim.sim.concentration", "15"); } if (biosimrc.get("biosim.learn.tn", "").equals("")) { biosimrc.put("biosim.learn.tn", "2"); } if (biosimrc.get("biosim.learn.tj", "").equals("")) { biosimrc.put("biosim.learn.tj", "2"); } if (biosimrc.get("biosim.learn.ti", "").equals("")) { biosimrc.put("biosim.learn.ti", "0.5"); } if (biosimrc.get("biosim.learn.bins", "").equals("")) { biosimrc.put("biosim.learn.bins", "4"); } if (biosimrc.get("biosim.learn.equaldata", "").equals("")) { biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins"); } if (biosimrc.get("biosim.learn.autolevels", "").equals("")) { biosimrc.put("biosim.learn.autolevels", "Auto"); } if (biosimrc.get("biosim.learn.ta", "").equals("")) { biosimrc.put("biosim.learn.ta", "1.15"); } if (biosimrc.get("biosim.learn.tr", "").equals("")) { biosimrc.put("biosim.learn.tr", "0.75"); } if (biosimrc.get("biosim.learn.tm", "").equals("")) { biosimrc.put("biosim.learn.tm", "0.0"); } if (biosimrc.get("biosim.learn.tt", "").equals("")) { biosimrc.put("biosim.learn.tt", "0.025"); } if (biosimrc.get("biosim.learn.debug", "").equals("")) { biosimrc.put("biosim.learn.debug", "0"); } if (biosimrc.get("biosim.learn.succpred", "").equals("")) { biosimrc.put("biosim.learn.succpred", "Successors"); } if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) { biosimrc.put("biosim.learn.findbaseprob", "False"); } // Open .biosimrc here // Packs the frame and displays it mainPanel = new JPanel(new BorderLayout()); tree = new FileTree(null, this, lema); log = new Log(); tab = new JTabbedPane(); tab.setPreferredSize(new Dimension(1050, 550)); tab.setUI(new TabbedPaneCloseButtonUI()); mainPanel.add(tree, "West"); mainPanel.add(tab, "Center"); mainPanel.add(log, "South"); frame.setContentPane(mainPanel); frame.setJMenuBar(menuBar); frame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; frame.setLocation(x, y); frame.setVisible(true); dispatcher = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_TYPED) { if (e.getKeyChar() == '') { if (tab.getTabCount() > 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher( dispatcher); if (save(tab.getSelectedIndex()) != 0) { tab.remove(tab.getSelectedIndex()); } KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( dispatcher); } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); } public void preferences() { if (!lema) { Undeclared = new JCheckBox("Check for undeclared units in SBML"); if (checkUndeclared) { Undeclared.setSelected(true); } else { Undeclared.setSelected(false); } Units = new JCheckBox("Check units in SBML"); if (checkUnits) { Units.setSelected(true); } else { Units.setSelected(false); } Preferences biosimrc = Preferences.userRoot(); JCheckBox dialog = new JCheckBox("Use File Dialog"); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { dialog.setSelected(true); } else { dialog.setSelected(false); } final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get("biosim.gcm.ACTIVED_VALUE", "")); final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", "")); final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", "")); final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.COOPERATIVITY_VALUE", "")); final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KASSOCIATION_VALUE", "")); final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", "")); final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get( "biosim.gcm.PROMOTER_COUNT_VALUE", "")); final JTextField INITIAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.INITIAL_VALUE", "")); final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "")); final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", "")); final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.RNAP_BINDING_VALUE", "")); final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", "")); final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.STOICHIOMETRY_VALUE", "")); JPanel labels = new JPanel(new GridLayout(15, 1)); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KASSOCIATION_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(15, 1)); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KBIO_VALUE); fields.add(KDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(KASSOCIATION_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_VALUE); fields.add(MAX_DIMER_VALUE); fields.add(OCR_VALUE); fields.add(RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); String[] choices = { "None", "Abstraction", "Logical Abstraction" }; final JComboBox abs = new JComboBox(choices); abs.setSelectedItem(biosimrc.get("biosim.sim.abs", "")); if (abs.getSelectedItem().equals("None")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else if (abs.getSelectedItem().equals("Abstraction")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else { choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser" }; } final JComboBox type = new JComboBox(choices); type.setSelectedItem(biosimrc.get("biosim.sim.type", "")); if (type.getSelectedItem().equals("ODE")) { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } else if (type.getSelectedItem().equals("Monte Carlo")) { choices = new String[] { "gillespie", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "atacs", "ctmc-transient" }; } else { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } final JComboBox sim = new JComboBox(choices); sim.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); abs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (abs.getSelectedItem().equals("None")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else if (abs.getSelectedItem().equals("Abstraction")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("Monte Carlo"); type.addItem("Markov"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } } }); type.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (type.getSelectedItem() == null) { } else if (type.getSelectedItem().equals("ODE")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Monte Carlo")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("gillespie"); sim.addItem("emc-sim"); sim.addItem("bunker"); sim.addItem("nmc"); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Markov")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("atacs"); sim.addItem("ctmc-transient"); sim.setSelectedItem(o); } else { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } } }); final JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", "")); final JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", "")); final JTextField step = new JTextField(biosimrc.get("biosim.sim.step", "")); final JTextField error = new JTextField(biosimrc.get("biosim.sim.error", "")); final JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", "")); final JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", "")); final JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", "")); final JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", "")); final JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", "")); final JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", "")); JPanel analysisLabels = new JPanel(new GridLayout(13, 1)); analysisLabels.add(new JLabel("Abstraction:")); analysisLabels.add(new JLabel("Simulation Type:")); analysisLabels.add(new JLabel("Possible Simulators/Analyzers:")); analysisLabels.add(new JLabel("Time Limit:")); analysisLabels.add(new JLabel("Print Interval:")); analysisLabels.add(new JLabel("Maximum Time Step:")); analysisLabels.add(new JLabel("Absolute Error:")); analysisLabels.add(new JLabel("Random Seed:")); analysisLabels.add(new JLabel("Runs:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 2:")); analysisLabels.add(new JLabel("QSSA Condition:")); analysisLabels.add(new JLabel("Max Concentration Threshold:")); JPanel analysisFields = new JPanel(new GridLayout(13, 1)); analysisFields.add(abs); analysisFields.add(type); analysisFields.add(sim); analysisFields.add(limit); analysisFields.add(interval); analysisFields.add(step); analysisFields.add(error); analysisFields.add(seed); analysisFields.add(runs); analysisFields.add(rapid1); analysisFields.add(rapid2); analysisFields.add(qssa); analysisFields.add(concentration); JPanel analysisPrefs = new JPanel(new GridLayout(1, 2)); analysisPrefs.add(analysisLabels); analysisPrefs.add(analysisFields); final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", "")); final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", "")); final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", "")); choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; final JComboBox bins = new JComboBox(choices); bins.setSelectedItem(biosimrc.get("biosim.learn.bins", "")); choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" }; final JComboBox equaldata = new JComboBox(choices); equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", "")); choices = new String[] { "Auto", "User" }; final JComboBox autolevels = new JComboBox(choices); autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", "")); final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", "")); final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", "")); final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", "")); final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", "")); choices = new String[] { "0", "1", "2", "3" }; final JComboBox debug = new JComboBox(choices); debug.setSelectedItem(biosimrc.get("biosim.learn.debug", "")); choices = new String[] { "Successors", "Predecessors", "Both" }; final JComboBox succpred = new JComboBox(choices); succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", "")); choices = new String[] { "True", "False" }; final JComboBox findbaseprob = new JComboBox(choices); findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", "")); JPanel learnLabels = new JPanel(new GridLayout(13, 1)); learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):")); learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):")); learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):")); learnLabels.add(new JLabel("Number Of Bins:")); learnLabels.add(new JLabel("Divide Bins:")); learnLabels.add(new JLabel("Generate Levels:")); learnLabels.add(new JLabel("Ratio For Activation (Ta):")); learnLabels.add(new JLabel("Ratio For Repression (Tr):")); learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):")); learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):")); learnLabels.add(new JLabel("Debug Level:")); learnLabels.add(new JLabel("Successors Or Predecessors:")); learnLabels.add(new JLabel("Basic FindBaseProb:")); JPanel learnFields = new JPanel(new GridLayout(13, 1)); learnFields.add(tn); learnFields.add(tj); learnFields.add(ti); learnFields.add(bins); learnFields.add(equaldata); learnFields.add(autolevels); learnFields.add(ta); learnFields.add(tr); learnFields.add(tm); learnFields.add(tt); learnFields.add(debug); learnFields.add(succpred); learnFields.add(findbaseprob); JPanel learnPrefs = new JPanel(new GridLayout(1, 2)); learnPrefs.add(learnLabels); learnPrefs.add(learnFields); JPanel generalPrefs = new JPanel(new BorderLayout()); generalPrefs.add(dialog, "North"); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); sbmlPrefsBordered.add(Undeclared, "North"); sbmlPrefsBordered.add(Units, "Center"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", dialog); prefTabs.addTab("SBML Preferences", sbmlPrefs); prefTabs.addTab("GCM Preferences", gcmPrefs); prefTabs.addTab("Analysis Preferences", analysisPrefs); prefTabs.addTab("Learn Preferences", learnPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (dialog.isSelected()) { biosimrc.put("biosim.general.file_browser", "FileDialog"); } else { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (Undeclared.isSelected()) { checkUndeclared = true; biosimrc.put("biosim.check.undeclared", "true"); } else { checkUndeclared = false; biosimrc.put("biosim.check.undeclared", "false"); } if (Units.isSelected()) { checkUnits = true; biosimrc.put("biosim.check.units", "true"); } else { checkUnits = false; biosimrc.put("biosim.check.units", "false"); } try { Double.parseDouble(KREP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KACT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBIO_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KASSOCIATION_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBASAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(OCR_VALUE.getText().trim()); biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(COOPERATIVITY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ACTIVED_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(MAX_DIMER_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(INITIAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(limit.getText().trim()); biosimrc.put("biosim.sim.limit", limit.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(interval.getText().trim()); biosimrc.put("biosim.sim.interval", interval.getText().trim()); } catch (Exception e1) { } try { if (step.getText().trim().equals("inf")) { biosimrc.put("biosim.sim.step", step.getText().trim()); } else { Double.parseDouble(step.getText().trim()); biosimrc.put("biosim.sim.step", step.getText().trim()); } } catch (Exception e1) { } try { Double.parseDouble(error.getText().trim()); biosimrc.put("biosim.sim.error", error.getText().trim()); } catch (Exception e1) { } try { Long.parseLong(seed.getText().trim()); biosimrc.put("biosim.sim.seed", seed.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(runs.getText().trim()); biosimrc.put("biosim.sim.runs", runs.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid1.getText().trim()); biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid2.getText().trim()); biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(qssa.getText().trim()); biosimrc.put("biosim.sim.qssa", qssa.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(concentration.getText().trim()); biosimrc.put("biosim.sim.concentration", concentration.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem()); biosimrc.put("biosim.sim.type", (String) type.getSelectedItem()); biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem()); try { Integer.parseInt(tn.getText().trim()); biosimrc.put("biosim.learn.tn", tn.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(tj.getText().trim()); biosimrc.put("biosim.learn.tj", tj.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ti.getText().trim()); biosimrc.put("biosim.learn.ti", ti.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem()); biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem()); biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem()); try { Double.parseDouble(ta.getText().trim()); biosimrc.put("biosim.learn.ta", ta.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tr.getText().trim()); biosimrc.put("biosim.learn.tr", tr.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tm.getText().trim()); biosimrc.put("biosim.learn.tm", tm.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tt.getText().trim()); biosimrc.put("biosim.learn.tt", tt.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem()); biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem()); biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem()); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters(); ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters(); } } } else { } } else { // Preferences biosimrc = Preferences.userRoot(); JPanel vhdlPrefs = new JPanel(); JPanel lhpnPrefs = new JPanel(); JTabbedPane prefTabsNoLema = new JTabbedPane(); prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs); prefTabsNoLema.addTab("LHPN Preferences", lhpnPrefs); Object[] options = { "Save", "Cancel" }; // int value = JOptionPane.showOptionDialog(frame, prefTabsNoLema, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } } public void about() { final JFrame f = new JFrame("About"); // frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + // File.separator // + "gui" // + File.separator + "icons" + File.separator + // "iBioSim.png").getImage()); JLabel bioSim = new JLabel("iBioSim", JLabel.CENTER); Font font = bioSim.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); bioSim.setFont(font); JLabel version = new JLabel("Version 1.02", JLabel.CENTER); JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER); JButton credits = new JButton("Credits"); credits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] options = { "Close" }; JOptionPane.showOptionDialog(f, "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen", "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } }); JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(credits); buttons.add(close); JPanel aboutPanel = new JPanel(new BorderLayout()); JPanel uOfUPanel = new JPanel(new BorderLayout()); uOfUPanel.add(bioSim, "North"); uOfUPanel.add(version, "Center"); uOfUPanel.add(uOfU, "South"); aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png")), "North"); // aboutPanel.add(bioSim, "North"); aboutPanel.add(uOfUPanel, "Center"); aboutPanel.add(buttons, "South"); f.setContentPane(aboutPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } public void exit() { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < numberRecentProj; i++) { biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText()); biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]); } System.exit(1); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == about) { about(); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = "iBioSim.html"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } File work = new File(directory); log.addText("Executing:\n" + command + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command + theFile, null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the exit menu item is selected else if (e.getSource() == exit) { exit(); } // if the open popup menu is selected on a sim directory else if (e.getActionCommand().equals("openSim")) { openSim(); } else if (e.getActionCommand().equals("openLearn")) { openLearn(); } else if (e.getActionCommand().equals("openSynth")) { openSynth(); } else if (e.getActionCommand().equals("openVerification")) { openVerify(); } // if the create simulation popup menu is selected on a dot file else if (e.getActionCommand().equals("createSim")) { try { simulate(true); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the simulate popup menu is selected on an sbml file else if (e.getActionCommand().equals("simulate")) { try { simulate(false); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the synthesis popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createSynthesis")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:", "Synthesis View ID", JOptionPane.PLAIN_MESSAGE); if (synthName != null && !synthName.trim().equals("")) { synthName = synthName.trim(); try { if (overwrite(root + separator + synthName, synthName)) { new File(root + separator + synthName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + synthName.trim() + ".syn")); out.write(("synthesis.file=" + circuitFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } try { FileInputStream in = new FileInputStream(new File(root + separator + circuitFileNoPath)); FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + circuitFileNoPath)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); String work = root + separator + synthName; String circuitFile = root + separator + synthName.trim() + separator + circuitFileNoPath; JPanel synthPane = new JPanel(); synthPane.add(new Synthesis(work, circuitFile, log, this)); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents ().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment (SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD Graph"); */ addTab(synthName, synthPane, null); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the verify popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createVerify")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:", "Verification View ID", JOptionPane.PLAIN_MESSAGE); if (verName != null && !verName.trim().equals("")) { verName = verName.trim(); try { if (overwrite(root + separator + verName, verName)) { new File(root + separator + verName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + verName.trim() + ".ver")); out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } try { FileInputStream in = new FileInputStream(new File(root + separator + circuitFileNoPath)); FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + circuitFileNoPath)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); String work = root + separator + verName; String circuitFile = root + separator + verName.trim() + separator + circuitFileNoPath; // log.addText(circuitFile); JPanel verPane = new JPanel(); Verification verify = new Verification(work, circuitFile, log, this); verify.save(); verPane.add(verify); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents ().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment (SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD Graph"); */ addTab(verName, verPane, null); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Verification View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the delete popup menu is selected else if (e.getActionCommand().contains("delete") || e.getSource() == delete) { if (!tree.getFile().equals(root)) { if (new File(tree.getFile()).isDirectory()) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } refreshTree(); } else { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); refreshTree(); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE); } } } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("createSBML")) { try { String[] dot = tree.getFile().split(separator); String sbmlFile = dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"; // log.addText("Executing:\ngcm2sbml.pl " + tree.getFile() + " " // + root // + separator + sbmlFile // Runtime exec = Runtime.getRuntime(); // String filename = tree.getFile(); // String directory = ""; // String theFile = ""; // if (filename.lastIndexOf('/') >= 0) { // directory = filename.substring(0, // filename.lastIndexOf('/') + 1); // theFile = filename.substring(filename.lastIndexOf('/') + 1); // if (filename.lastIndexOf('\\') >= 0) { // directory = filename.substring(0, filename // .lastIndexOf('\\') + 1); // theFile = filename // .substring(filename.lastIndexOf('\\') + 1); // File work = new File(directory); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + sbmlFile); refreshTree(); addTab(sbmlFile, new SBML_Editor(root + separator + sbmlFile, null, log, this, null, null), "SBML Editor"); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("dotEditor")) { try { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { File work = new File(directory); addTab(theFile, new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log), "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, 1, 1, 1, tree.getFile().substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the browse popup menu is selected on an sbml file else if (e.getActionCommand().equals("browse")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, 1, 1, 1, tree.getFile().substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + tree.getFile() + "\n"); Runtime exec = Runtime.getRuntime(); Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); String error = ""; String output = ""; InputStream reb = browse.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = browse.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } browse.waitFor(); String command = ""; if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { command = "cmd /c start "; } log.addText("Executing:\n" + command + directory + out + ".xhtml\n"); exec.exec(command + out + ".xhtml", null, work); } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph dot popup menu is selected else if (e.getActionCommand().equals("graphDot")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new menu item is selected else if (e.getSource() == newProj) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } String filename = Buttons.browse(frame, null, null, JFileChooser.DIRECTORIES_ONLY, "New"); if (!filename.trim().equals("")) { filename = filename.trim(); File f = new File(filename); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return; } } new File(filename).mkdir(); try { new FileWriter(new File(filename + separator + ".prj")).close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } } // if the open project menu item is selected else if (e.getSource() == pref) { preferences(); } else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } File f; if (root == null) { f = null; } else { f = new File(root); } String projDir = ""; if (e.getSource() == openProj) { projDir = Buttons.browse(frame, f, null, JFileChooser.DIRECTORIES_ONLY, "Open"); } else if (e.getSource() == recentProjects[0]) { projDir = recentProjectPaths[0]; } else if (e.getSource() == recentProjects[1]) { projDir = recentProjectPaths[1]; } else if (e.getSource() == recentProjects[2]) { projDir = recentProjectPaths[2]; } else if (e.getSource() == recentProjects[3]) { projDir = recentProjectPaths[3]; } else if (e.getSource() == recentProjects[4]) { projDir = recentProjectPaths[4]; } if (!projDir.equals("")) { if (new File(projDir).isDirectory()) { boolean isProject = false; for (String temp : new File(projDir).list()) { if (temp.equals(".prj")) { isProject = true; } } if (isProject) { root = projDir; refresh(); tab.removeAll(); addRecentProject(projDir); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new circuit model menu item is selected else if (e.getSource() == newCircuit) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 4).equals(".gcm")) { simName += ".gcm"; } } else { simName += ".gcm"; } String modelID = ""; if (simName.length() > 3) { if (simName.substring(simName.length() - 4).equals(".gcm")) { modelID = simName.substring(0, simName.length() - 4); } else { modelID = simName.substring(0, simName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); new GCMFile().save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } addTab(f.getName(), new GCM2SBMLEditor(root + separator, f.getName(), this, log), "GCM Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new SBML model menu item is selected else if (e.getSource() == newModel) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) { simName += ".sbml"; } } else { simName += ".sbml"; } String modelID = ""; if (simName.length() > 4) { if (simName.substring(simName.length() - 5).equals(".sbml")) { modelID = simName.substring(0, simName.length() - 5); } else { modelID = simName.substring(0, simName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { String f = new String(root + separator + simName); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(2, 3); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + simName); addTab(f.split(separator)[f.split(separator).length - 1], new SBML_Editor(f, null, log, this, null, null), "SBML Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new vhdl menu item is selected else if (e.getSource() == newVhdl) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 4) { if (!vhdlName.substring(vhdlName.length() - 5).equals(".vhd")) { vhdlName += ".vhd"; } } else { vhdlName += ".vhd"; } String modelID = ""; if (vhdlName.length() > 3) { if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) { modelID = vhdlName.substring(0, vhdlName.length() - 4); } else { modelID = vhdlName.substring(0, vhdlName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new lhpn menu item is selected else if (e.getSource() == newLhpn) { if (root != null) { try { String lhpnName = JOptionPane.showInputDialog(frame, "Enter LHPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 1) { if (!lhpnName.substring(lhpnName.length() - 2).equals(".g")) { lhpnName += ".g"; } } else { lhpnName += ".g"; } String modelID = ""; if (lhpnName.length() > 1) { if (lhpnName.substring(lhpnName.length() - 2).equals(".g")) { modelID = lhpnName.substring(0, lhpnName.length() - 2); } else { modelID = lhpnName.substring(0, lhpnName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + lhpnName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new csp menu item is selected else if (e.getSource() == newCsp) { if (root != null) { try { String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (cspName != null && !cspName.trim().equals("")) { cspName = cspName.trim(); if (cspName.length() > 3) { if (!cspName.substring(cspName.length() - 4).equals(".csp")) { cspName += ".csp"; } } else { cspName += ".csp"; } String modelID = ""; if (cspName.length() > 3) { if (cspName.substring(cspName.length() - 4).equals(".csp")) { modelID = cspName.substring(0, cspName.length() - 4); } else { modelID = cspName.substring(0, cspName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + cspName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new hse menu item is selected else if (e.getSource() == newHse) { if (root != null) { try { String hseName = JOptionPane.showInputDialog(frame, "Enter Handshaking Expansion Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (hseName != null && !hseName.trim().equals("")) { hseName = hseName.trim(); if (hseName.length() > 3) { if (!hseName.substring(hseName.length() - 4).equals(".hse")) { hseName += ".hse"; } } else { hseName += ".hse"; } String modelID = ""; if (hseName.length() > 3) { if (hseName.substring(hseName.length() - 4).equals(".hse")) { modelID = hseName.substring(0, hseName.length() - 4); } else { modelID = hseName.substring(0, hseName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + hseName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new unc menu item is selected else if (e.getSource() == newUnc) { if (root != null) { try { String uncName = JOptionPane.showInputDialog(frame, "Enter Extended Burst Mode Machine ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (uncName != null && !uncName.trim().equals("")) { uncName = uncName.trim(); if (uncName.length() > 3) { if (!uncName.substring(uncName.length() - 4).equals(".unc")) { uncName += ".unc"; } } else { uncName += ".unc"; } String modelID = ""; if (uncName.length() > 3) { if (uncName.substring(uncName.length() - 4).equals(".unc")) { modelID = uncName.substring(0, uncName.length() - 4); } else { modelID = uncName.substring(0, uncName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + uncName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newRsg) { if (root != null) { try { String rsgName = JOptionPane.showInputDialog(frame, "Enter Reduced State Graph Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (rsgName != null && !rsgName.trim().equals("")) { rsgName = rsgName.trim(); if (rsgName.length() > 3) { if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) { rsgName += ".rsg"; } } else { rsgName += ".rsg"; } String modelID = ""; if (rsgName.length() > 3) { if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) { modelID = rsgName.substring(0, rsgName.length() - 4); } else { modelID = rsgName.substring(0, rsgName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + rsgName); f.createNewFile(); String[] command = { "emacs", f.getName() }; Runtime.getRuntime().exec(command); refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import SBML"); if (!filename.trim().equals("")) { if (new File(filename.trim()).isDirectory()) { JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML files contain the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; for (String s : new File(filename.trim()).list()) { try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim() + separator + s); if (document.getNumErrors() == 0) { if (overwrite(root + separator + s, s)) { long numErrors = document.checkConsistency(); if (numErrors > 0) { display = true; messageArea .append(" messageArea.append(s); messageArea .append("\n for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // replace messageArea.append(i + ":" + error + "\n"); } } // FileOutputStream out = new FileOutputStream(new File(root // + separator + s)); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + s); // String doc = writer.writeToString(document); // byte[] output = doc.getBytes(); // out.write(output); // out.close(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } refreshTree(); if (display) { final JFrame f = new JFrame("SBML Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } else { String[] file = filename.trim().split(separator); try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim()); if (document.getNumErrors() > 0) { JOptionPane.showMessageDialog(frame, "Invalid SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // replace messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } // FileOutputStream out = new FileOutputStream(new File(root // + separator + file[file.length - 1])); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + file[file.length - 1]); // String doc = writer.writeToString(document); // byte[] output = doc.getBytes(); // out.write(output); // out.close(); refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import dot menu item is selected else if (e.getSource() == importDot) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit"); if (new File(filename.trim()).isDirectory()) { for (String s : new File(filename.trim()).list()) { if (!(filename.trim() + separator + s).equals("") && (filename.trim() + separator + s).length() > 3 && (filename.trim() + separator + s).substring( (filename.trim() + separator + s).length() - 4, (filename.trim() + separator + s).length()).equals(".gcm")) { try { // GCMParser parser = new GCMParser((filename.trim() + separator + s)); if (overwrite(root + separator + s, s)) { FileOutputStream out = new FileOutputStream(new File(root + separator + s)); FileInputStream in = new FileInputStream(new File( (filename.trim() + separator + s))); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { if (filename.trim().length() > 3 && !filename.trim().substring(filename.trim().length() - 4, filename.trim().length()) .equals(".gcm")) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.trim().equals("")) { String[] file = filename.trim().split(separator); try { // GCMParser parser = new GCMParser(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename.trim())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import vhdl menu item is selected else if (e.getSource() == importVhdl) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import VHDL Model"); if (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals(".vhd")) { JOptionPane.showMessageDialog(frame, "You must select a valid vhdl file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import lhpn menu item is selected else if (e.getSource() == importLhpn) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import LHPN"); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals(".g")) { JOptionPane.showMessageDialog(frame, "You must select a valid lhpn file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import csp menu item is selected else if (e.getSource() == importCsp) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import CSP"); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals(".csp")) { JOptionPane.showMessageDialog(frame, "You must select a valid csp file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import hse menu item is selected else if (e.getSource() == importHse) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import HSE"); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals(".hse")) { JOptionPane.showMessageDialog(frame, "You must select a valid handshaking expansion file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import unc menu item is selected else if (e.getSource() == importUnc) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import UNC"); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals(".unc")) { JOptionPane.showMessageDialog(frame, "You must select a valid expanded burst mode machine file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import rsg menu item is selected else if (e.getSource() == importRsg) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import RSG"); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals(".rsg")) { JOptionPane.showMessageDialog(frame, "You must select a valid rsg file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the Graph data menu item is clicked else if (e.getSource() == graph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName .trim(), true, false); addTab(graphName.trim(), g, "TSD Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == probGraph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Probability Graph:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName .trim(), false, false); addTab(graphName.trim(), g, "Probability Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLearn")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE); if (lrnName != null && !lrnName.trim().equals("")) { lrnName = lrnName.trim(); try { if (overwrite(root + separator + lrnName, lrnName)) { new File(root + separator + lrnName).mkdir(); // new FileWriter(new File(root + separator + // lrnName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn")); out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JTabbedPane lrnTab = new JTabbedPane(); lrnTab.addTab("Data Manager", new DataManager(root + separator + lrnName, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); lrnTab.addTab("Learn", new Learn(root + separator + lrnName, log, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("TSD Graph", new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator + lrnName, "time", this, null, log, null, true, true)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents ().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment (SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD Graph"); */ addTab(lrnName, lrnTab, null); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Learn View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("viewModel")) { try { if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String cmd = "atacs -llodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String cmd = "atacs -lvslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String cmd = "atacs -lcslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String cmd = "atacs -lhslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String cmd = "atacs -lxodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String cmd = "atacs -lsodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("copy") || e.getSource() == copy) { if (!tree.getFile().equals(root)) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } try { if (!copy.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".sbml") && !copy.substring(copy.length() - 4).equals(".xml")) { copy += ".sbml"; } } else { copy += ".sbml"; } if (copy.length() > 4) { if (copy.substring(copy.length() - 5).equals(".sbml")) { modelID = copy.substring(0, copy.length() - 5); } else { modelID = copy.substring(0, copy.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".vhd")) { copy += ".vhd"; } } else { copy += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".g")) { copy += ".g"; } } else { copy += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".csp")) { copy += ".csp"; } } else { copy += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".hse")) { copy += ".hse"; } } else { copy += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".unc")) { copy += ".unc"; } } else { copy += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".rsg")) { copy += ".rsg"; } } else { copy += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".grf")) { copy += ".grf"; } } else { copy += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".prb")) { copy += ".prb"; } } else { copy += ".prb"; } } } if (copy .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + copy, copy)) { if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(tree.getFile()); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy); } else if ((tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm") || tree.getFile().substring(tree.getFile().length() - 4).equals(".grf") || tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd") || tree.getFile().substring(tree.getFile().length() - 4).equals(".csp") || tree.getFile().substring(tree.getFile().length() - 4).equals(".hse") || tree.getFile().substring(tree.getFile().length() - 4).equals(".unc") || tree .getFile().substring(tree.getFile().length() - 4).equals(".rsg")) || (tree.getFile().length() >= 2 && tree.getFile().substring( tree.getFile().length() - 2).equals(".g"))) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); FileInputStream in = new FileInputStream(new File(tree.getFile())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { new File(root + separator + copy).mkdir(); // new FileWriter(new File(root + separator + copy + // separator + // ".sim")).close(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile() + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy + separator + ss); } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); FileInputStream in = new FileInputStream(new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring( ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } else { new File(root + separator + copy).mkdir(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring( ss.length() - 4).equals(".lrn"))) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".lrn")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } } refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("rename") || e.getSource() == rename) { if (!tree.getFile().equals(root)) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".sbml") && !rename.substring(rename.length() - 4).equals(".xml")) { rename += ".sbml"; } } else { rename += ".sbml"; } if (rename.length() > 4) { if (rename.substring(rename.length() - 5).equals(".sbml")) { modelID = rename.substring(0, rename.length() - 5); } else { modelID = rename.substring(0, rename.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".gcm")) { rename += ".gcm"; } } else { rename += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".vhd")) { rename += ".vhd"; } } else { rename += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".g")) { rename += ".g"; } } else { rename += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".csp")) { rename += ".csp"; } } else { rename += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".hse")) { rename += ".hse"; } } else { rename += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".unc")) { rename += ".unc"; } } else { rename += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".rsg")) { rename += ".rsg"; } } else { rename += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".grf")) { rename += ".grf"; } } else { rename += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".prb")) { rename += ".prb"; } } else { rename += ".prb"; } } if (rename .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + rename, rename)) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(root + separator + rename); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + rename); } if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".vhd") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".csp") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".hse") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".unc") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".rsg")) { updateViews(rename); } if (new File(root + separator + rename).isDirectory()) { if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").renameTo(new File(root + separator + rename + separator + rename + ".sim")); } else if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").renameTo(new File(root + separator + rename + separator + rename + ".sim")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").renameTo(new File(root + separator + rename + separator + rename + ".lrn")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").renameTo(new File(root + separator + rename + separator + rename + ".grf")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").renameTo(new File(root + separator + rename + separator + rename + ".prb")); } } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { ((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID); ((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && (tree.getFile().substring(tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring(tree.getFile().length() - 4).equals(".prb"))) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 2)); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else { JTabbedPane t = new JTabbedPane(); int selected = ((JTabbedPane) tab.getComponentAt(i)).getSelectedIndex(); boolean analysis = false; ArrayList<Component> comps = new ArrayList<Component>(); for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getTabCount(); j++) { Component c = ((JTabbedPane) tab.getComponentAt(i)).getComponent(j); comps.add(c); } for (Component c : comps) { if (c instanceof Reb2Sac) { ((Reb2Sac) c).setSim(rename); analysis = true; } else if (c instanceof SBML_Editor) { String properties = root + separator + rename + separator + rename + ".sim"; new File(properties) .renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) c).isDirty(); ((SBML_Editor) c).setParamFileAndSimDir(properties, root + separator + rename); ((SBML_Editor) c).save(false, "", true); ((SBML_Editor) c).updateSBML(i, 0); ((SBML_Editor) c).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")) .renameTo(new File(properties)); } else if (c instanceof Graph) { Graph g = ((Graph) c); g.setDirectory(root + separator + rename); if (g.isTSDGraph()) { g.setGraphName(rename + ".grf"); } else { g.setGraphName(rename + ".prb"); } } else if (c instanceof Learn) { Learn l = ((Learn) c); l.setDirectory(root + separator + rename); } else if (c instanceof DataManager) { DataManager d = ((DataManager) c); d.setDirectory(root + separator + rename); } if (analysis) { if (c instanceof Reb2Sac) { t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1).setName("Simulate"); } else if (c instanceof SBML_Editor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1).setName("SBML Editor"); } else if (c instanceof Graph) { if (((Graph) c).isTSDGraph()) { t.addTab("TSD Graph", c); t.getComponentAt(t.getComponents().length - 1).setName("TSD Graph"); } else { t.addTab("Probability Graph", c); t.getComponentAt(t.getComponents().length - 1).setName("ProbGraph"); } } else { t.addTab("Abstraction Options", c); t.getComponentAt(t.getComponents().length - 1).setName(""); } } } if (analysis) { t.setSelectedIndex(selected); tab.setComponentAt(i, t); } tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } } } refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("openGraph")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .contains(".grf")) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], true, false), "TSD Graph"); } else { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], false, false), "Probability Graph"); } } } } public int getTab(String name) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { return i; } } return -1; } public void deleteDir(File dir) { int count = 0; do { File[] list = dir.listFiles(); System.gc(); for (int i = 0; i < list.length; i++) { if (list[i].isDirectory()) { deleteDir(list[i]); } else { list[i].delete(); } } count++; } while (!dir.delete() && count != 100); if (count == 100) { JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method adds a new project to recent list */ public void addRecentProject(String projDir) { // boolean newOne = true; for (int i = 0; i < numberRecentProj; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = 0; j <= i; j++) { String save = recentProjectPaths[j]; recentProjects[j].setText(projDir.split(separator)[projDir.split(separator).length - 1]); file.add(recentProjects[j]); recentProjectPaths[j] = projDir; projDir = save; } for (int j = i + 1; j < numberRecentProj; j++) { file.add(recentProjects[j]); } return; } } if (numberRecentProj < 5) { numberRecentProj++; } for (int i = 0; i < numberRecentProj; i++) { String save = recentProjectPaths[i]; recentProjects[i].setText(projDir.split(separator)[projDir.split(separator).length - 1]); file.add(recentProjects[i]); recentProjectPaths[i] = projDir; projDir = save; } } /** * This method refreshes the menu. */ public void refresh() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema); mainPanel.add(tree, "West"); mainPanel.validate(); } /** * This method refreshes the tree. */ public void refreshTree() { tree.fixTree(); mainPanel.validate(); updateGCM(); } /** * This method adds the given Component to a tab. */ public void addTab(String name, Component panel, String tabName) { tab.addTab(name, panel); if (tabName != null) { tab.getComponentAt(tab.getComponents().length - 1).setName(tabName); } else { tab.getComponentAt(tab.getComponents().length - 1).setName(name); } tab.setSelectedIndex(tab.getComponents().length - 1); } /** * This method removes the given component from the tabs. */ public void removeTab(Component component) { tab.remove(component); } public JTabbedPane getTab() { return tab; } /** * Prompts the user to save work that has been done. */ public int save(int index) { if (tab.getComponentAt(index).getName().contains(("GCM"))) { if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) { GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index); if (editor.isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { editor.save("gcm"); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().equals("SBML Editor")) { if (tab.getComponentAt(index) instanceof SBML_Editor) { if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().contains("Graph")) { if (tab.getComponentAt(index) instanceof Graph) { if (((Graph) tab.getComponentAt(index)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else { if (tab.getComponentAt(index) instanceof JTabbedPane) { for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName().equals( "Simulate")) { if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save simulation option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "SBML Editor")) { if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save( false, "", true); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { if (((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Synthesis")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Synthesis) { if (((Synthesis) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save synthesis option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Synthesis) { ((Synthesis) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Verification")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Verification) { if (((Verification) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save verification option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Verification) { ((Verification) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Data Manager")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) { ((DataManager) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .saveChanges(tab.getTitleAt(index)); } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().contains( "Graph")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { if (((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save graph changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)); g.save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } } } return 1; } } /** * Saves a circuit from a learn view to the project view */ public void saveGcm(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Returns the frame. */ public JFrame frame() { return frame; } public void mousePressed(MouseEvent e) { if (e.isPopupTrigger() && tree.getFile() != null) { popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (tree.getFile() != null) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { addTab(theFile, new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log), "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String filename = tree.getFile(); /* * String directory = ""; String theFile = ""; if * (filename.lastIndexOf('/') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('/') + 1); theFile = * filename.substring(filename.lastIndexOf('/') + 1); } if * (filename.lastIndexOf('\\') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = * filename.substring(filename.lastIndexOf('\\') + 1); } */ String[] command = { "emacs", filename }; Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { try { String filename = tree.getFile(); /* * String directory = ""; String theFile = ""; if * (filename.lastIndexOf('/') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('/') + 1); theFile = * filename.substring(filename.lastIndexOf('/') + 1); } if * (filename.lastIndexOf('\\') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = * filename.substring(filename.lastIndexOf('\\') + 1); } */ String[] cmd = { "emacs", filename }; Runtime.getRuntime().exec(cmd); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this lhpn file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { try { String filename = tree.getFile(); /* * String directory = ""; String theFile = ""; if * (filename.lastIndexOf('/') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('/') + 1); theFile = * filename.substring(filename.lastIndexOf('/') + 1); } if * (filename.lastIndexOf('\\') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = * filename.substring(filename.lastIndexOf('\\') + 1); } */ String[] command = { "emacs", filename }; Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this csp file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { try { String filename = tree.getFile(); /* * String directory = ""; String theFile = ""; if * (filename.lastIndexOf('/') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('/') + 1); theFile = * filename.substring(filename.lastIndexOf('/') + 1); } if * (filename.lastIndexOf('\\') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = * filename.substring(filename.lastIndexOf('\\') + 1); } */ String[] command = { "emacs", filename }; Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this hse file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { try { String filename = tree.getFile(); /* * String directory = ""; String theFile = ""; if * (filename.lastIndexOf('/') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('/') + 1); theFile = * filename.substring(filename.lastIndexOf('/') + 1); } if * (filename.lastIndexOf('\\') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = * filename.substring(filename.lastIndexOf('\\') + 1); } */ String[] command = { "emacs", filename }; Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this unc file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { try { String filename = tree.getFile(); /* * String directory = ""; String theFile = ""; if * (filename.lastIndexOf('/') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('/') + 1); theFile = * filename.substring(filename.lastIndexOf('/') + 1); } if * (filename.lastIndexOf('\\') >= 0) { directory = * filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = * filename.substring(filename.lastIndexOf('\\') + 1); } */ String[] command = { "emacs", filename }; Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree .getFile(), log, tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1], true, false), "TSD Graph"); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree .getFile(), log, tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1], false, false), "Probability Graph"); } } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } if (sim) { openSim(); } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else { openLearn(); } } } } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger() && tree.getFile() != null) { popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.add(createAnalysis); popup.add(createLearn); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } private void simulate(boolean isDot) throws Exception { if (isDot) { String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String[] dot = tree.getFile().split(separator); String sbmlFile = /* * root + separator + simName + separator + */(dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + simName + separator + sbmlFile); try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + separator + (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(), log, simTab, null); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } else { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile()); // document.setLevel(2); document.setLevelAndVersion(2, 3); String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String sbmlFile = tree.getFile(); String[] sbml1 = tree.getFile().split(separator); String sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((sbml1[sbml1.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } new FileOutputStream(new File(sbmlFileProp)).close(); /* * try { FileOutputStream out = new FileOutputStream(new * File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); String doc = * writer.writeToString(document); byte[] output = doc.getBytes(); * out.write(output); out.close(); } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy sbml file to * output location.", "Error", JOptionPane.ERROR_MESSAGE); } */ refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(), log, simTab, null); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } } private void openLearn() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i] .substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(), this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); lrnTab.addTab("Learn", new Learn(tree.getFile(), log, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("TSD Graph", new Graph(null, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, true)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * else { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(), * this)); lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data available"); * font = noData1.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD * Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openSynth() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel synthPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i] .substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String synthFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn"; String synthFile2 = tree.getFile() + separator + ".syn"; Properties load = new Properties(); String synthesisFile = ""; try { if (new File(synthFile2).exists()) { FileInputStream in = new FileInputStream(new File(synthFile2)); load.load(in); in.close(); new File(synthFile2).delete(); } if (new File(synthFile).exists()) { FileInputStream in = new FileInputStream(new File(synthFile)); load.load(in); in.close(); if (load.containsKey("synthesis.file")) { synthesisFile = load.getProperty("synthesis.file"); synthesisFile = synthesisFile.split(separator)[synthesisFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(synthesisFile)); load.store(out, synthesisFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(synthesisFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + synthesisFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { synthPanel.add(new Synthesis(tree.getFile(), "flag", log, this)); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], synthPanel, null); } } private void openVerify() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel verPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i] .substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String verFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".ver"; String verFile2 = tree.getFile() + separator + ".ver"; Properties load = new Properties(); String verifyFile = ""; try { if (new File(verFile2).exists()) { FileInputStream in = new FileInputStream(new File(verFile2)); load.load(in); in.close(); new File(verFile2).delete(); } if (new File(verFile).exists()) { FileInputStream in = new FileInputStream(new File(verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(verifyFile)); load.store(out, verifyFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(verifyFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(verFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { verPanel.add(new Verification(tree.getFile(), "flag", log, this)); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], verPanel, null); } } private void openSim() { String filename = tree.getFile(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(filename.split(separator)[filename.split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (filename != null && !filename.equals("")) { if (new File(filename).isDirectory()) { if (new File(filename + separator + ".sim").exists()) { new File(filename + separator + ".sim").delete(); } String[] list = new File(filename).list(); String getAFile = ""; // String probFile = ""; String openFile = ""; // String graphFile = ""; String open = null; String openProb = null; int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals("sbml")) { getAFile = filename + separator + list[i]; } else if (end.equals(".xml") && getAFile.equals("")) { getAFile = filename + separator + list[i]; } else if (end.equals(".txt") && list[i].contains("sim-rep")) { // probFile = filename + separator + list[i]; } else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) { openFile = filename + separator + list[i]; } else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = filename + separator + // list[i]; } } else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) { // graphFile = filename + separator + // list[i]; } else if (end.contains("=")) { // graphFile = filename + separator + // list[i]; } } else if (end.equals(".grf")) { open = filename + separator + list[i]; } else if (end.equals(".prb")) { openProb = filename + separator + list[i]; } } else if (new File(filename + separator + list[i]).isDirectory()) { String[] s = new File(filename + separator + list[i]).list(); for (int j = 0; j < s.length; j++) { if (s[j].contains("sim-rep")) { // probFile = filename + separator + list[i] // + separator + } else if (s[j].contains(".tsd")) { // graphFile = filename + separator + // list[i] + separator + } } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"; String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; if (new File(pmsFile).exists()) { if (new File(simFile).exists()) { new File(pmsFile).delete(); } else { new File(pmsFile).renameTo(new File(simFile)); } } String sbmlLoadFile = ""; if (new File(simFile).exists()) { try { Scanner s = new Scanner(new File(simFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]; if (sbmlLoadFile.equals("")) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + "the sbml linked to this view is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!(new File(root + separator + sbmlLoadFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (s.hasNextLine()) { s.nextLine(); } s.close(); File f = new File(sbmlLoadFile); if (!f.exists()) { sbmlLoadFile = root + separator + f.getName(); } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else { sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1]; if (!new File(sbmlLoadFile).exists()) { sbmlLoadFile = getAFile; /* * JOptionPane.showMessageDialog(frame, "Unable to load sbml * file.", "Error", JOptionPane.ERROR_MESSAGE); return; */ } } if (!new File(sbmlLoadFile).exists()) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1] + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); // if (open != null) { simTab.addTab("TSD Graph", reb2sac.createGraph(open)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); /* * } else if (!graphFile.equals("")) { simTab.addTab("TSD Graph", * reb2sac.createGraph(open)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } / else { JLabel noData = new * JLabel("No data available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } */ // if (openProb != null) { simTab.addTab("Probability Graph", reb2sac.createProbGraph(openProb)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * } else if (!probFile.equals("")) { simTab.addTab("Probability * Graph", reb2sac.createProbGraph(openProb)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } else { JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment (SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } /** * Embedded class that allows tabs to be closed. */ class TabbedPaneCloseButtonUI extends BasicTabbedPaneUI { public TabbedPaneCloseButtonUI() { super(); } protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect); Rectangle rect = rects[tabIndex]; g.setColor(Color.black); g.drawRect(rect.x + rect.width - 19, rect.y + 4, 13, 12); g.drawLine(rect.x + rect.width - 16, rect.y + 7, rect.x + rect.width - 10, rect.y + 13); g.drawLine(rect.x + rect.width - 10, rect.y + 7, rect.x + rect.width - 16, rect.y + 13); g.drawLine(rect.x + rect.width - 15, rect.y + 7, rect.x + rect.width - 9, rect.y + 13); g.drawLine(rect.x + rect.width - 9, rect.y + 7, rect.x + rect.width - 15, rect.y + 13); } protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + 24; } protected MouseListener createMouseListener() { return new MyMouseHandler(); } class MyMouseHandler extends MouseHandler { public MyMouseHandler() { super(); } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); int tabIndex = -1; int tabCount = tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (rects[i].contains(x, y)) { tabIndex = i; break; } } if (tabIndex >= 0 && !e.isPopupTrigger()) { Rectangle tabRect = rects[tabIndex]; y = y - tabRect.y; if ((x >= tabRect.x + tabRect.width - 18) && (x <= tabRect.x + tabRect.width - 8) && (y >= 5) && (y <= 15)) { if (save(tabIndex) == 1) { tabPane.remove(tabIndex); } } } } } } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public JMenuItem getExitButton() { return exit; } /** * This is the main method. It excecutes the BioSim GUI FrontEnd program. */ public static void main(String args[]) { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname + " environment variable does not include\nthe" + " directory containing the libsbml library file."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment" + " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file."); System.exit(1); } catch (SecurityException e) { System.err.println("Could not load the libSBML library files due to a" + " security exception."); System.exit(1); } if (args.length > 0 && args[0].equals("-lema")) { new BioSim(true); } else { new BioSim(false); } } public void copySim(String newSim) { try { new File(root + separator + newSim).mkdir(); // new FileWriter(new File(root + separator + newSim + separator + // ".sim")).close(); String oldSim = tab.getTitleAt(tab.getSelectedIndex()); String[] s = new File(root + separator + oldSim).list(); String sbmlFile = ""; String propertiesFile = ""; String sbmlLoadFile = null; for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(root + separator + oldSim + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + newSim + separator + ss); sbmlFile = root + separator + newSim + separator + ss; } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); propertiesFile = root + separator + newSim + separator + ss; } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring(ss.length() - 4) .equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else { out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); } FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); if (ss.substring(ss.length() - 4).equals(".pms")) { if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) { new File(root + separator + newSim + separator + ss).delete(); } else { new File(root + separator + newSim + separator + ss).renameTo(new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim")); } ss = ss.substring(0, ss.length() - 4) + ".sim"; } if (ss.substring(ss.length() - 4).equals(".sim")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (scan.hasNextLine()) { scan.nextLine(); } scan.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD * Graph"); JLabel noData1 = new JLabel("No data available"); Font font1 = * noData1.getFont(); font1 = font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ tab.setComponentAt(tab.getSelectedIndex(), simTab); tab.setTitleAt(tab.getSelectedIndex(), newSim); tab.getComponentAt(tab.getSelectedIndex()).setName(newSim); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } public void refreshLearn(String learnName, boolean data) { for (int i = 0; i < tab.getComponentCount(); i++) { if (tab.getTitleAt(i).equals(learnName)) { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals("TSD Graph")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) { ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)).refresh(); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null, "amount", learnName + " data", "tsd.printer", root + separator + learnName, "time", this, null, log, null, true, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("TSD Graph"); } /* * } else { JLabel noData1 = new JLabel("No data available"); Font * font = noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); noData1.setHorizontalAlignment * (SwingConstants.CENTER); ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData1); ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j ).setName("TSD Graph"); } */ } else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) { } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn(root + separator + learnName, log, this)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("Learn"); } /* * } else { JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, noData); * ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j * ).setName("Learn"); } */ } } } } } private void updateGCM() { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles(); tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename()); } } } public void updateViews(String updatedFile) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".sim"; String properties2 = root + separator + tab + separator + tab + ".lrn"; if (new File(properties).exists()) { String check = ""; try { Scanner s = new Scanner(new File(properties)); if (s.hasNextLine()) { check = s.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } s.close(); } catch (Exception e) { } if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("SBML Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty(); ((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true); if (updatedFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + updatedFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); } else { ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile); } ((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File(properties)); } } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } ArrayList<String> saved = new ArrayList<String>(); if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { saved.add(this.tab.getTitleAt(i)); GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i); if (gcm.getSBMLFile().equals(updatedFile)) { gcm.save("save"); } } String[] files = new File(root).list(); for (String s : files) { if (s.contains(".gcm") && !saved.contains(s)) { GCMFile gcm = new GCMFile(); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(updatedFile)) { updateViews(s); } } } } } public String getRoot() { return root; } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, name + " already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { String[] views = canDelete(name); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { tab.remove(i); } } File dir = new File(fullPath); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } return true; } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to overwrite file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File", JOptionPane.ERROR_MESSAGE); return false; } } else { return false; } } else { return true; } } public void updateOpenSBML(String sbmlName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (sbmlName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof SBML_Editor) { SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null); this.tab.setComponentAt(i, newSBML); this.tab.getComponentAt(i).setName("SBML Editor"); newSBML.save(false, "", false); } } } } private String[] canDelete(String filename) { ArrayList<String> views = new ArrayList<String>(); String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } scan.close(); } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } if (check.equals(filename)) { views.add(s); } } } String[] usingViews = views.toArray(new String[0]); sort(usingViews); return usingViews; } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } private void reassignViews(String oldName, String newName) { String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { ArrayList<String> copy = new ArrayList<String>(); Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; if (check.equals(oldName)) { while (scan.hasNextLine()) { copy.add(scan.nextLine()); } scan.close(); FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim")); out.write((newName + "\n").getBytes()); for (String cop : copy) { out.write((cop + "\n").getBytes()); } out.close(); } else { scan.close(); } } } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; if (check.equals(oldName)) { p.setProperty("genenet.file", newName); FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn")); p.store(store, "Learn File Data"); store.close(); } } } catch (Exception e) { } } } } } }
package modules.admin.User; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.skyve.CORE; import org.skyve.EXT; import org.skyve.domain.Bean; import org.skyve.domain.messages.Message; import org.skyve.domain.messages.ValidationException; import org.skyve.domain.types.DateTime; import org.skyve.metadata.SortDirection; import org.skyve.metadata.controller.ImplicitActionName; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.customer.CustomerRole; import org.skyve.metadata.model.document.Bizlet; import org.skyve.metadata.module.Module; import org.skyve.metadata.user.Role; import org.skyve.persistence.DocumentQuery; import org.skyve.persistence.Persistence; import org.skyve.util.Binder; import org.skyve.web.WebContext; import modules.admin.Configuration.ComplexityModel; import modules.admin.domain.ChangePassword; import modules.admin.domain.Configuration; import modules.admin.domain.Contact; import modules.admin.domain.DataGroup; import modules.admin.domain.Group; import modules.admin.domain.User; import modules.admin.domain.User.GroupSelection; import modules.admin.domain.User.WizardState; public class UserBizlet extends Bizlet<UserExtension> { private static final long serialVersionUID = 5947293714061984815L; /** * Populate the data group association if required. */ @Override public UserExtension newInstance(UserExtension bean) throws Exception { Persistence persistence = CORE.getPersistence(); org.skyve.metadata.user.User user = persistence.getUser(); String myDataGroupId = user.getDataGroupId(); if (myDataGroupId != null) { DocumentQuery query = persistence.newDocumentQuery(DataGroup.MODULE_NAME, DataGroup.DOCUMENT_NAME); query.getFilter().addEquals(Bean.DOCUMENT_ID, myDataGroupId); List<DataGroup> dataGroups = query.beanResults(); for (DataGroup dataGroup : dataGroups) { bean.setDataGroup(dataGroup); } // ensure that the new user record belongs to user's data group bean.setBizDataGroupId(myDataGroupId); } // set defaults bean.setCreatedDateTime(new DateTime()); bean.setWizardState(WizardState.confirmContact); // check whether creating a new security group will be mandatory when creating a user // this occurs if there are no security groups yet defined DocumentQuery q = CORE.getPersistence().newDocumentQuery(Group.MODULE_NAME, Group.DOCUMENT_NAME); bean.setGroupSelection((q.beanResults().isEmpty() ? GroupSelection.newGroup : GroupSelection.existingGroups)); bean.setGroupsExist((q.beanResults().isEmpty() ? Boolean.FALSE : Boolean.TRUE)); return bean; } public static String bizKey(User user) { org.skyve.metadata.user.User mUser = CORE.getUser(); StringBuilder sb = new StringBuilder(64); try { Customer customer = mUser.getCustomer(); if (Boolean.TRUE.equals(user.getInactive())) { sb.append("INACTIVE "); } sb.append(Binder.formatMessage(customer, "{userName} - {contact.bizKey}", user)); } catch (@SuppressWarnings("unused") Exception e) { sb.append("Unknown"); } return sb.toString(); } @Override public void preRerender(String source, UserExtension bean, WebContext webContext) throws Exception { if (User.groupSelectionPropertyName.equals(source)) { if (GroupSelection.newGroup.equals(bean.getGroupSelection())) { bean.setNewGroup(Group.newInstance()); } else { bean.setNewGroup(null); } } super.preRerender(source, bean, webContext); } @Override public UserExtension preExecute(ImplicitActionName actionName, UserExtension bean, Bean parentBean, WebContext webContext) throws Exception { if (ImplicitActionName.Save.equals(actionName) || ImplicitActionName.OK.equals(actionName)) { // if a new group was created, assign the user to the group membership if (bean.getNewGroup() != null) { bean.getGroups().add(bean.getNewGroup()); } } return super.preExecute(actionName, bean, parentBean, webContext); } /** * Ensure that if a password is entered, it is applied to the user's hashed * password. */ @Override public void validate(UserExtension user, ValidationException e) throws Exception { validateUserContact(user, e); validateUserNameAndPassword(user, e); validateGroups(user, e); // ensure that the user record belongs to assigned user's data group user.setBizDataGroupId((user.getDataGroup() != null) ? user.getDataGroup().getBizId() : null); } @Override public List<DomainValue> getVariantDomainValues(String fieldName) throws Exception { Persistence persistence = CORE.getPersistence(); if (User.groupsPropertyName.equals(fieldName)) { DocumentQuery query = persistence.newDocumentQuery(Group.MODULE_NAME, Group.DOCUMENT_NAME); query.addBoundOrdering(Group.namePropertyName, SortDirection.ascending); List<Group> groups = query.beanResults(); List<DomainValue> result = new ArrayList<>(groups.size()); for (Group group : groups) { result.add(new DomainValue(group.getBizId(), group.getBizKey())); } return result; } else if (User.dataGroupPropertyName.equals(fieldName)) { DocumentQuery query = persistence.newDocumentQuery(DataGroup.MODULE_NAME, DataGroup.DOCUMENT_NAME); query.addBoundOrdering(DataGroup.namePropertyName, SortDirection.ascending); List<DataGroup> groups = query.beanResults(); List<DomainValue> result = new ArrayList<>(groups.size()); for (DataGroup group : groups) { result.add(new DomainValue(group.getBizId(), group.getBizKey())); } return result; } else if (User.homeModulePropertyName.equals(fieldName)) { org.skyve.metadata.user.User user = persistence.getUser(); Customer customer = user.getCustomer(); Set<String> moduleNames = user.getAccessibleModuleNames(); List<DomainValue> result = new ArrayList<>(); for (String moduleName : moduleNames) { result.add(new DomainValue(moduleName, customer.getModule(moduleName).getTitle())); } return result; } return super.getVariantDomainValues(fieldName); } public static List<DomainValue> getCustomerRoleValues(org.skyve.metadata.user.User user) { List<DomainValue> result = new ArrayList<>(); Customer customer = user.getCustomer(); // Add customer roles for (CustomerRole role : customer.getRoles()) { result.add(new DomainValue(role.getName())); } if (customer.isAllowModuleRoles()) { for (Module module : customer.getModules()) { for (Role role : module.getRoles()) { String roleName = role.getName(); String roleDescription = role.getDescription(); if (roleDescription != null) { if (roleDescription.length() > 50) { roleDescription = roleDescription.substring(0, 47) + "..."; } result.add(new DomainValue(String.format("%s.%s", module.getName(), roleName), String.format("%s - %s (%s)", module.getTitle(), roleName, roleDescription))); } else { result.add(new DomainValue(String.format("%s.%s", module.getName(), roleName), String.format("%s - %s", module.getTitle(), roleName))); } } } } return result; } @Override public void preSave(UserExtension bean) throws Exception { if (bean.getGeneratedPassword() != null) { bean.setPasswordExpired(Boolean.TRUE); } // contact must be same datagroup as user if (bean.getContact() != null) { if (bean.getDataGroup() == null) { bean.getContact().setBizDataGroupId(null); } else { bean.getContact().setBizDataGroupId(bean.getDataGroup().getBizId()); } } } /** * Reset the assigned roles model. */ @Override public void postSave(UserExtension bean) throws Exception { bean.clearAssignedRoles(); bean.setNewGroup(null); bean.setNewPassword(null); } public static void validateUserContact(UserExtension bean, ValidationException e) { if (bean.getContact() == null) { e.getMessages().add(new Message(Binder.createCompoundBinding(User.contactPropertyName, Contact.namePropertyName), "You must specify a contact person for this user.")); } else if (bean.getContact().getName() == null) { e.getMessages().add(new Message(Binder.createCompoundBinding(User.contactPropertyName, Contact.namePropertyName), "You must enter a name.")); } else if (bean.getContact().getEmail1() == null) { e.getMessages().add(new Message(Binder.createCompoundBinding(User.contactPropertyName, Contact.email1PropertyName), "You must enter an email address.")); } } public static void validateUserNameAndPassword(UserExtension user, ValidationException e) throws Exception { // validate username is not null, not too short and unique if (user.getUserName() == null) { e.getMessages().add(new Message(User.userNamePropertyName, "Username is required.")); } else if (!user.isPersisted() && user.getUserName().length() < ComplexityModel.MINIMUM_USERNAME_LENGTH) { e.getMessages().add(new Message(User.userNamePropertyName, "Username is too short.")); } else { Persistence pers = CORE.getPersistence(); DocumentQuery q = pers.newDocumentQuery(User.MODULE_NAME, User.DOCUMENT_NAME); q.getFilter().addEquals(User.userNamePropertyName, user.getUserName()); q.getFilter().addNotEquals(Bean.DOCUMENT_ID, user.getBizId()); List<User> otherUsers = q.beanResults(); if (!otherUsers.isEmpty()) { e.getMessages().add(new Message(User.userNamePropertyName, "This username is already being used - try again.")); } else { // validate password String hashedPassword = user.getPassword(); String newPassword = user.getNewPassword(); String confirmPassword = user.getConfirmPassword(); if ((newPassword == null) && (confirmPassword == null)) { if (hashedPassword == null) { Message message = new Message(User.newPasswordPropertyName, "A password is required."); message.addBinding(User.confirmPasswordPropertyName); e.getMessages().add(message); } } else { if ((newPassword == null) || (confirmPassword == null)) { Message message = new Message(User.newPasswordPropertyName, "New Password and Confirm Password are required to change the password."); message.addBinding(User.confirmPasswordPropertyName); e.getMessages().add(message); } else if (newPassword.equals(confirmPassword)) { // check for suitable complexity Configuration configuration = Configuration.newInstance(); ComplexityModel cm = new ComplexityModel(configuration.getPasswordComplexityModel()); if (!newPassword.matches(cm.getComparison())) { StringBuilder sb = new StringBuilder(64); sb.append("The password you have entered is not sufficiently complex. "); sb.append(cm.getRule()); sb.append(" Please re-enter and confirm the password."); Message message = new Message(ChangePassword.newPasswordPropertyName, sb.toString()); e.getMessages().add(message); } hashedPassword = EXT.hashPassword(newPassword); user.setPassword(hashedPassword); // clear reset password details if (user.getGeneratedPassword() != null && !user.getGeneratedPassword().equals(user.getNewPassword())) { user.setPasswordExpired(Boolean.FALSE); user.setGeneratedPassword(null); user.setPasswordLastChanged(new DateTime()); } // clear out the new password entry fields user.setNewPassword(null); user.setConfirmPassword(null); } else { Message message = new Message(User.newPasswordPropertyName, "You did not type the same password. Please re-enter the password again."); message.addBinding(User.confirmPasswordPropertyName); e.getMessages().add(message); } } } } } public static void validateGroups(User user, ValidationException e) { if (user.getRoles().isEmpty() && user.getGroups().isEmpty()) { e.getMessages().add(new Message("At least 1 role or group is required to enable correct login for this user.")); } } }
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.CompatibilityFixer; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; import gcm2sbml.util.GlobalConstants; import graph.Graph; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTabbedPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.plaf.basic.BasicTabbedPaneUI; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import learn.Learn; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; /** * This class creates a GUI for the Tstubd program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * are selected. * * @author Curtis Madsen */ public class BioSim implements MouseListener, ActionListener { private JFrame frame; // Frame where components of the GUI are displayed private JMenu file; // The file menu private JMenuItem newProj; // The new menu item private JMenuItem newModel; // The new menu item private JMenuItem newCircuit; // The new menu item private JMenuItem exit; // The exit menu item private JMenuItem importSbml; // The import sbml menu item private JMenuItem importDot; // The import dot menu item private JMenuItem manual; // The manual menu item private JMenuItem about; // The about menu item private JMenuItem openProj; // The open menu item private JMenuItem pref; // The preferences menu item private JMenuItem graph; // The graph menu item private JMenuItem probGraph; private String root; // The root directory private FileTree tree; // FileTree private JTabbedPane tab; // JTabbedPane for different tools private JPanel mainPanel; // the main panel private Log log; // the log private JPopupMenu popup; // popup menu private String separator; private KeyEventDispatcher dispatcher; private JMenuItem recentProjects[]; private String recentProjectPaths[]; private int numberRecentProj; private int ShortCutKey; public boolean checkUndeclared, checkUnits; private JCheckBox Undeclared, Units; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean lema; public class MacOSAboutHandler extends Application { public MacOSAboutHandler() { addApplicationListener(new AboutBoxHandler()); } class AboutBoxHandler extends ApplicationAdapter { public void handleAbout(ApplicationEvent event) { about(); event.setHandled(true); } } } public class MacOSPreferencesHandler extends Application { public MacOSPreferencesHandler() { addApplicationListener(new PreferencesHandler()); } class PreferencesHandler extends ApplicationAdapter { public void handlePreferences(ApplicationEvent event) { preferences(); event.setHandled(true); } } } public class MacOSQuitHandler extends Application { public MacOSQuitHandler() { addApplicationListener(new QuitHandler()); } class QuitHandler extends ApplicationAdapter { public void handleQuit(ApplicationEvent event) { exit(); event.setHandled(true); } } } /** * This is the constructor for the Proj class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. * * @throws Exception */ public BioSim(boolean lema) { this.lema = lema; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Creates a new frame frame = new JFrame("iBioSim"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png").getImage()); // Makes it so that clicking the x in the corner closes the program WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { exit.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; frame.addWindowListener(w); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); popup = new JPopupMenu(); // Creates a menu for the frame JMenuBar menuBar = new JMenuBar(); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); JMenu help = new JMenu("Help"); help.setMnemonic(KeyEvent.VK_H); JMenu importMenu = new JMenu("Import"); JMenu newMenu = new JMenu("New"); menuBar.add(file); menuBar.add(help); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); pref = new JMenuItem("Preferences"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); graph = new JMenuItem("TSD Graph"); probGraph = new JMenuItem("Probability Graph"); importSbml = new JMenuItem("SBML Model"); importDot = new JMenuItem("Genetic Circuit Model"); exit = new JMenuItem("Exit"); openProj.addActionListener(this); pref.addActionListener(this); manual.addActionListener(this); newProj.addActionListener(this); newCircuit.addActionListener(this); newModel.addActionListener(this); exit.addActionListener(this); about.addActionListener(this); importSbml.addActionListener(this); importDot.addActionListener(this); graph.addActionListener(this); probGraph.addActionListener(this); ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ShortCutKey)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey)); newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ShortCutKey)); newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ShortCutKey)); probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey)); importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, ShortCutKey)); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); newCircuit.setMnemonic(KeyEvent.VK_G); newCircuit.setDisplayedMnemonicIndex(8); newModel.setMnemonic(KeyEvent.VK_S); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_R); importDot.setMnemonic(KeyEvent.VK_E); importDot.setDisplayedMnemonicIndex(14); importSbml.setMnemonic(KeyEvent.VK_B); importDot.setEnabled(false); importSbml.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); file.add(newMenu); newMenu.add(newProj); newMenu.add(newCircuit); newMenu.add(newModel); newMenu.add(graph); newMenu.add(probGraph); file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(importMenu); importMenu.add(importDot); importMenu.add(importSbml); file.addSeparator(); help.add(manual); if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { file.add(pref); file.add(exit); file.addSeparator(); help.add(about); } root = null; // Create recent project menu items numberRecentProj = 0; recentProjects = new JMenuItem[5]; recentProjectPaths = new String[5]; for (int i = 0; i < 5; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_5); Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < 5; i++) { recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } if (biosimrc.get("biosim.check.undeclared", "").equals("false")) { checkUndeclared = false; } else { checkUndeclared = true; } if (biosimrc.get("biosim.check.units", "").equals("false")) { checkUnits = false; } else { checkUnits = true; } if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KREP_VALUE", ".5"); } if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KACT_VALUE", ".0033"); } if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBIO_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2"); } if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001"); } if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.OCR_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075"); } if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_VALUE", "30"); } if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2"); } if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25"); } if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1"); } if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.INITIAL_VALUE", "0"); } // Open .biosimrc here // Packs the frame and displays it mainPanel = new JPanel(new BorderLayout()); tree = new FileTree(null, this); log = new Log(); tab = new JTabbedPane(); tab.setPreferredSize(new Dimension(1050, 550)); tab.setUI(new TabbedPaneCloseButtonUI()); mainPanel.add(tree, "West"); mainPanel.add(tab, "Center"); mainPanel.add(log, "South"); frame.setContentPane(mainPanel); frame.setJMenuBar(menuBar); frame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; frame.setLocation(x, y); frame.setVisible(true); dispatcher = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_TYPED) { if (e.getKeyChar() == '') { if (tab.getTabCount() > 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher( dispatcher); if (save(tab.getSelectedIndex()) != 0) { tab.remove(tab.getSelectedIndex()); } KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( dispatcher); } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); } public void preferences() { final JFrame f = new JFrame("Preferences"); Undeclared = new JCheckBox("Check for undeclared units in SBML"); if (checkUndeclared) { Undeclared.setSelected(true); } else { Undeclared.setSelected(false); } Units = new JCheckBox("Check units in SBML"); if (checkUnits) { Units.setSelected(true); } else { Units.setSelected(false); } Preferences biosimrc = Preferences.userRoot(); final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get("biosim.gcm.ACTIVED_VALUE", "")); final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", "")); final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", "")); final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.COOPERATIVITY_VALUE", "")); final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KASSOCIATION_VALUE", "")); final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", "")); final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get( "biosim.gcm.PROMOTER_COUNT_VALUE", "")); final JTextField INITIAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.INITIAL_VALUE", "")); final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc .get("biosim.gcm.MAX_DIMER_VALUE", "")); final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", "")); final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.RNAP_BINDING_VALUE", "")); final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", "")); final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.STOICHIOMETRY_VALUE", "")); JPanel labels = new JPanel(new GridLayout(15, 1)); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KASSOCIATION_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(15, 1)); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KBIO_VALUE); fields.add(KDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(KASSOCIATION_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_VALUE); fields.add(MAX_DIMER_VALUE); fields.add(OCR_VALUE); fields.add(RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); sbmlPrefsBordered.add(Undeclared, "North"); sbmlPrefsBordered.add(Units, "Center"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("SBML Preferences", sbmlPrefs); prefTabs.addTab("GCM Preferences", gcmPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (Undeclared.isSelected()) { checkUndeclared = true; biosimrc.put("biosim.check.undeclared", "true"); } else { checkUndeclared = false; biosimrc.put("biosim.check.undeclared", "false"); } if (Units.isSelected()) { checkUnits = true; biosimrc.put("biosim.check.units", "true"); } else { checkUnits = false; biosimrc.put("biosim.check.units", "false"); } try { Double.parseDouble(KREP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KACT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBIO_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KASSOCIATION_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBASAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(OCR_VALUE.getText().trim()); biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(COOPERATIVITY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ACTIVED_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(MAX_DIMER_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(INITIAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim()); } catch (Exception e1) { } f.dispose(); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters(); ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters(); } } } else { } } public void about() { final JFrame f = new JFrame("About"); // frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + File.separator // + "gui" // + File.separator + "icons" + File.separator + "iBioSim.png").getImage()); JLabel bioSim = new JLabel("iBioSim", JLabel.CENTER); Font font = bioSim.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); bioSim.setFont(font); JLabel version = new JLabel("Version 1.0", JLabel.CENTER); JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER); JButton credits = new JButton("Credits"); credits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] options = { "Close" }; JOptionPane.showOptionDialog(f, "Nathan Barker\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen", "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } }); JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(credits); buttons.add(close); JPanel aboutPanel = new JPanel(new BorderLayout()); JPanel uOfUPanel = new JPanel(new BorderLayout()); uOfUPanel.add(bioSim, "North"); uOfUPanel.add(version, "Center"); uOfUPanel.add(uOfU, "South"); aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png")), "North"); // aboutPanel.add(bioSim, "North"); aboutPanel.add(uOfUPanel, "Center"); aboutPanel.add(buttons, "South"); f.setContentPane(aboutPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } public void exit() { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < numberRecentProj; i++) { biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText()); biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]); } System.exit(1); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == about) { about(); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = "iBioSim.html"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } File work = new File(directory); log.addText("Executing:\n" + command + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command + theFile, null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the exit menu item is selected else if (e.getSource() == exit) { exit(); } // if the open popup menu is selected on a sim directory else if (e.getActionCommand().equals("openSim")) { openSim(); } else if (e.getActionCommand().equals("openLearn")) { openLearn(); } // if the create simulation popup menu is selected on a dot file else if (e.getActionCommand().equals("createSim")) { try { simulate(true); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the simulate popup menu is selected on an sbml file else if (e.getActionCommand().equals("simulate")) { try { simulate(false); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the delete popup menu is selected on a sim directory else if (e.getActionCommand().equals("deleteSim")) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } refreshTree(); } // if the delete popup menu is selected else if (e.getActionCommand().equals("delete")) { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); refreshTree(); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("createSBML")) { try { String[] dot = tree.getFile().split(separator); String sbmlFile = dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"; // log.addText("Executing:\ngcm2sbml.pl " + tree.getFile() + " " + root // + separator + sbmlFile // Runtime exec = Runtime.getRuntime(); // String filename = tree.getFile(); // String directory = ""; // String theFile = ""; // if (filename.lastIndexOf('/') >= 0) { // directory = filename.substring(0, // filename.lastIndexOf('/') + 1); // theFile = filename.substring(filename.lastIndexOf('/') + 1); // if (filename.lastIndexOf('\\') >= 0) { // directory = filename.substring(0, filename // .lastIndexOf('\\') + 1); // theFile = filename // .substring(filename.lastIndexOf('\\') + 1); // File work = new File(directory); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + sbmlFile); refreshTree(); addTab(sbmlFile, new SBML_Editor(root + separator + sbmlFile, null, log, this, null, null), "SBML Editor"); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("dotEditor")) { try { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { File work = new File(directory); addTab(theFile, new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log), "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, 1, 1, 1, tree.getFile().substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the browse popup menu is selected on an sbml file else if (e.getActionCommand().equals("browse")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, 1, 1, 1, tree.getFile().substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + tree.getFile() + "\n"); Runtime exec = Runtime.getRuntime(); Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); String error = ""; String output = ""; InputStream reb = browse.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = browse.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } browse.waitFor(); String command = ""; if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { command = "cmd /c start "; } log.addText("Executing:\n" + command + directory + out + ".xhtml\n"); exec.exec(command + out + ".xhtml", null, work); } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph dot popup menu is selected else if (e.getActionCommand().equals("graphDot")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new menu item is selected else if (e.getSource() == newProj) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } String filename = Buttons.browse(frame, null, null, JFileChooser.DIRECTORIES_ONLY, "New"); if (!filename.trim().equals("")) { filename = filename.trim(); File f = new File(filename); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return; } } new File(filename).mkdir(); try { new FileWriter(new File(filename + separator + ".prj")).close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbml.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } } // if the open project menu item is selected else if (e.getSource() == pref) { preferences(); } else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } File f; if (root == null) { f = null; } else { f = new File(root); } String projDir = ""; if (e.getSource() == openProj) { projDir = Buttons.browse(frame, f, null, JFileChooser.DIRECTORIES_ONLY, "Open"); } else if (e.getSource() == recentProjects[0]) { projDir = recentProjectPaths[0]; } else if (e.getSource() == recentProjects[1]) { projDir = recentProjectPaths[1]; } else if (e.getSource() == recentProjects[2]) { projDir = recentProjectPaths[2]; } else if (e.getSource() == recentProjects[3]) { projDir = recentProjectPaths[3]; } else if (e.getSource() == recentProjects[4]) { projDir = recentProjectPaths[4]; } if (!projDir.equals("")) { if (new File(projDir).isDirectory()) { boolean isProject = false; for (String temp : new File(projDir).list()) { if (temp.equals(".prj")) { isProject = true; } } if (isProject) { root = projDir; refresh(); tab.removeAll(); addRecentProject(projDir); importDot.setEnabled(true); importSbml.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new circuit model menu item is selected else if (e.getSource() == newCircuit) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 4).equals(".gcm")) { simName += ".gcm"; } } else { simName += ".gcm"; } String modelID = ""; if (simName.length() > 3) { if (simName.substring(simName.length() - 4).equals(".gcm")) { modelID = simName.substring(0, simName.length() - 4); } else { modelID = simName.substring(0, simName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); new GCMFile().save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } addTab(f.getName(), new GCM2SBMLEditor(root + separator, f.getName(), this, log), "GCM Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new SBML model menu item is selected else if (e.getSource() == newModel) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) { simName += ".sbml"; } } else { simName += ".sbml"; } String modelID = ""; if (simName.length() > 4) { if (simName.substring(simName.length() - 5).equals(".sbml")) { modelID = simName.substring(0, simName.length() - 5); } else { modelID = simName.substring(0, simName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane.showMessageDialog(frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(2, 3); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); document.getModel().setId(modelID); FileOutputStream out = new FileOutputStream(f); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); addTab( f.getAbsolutePath().split(separator)[f.getAbsolutePath().split(separator).length - 1], new SBML_Editor(f.getAbsolutePath(), null, log, this, null, null), "SBML Editor"); refreshTree(); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import SBML"); if (!filename.equals("")) { String[] file = filename.split(separator); try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename); if (document.getNumErrors() > 0) { JOptionPane.showMessageDialog(frame, "Invalid SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } else { long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); String message = "Imported SBML file contains the errors listed below. "; message += "It is recommended that you fix them before using this model or you may get unexpected results.\n\n"; for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // .replace(". message += i + ":" + error + "\n"; } JTextArea messageArea = new JTextArea(message); messageArea.setLineWrap(true); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import dot menu item is selected else if (e.getSource() == importDot) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import Genetic Circuit"); if (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals(".gcm")) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { // GCMParser parser = new GCMParser(filename); FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the Graph data menu item is clicked else if (e.getSource() == graph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName .trim(), true, false); addTab(graphName.trim(), g, "TSD Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == probGraph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Probability Graph:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName .trim(), false, false); addTab(graphName.trim(), g, "Probability Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLearn")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE); if (lrnName != null && !lrnName.trim().equals("")) { lrnName = lrnName.trim(); try { if (overwrite(root + separator + lrnName, lrnName)) { new File(root + separator + lrnName).mkdir(); // new FileWriter(new File(root + separator + lrnName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn")); out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JTabbedPane lrnTab = new JTabbedPane(); lrnTab.addTab("Data Manager", new DataManager(root + separator + lrnName, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); lrnTab.addTab("Learn", new Learn(root + separator + lrnName, log, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("TSD Graph", new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator + lrnName, "time", this, null, log, null, true, true)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); */ addTab(lrnName, lrnTab, null); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Learn View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("copy")) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } try { if (!copy.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".sbml") && !copy.substring(copy.length() - 4).equals(".xml")) { copy += ".sbml"; } } else { copy += ".sbml"; } if (copy.length() > 4) { if (copy.substring(copy.length() - 5).equals(".sbml")) { modelID = copy.substring(0, copy.length() - 5); } else { modelID = copy.substring(0, copy.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".grf")) { copy += ".grf"; } } else { copy += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".prb")) { copy += ".prb"; } } else { copy += ".prb"; } } } if (copy .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + copy, copy)) { if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(tree.getFile()); document.getModel().setId(modelID); FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm") || tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); FileInputStream in = new FileInputStream(new File(tree.getFile())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { new File(root + separator + copy).mkdir(); // new FileWriter(new File(root + separator + copy + separator + // ".sim")).close(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile() + separator + ss); FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); FileInputStream in = new FileInputStream( new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring( ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream( new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } else { new File(root + separator + copy).mkdir(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring( ss.length() - 4).equals(".lrn"))) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".lrn")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream( new File(tree.getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } } refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("rename")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".sbml") && !rename.substring(rename.length() - 4).equals(".xml")) { rename += ".sbml"; } } else { rename += ".sbml"; } if (rename.length() > 4) { if (rename.substring(rename.length() - 5).equals(".sbml")) { modelID = rename.substring(0, rename.length() - 5); } else { modelID = rename.substring(0, rename.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".gcm")) { rename += ".gcm"; } } else { rename += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".grf")) { rename += ".grf"; } } else { rename += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".prb")) { rename += ".prb"; } } else { rename += ".prb"; } } if (rename .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + rename, rename)) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(root + separator + rename); document.getModel().setId(modelID); FileOutputStream out = new FileOutputStream(new File(root + separator + rename)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); } if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm")) { updateViews(rename); } if (new File(root + separator + rename).isDirectory()) { if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".sim").renameTo(new File(root + separator + rename + separator + rename + ".sim")); } else if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".pms").renameTo(new File(root + separator + rename + separator + rename + ".sim")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn").renameTo(new File(root + separator + rename + separator + rename + ".lrn")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".grf").renameTo(new File(root + separator + rename + separator + rename + ".grf")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".prb").renameTo(new File(root + separator + rename + separator + rename + ".prb")); } } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { ((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID); ((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && (tree.getFile().substring(tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring(tree.getFile().length() - 4).equals(".prb"))) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename .length() - 4)); } else { JTabbedPane t = new JTabbedPane(); int selected = ((JTabbedPane) tab.getComponentAt(i)).getSelectedIndex(); boolean analysis = false; ArrayList<Component> comps = new ArrayList<Component>(); for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getTabCount(); j++) { Component c = ((JTabbedPane) tab.getComponentAt(i)).getComponent(j); comps.add(c); } for (Component c : comps) { if (c instanceof Reb2Sac) { ((Reb2Sac) c).setSim(rename); analysis = true; } else if (c instanceof SBML_Editor) { String properties = root + separator + rename + separator + rename + ".sim"; new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) c).isDirty(); ((SBML_Editor) c) .setParamFileAndSimDir(properties, root + separator + rename); ((SBML_Editor) c).save(false, "", true); ((SBML_Editor) c).updateSBML(i, 0); ((SBML_Editor) c).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File(properties)); } else if (c instanceof Graph) { Graph g = ((Graph) c); g.setDirectory(root + separator + rename); if (g.isTSDGraph()) { g.setGraphName(rename + ".grf"); } else { g.setGraphName(rename + ".prb"); } } else if (c instanceof Learn) { Learn l = ((Learn) c); l.setDirectory(root + separator + rename); } else if (c instanceof DataManager) { DataManager d = ((DataManager) c); d.setDirectory(root + separator + rename); } if (analysis) { if (c instanceof Reb2Sac) { t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1).setName("Simulate"); } else if (c instanceof SBML_Editor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1).setName("SBML Editor"); } else if (c instanceof Graph) { if (((Graph) c).isTSDGraph()) { t.addTab("TSD Graph", c); t.getComponentAt(t.getComponents().length - 1).setName("TSD Graph"); } else { t.addTab("Probability Graph", c); t.getComponentAt(t.getComponents().length - 1).setName("ProbGraph"); } } else { t.addTab("Abstraction Options", c); t.getComponentAt(t.getComponents().length - 1).setName(""); } } } if (analysis) { t.setSelectedIndex(selected); tab.setComponentAt(i, t); } tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } } } refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("openGraph")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .contains(".grf")) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], true, false), "TSD Graph"); } else { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], false, false), "Probability Graph"); } } } } public int getTab(String name) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { return i; } } return -1; } public void deleteDir(File dir) { int count = 0; do { File[] list = dir.listFiles(); System.gc(); for (int i = 0; i < list.length; i++) { if (list[i].isDirectory()) { deleteDir(list[i]); } else { list[i].delete(); } } count++; } while (!dir.delete() && count != 100); if (count == 100) { JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method adds a new project to recent list */ public void addRecentProject(String projDir) { // boolean newOne = true; for (int i = 0; i < numberRecentProj; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = 0; j <= i; j++) { String save = recentProjectPaths[j]; recentProjects[j].setText(projDir.split(separator)[projDir.split(separator).length - 1]); file.add(recentProjects[j]); recentProjectPaths[j] = projDir; projDir = save; } for (int j = i + 1; j < numberRecentProj; j++) { file.add(recentProjects[j]); } return; } } if (numberRecentProj < 5) { numberRecentProj++; } for (int i = 0; i < numberRecentProj; i++) { String save = recentProjectPaths[i]; recentProjects[i].setText(projDir.split(separator)[projDir.split(separator).length - 1]); file.add(recentProjects[i]); recentProjectPaths[i] = projDir; projDir = save; } } /** * This method refreshes the menu. */ public void refresh() { mainPanel.remove(tree); tree = new FileTree(new File(root), this); mainPanel.add(tree, "West"); mainPanel.validate(); } /** * This method refreshes the tree. */ public void refreshTree() { tree.fixTree(); mainPanel.validate(); updateGCM(); } /** * This method adds the given Component to a tab. */ public void addTab(String name, Component panel, String tabName) { tab.addTab(name, panel); if (tabName != null) { tab.getComponentAt(tab.getComponents().length - 1).setName(tabName); } else { tab.getComponentAt(tab.getComponents().length - 1).setName(name); } tab.setSelectedIndex(tab.getComponents().length - 1); } /** * This method removes the given component from the tabs. */ public void removeTab(Component component) { tab.remove(component); } public JTabbedPane getTab() { return tab; } /** * Prompts the user to save work that has been done. */ public int save(int index) { if (tab.getComponentAt(index).getName().contains(("GCM"))) { if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) { GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index); if (editor.isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { editor.save("gcm"); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().equals("SBML Editor")) { if (tab.getComponentAt(index) instanceof SBML_Editor) { if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().contains("Graph")) { if (tab.getComponentAt(index) instanceof Graph) { if (((Graph) tab.getComponentAt(index)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else { if (tab.getComponentAt(index) instanceof JTabbedPane) { for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName().equals( "Simulate")) { if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save simulation option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "SBML Editor")) { if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save( false, "", true); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { if (((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals( "Data Manager")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) { ((DataManager) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .saveChanges(tab.getTitleAt(index)); } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().contains( "Graph")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { if (((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save graph changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)); g.save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } } } return 1; } } /** * Saves a circuit from a learn view to the project view */ public void saveGcm(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Returns the frame. */ public JFrame frame() { return frame; } public void mousePressed(MouseEvent e) { if (e.isPopupTrigger() && tree.getFile() != null) { popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (tree.getFile() != null) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { addTab(theFile, new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log), "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree .getFile(), log, tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1], true, false), "TSD Graph"); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree .getFile(), log, tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1], false, false), "Probability Graph"); } } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { openSim(); } else { openLearn(); } } } } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger() && tree.getFile() != null) { popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } private void simulate(boolean isDot) throws Exception { if (isDot) { String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + separator + // ".sim")).close(); String[] dot = tree.getFile().split(separator); String sbmlFile = /* * root + separator + simName + separator + */(dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + simName + separator + sbmlFile); try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + separator + (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(), log, simTab, null); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } else { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile()); // document.setLevel(2); document.setLevelAndVersion(2, 3); String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + separator + // ".sim")).close(); String sbmlFile = tree.getFile(); String[] sbml1 = tree.getFile().split(separator); String sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((sbml1[sbml1.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } new FileOutputStream(new File(sbmlFileProp)).close(); /* * try { FileOutputStream out = new FileOutputStream(new * File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); String doc = * writer.writeToString(document); byte[] output = doc.getBytes(); * out.write(output); out.close(); } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy sbml file to * output location.", "Error", JOptionPane.ERROR_MESSAGE); } */ refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(), log, simTab, null); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } } private void openLearn() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i] .substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(), this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); lrnTab.addTab("Learn", new Learn(tree.getFile(), log, this)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("TSD Graph", new Graph(null, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, true)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * else { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(), * this)); lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data available"); * font = noData1.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD * Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openSim() { String filename = tree.getFile(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(filename.split(separator)[filename.split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (filename != null && !filename.equals("")) { if (new File(filename).isDirectory()) { if (new File(filename + separator + ".sim").exists()) { new File(filename + separator + ".sim").delete(); } String[] list = new File(filename).list(); String getAFile = ""; // String probFile = ""; String openFile = ""; // String graphFile = ""; String open = null; String openProb = null; int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals("sbml")) { getAFile = filename + separator + list[i]; } else if (end.equals(".xml") && getAFile.equals("")) { getAFile = filename + separator + list[i]; } else if (end.equals(".txt") && list[i].contains("sim-rep")) { // probFile = filename + separator + list[i]; } else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) { openFile = filename + separator + list[i]; } else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i].length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = filename + separator + list[i]; } } else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) { // graphFile = filename + separator + list[i]; } else if (end.contains("=")) { // graphFile = filename + separator + list[i]; } } else if (end.equals(".grf")) { open = filename + separator + list[i]; } else if (end.equals(".prb")) { openProb = filename + separator + list[i]; } } else if (new File(filename + separator + list[i]).isDirectory()) { String[] s = new File(filename + separator + list[i]).list(); for (int j = 0; j < s.length; j++) { if (s[j].contains("sim-rep")) { // probFile = filename + separator + list[i] + separator + } else if (s[j].contains(".tsd")) { // graphFile = filename + separator + list[i] + separator + } } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"; String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; if (new File(pmsFile).exists()) { if (new File(simFile).exists()) { new File(pmsFile).delete(); } else { new File(pmsFile).renameTo(new File(simFile)); } } String sbmlLoadFile = null; if (new File(simFile).exists()) { try { Scanner s = new Scanner(new File(simFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]; if (sbmlLoadFile == null || !(new File(root + separator + sbmlLoadFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (s.hasNextLine()) { s.nextLine(); } s.close(); File f = new File(sbmlLoadFile); if (!f.exists()) { sbmlLoadFile = root + separator + f.getName(); } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else { sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1]; if (!new File(sbmlLoadFile).exists()) { sbmlLoadFile = getAFile; /* * JOptionPane.showMessageDialog(frame, "Unable to load sbml * file.", "Error", JOptionPane.ERROR_MESSAGE); return; */ } } if (sbmlLoadFile == null) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1] + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); // if (open != null) { simTab.addTab("TSD Graph", reb2sac.createGraph(open)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); * 1).setName("TSD Graph"); } /* else { JLabel noData = new * JLabel("No data available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } */ // if (openProb != null) { simTab.addTab("Probability Graph", reb2sac.createProbGraph(openProb)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * } else if (!probFile.equals("")) { simTab.addTab("Probability * Graph", reb2sac.createProbGraph(openProb)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } else { JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } /** * Embedded class that allows tabs to be closed. */ class TabbedPaneCloseButtonUI extends BasicTabbedPaneUI { public TabbedPaneCloseButtonUI() { super(); } protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect); Rectangle rect = rects[tabIndex]; g.setColor(Color.black); g.drawRect(rect.x + rect.width - 19, rect.y + 4, 13, 12); g.drawLine(rect.x + rect.width - 16, rect.y + 7, rect.x + rect.width - 10, rect.y + 13); g.drawLine(rect.x + rect.width - 10, rect.y + 7, rect.x + rect.width - 16, rect.y + 13); g.drawLine(rect.x + rect.width - 15, rect.y + 7, rect.x + rect.width - 9, rect.y + 13); g.drawLine(rect.x + rect.width - 9, rect.y + 7, rect.x + rect.width - 15, rect.y + 13); } protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + 24; } protected MouseListener createMouseListener() { return new MyMouseHandler(); } class MyMouseHandler extends MouseHandler { public MyMouseHandler() { super(); } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); int tabIndex = -1; int tabCount = tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (rects[i].contains(x, y)) { tabIndex = i; break; } } if (tabIndex >= 0 && !e.isPopupTrigger()) { Rectangle tabRect = rects[tabIndex]; y = y - tabRect.y; if ((x >= tabRect.x + tabRect.width - 18) && (x <= tabRect.x + tabRect.width - 8) && (y >= 5) && (y <= 15)) { if (save(tabIndex) == 1) { tabPane.remove(tabIndex); } } } } } } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public JMenuItem getExitButton() { return exit; } /** * This is the main method. It excecutes the BioSim GUI FrontEnd program. */ public static void main(String args[]) { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname + " environment variable does not include\nthe" + " directory containing the libsbml library file."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment" + " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file."); System.exit(1); } catch (SecurityException e) { System.err.println("Could not load the libSBML library files due to a" + " security exception."); System.exit(1); } if (args.length > 0 && args[0].equals("-lema")) { new BioSim(true); } else { new BioSim(false); } } public void copySim(String newSim) { try { new File(root + separator + newSim).mkdir(); // new FileWriter(new File(root + separator + newSim + separator + // ".sim")).close(); String oldSim = tab.getTitleAt(tab.getSelectedIndex()); String[] s = new File(root + separator + oldSim).list(); String sbmlFile = ""; String propertiesFile = ""; String sbmlLoadFile = null; for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(root + separator + oldSim + separator + ss); FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); SBMLWriter writer = new SBMLWriter(); String doc = writer.writeToString(document); byte[] output = doc.getBytes(); out.write(output); out.close(); sbmlFile = root + separator + newSim + separator + ss; } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); propertiesFile = root + separator + newSim + separator + ss; } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring(ss.length() - 4) .equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else { out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); } FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); if (ss.substring(ss.length() - 4).equals(".pms")) { if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) { new File(root + separator + newSim + separator + ss).delete(); } else { new File(root + separator + newSim + separator + ss).renameTo(new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim")); } ss = ss.substring(0, ss.length() - 4) + ".sim"; } if (ss.substring(ss.length() - 4).equals(".sim")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (scan.hasNextLine()) { scan.nextLine(); } scan.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("TSD Graph", reb2sac.createGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); simTab.addTab("Probability Graph", reb2sac.createProbGraph(null)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD * Graph"); JLabel noData1 = new JLabel("No data available"); Font font1 = * noData1.getFont(); font1 = font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ tab.setComponentAt(tab.getSelectedIndex(), simTab); tab.setTitleAt(tab.getSelectedIndex(), newSim); tab.getComponentAt(tab.getSelectedIndex()).setName(newSim); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } public void refreshLearn(String learnName, boolean data) { for (int i = 0; i < tab.getComponentCount(); i++) { if (tab.getTitleAt(i).equals(learnName)) { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals("TSD Graph")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) { ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)).refresh(); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null, "amount", learnName + " data", "tsd.printer", root + separator + learnName, "time", this, null, log, null, true, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("TSD Graph"); } /* * } else { JLabel noData1 = new JLabel("No data available"); Font * font = noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, noData1); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j).setName("TSD Graph"); } */ } else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) { } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn(root + separator + learnName, log, this)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("Learn"); } /* * } else { JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, noData); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j).setName("Learn"); } */ } } } } } private void updateGCM() { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles(); tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename()); } } } public void updateViews(String updatedFile) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".sim"; String properties2 = root + separator + tab + separator + tab + ".lrn"; if (new File(properties).exists()) { String check = ""; try { Scanner s = new Scanner(new File(properties)); if (s.hasNextLine()) { check = s.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } s.close(); } catch (Exception e) { } if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("SBML Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty(); ((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true); if (updatedFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + updatedFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); } else { ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile); } ((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File(properties)); } } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } ArrayList<String> saved = new ArrayList<String>(); if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { saved.add(this.tab.getTitleAt(i)); GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i); if (gcm.getSBMLFile().equals(updatedFile)) { gcm.save("save"); } } String[] files = new File(root).list(); for (String s : files) { if (s.contains(".gcm") && !saved.contains(s)) { GCMFile gcm = new GCMFile(); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(updatedFile)) { updateViews(s); } } } } } public String getRoot() { return root; } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { String[] views = canDelete(name); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { tab.remove(i); } } File dir = new File(fullPath); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } return true; } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to overwrite file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File", JOptionPane.ERROR_MESSAGE); return false; } } else { return false; } } else { return true; } } public void updateOpenSBML(String sbmlName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (sbmlName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof SBML_Editor) { SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null); this.tab.setComponentAt(i, newSBML); this.tab.getComponentAt(i).setName("SBML Editor"); newSBML.save(false, "", false); } } } } private String[] canDelete(String filename) { ArrayList<String> views = new ArrayList<String>(); String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } scan.close(); } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } if (check.equals(filename)) { views.add(s); } } } String[] usingViews = views.toArray(new String[0]); sort(usingViews); return usingViews; } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } private void reassignViews(String oldName, String newName) { String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { ArrayList<String> copy = new ArrayList<String>(); Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; if (check.equals(oldName)) { while (scan.hasNextLine()) { copy.add(scan.nextLine()); } scan.close(); FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim")); out.write((newName + "\n").getBytes()); for (String cop : copy) { out.write((cop + "\n").getBytes()); } out.close(); } else { scan.close(); } } } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; if (check.equals(oldName)) { p.setProperty("genenet.file", newName); FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn")); p.store(store, "Learn File Data"); store.close(); } } } catch (Exception e) { } } } } } }
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.gui.grappa.GCIGrappaPanel; import gcm2sbml.gui.modelview.ModelView; import gcm2sbml.gui.modelview.movie.MovieContainer; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.CompatibilityFixer; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; import gcm2sbml.util.GlobalConstants; import lhpn2sbml.parser.LhpnFile; import lhpn2sbml.parser.Lpn2verilog; import lhpn2sbml.parser.Translator; import lhpn2sbml.gui.*; import graph.Graph; import stategraph.StateGraph; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.Point; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.MouseWheelEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; //import java.awt.event.ComponentListener; //import java.awt.event.ComponentEvent; import java.awt.event.WindowFocusListener; //import java.awt.event.FocusListener; //import java.awt.event.FocusEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; //import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JViewport; //import javax.swing.tree.TreePath; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.basic.BasicTabbedPaneUI; import tabs.CloseAndMaxTabbedPane; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import learn.Learn; import learn.LearnLHPN; import synthesis.Synthesis; import verification.*; import org.sbml.libsbml.*; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; import java.net.*; import uk.ac.ebi.biomodels.*; import att.grappa.*; //import datamanager.DataManagerLHPN; /** * This class creates a GUI for the Tstubd program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * are selected. * * @author Curtis Madsen */ public class BioSim implements MouseListener, ActionListener, MouseMotionListener, MouseWheelListener, WindowFocusListener { private JFrame frame; // Frame where components of the GUI are displayed private JMenuBar menuBar; private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu, viewModel; // The // file // menu private JMenuItem newProj; // The new menu item private JMenuItem newModel; // The new menu item private JMenuItem newCircuit; // The new menu item private JMenuItem newVhdl; // The new vhdl menu item private JMenuItem newS; // The new assembly file menu item private JMenuItem newInst; // The new instruction file menu item private JMenuItem newLhpn; // The new lhpn menu item private JMenuItem newG; // The new petri net menu item private JMenuItem newCsp; // The new csp menu item private JMenuItem newHse; // The new handshaking extension menu item private JMenuItem newUnc; // The new extended burst mode menu item private JMenuItem newRsg; // The new rsg menu item private JMenuItem newSpice; // The new spice circuit item private JMenuItem exit; // The exit menu item private JMenuItem importSbml; // The import sbml menu item private JMenuItem importBioModel; // The import sbml menu item private JMenuItem importDot; // The import dot menu item private JMenuItem importVhdl; // The import vhdl menu item private JMenuItem importS; // The import assembly file menu item private JMenuItem importInst; // The import instruction file menu item private JMenuItem importLpn; // The import lpn menu item private JMenuItem importG; // The import .g file menu item private JMenuItem importCsp; // The import csp menu item private JMenuItem importHse; // The import handshaking extension menu // item private JMenuItem importUnc; // The import extended burst mode menu item private JMenuItem importRsg; // The import rsg menu item private JMenuItem importSpice; // The import spice circuit item private JMenuItem manual; // The manual menu item private JMenuItem about; // The about menu item private JMenuItem openProj; // The open menu item private JMenuItem pref; // The preferences menu item private JMenuItem graph; // The graph menu item private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng, exportSvg, exportTsd; private String root; // The root directory private FileTree tree; // FileTree private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools private JToolBar toolbar; // Tool bar for common options private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool // Bar // options private JPanel mainPanel; // the main panel private static Boolean LPN2SBML = true; public Log log; // the log private JPopupMenu popup; // popup menu private String separator; private KeyEventDispatcher dispatcher; private JMenuItem recentProjects[]; private String recentProjectPaths[]; private int numberRecentProj; private int ShortCutKey; public boolean checkUndeclared, checkUnits; private JCheckBox Undeclared, Units, viewerCheck; private JTextField viewerField; private JLabel viewerLabel; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean async, popupFlag = false, menuFlag = false, treeSelected = false; public boolean atacs, lema; private String viewer; private String[] BioModelIds = null; private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml, saveAsTemplate, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules, viewTrace, viewLog, viewCoverage, viewVHDL, viewVerilog, viewLHPN, saveSbml, saveTemp, saveModel, viewSG, viewModGraph, viewModBrowser, createAnal, createLearn, createSbml, createSynth, createVer, close, closeAll; public String ENVVAR; public static final int SBML_LEVEL = 2; public static final int SBML_VERSION = 4; public static final Object[] OPTIONS = { "Yes", "No", "Yes To All", "No To All", "Cancel" }; public static final int YES_OPTION = JOptionPane.YES_OPTION; public static final int NO_OPTION = JOptionPane.NO_OPTION; public static final int YES_TO_ALL_OPTION = JOptionPane.CANCEL_OPTION; public static final int NO_TO_ALL_OPTION = 3; public static final int CANCEL_OPTION = 4; public class MacOSAboutHandler extends Application { public MacOSAboutHandler() { addApplicationListener(new AboutBoxHandler()); } class AboutBoxHandler extends ApplicationAdapter { public void handleAbout(ApplicationEvent event) { about(); event.setHandled(true); } } } public class MacOSPreferencesHandler extends Application { public MacOSPreferencesHandler() { addApplicationListener(new PreferencesHandler()); } class PreferencesHandler extends ApplicationAdapter { public void handlePreferences(ApplicationEvent event) { preferences(); event.setHandled(true); } } } public class MacOSQuitHandler extends Application { public MacOSQuitHandler() { addApplicationListener(new QuitHandler()); } class QuitHandler extends ApplicationAdapter { public void handleQuit(ApplicationEvent event) { exit(); event.setHandled(true); } } } /** * This is the constructor for the Proj class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. * * @throws Exception */ public BioSim(boolean lema, boolean atacs, boolean LPN2SBML) { this.lema = lema; this.atacs = atacs; this.LPN2SBML = LPN2SBML; async = lema || atacs; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } if (atacs) { ENVVAR = System.getenv("ATACSGUI"); } else if (lema) { ENVVAR = System.getenv("LEMA"); } else { ENVVAR = System.getenv("BIOSIM"); } // Creates a new frame if (lema) { frame = new JFrame("LEMA"); frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "LEMA.png").getImage()); } else if (atacs) { frame = new JFrame("ATACS"); frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "ATACS.png").getImage()); } else { frame = new JFrame("iBioSim"); frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } // Makes it so that clicking the x in the corner closes the program WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { exit.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; frame.addWindowListener(w); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowFocusListener(this); popup = new JPopupMenu(); popup.addMouseListener(this); // popup.addFocusListener(this); // popup.addComponentListener(this); // Sets up the Tool Bar toolbar = new JToolBar(); String imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "save.png"; saveButton = makeToolButton(imgName, "save", "Save", "Save"); // toolButton = new JButton("Save"); toolbar.add(saveButton); imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "saveas.png"; saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As"); toolbar.add(saveasButton); imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "run-icon.jpg"; runButton = makeToolButton(imgName, "run", "Save and Run", "Run"); // toolButton = new JButton("Run"); toolbar.add(runButton); imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "refresh.jpg"; refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh"); toolbar.add(refreshButton); imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "savecheck.png"; checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check"); toolbar.add(checkButton); imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "export.jpg"; exportButton = makeToolButton(imgName, "export", "Export", "Export"); toolbar.add(exportButton); saveButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); saveasButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // Creates a menu for the frame menuBar = new JMenuBar(); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); help = new JMenu("Help"); help.setMnemonic(KeyEvent.VK_H); edit = new JMenu("Edit"); edit.setMnemonic(KeyEvent.VK_E); importMenu = new JMenu("Import"); exportMenu = new JMenu("Export"); newMenu = new JMenu("New"); saveAsMenu = new JMenu("Save As"); view = new JMenu("View"); viewModel = new JMenu("Model"); tools = new JMenu("Tools"); menuBar.add(file); menuBar.add(edit); menuBar.add(view); menuBar.add(tools); menuBar.add(help); // menuBar.addFocusListener(this); // menuBar.addMouseListener(this); // file.addMouseListener(this); // edit.addMouseListener(this); // view.addMouseListener(this); // tools.addMouseListener(this); // help.addMouseListener(this); copy = new JMenuItem("Copy"); rename = new JMenuItem("Rename"); delete = new JMenuItem("Delete"); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); close = new JMenuItem("Close"); closeAll = new JMenuItem("Close All"); pref = new JMenuItem("Preferences"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); newSpice = new JMenuItem("Spice Circuit"); newVhdl = new JMenuItem("VHDL-AMS Model"); newS = new JMenuItem("Assembly File"); newInst = new JMenuItem("Instruction File"); newLhpn = new JMenuItem("Labeled Petri Net"); newG = new JMenuItem("Petri Net"); newCsp = new JMenuItem("CSP Model"); newHse = new JMenuItem("Handshaking Expansion"); newUnc = new JMenuItem("Extended Burst Mode Machine"); newRsg = new JMenuItem("Reduced State Graph"); graph = new JMenuItem("TSD Graph"); probGraph = new JMenuItem("Histogram"); importSbml = new JMenuItem("SBML Model"); importBioModel = new JMenuItem("BioModel"); importDot = new JMenuItem("Genetic Circuit Model"); importG = new JMenuItem("Petri Net"); importLpn = new JMenuItem("Labeled Petri Net"); importVhdl = new JMenuItem("VHDL-AMS Model"); importS = new JMenuItem("Assembly File"); importInst = new JMenuItem("Instruction File"); importSpice = new JMenuItem("Spice Circuit"); importCsp = new JMenuItem("CSP Model"); importHse = new JMenuItem("Handshaking Expansion"); importUnc = new JMenuItem("Extended Burst Mode Machine"); importRsg = new JMenuItem("Reduced State Graph"); exportCsv = new JMenuItem("Comma Separated Values (csv)"); exportDat = new JMenuItem("Tab Delimited Data (dat)"); exportEps = new JMenuItem("Encapsulated Postscript (eps)"); exportJpg = new JMenuItem("JPEG (jpg)"); exportPdf = new JMenuItem("Portable Document Format (pdf)"); exportPng = new JMenuItem("Portable Network Graphics (png)"); exportSvg = new JMenuItem("Scalable Vector Graphics (svg)"); exportTsd = new JMenuItem("Time Series Data (tsd)"); save = new JMenuItem("Save"); if (async) { saveModel = new JMenuItem("Save Models"); } else { saveModel = new JMenuItem("Save GCM"); } saveAs = new JMenuItem("Save As"); saveAsGcm = new JMenuItem("Genetic Circuit Model"); saveAsGraph = new JMenuItem("Graph"); saveAsSbml = new JMenuItem("Save SBML Model"); saveAsTemplate = new JMenuItem("Save SBML Template"); // saveGcmAsLhpn = new JMenuItem("Save LPN Model"); saveAsLhpn = new JMenuItem("LPN"); run = new JMenuItem("Save and Run"); check = new JMenuItem("Save and Check"); saveSbml = new JMenuItem("Save as SBML"); saveTemp = new JMenuItem("Save as SBML Template"); // saveParam = new JMenuItem("Save Parameters"); refresh = new JMenuItem("Refresh"); export = new JMenuItem("Export"); viewCircuit = new JMenuItem("Circuit"); viewRules = new JMenuItem("Production Rules"); viewTrace = new JMenuItem("Error Trace"); viewLog = new JMenuItem("Log"); viewCoverage = new JMenuItem("Coverage Report"); viewVHDL = new JMenuItem("VHDL-AMS Model"); viewVerilog = new JMenuItem("Verilog Model"); // SB //Being generic for // System Verilog and // Verilog-AMS viewLHPN = new JMenuItem("LPN Model"); viewModGraph = new JMenuItem("Model"); viewModBrowser = new JMenuItem("Model in Browser"); viewSG = new JMenuItem("State Graph"); createAnal = new JMenuItem("Analysis Tool"); createLearn = new JMenuItem("Learn Tool"); createSbml = new JMenuItem("Create SBML File"); createSynth = new JMenuItem("Synthesis Tool"); createVer = new JMenuItem("Verification Tool"); exit = new JMenuItem("Exit"); copy.addActionListener(this); rename.addActionListener(this); delete.addActionListener(this); openProj.addActionListener(this); close.addActionListener(this); closeAll.addActionListener(this); pref.addActionListener(this); manual.addActionListener(this); newProj.addActionListener(this); newCircuit.addActionListener(this); newModel.addActionListener(this); newVhdl.addActionListener(this); newS.addActionListener(this); newInst.addActionListener(this); newLhpn.addActionListener(this); newG.addActionListener(this); newCsp.addActionListener(this); newHse.addActionListener(this); newUnc.addActionListener(this); newRsg.addActionListener(this); newSpice.addActionListener(this); exit.addActionListener(this); about.addActionListener(this); importSbml.addActionListener(this); importBioModel.addActionListener(this); importDot.addActionListener(this); importVhdl.addActionListener(this); importS.addActionListener(this); importInst.addActionListener(this); importLpn.addActionListener(this); importG.addActionListener(this); importCsp.addActionListener(this); importHse.addActionListener(this); importUnc.addActionListener(this); importRsg.addActionListener(this); importSpice.addActionListener(this); exportCsv.addActionListener(this); exportDat.addActionListener(this); exportEps.addActionListener(this); exportJpg.addActionListener(this); exportPdf.addActionListener(this); exportPng.addActionListener(this); exportSvg.addActionListener(this); exportTsd.addActionListener(this); graph.addActionListener(this); probGraph.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); saveAsSbml.addActionListener(this); saveAsTemplate.addActionListener(this); // saveGcmAsLhpn.addActionListener(this); run.addActionListener(this); check.addActionListener(this); saveSbml.addActionListener(this); saveTemp.addActionListener(this); saveModel.addActionListener(this); // saveParam.addActionListener(this); export.addActionListener(this); viewCircuit.addActionListener(this); viewRules.addActionListener(this); viewTrace.addActionListener(this); viewLog.addActionListener(this); viewCoverage.addActionListener(this); viewVHDL.addActionListener(this); viewVerilog.addActionListener(this); viewLHPN.addActionListener(this); viewModGraph.addActionListener(this); viewModBrowser.addActionListener(this); viewSG.addActionListener(this); createAnal.addActionListener(this); createLearn.addActionListener(this); createSbml.addActionListener(this); createSynth.addActionListener(this); createVer.addActionListener(this); save.setActionCommand("save"); saveAs.setActionCommand("saveas"); run.setActionCommand("run"); check.setActionCommand("check"); refresh.setActionCommand("refresh"); export.setActionCommand("export"); if (atacs) { viewModGraph.setActionCommand("viewModel"); } else { viewModGraph.setActionCommand("graph"); } viewModBrowser.setActionCommand("browse"); viewSG.setActionCommand("stateGraph"); createLearn.setActionCommand("createLearn"); createSbml.setActionCommand("createSBML"); createSynth.setActionCommand("createSynthesis"); createVer.setActionCommand("createVerify"); ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey)); rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); // newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, // ShortCutKey)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey)); close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey)); closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey | KeyEvent.SHIFT_MASK)); // saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, // ShortCutKey)); // newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey)); // newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, // ShortCutKey)); // newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, // ShortCutKey)); // about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, // ShortCutKey)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey)); pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey)); viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0)); if (lema) { // viewCoverage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, // 0)); // SB viewVHDL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0)); viewVerilog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); viewLHPN.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); viewTrace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0)); } else { viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey)); createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey)); } Action newAction = new NewAction(); Action saveAction = new SaveAction(); Action importAction = new ImportAction(); Action exportAction = new ExportAction(); Action modelAction = new ModelAction(); newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new"); newMenu.getActionMap().put("new", newAction); saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "save"); saveAsMenu.getActionMap().put("save", saveAction); importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "import"); importMenu.getActionMap().put("import", importAction); exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "export"); exportMenu.getActionMap().put("export", exportAction); viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "model"); viewModel.getActionMap().put("model", modelAction); // graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, // ShortCutKey)); // probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); // if (!lema) { // importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // else { // importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, // ShortCutKey)); // importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); newMenu.setMnemonic(KeyEvent.VK_N); saveAsMenu.setMnemonic(KeyEvent.VK_A); importMenu.setMnemonic(KeyEvent.VK_I); exportMenu.setMnemonic(KeyEvent.VK_E); viewModel.setMnemonic(KeyEvent.VK_M); copy.setMnemonic(KeyEvent.VK_C); rename.setMnemonic(KeyEvent.VK_R); delete.setMnemonic(KeyEvent.VK_D); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); close.setMnemonic(KeyEvent.VK_W); newCircuit.setMnemonic(KeyEvent.VK_G); newModel.setMnemonic(KeyEvent.VK_S); newVhdl.setMnemonic(KeyEvent.VK_V); newLhpn.setMnemonic(KeyEvent.VK_L); newG.setMnemonic(KeyEvent.VK_N); newSpice.setMnemonic(KeyEvent.VK_P); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_H); if (!async) { importDot.setMnemonic(KeyEvent.VK_G); } else { importLpn.setMnemonic(KeyEvent.VK_L); } importSbml.setMnemonic(KeyEvent.VK_S); // importBioModel.setMnemonic(KeyEvent.VK_S); importVhdl.setMnemonic(KeyEvent.VK_V); importSpice.setMnemonic(KeyEvent.VK_P); save.setMnemonic(KeyEvent.VK_S); run.setMnemonic(KeyEvent.VK_R); check.setMnemonic(KeyEvent.VK_K); exportCsv.setMnemonic(KeyEvent.VK_C); exportEps.setMnemonic(KeyEvent.VK_E); exportDat.setMnemonic(KeyEvent.VK_D); exportJpg.setMnemonic(KeyEvent.VK_J); exportPdf.setMnemonic(KeyEvent.VK_F); exportPng.setMnemonic(KeyEvent.VK_G); exportSvg.setMnemonic(KeyEvent.VK_S); exportTsd.setMnemonic(KeyEvent.VK_T); pref.setMnemonic(KeyEvent.VK_P); viewModGraph.setMnemonic(KeyEvent.VK_G); viewModBrowser.setMnemonic(KeyEvent.VK_B); createAnal.setMnemonic(KeyEvent.VK_A); createLearn.setMnemonic(KeyEvent.VK_L); importDot.setEnabled(false); importSbml.setEnabled(false); importBioModel.setEnabled(false); importVhdl.setEnabled(false); importS.setEnabled(false); importInst.setEnabled(false); importLpn.setEnabled(false); importG.setEnabled(false); importCsp.setEnabled(false); importHse.setEnabled(false); importUnc.setEnabled(false); importRsg.setEnabled(false); importSpice.setEnabled(false); exportMenu.setEnabled(false); // exportCsv.setEnabled(false); // exportDat.setEnabled(false); // exportEps.setEnabled(false); // exportJpg.setEnabled(false); // exportPdf.setEnabled(false); // exportPng.setEnabled(false); // exportSvg.setEnabled(false); // exportTsd.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); newVhdl.setEnabled(false); newS.setEnabled(false); newInst.setEnabled(false); newLhpn.setEnabled(false); newG.setEnabled(false); newCsp.setEnabled(false); newHse.setEnabled(false); newUnc.setEnabled(false); newRsg.setEnabled(false); newSpice.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); save.setEnabled(false); saveModel.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); run.setEnabled(false); check.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); // saveParam.setEnabled(false); refresh.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); viewSG.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); edit.add(copy); edit.add(rename); // edit.add(refresh); edit.add(delete); // edit.addSeparator(); // edit.add(pref); file.add(newMenu); newMenu.add(newProj); if (!async) { newMenu.add(newCircuit); newMenu.add(newLhpn); newMenu.add(newModel); } else if (atacs) { newMenu.add(newVhdl); newMenu.add(newG); newMenu.add(newLhpn); newMenu.add(newCsp); newMenu.add(newHse); newMenu.add(newUnc); newMenu.add(newRsg); } else { newMenu.add(newVhdl); newMenu.add(newS); newMenu.add(newInst); newMenu.add(newLhpn); // newMenu.add(newSpice); } newMenu.add(graph); if (!async) { newMenu.add(probGraph); } file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(close); file.add(closeAll); file.addSeparator(); file.add(save); // file.add(saveAsMenu); if (!async) { saveAsMenu.add(saveAsGcm); saveAsMenu.add(saveAsGraph); saveAsMenu.add(saveAsSbml); saveAsMenu.add(saveAsTemplate); // saveAsMenu.add(saveGcmAsLhpn); } else { saveAsMenu.add(saveAsLhpn); saveAsMenu.add(saveAsGraph); } file.add(saveAs); if (!async) { file.add(saveAsSbml); file.add(saveAsTemplate); // file.add(saveGcmAsLhpn); } file.add(saveModel); // file.add(saveParam); file.add(run); if (!async) { file.add(check); } file.addSeparator(); file.add(importMenu); if (!async) { importMenu.add(importDot); importMenu.add(importLpn); importMenu.add(importSbml); importMenu.add(importBioModel); } else if (atacs) { importMenu.add(importVhdl); importMenu.add(importG); importMenu.add(importLpn); importMenu.add(importCsp); importMenu.add(importHse); importMenu.add(importUnc); importMenu.add(importRsg); } else { importMenu.add(importVhdl); importMenu.add(importS); importMenu.add(importInst); importMenu.add(importLpn); // importMenu.add(importSpice); } file.add(exportMenu); exportMenu.add(exportCsv); exportMenu.add(exportDat); exportMenu.add(exportEps); exportMenu.add(exportJpg); exportMenu.add(exportPdf); exportMenu.add(exportPng); exportMenu.add(exportSvg); exportMenu.add(exportTsd); file.addSeparator(); // file.add(save); // file.add(saveAs); // file.add(run); // file.add(check); // if (!lema) { // file.add(saveParam); // file.addSeparator(); // file.add(export); // if (!lema) { // file.add(saveSbml); // file.add(saveTemp); help.add(manual); if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { edit.addSeparator(); edit.add(pref); file.add(exit); file.addSeparator(); help.add(about); } if (lema) { view.add(viewVHDL); view.add(viewVerilog); view.add(viewLHPN); view.addSeparator(); view.add(viewCoverage); view.add(viewLog); view.add(viewTrace); } else if (atacs) { view.add(viewModGraph); view.add(viewCircuit); view.add(viewRules); view.add(viewTrace); view.add(viewLog); } else { view.add(viewModGraph); view.add(viewModBrowser); view.add(viewSG); view.add(viewLog); view.addSeparator(); view.add(refresh); } if (!async) { tools.add(createAnal); } if (!atacs) { tools.add(createLearn); } if (atacs) { tools.add(createSynth); } if (async) { tools.add(createVer); } // else { // tools.add(createSbml); root = null; // Create recent project menu items numberRecentProj = 0; recentProjects = new JMenuItem[5]; recentProjectPaths = new String[5]; for (int i = 0; i < 5; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjects[i].setActionCommand("recent" + i); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_5); Preferences biosimrc = Preferences.userRoot(); viewer = biosimrc.get("biosim.general.viewer", ""); for (int i = 0; i < 5; i++) { if (atacs) { recentProjects[i].setText(biosimrc.get("atacs.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("atacs.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } else if (lema) { recentProjects[i].setText(biosimrc.get("lema.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("lema.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } else { recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } } if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { // file.add(pref); // file.add(exit); help.add(about); } if (biosimrc.get("biosim.check.undeclared", "").equals("false")) { checkUndeclared = false; } else { checkUndeclared = true; } if (biosimrc.get("biosim.check.units", "").equals("false")) { checkUnits = false; } else { checkUnits = true; } if (biosimrc.get("biosim.general.file_browser", "").equals("")) { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KREP_VALUE", ".5"); } if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KACT_VALUE", ".0033"); } if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBIO_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2"); } if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001"); } if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.OCR_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075"); } if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_VALUE", "30"); } if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2"); } if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25"); } if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1"); } if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.INITIAL_VALUE", "0"); } if (biosimrc.get("biosim.sim.abs", "").equals("")) { biosimrc.put("biosim.sim.abs", "None"); } if (biosimrc.get("biosim.sim.type", "").equals("")) { biosimrc.put("biosim.sim.type", "ODE"); } if (biosimrc.get("biosim.sim.sim", "").equals("")) { biosimrc.put("biosim.sim.sim", "rkf45"); } if (biosimrc.get("biosim.sim.limit", "").equals("")) { biosimrc.put("biosim.sim.limit", "100.0"); } if (biosimrc.get("biosim.sim.useInterval", "").equals("")) { biosimrc.put("biosim.sim.useInterval", "Print Interval"); } if (biosimrc.get("biosim.sim.interval", "").equals("")) { biosimrc.put("biosim.sim.interval", "1.0"); } if (biosimrc.get("biosim.sim.step", "").equals("")) { biosimrc.put("biosim.sim.step", "inf"); } if (biosimrc.get("biosim.sim.min.step", "").equals("")) { biosimrc.put("biosim.sim.min.step", "0"); } if (biosimrc.get("biosim.sim.error", "").equals("")) { biosimrc.put("biosim.sim.error", "1.0E-9"); } if (biosimrc.get("biosim.sim.seed", "").equals("")) { biosimrc.put("biosim.sim.seed", "314159"); } if (biosimrc.get("biosim.sim.runs", "").equals("")) { biosimrc.put("biosim.sim.runs", "1"); } if (biosimrc.get("biosim.sim.rapid1", "").equals("")) { biosimrc.put("biosim.sim.rapid1", "0.1"); } if (biosimrc.get("biosim.sim.rapid2", "").equals("")) { biosimrc.put("biosim.sim.rapid2", "0.1"); } if (biosimrc.get("biosim.sim.qssa", "").equals("")) { biosimrc.put("biosim.sim.qssa", "0.1"); } if (biosimrc.get("biosim.sim.concentration", "").equals("")) { biosimrc.put("biosim.sim.concentration", "15"); } if (biosimrc.get("biosim.learn.tn", "").equals("")) { biosimrc.put("biosim.learn.tn", "2"); } if (biosimrc.get("biosim.learn.tj", "").equals("")) { biosimrc.put("biosim.learn.tj", "2"); } if (biosimrc.get("biosim.learn.ti", "").equals("")) { biosimrc.put("biosim.learn.ti", "0.5"); } if (biosimrc.get("biosim.learn.bins", "").equals("")) { biosimrc.put("biosim.learn.bins", "4"); } if (biosimrc.get("biosim.learn.equaldata", "").equals("")) { biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins"); } if (biosimrc.get("biosim.learn.autolevels", "").equals("")) { biosimrc.put("biosim.learn.autolevels", "Auto"); } if (biosimrc.get("biosim.learn.ta", "").equals("")) { biosimrc.put("biosim.learn.ta", "1.15"); } if (biosimrc.get("biosim.learn.tr", "").equals("")) { biosimrc.put("biosim.learn.tr", "0.75"); } if (biosimrc.get("biosim.learn.tm", "").equals("")) { biosimrc.put("biosim.learn.tm", "0.0"); } if (biosimrc.get("biosim.learn.tt", "").equals("")) { biosimrc.put("biosim.learn.tt", "0.025"); } if (biosimrc.get("biosim.learn.debug", "").equals("")) { biosimrc.put("biosim.learn.debug", "0"); } if (biosimrc.get("biosim.learn.succpred", "").equals("")) { biosimrc.put("biosim.learn.succpred", "Successors"); } if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) { biosimrc.put("biosim.learn.findbaseprob", "False"); } // Open .biosimrc here // Packs the frame and displays it mainPanel = new JPanel(new BorderLayout()); tree = new FileTree(null, this, lema, atacs); log = new Log(); tab = new CloseAndMaxTabbedPane(false, this); tab.setPreferredSize(new Dimension(1100, 550)); // tab.getPaneUI().addMouseListener(this); mainPanel.add(tree, "West"); mainPanel.add(tab, "Center"); mainPanel.add(log, "South"); mainPanel.add(toolbar, "North"); frame.setContentPane(mainPanel); frame.setJMenuBar(menuBar); // frame.getGlassPane().setVisible(true); // frame.getGlassPane().addMouseListener(this); // frame.getGlassPane().addMouseMotionListener(this); // frame.getGlassPane().addMouseWheelListener(this); frame.addMouseListener(this); menuBar.addMouseListener(this); frame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; frame.setSize(frameSize); } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; frame.setSize(frameSize); } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; frame.setLocation(x, y); frame.setVisible(true); dispatcher = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_TYPED) { if (e.getKeyChar() == '') { if (tab.getTabCount() > 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager() .removeKeyEventDispatcher(dispatcher); if (save(tab.getSelectedIndex(), 0) != 0) { tab.remove(tab.getSelectedIndex()); } KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(dispatcher); } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); } public void preferences() { if (!async) { Undeclared = new JCheckBox("Check for undeclared units in SBML"); if (checkUndeclared) { Undeclared.setSelected(true); } else { Undeclared.setSelected(false); } Units = new JCheckBox("Check units in SBML"); if (checkUnits) { Units.setSelected(true); } else { Units.setSelected(false); } Preferences biosimrc = Preferences.userRoot(); JCheckBox dialog = new JCheckBox("Use File Dialog"); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { dialog.setSelected(true); } else { dialog.setSelected(false); } final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get( "biosim.gcm.ACTIVED_VALUE", "")); final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", "")); final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", "")); final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.COOPERATIVITY_VALUE", "")); final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KASSOCIATION_VALUE", "")); final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", "")); final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get( "biosim.gcm.PROMOTER_COUNT_VALUE", "")); final JTextField INITIAL_VALUE = new JTextField(biosimrc.get( "biosim.gcm.INITIAL_VALUE", "")); final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get( "biosim.gcm.MAX_DIMER_VALUE", "")); final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", "")); final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.RNAP_BINDING_VALUE", "")); final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", "")); final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.STOICHIOMETRY_VALUE", "")); JPanel labels = new JPanel(new GridLayout(15, 1)); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.KASSOCIATION_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):")); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(15, 1)); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KBIO_VALUE); fields.add(KDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(KASSOCIATION_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_VALUE); fields.add(MAX_DIMER_VALUE); fields.add(OCR_VALUE); fields.add(RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); String[] choices = { "None", "Abstraction", "Logical Abstraction" }; JTextField simCommand = new JTextField(biosimrc.get("biosim.sim.command", "")); final JComboBox abs = new JComboBox(choices); abs.setSelectedItem(biosimrc.get("biosim.sim.abs", "")); if (abs.getSelectedItem().equals("None")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else if (abs.getSelectedItem().equals("Abstraction")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else { choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser", "LPN" }; } final JComboBox type = new JComboBox(choices); type.setSelectedItem(biosimrc.get("biosim.sim.type", "")); if (type.getSelectedItem().equals("ODE")) { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } else if (type.getSelectedItem().equals("Monte Carlo")) { choices = new String[] { "gillespie", "mpde", "mp", "mp-adaptive", "mp-event", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "markov-chain-analysis", "atacs", "ctmc-transient" }; } else { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } final JComboBox sim = new JComboBox(choices); sim.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); abs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (abs.getSelectedItem().equals("None")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else if (abs.getSelectedItem().equals("Abstraction")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("Monte Carlo"); type.addItem("Markov"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.addItem("LPN"); type.setSelectedItem(o); } } }); type.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (type.getSelectedItem() == null) { } else if (type.getSelectedItem().equals("ODE")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Monte Carlo")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("gillespie"); sim.addItem("mpde"); sim.addItem("mp"); sim.addItem("mp-adaptive"); sim.addItem("mp-event"); sim.addItem("emc-sim"); sim.addItem("bunker"); sim.addItem("nmc"); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Markov")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("atacs"); sim.addItem("ctmc-transient"); sim.setSelectedItem(o); } else { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } } }); JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", "")); JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", "")); JTextField minStep = new JTextField(biosimrc.get("biosim.sim.min.step", "")); JTextField step = new JTextField(biosimrc.get("biosim.sim.step", "")); JTextField error = new JTextField(biosimrc.get("biosim.sim.error", "")); JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", "")); JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", "")); JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", "")); JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", "")); JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", "")); JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", "")); choices = new String[] { "Print Interval", "Minimum Print Interval", "Number Of Steps" }; JComboBox useInterval = new JComboBox(choices); useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", "")); JPanel analysisLabels = new JPanel(new GridLayout(15, 1)); analysisLabels.add(new JLabel("Simulation Command:")); analysisLabels.add(new JLabel("Abstraction:")); analysisLabels.add(new JLabel("Simulation Type:")); analysisLabels.add(new JLabel("Possible Simulators/Analyzers:")); analysisLabels.add(new JLabel("Time Limit:")); analysisLabels.add(useInterval); analysisLabels.add(new JLabel("Minimum Time Step:")); analysisLabels.add(new JLabel("Maximum Time Step:")); analysisLabels.add(new JLabel("Absolute Error:")); analysisLabels.add(new JLabel("Random Seed:")); analysisLabels.add(new JLabel("Runs:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:")); analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:")); analysisLabels.add(new JLabel("QSSA Condition:")); analysisLabels.add(new JLabel("Max Concentration Threshold:")); JPanel analysisFields = new JPanel(new GridLayout(15, 1)); analysisFields.add(simCommand); analysisFields.add(abs); analysisFields.add(type); analysisFields.add(sim); analysisFields.add(limit); analysisFields.add(interval); analysisFields.add(minStep); analysisFields.add(step); analysisFields.add(error); analysisFields.add(seed); analysisFields.add(runs); analysisFields.add(rapid1); analysisFields.add(rapid2); analysisFields.add(qssa); analysisFields.add(concentration); JPanel analysisPrefs = new JPanel(new GridLayout(1, 2)); analysisPrefs.add(analysisLabels); analysisPrefs.add(analysisFields); final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", "")); final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", "")); final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", "")); choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; final JComboBox bins = new JComboBox(choices); bins.setSelectedItem(biosimrc.get("biosim.learn.bins", "")); choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" }; final JComboBox equaldata = new JComboBox(choices); equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", "")); choices = new String[] { "Auto", "User" }; final JComboBox autolevels = new JComboBox(choices); autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", "")); final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", "")); final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", "")); final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", "")); final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", "")); choices = new String[] { "0", "1", "2", "3" }; final JComboBox debug = new JComboBox(choices); debug.setSelectedItem(biosimrc.get("biosim.learn.debug", "")); choices = new String[] { "Successors", "Predecessors", "Both" }; final JComboBox succpred = new JComboBox(choices); succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", "")); choices = new String[] { "True", "False" }; final JComboBox findbaseprob = new JComboBox(choices); findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", "")); JPanel learnLabels = new JPanel(new GridLayout(13, 1)); learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):")); learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):")); learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):")); learnLabels.add(new JLabel("Number Of Bins:")); learnLabels.add(new JLabel("Divide Bins:")); learnLabels.add(new JLabel("Generate Levels:")); learnLabels.add(new JLabel("Ratio For Activation (Ta):")); learnLabels.add(new JLabel("Ratio For Repression (Tr):")); learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):")); learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):")); learnLabels.add(new JLabel("Debug Level:")); learnLabels.add(new JLabel("Successors Or Predecessors:")); learnLabels.add(new JLabel("Basic FindBaseProb:")); JPanel learnFields = new JPanel(new GridLayout(13, 1)); learnFields.add(tn); learnFields.add(tj); learnFields.add(ti); learnFields.add(bins); learnFields.add(equaldata); learnFields.add(autolevels); learnFields.add(ta); learnFields.add(tr); learnFields.add(tm); learnFields.add(tt); learnFields.add(debug); learnFields.add(succpred); learnFields.add(findbaseprob); JPanel learnPrefs = new JPanel(new GridLayout(1, 2)); learnPrefs.add(learnLabels); learnPrefs.add(learnFields); JPanel generalPrefs = new JPanel(new BorderLayout()); generalPrefs.add(dialog, "North"); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); sbmlPrefsBordered.add(Undeclared, "North"); sbmlPrefsBordered.add(Units, "Center"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", dialog); prefTabs.addTab("SBML Preferences", sbmlPrefs); prefTabs.addTab("GCM Preferences", gcmPrefs); prefTabs.addTab("Analysis Preferences", analysisPrefs); prefTabs.addTab("Learn Preferences", learnPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (dialog.isSelected()) { biosimrc.put("biosim.general.file_browser", "FileDialog"); } else { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (Undeclared.isSelected()) { checkUndeclared = true; biosimrc.put("biosim.check.undeclared", "true"); } else { checkUndeclared = false; biosimrc.put("biosim.check.undeclared", "false"); } if (Units.isSelected()) { checkUnits = true; biosimrc.put("biosim.check.units", "true"); } else { checkUnits = false; biosimrc.put("biosim.check.units", "false"); } try { Double.parseDouble(KREP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KACT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBIO_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KASSOCIATION_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KBASAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(OCR_VALUE.getText().trim()); biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(COOPERATIVITY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(ACTIVED_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(MAX_DIMER_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(INITIAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim()); } catch (Exception e1) { } try { biosimrc.put("biosim.sim.command", simCommand.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(limit.getText().trim()); biosimrc.put("biosim.sim.limit", limit.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(interval.getText().trim()); biosimrc.put("biosim.sim.interval", interval.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(minStep.getText().trim()); biosimrc.put("biosim.min.sim.step", minStep.getText().trim()); } catch (Exception e1) { } try { if (step.getText().trim().equals("inf")) { biosimrc.put("biosim.sim.step", step.getText().trim()); } else { Double.parseDouble(step.getText().trim()); biosimrc.put("biosim.sim.step", step.getText().trim()); } } catch (Exception e1) { } try { Double.parseDouble(error.getText().trim()); biosimrc.put("biosim.sim.error", error.getText().trim()); } catch (Exception e1) { } try { Long.parseLong(seed.getText().trim()); biosimrc.put("biosim.sim.seed", seed.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(runs.getText().trim()); biosimrc.put("biosim.sim.runs", runs.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid1.getText().trim()); biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid2.getText().trim()); biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(qssa.getText().trim()); biosimrc.put("biosim.sim.qssa", qssa.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(concentration.getText().trim()); biosimrc.put("biosim.sim.concentration", concentration.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem()); biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem()); biosimrc.put("biosim.sim.type", (String) type.getSelectedItem()); biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem()); try { Integer.parseInt(tn.getText().trim()); biosimrc.put("biosim.learn.tn", tn.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(tj.getText().trim()); biosimrc.put("biosim.learn.tj", tj.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ti.getText().trim()); biosimrc.put("biosim.learn.ti", ti.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem()); biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem()); biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem()); try { Double.parseDouble(ta.getText().trim()); biosimrc.put("biosim.learn.ta", ta.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tr.getText().trim()); biosimrc.put("biosim.learn.tr", tr.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tm.getText().trim()); biosimrc.put("biosim.learn.tm", tm.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tt.getText().trim()); biosimrc.put("biosim.learn.tt", tt.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem()); biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem()); biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem()); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters(); ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters(); } } } else { } } else { Preferences biosimrc = Preferences.userRoot(); JPanel prefPanel = new JPanel(new GridLayout(0, 2)); JLabel verCmdLabel = new JLabel("Verification command:"); JTextField verCmd = new JTextField(biosimrc.get("biosim.verification.command", "")); viewerLabel = new JLabel("External Editor for non-LPN files:"); viewerField = new JTextField(biosimrc.get("biosim.general.viewer", "")); prefPanel.add(verCmdLabel); prefPanel.add(verCmd); prefPanel.add(viewerLabel); prefPanel.add(viewerField); // Preferences biosimrc = Preferences.userRoot(); // JPanel vhdlPrefs = new JPanel(); // JPanel lhpnPrefs = new JPanel(); // JTabbedPane prefTabsNoLema = new JTabbedPane(); // prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs); // prefTabsNoLema.addTab("LPN Preferences", lhpnPrefs); JCheckBox dialog = new JCheckBox("Use File Dialog"); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { dialog.setSelected(true); } else { dialog.setSelected(false); } prefPanel.add(dialog); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefPanel, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { viewer = viewerField.getText(); biosimrc.put("biosim.general.viewer", viewer); biosimrc.put("biosim.verification.command", verCmd.getText()); if (dialog.isSelected()) { biosimrc.put("biosim.general.file_browser", "FileDialog"); } else { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } } } } public void about() { final JFrame f = new JFrame("About"); // frame.setIconImage(new ImageIcon(ENVVAR + // File.separator // + "gui" // + File.separator + "icons" + File.separator + // "iBioSim.png").getImage()); JLabel name; JLabel version; final String developers; if (lema) { name = new JLabel("LEMA", JLabel.CENTER); version = new JLabel("Version 1.4", JLabel.CENTER); developers = "Satish Batchu\nKevin Jones\nScott Little\nCurtis Madsen\nChris Myers\nNicholas Seegmiller\n" + "Robert Thacker\nDavid Walter"; } else if (atacs) { name = new JLabel("ATACS", JLabel.CENTER); version = new JLabel("Version 6.4", JLabel.CENTER); developers = "Wendy Belluomini\nJeff Cuthbert\nHans Jacobson\nKevin Jones\nSung-Tae Jung\n" + "Christopher Krieger\nScott Little\nCurtis Madsen\nEric Mercer\nChris Myers\n" + "Curt Nelson\nEric Peskin\nNicholas Seegmiller\nDavid Walter\nHao Zheng"; } else { name = new JLabel("iBioSim", JLabel.CENTER); version = new JLabel("Version 1.4", JLabel.CENTER); developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen"; } Font font = name.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); name.setFont(font); JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER); JButton credits = new JButton("Credits"); credits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] options = { "Close" }; JOptionPane.showOptionDialog(f, developers, "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } }); JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(credits); buttons.add(close); JPanel aboutPanel = new JPanel(new BorderLayout()); JPanel uOfUPanel = new JPanel(new BorderLayout()); uOfUPanel.add(name, "North"); uOfUPanel.add(version, "Center"); uOfUPanel.add(uOfU, "South"); if (lema) { aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "LEMA.png")), "North"); } else if (atacs) { aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "ATACS.png")), "North"); } else { aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator + "gui" + separator + "icons" + separator + "iBioSim.png")), "North"); } // aboutPanel.add(bioSim, "North"); aboutPanel.add(uOfUPanel, "Center"); aboutPanel.add(buttons, "South"); f.setContentPane(aboutPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } public void exit() { int autosave = 0; for (int i = 0; i < tab.getTabCount(); i++) { int save = save(i, autosave); if (save == 0) { return; } else if (save == 2) { autosave = 1; } else if (save == 3) { autosave = 2; } } Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < numberRecentProj; i++) { if (atacs) { biosimrc.put("atacs.recent.project." + i, recentProjects[i].getText()); biosimrc.put("atacs.recent.project.path." + i, recentProjectPaths[i]); } else if (lema) { biosimrc.put("lema.recent.project." + i, recentProjects[i].getText()); biosimrc.put("lema.recent.project.path." + i, recentProjectPaths[i]); } else { biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText()); biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]); } } System.exit(1); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == viewCircuit) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); } } else if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).viewLhpn(); } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Verification) { ((Verification) array[0]).viewCircuit(); } else if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewCircuit(); } } } else if (e.getSource() == viewLog) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { if (new File(root + separator + "atacs.log").exists()) { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame(), "No log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (comp instanceof Verification) { ((Verification) comp).viewLog(); } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewLog(); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewLog(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLog(); } } } else if (e.getSource() == viewCoverage) { Component comp = tab.getSelectedComponent(); //if (treeSelected) { // JOptionPane.showMessageDialog(frame(), "No Coverage report exists.", "Error", // JOptionPane.ERROR_MESSAGE); //else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewCoverage(); } } else if (e.getSource() == viewVHDL) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { String vhdFile = tree.getFile(); if (new File(vhdFile).exists()) { File vhdlAmsFile = new File(vhdFile); BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "VHDL-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view VHDL-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewVHDL(); } } } else if (e.getSource() == viewVerilog) { // SB should change to // systemverilog?? Component comp = tab.getSelectedComponent(); if (treeSelected) { try { String vamsFileName = tree.getFile(); if (new File(vamsFileName).exists()) { File vamsFile = new File(vamsFileName); BufferedReader input = new BufferedReader(new FileReader(vamsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "Verilog Model", JOptionPane.INFORMATION_MESSAGE); // Being // generic // for // System // Verilog // and // Verilog-AMS } else { JOptionPane .showMessageDialog(this.frame(), "Verilog model does not exist.", "Error", JOptionPane.ERROR_MESSAGE);// Being // generic // for // System // Verilog // and // Verilog-AMS } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view Verilog model.", "Error", JOptionPane.ERROR_MESSAGE);// Being generic // for System // Verilog and // Verilog-AMS } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewVerilog(); } } } else if (e.getSource() == viewLHPN) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException e2) { e2.printStackTrace(); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); } } } // else if (e.getSource() == saveParam) { // Component comp = tab.getSelectedComponent(); // if (comp instanceof JTabbedPane) { // Component component = ((JTabbedPane) comp).getSelectedComponent(); // if (component instanceof Learn) { // ((Learn) component).save(); // else if (component instanceof LearnLHPN) { // ((LearnLHPN) component).save(); // else { // ((Reb2Sac) ((JTabbedPane) comp).getComponentAt(0)).save(); else if (e.getSource() == saveModel) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { for (Component component : ((JTabbedPane) comp).getComponents()) { if (component instanceof Learn) { ((Learn) component).saveGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).saveLhpn(); } } } } else if (e.getSource() == saveSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("SBML"); } else if (e.getSource() == saveTemp) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("template"); } else if (e.getSource() == saveAsGcm) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("GCM"); } // else if (e.getSource() == saveGcmAsLhpn) { // Component comp = tab.getSelectedComponent(); // ((GCM2SBMLEditor) comp).save("LHPN"); else if (e.getSource() == saveAsLhpn) { Component comp = tab.getSelectedComponent(); ((LHPNEditor) comp).save(); } else if (e.getSource() == saveAsGraph) { Component comp = tab.getSelectedComponent(); ((Graph) comp).save(); } else if (e.getSource() == saveAsSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML"); } else if (e.getSource() == saveAsTemplate) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML template"); } else if (e.getSource() == close && tab.getSelectedComponent() != null) { Component comp = tab.getSelectedComponent(); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), tab.getSelectedIndex()); } else if (e.getSource() == closeAll) { while (tab.getSelectedComponent() != null) { int index = tab.getSelectedIndex(); Component comp = tab.getComponent(index); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), index); } } else if (e.getSource() == viewRules) { Component comp = tab.getSelectedComponent(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).viewRules(); } else if (e.getSource() == viewTrace) { Component comp = tab.getSelectedComponent(); if (comp instanceof Verification) { ((Verification) comp).viewTrace(); } else if (comp instanceof Synthesis) { ((Synthesis) comp).viewTrace(); } } else if (e.getSource() == exportCsv) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(5); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5); } } else if (e.getSource() == exportDat) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(6); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(); } } else if (e.getSource() == exportEps) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(3); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3); } } else if (e.getSource() == exportJpg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(0); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0); } } else if (e.getSource() == exportPdf) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(2); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2); } } else if (e.getSource() == exportPng) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(1); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1); } } else if (e.getSource() == exportSvg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(4); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4); } } else if (e.getSource() == exportTsd) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(7); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7); } } else if (e.getSource() == about) { about(); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = ""; if (!async) { theFile = "iBioSim.html"; } else if (atacs) { theFile = "ATACS.html"; } else { theFile = "LEMA.html"; } String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { directory = ENVVAR + "/docs/"; command = "open "; } else { directory = ENVVAR + "\\docs\\"; command = "cmd /c start "; } File work = new File(directory); log.addText("Executing:\n" + command + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command + theFile, null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the exit menu item is selected else if (e.getSource() == exit) { exit(); } // if the open popup menu is selected on a sim directory else if (e.getActionCommand().equals("openSim")) { openSim(); // Translator t1 = new Translator(); // t1.BuildTemplate(tree.getFile()); // t1.outputSBML(); } else if (e.getActionCommand().equals("openLearn")) { if (lema) { openLearnLHPN(); } else { openLearn(); } } else if (e.getActionCommand().equals("openSynth")) { openSynth(); } else if (e.getActionCommand().equals("openVerification")) { openVerify(); } else if (e.getActionCommand().equals("convertToSBML")) { Translator t1 = new Translator(); t1.BuildTemplate(tree.getFile()); t1.outputSBML(); String theFile = ""; if (tree.getFile().lastIndexOf('/') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1); } if (tree.getFile().lastIndexOf('\\') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1); } updateOpenSBML(theFile.replace(".lpn", ".xml")); refreshTree(); } else if (e.getActionCommand().equals("convertToVerilog")) { new Lpn2verilog(tree.getFile()); refreshTree(); } else if (e.getActionCommand().equals("createAnalysis")) { // TODO // new Translator().BuildTemplate(tree.getFile()); // refreshTree(); try { simulate(2); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid lpn file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the create simulation popup menu is selected on a dot file else if (e.getActionCommand().equals("createSim")) { try { simulate(1); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the simulate popup menu is selected on an sbml file else if (e.getActionCommand().equals("simulate")) { try { simulate(0); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the synthesis popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createSynthesis")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) == 0) { return; } break; } } String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:", "Synthesis View ID", JOptionPane.PLAIN_MESSAGE); if (synthName != null && !synthName.trim().equals("")) { synthName = synthName.trim(); try { if (overwrite(root + separator + synthName, synthName)) { new File(root + separator + synthName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + synthName.trim() + ".syn")); out .write(("synthesis.file=" + circuitFileNoPath + "\n") .getBytes()); out.close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } try { FileInputStream in = new FileInputStream(new File(root + separator + circuitFileNoPath)); FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + circuitFileNoPath)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); String work = root + separator + synthName; String circuitFile = root + separator + synthName.trim() + separator + circuitFileNoPath; JPanel synthPane = new JPanel(); Synthesis synth = new Synthesis(work, circuitFile, log, this); // synth.addMouseListener(this); synthPane.add(synth); /* * JLabel noData = new JLabel("No data available"); * Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); * lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = * new JLabel("No data available"); font = * noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt * (lrnTab.getComponents().length - * 1).setName("TSD Graph"); */ addTab(synthName, synthPane, "Synthesis"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the verify popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createVerify")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:", "Verification View ID", JOptionPane.PLAIN_MESSAGE); if (verName != null && !verName.trim().equals("")) { verName = verName.trim(); // try { if (overwrite(root + separator + verName, verName)) { new File(root + separator + verName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + verName.trim() + ".ver")); out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes()); out.close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } /* * try { FileInputStream in = new FileInputStream(new * File(root + separator + circuitFileNoPath)); * FileOutputStream out = new FileOutputStream(new * File(root + separator + verName.trim() + separator + * circuitFileNoPath)); int read = in.read(); while * (read != -1) { out.write(read); read = in.read(); } * in.close(); out.close(); } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy * circuit file!", "Error Saving File", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); // String work = root + separator + verName; // log.addText(circuitFile); // JTabbedPane verTab = new JTabbedPane(); // JPanel verPane = new JPanel(); Verification verify = new Verification(root + separator + verName, verName, circuitFileNoPath, log, this, lema, atacs); // verify.addMouseListener(this); verify.save(); // verPane.add(verify); // JPanel abstPane = new JPanel(); // AbstPane abst = new AbstPane(root + separator + // verName, verify, // circuitFileNoPath, log, this, lema, atacs); // abstPane.add(abst); // verTab.addTab("verify", verPane); // verTab.addTab("abstract", abstPane); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - * 1).setName("TSD Graph"); */ addTab(verName, verify, "Verification"); } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Verification View directory.", "Error", // JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the delete popup menu is selected else if (e.getActionCommand().contains("delete") || e.getSource() == delete) { if (!tree.getFile().equals(root)) { if (new File(tree.getFile()).isDirectory()) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } refreshTree(); } else { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); refreshTree(); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE); } } } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("createSBML")) { try { String theFile = ""; String filename = tree.getFile(); GCMFile gcm = new GCMFile(root); gcm.load(filename); GCMParser parser = new GCMParser(filename); GeneticNetwork network = null; try { network = parser.buildNetwork(); } catch (IllegalStateException e1) { JOptionPane.showMessageDialog(frame, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return; } network.loadProperties(gcm); if (filename.lastIndexOf('/') >= 0) { theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { theFile = filename.substring(filename.lastIndexOf('\\') + 1); } if (new File(root + separator + theFile.replace(".gcm", "") + ".xml").exists()) { String[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "") + ".xml already exists. Overwrite file?", "Save file", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { GeneticNetwork.setRoot(root + separator); network.mergeSBML(root + separator + theFile.replace(".gcm", "") + ".xml"); log.addText("Saving GCM file as SBML file:\n" + root + separator + theFile.replace(".gcm", "") + ".xml\n"); refreshTree(); updateOpenSBML(theFile.replace(".gcm", "") + ".xml"); } else { // Do nothing } } else { GeneticNetwork.setRoot(root + separator); network.mergeSBML(root + separator + theFile.replace(".gcm", "") + ".xml"); log.addText("Saving GCM file as SBML file:\n" + root + separator + theFile.replace(".gcm", "") + ".xml\n"); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLHPN")) { try { String theFile = ""; String filename = tree.getFile(); GCMFile gcm = new GCMFile(root); gcm.load(filename); if (filename.lastIndexOf('/') >= 0) { theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { theFile = filename.substring(filename.lastIndexOf('\\') + 1); } if (new File(root + separator + theFile.replace(".gcm", "") + ".lpn").exists()) { String[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "") + ".lpn already exists. Overwrite file?", "Save file", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { gcm.createLogicalModel(root + separator + theFile.replace(".gcm", "") + ".lpn", log, this, theFile.replace(".gcm", "") + ".lpn"); } else { // Do nothing } } else { gcm.createLogicalModel(root + separator + theFile.replace(".gcm", "") + ".lpn", log, this, theFile.replace(".gcm", "") + ".lpn"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create LPN file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("dotEditor")) { try { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { File work = new File(directory); GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("stateGraph")) { try { String directory = root + separator + tab.getTitleAt(tab.getSelectedIndex()); File work = new File(directory); for (String f : new File(directory).list()) { if (f.contains("_sg.dot")) { Runtime exec = Runtime.getRuntime(); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + separator + f + "\n"); exec.exec("dotty " + f, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + separator + f + "\n"); exec.exec("open " + f, null, work); } else { log.addText("Executing:\ndotty " + directory + separator + f + "\n"); exec.exec("dotty " + f, null, work); } return; } } JOptionPane.showMessageDialog(frame, "State graph file has not been generated.", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing state graph.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("graphTree")) { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } File work = new File(directory); String out = theFile; try { if (out.contains(".lpn")) { String file = theFile; String[] findTheFile = file.split("\\."); theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + file; Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } return; } if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".gcm")) { try { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } return; } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); JList empty = new JList(); run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1, new String[0], new String[0], "tsd.printer", "amount", (directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty, null); log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (theFile.substring(theFile.length() - 4).equals("sbml")) { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties"; } else { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { String directory = ""; String theFile = ""; /* * if (!treeSelected) { Component comp = tab.getSelectedComponent(); * if (comp instanceof JTabbedPane) { Component component = * ((JTabbedPane) comp).getSelectedComponent(); if (component * instanceof Learn) { ((Learn) component).viewGcm(); return; } } * else if (comp instanceof LHPNEditor) { try { String filename = * tab.getTitleAt(tab.getSelectedIndex()); String[] findTheFile = * filename.split("\\."); theFile = findTheFile[0] + ".dot"; File * dot = new File(root + separator + theFile); dot.delete(); String * cmd = "atacs -cPllodpl " + filename; File work = new File(root); * Runtime exec = Runtime.getRuntime(); Process ATACS = * exec.exec(cmd, null, work); ATACS.waitFor(); * log.addText("Executing:\n" + cmd); if (dot.exists()) { String * command = ""; if * (System.getProperty("os.name").contentEquals("Linux")) { // * directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if * (System.getProperty("os.name").toLowerCase().startsWith( * "mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; * } else { // directory = ENVVAR + "\\docs\\"; command = * "dotty start "; } log.addText(command + root + separator + * theFile + "\n"); exec.exec(command + theFile, null, work); } else * { File log = new File(root + separator + "atacs.log"); * BufferedReader input = new BufferedReader(new FileReader(log)); * String line = null; JTextArea messageArea = new JTextArea(); * while ((line = input.readLine()) != null) { * messageArea.append(line); * messageArea.append(System.getProperty("line.separator")); } * input.close(); messageArea.setLineWrap(true); * messageArea.setWrapStyleWord(true); * messageArea.setEditable(false); JScrollPane scrolls = new * JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); * scrolls.setPreferredSize(new Dimension(500, 500)); * scrolls.setViewportView(messageArea); * JOptionPane.showMessageDialog(frame(), scrolls, "Log", * JOptionPane.INFORMATION_MESSAGE); } return; } catch (Exception * e1) { JOptionPane.showMessageDialog(frame, * "Unable to view this lpn.", "Error", JOptionPane.ERROR_MESSAGE); * return; } } else if (comp instanceof SBML_Editor) { directory = * root + separator; theFile = * tab.getTitleAt(tab.getSelectedIndex()); } else if (comp * instanceof GCM2SBMLEditor) { directory = root + separator; * theFile = tab.getTitleAt(tab.getSelectedIndex()); } } else { */ String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } File work = new File(directory); String out = theFile; try { if (out.contains(".lpn")) { String file = theFile; String[] findTheFile = file.split("\\."); theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + file; Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } return; } if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".gcm")) { try { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } return; } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); JList empty = new JList(); run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1, new String[0], new String[0], "tsd.printer", "amount", (directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty, null); log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (theFile.substring(theFile.length() - 4).equals("sbml")) { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties"; } else { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the browse popup menu is selected on an sbml file else if (e.getActionCommand().equals("browse")) { String directory; String theFile; /* * if (!treeSelected) { Component comp = tab.getSelectedComponent(); * if (comp instanceof SBML_Editor) { if * (save(tab.getSelectedIndex(), 0) != 1) { return; } theFile = * tab.getTitleAt(tab.getSelectedIndex()); directory = root + * separator; } else { return; } } else { */ String filename = tree.getFile(); directory = ""; theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } try { Run run = new Run(null); JCheckBox dummy = new JCheckBox(); JList empty = new JList(); dummy.setSelected(false); run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1, new String[0], new String[0], "tsd.printer", "amount", (directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty, null); log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); String error = ""; String output = ""; InputStream reb = browse.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = browse.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } browse.waitFor(); String command = ""; if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { command = "cmd /c start "; } log.addText("Executing:\n" + command + directory + out + ".xhtml\n"); exec.exec(command + out + ".xhtml", null, work); } String remove; if (theFile.substring(theFile.length() - 4).equals("sbml")) { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties"; } else { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph dot popup menu is selected /* * else if (e.getActionCommand().equals("graphDot")) { if * (!treeSelected) { Component comp = tab.getSelectedComponent(); if * (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) * comp).getSelectedComponent(); if (component instanceof Learn) { * ((Learn) component).viewGcm(); } } } else { try { String filename = * tree.getFile(); String directory = ""; String theFile = ""; if * (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, * filename.lastIndexOf('/') + 1); theFile = * filename.substring(filename.lastIndexOf('/') + 1); } if * (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, * filename.lastIndexOf('\\') + 1); theFile = * filename.substring(filename.lastIndexOf('\\') + 1); } File work = new * File(directory); if * (System.getProperty("os.name").contentEquals("Linux")) { * log.addText("Executing:\ndotty " + directory + theFile + "\n"); * Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, * null, work); } else if * (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { * log.addText("Executing:\nopen " + directory + theFile + "\n"); * Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " * + theFile + ".dot", null, work); exec = Runtime.getRuntime(); * exec.exec("open " + theFile + ".dot", null, work); } else { * log.addText("Executing:\ndotty " + directory + theFile + "\n"); * Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, * null, work); } } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", * "Error", JOptionPane.ERROR_MESSAGE); } } } */ // if the save button is pressed on the Tool Bar else if (e.getActionCommand().equals("save")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).save(); } else if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).save("Save GCM"); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(false, "", true); } else if (comp instanceof Graph) { ((Graph) comp).save(); } else if (comp instanceof Verification) { ((Verification) comp).save(); } else if (comp instanceof JTabbedPane) { for (Component component : ((JTabbedPane) comp).getComponents()) { int index = ((JTabbedPane) comp).getSelectedIndex(); if (component instanceof Graph) { ((Graph) component).save(); } else if (component instanceof Learn) { ((Learn) component).save(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); } else if (component instanceof DataManager) { ((DataManager) component).saveChanges(((JTabbedPane) comp) .getTitleAt(index)); } else if (component instanceof SBML_Editor) { ((SBML_Editor) component).save(false, "", true); } else if (component instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) component).saveParams(false, ""); } else if (component instanceof Reb2Sac) { ((Reb2Sac) component).save(); } } } if (comp instanceof JPanel) { if (comp.getName().equals("Synthesis")) { // ((Synthesis) tab.getSelectedComponent()).save(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).save(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); try { File output = new File(root + separator + fileName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + fileName); this.updateAsyncViews(fileName); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the save as button is pressed on the Tool Bar else if (e.getActionCommand().equals("saveas")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter LPN name:", "LPN Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".lpn")) { newName = newName + ".lpn"; } ((LHPNEditor) comp).saveAs(newName); tab.setTitleAt(tab.getSelectedIndex(), newName); } else if (comp instanceof GCM2SBMLEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:", "GCM Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (newName.contains(".gcm")) { newName = newName.replace(".gcm", ""); } ((GCM2SBMLEditor) comp).saveAs(newName); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).saveAs(); } else if (comp instanceof Graph) { ((Graph) comp).saveAs(); } else if (comp instanceof Verification) { ((Verification) comp).saveAs(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).saveAs(); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Synthesis")) { Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).saveAs(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); String newName = ""; if (fileName.endsWith(".vhd")) { newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".vhd")) { newName = newName + ".vhd"; } } else if (fileName.endsWith(".s")) { newName = JOptionPane.showInputDialog(frame(), "Enter Assembly File Name:", "Assembly File Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".s")) { newName = newName + ".s"; } } else if (fileName.endsWith(".inst")) { newName = JOptionPane.showInputDialog(frame(), "Enter Instruction File Name:", "Instruction File Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".inst")) { newName = newName + ".inst"; } } else if (fileName.endsWith(".g")) { newName = JOptionPane.showInputDialog(frame(), "Enter Petri net name:", "Petri net Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".g")) { newName = newName + ".g"; } } else if (fileName.endsWith(".csp")) { newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".csp")) { newName = newName + ".csp"; } } else if (fileName.endsWith(".hse")) { newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".hse")) { newName = newName + ".hse"; } } else if (fileName.endsWith(".unc")) { newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".unc")) { newName = newName + ".unc"; } } else if (fileName.endsWith(".rsg")) { newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".rsg")) { newName = newName + ".rsg"; } } try { File output = new File(root + separator + newName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + newName); File oldFile = new File(root + separator + fileName); oldFile.delete(); tab.setTitleAt(tab.getSelectedIndex(), newName); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the run button is selected on the tool bar else if (e.getActionCommand().equals("run")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); int index = -1; for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) { index = i; break; } } if (component instanceof Graph) { if (index != -1) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton() .doClick(); } else { ((Graph) component).save(); ((Graph) component).run(); } } else if (component instanceof Learn) { ((Learn) component).save(); new Thread((Learn) component).start(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); ((LearnLHPN) component).learn(); } else if (component instanceof SBML_Editor) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof Reb2Sac) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JPanel) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JScrollPane) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } } else if (comp instanceof Verification) { ((Verification) comp).save(); new Thread((Verification) comp).start(); } else if (comp instanceof Synthesis) { ((Synthesis) comp).save(); new Thread((Synthesis) comp).start(); } } else if (e.getActionCommand().equals("refresh")) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).refresh(); } } else if (comp instanceof Graph) { ((Graph) comp).refresh(); } } else if (e.getActionCommand().equals("check")) { Component comp = tab.getSelectedComponent(); if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(true, "", true); ((SBML_Editor) comp).check(); } } else if (e.getActionCommand().equals("export")) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).export(); } } } // if the new menu item is selected else if (e.getSource() == newProj) { int autosave = 0; for (int i = 0; i < tab.getTabCount(); i++) { int save = save(i, autosave); if (save == 0) { return; } else if (save == 2) { autosave = 1; } else if (save == 3) { autosave = 2; } } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.project_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.project_dir", "")); } String filename = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "New", -1); if (!filename.trim().equals("")) { filename = filename.trim(); biosimrc.put("biosim.general.project_dir", filename); File f = new File(filename); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return; } } new File(filename).mkdir(); try { if (lema) { new FileWriter(new File(filename + separator + "LEMA.prj")).close(); } else if (atacs) { new FileWriter(new File(filename + separator + "ATACS.prj")).close(); } else { new FileWriter(new File(filename + separator + "BioSim.prj")).close(); } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbml.setEnabled(true); importBioModel.setEnabled(true); importVhdl.setEnabled(true); importS.setEnabled(true); importInst.setEnabled(true); importLpn.setEnabled(true); importG.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newS.setEnabled(true); newInst.setEnabled(true); newLhpn.setEnabled(true); newG.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } } // if the open project menu item is selected else if (e.getSource() == pref) { preferences(); } else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) { int autosave = 0; for (int i = 0; i < tab.getTabCount(); i++) { int save = save(i, autosave); if (save == 0) { return; } else if (save == 2) { autosave = 1; } else if (save == 3) { autosave = 2; } } Preferences biosimrc = Preferences.userRoot(); String projDir = ""; if (e.getSource() == openProj) { File file; if (biosimrc.get("biosim.general.project_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.project_dir", "")); } projDir = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "Open", -1); if (projDir.endsWith(".prj")) { biosimrc.put("biosim.general.project_dir", projDir); String[] tempArray = projDir.split(separator); projDir = ""; for (int i = 0; i < tempArray.length - 1; i++) { projDir = projDir + tempArray[i] + separator; } } } else if (e.getSource() == recentProjects[0]) { projDir = recentProjectPaths[0]; } else if (e.getSource() == recentProjects[1]) { projDir = recentProjectPaths[1]; } else if (e.getSource() == recentProjects[2]) { projDir = recentProjectPaths[2]; } else if (e.getSource() == recentProjects[3]) { projDir = recentProjectPaths[3]; } else if (e.getSource() == recentProjects[4]) { projDir = recentProjectPaths[4]; } // log.addText(projDir); if (!projDir.equals("")) { biosimrc.put("biosim.general.project_dir", projDir); if (new File(projDir).isDirectory()) { boolean isProject = false; for (String temp : new File(projDir).list()) { if (temp.equals(".prj")) { isProject = true; } if (lema && temp.equals("LEMA.prj")) { isProject = true; } else if (atacs && temp.equals("ATACS.prj")) { isProject = true; } else if (temp.equals("BioSim.prj")) { isProject = true; } } if (isProject) { root = projDir; refresh(); tab.removeAll(); addRecentProject(projDir); importDot.setEnabled(true); importSbml.setEnabled(true); importBioModel.setEnabled(true); importVhdl.setEnabled(true); importS.setEnabled(true); importInst.setEnabled(true); importLpn.setEnabled(true); importG.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newS.setEnabled(true); newInst.setEnabled(true); newLhpn.setEnabled(true); newG.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new circuit model menu item is selected else if (e.getSource() == newCircuit) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 3) { if (!simName.substring(simName.length() - 4).equals(".gcm")) { simName += ".gcm"; } } else { simName += ".gcm"; } String modelID = ""; if (simName.length() > 3) { if (simName.substring(simName.length() - 4).equals(".gcm")) { modelID = simName.substring(0, simName.length() - 4); } else { modelID = simName.substring(0, simName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); new GCMFile(root).save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f .getName(), this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(f.getName(), gcm, "GCM Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new SBML model menu item is selected else if (e.getSource() == newModel) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) { simName += ".xml"; } } else { simName += ".xml"; } String modelID = ""; if (simName.length() > 4) { if (simName.substring(simName.length() - 5).equals(".sbml")) { modelID = simName.substring(0, simName.length() - 5); } else { modelID = simName.substring(0, simName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { String f = new String(root + separator + simName); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(BioSim.SBML_LEVEL, BioSim.SBML_VERSION); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + simName); SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null); // sbml.addMouseListener(this); addTab(f.split(separator)[f.split(separator).length - 1], sbml, "SBML Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new vhdl menu item is selected else if (e.getSource() == newVhdl) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 3) { if (!vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) { vhdlName += ".vhd"; } } else { vhdlName += ".vhd"; } String modelID = ""; if (vhdlName.length() > 3) { if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) { modelID = vhdlName.substring(0, vhdlName.length() - 4); } else { modelID = vhdlName.substring(0, vhdlName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + vhdlName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(vhdlName, scroll, "VHDL Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new assembly menu item is selected else if (e.getSource() == newS) { if (root != null) { try { String SName = JOptionPane.showInputDialog(frame, "Enter Assembly File Name:", "Assembly File Name", JOptionPane.PLAIN_MESSAGE); if (SName != null && !SName.trim().equals("")) { SName = SName.trim(); if (SName.length() > 1) { if (!SName.substring(SName.length() - 2).equals(".s")) { SName += ".s"; } } else { SName += ".s"; } String modelID = ""; if (SName.length() > 1) { if (SName.substring(SName.length() - 2).equals(".s")) { modelID = SName.substring(0, SName.length() - 2); } else { modelID = SName.substring(0, SName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A assembly file name can only contain letters, numbers, and underscores.", "Invalid File Name", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + SName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + SName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(SName, scroll, "Assembly File Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new assembly file.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new instruction file menu item is selected else if (e.getSource() == newInst) { if (root != null) { try { String InstName = JOptionPane.showInputDialog(frame, "Enter Instruction File Name:", "Instruction File Name", JOptionPane.PLAIN_MESSAGE); if (InstName != null && !InstName.trim().equals("")) { InstName = InstName.trim(); if (InstName.length() > 4) { if (!InstName.substring(InstName.length() - 5).equals(".inst")) { InstName += ".inst"; } } else { InstName += ".inst"; } String modelID = ""; if (InstName.length() > 4) { if (InstName.substring(InstName.length() - 5).equals(".inst")) { modelID = InstName.substring(0, InstName.length() - 5); } else { modelID = InstName.substring(0, InstName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A instruction file name can only contain letters, numbers, and underscores.", "Invalid File Name", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + InstName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + InstName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(InstName, scroll, "Instruction File Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new instruction file.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new petri net menu item is selected else if (e.getSource() == newG) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter Petri Net Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 1) { if (!vhdlName.substring(vhdlName.length() - 2).equals(".g")) { vhdlName += ".g"; } } else { vhdlName += ".g"; } String modelID = ""; if (vhdlName.length() > 1) { if (vhdlName.substring(vhdlName.length() - 2).equals(".g")) { modelID = vhdlName.substring(0, vhdlName.length() - 2); } else { modelID = vhdlName.substring(0, vhdlName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + vhdlName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(vhdlName, scroll, "Petri Net Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new lhpn menu item is selected else if (e.getSource() == newLhpn) { if (root != null) { try { String lhpnName = JOptionPane.showInputDialog(frame, "Enter LPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 3) { if (!lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) { lhpnName += ".lpn"; } } else { lhpnName += ".lpn"; } String modelID = ""; if (lhpnName.length() > 3) { if (lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) { modelID = lhpnName.substring(0, lhpnName.length() - 4); } else { modelID = lhpnName.substring(0, lhpnName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { // if (overwrite(root + separator + lhpnName, // lhpnName)) { // File f = new File(root + separator + lhpnName); // f.delete(); // f.createNewFile(); // new LHPNFile(log).save(f.getAbsolutePath()); // int i = getTab(f.getName()); // if (i != -1) { // tab.remove(i); // addTab(f.getName(), new LHPNEditor(root + // separator, f.getName(), // null, this, log), "LPN Editor"); // refreshTree(); if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.createNewFile(); new LhpnFile(log).save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(), null, this, log); // lhpn.addMouseListener(this); addTab(f.getName(), lhpn, "LHPN Editor"); refreshTree(); } // File f = new File(root + separator + lhpnName); // f.createNewFile(); // String[] command = { "emacs", f.getName() }; // Runtime.getRuntime().exec(command); // refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new csp menu item is selected else if (e.getSource() == newCsp) { if (root != null) { try { String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (cspName != null && !cspName.trim().equals("")) { cspName = cspName.trim(); if (cspName.length() > 3) { if (!cspName.substring(cspName.length() - 4).equals(".csp")) { cspName += ".csp"; } } else { cspName += ".csp"; } String modelID = ""; if (cspName.length() > 3) { if (cspName.substring(cspName.length() - 4).equals(".csp")) { modelID = cspName.substring(0, cspName.length() - 4); } else { modelID = cspName.substring(0, cspName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + cspName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + cspName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(cspName, scroll, "CSP Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new hse menu item is selected else if (e.getSource() == newHse) { if (root != null) { try { String hseName = JOptionPane.showInputDialog(frame, "Enter Handshaking Expansion Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (hseName != null && !hseName.trim().equals("")) { hseName = hseName.trim(); if (hseName.length() > 3) { if (!hseName.substring(hseName.length() - 4).equals(".hse")) { hseName += ".hse"; } } else { hseName += ".hse"; } String modelID = ""; if (hseName.length() > 3) { if (hseName.substring(hseName.length() - 4).equals(".hse")) { modelID = hseName.substring(0, hseName.length() - 4); } else { modelID = hseName.substring(0, hseName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + hseName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + hseName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(hseName, scroll, "HSE Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new unc menu item is selected else if (e.getSource() == newUnc) { if (root != null) { try { String uncName = JOptionPane.showInputDialog(frame, "Enter Extended Burst Mode Machine ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (uncName != null && !uncName.trim().equals("")) { uncName = uncName.trim(); if (uncName.length() > 3) { if (!uncName.substring(uncName.length() - 4).equals(".unc")) { uncName += ".unc"; } } else { uncName += ".unc"; } String modelID = ""; if (uncName.length() > 3) { if (uncName.substring(uncName.length() - 4).equals(".unc")) { modelID = uncName.substring(0, uncName.length() - 4); } else { modelID = uncName.substring(0, uncName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + uncName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + uncName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(uncName, scroll, "UNC Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newRsg) { if (root != null) { try { String rsgName = JOptionPane.showInputDialog(frame, "Enter Reduced State Graph Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (rsgName != null && !rsgName.trim().equals("")) { rsgName = rsgName.trim(); if (rsgName.length() > 3) { if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) { rsgName += ".rsg"; } } else { rsgName += ".rsg"; } String modelID = ""; if (rsgName.length() > 3) { if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) { modelID = rsgName.substring(0, rsgName.length() - 4); } else { modelID = rsgName.substring(0, rsgName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + rsgName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + rsgName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(rsgName, scroll, "RSG Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newSpice) { if (root != null) { try { String spiceName = JOptionPane.showInputDialog(frame, "Enter Spice Circuit ID:", "Circuit ID", JOptionPane.PLAIN_MESSAGE); if (spiceName != null && !spiceName.trim().equals("")) { spiceName = spiceName.trim(); if (spiceName.length() > 3) { if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) { spiceName += ".cir"; } } else { spiceName += ".cir"; } String modelID = ""; if (spiceName.length() > 3) { if (spiceName.substring(spiceName.length() - 4).equals(".cir")) { modelID = spiceName.substring(0, spiceName.length() - 4); } else { modelID = spiceName.substring(0, spiceName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + spiceName); f.createNewFile(); refreshTree(); if (!viewer.equals("")) { String command = viewer + " " + root + separator + spiceName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(spiceName, scroll, "Spice Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1); if (!filename.trim().equals("")) { biosimrc.put("biosim.general.import_dir", filename.trim()); if (new File(filename.trim()).isDirectory()) { JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML files contain the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; for (String s : new File(filename.trim()).list()) { if (s.endsWith(".xml") || s.endsWith(".sbml")) { try { SBMLDocument document = readSBML(filename.trim() + separator + s); checkModelCompleteness(document); if (overwrite(root + separator + s, s)) { long numErrors = document.checkConsistency(); if (numErrors > 0) { display = true; messageArea .append(" messageArea.append(s); messageArea .append("\n for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } } SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + s); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } } refreshTree(); if (display) { final JFrame f = new JFrame("SBML Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } else { String[] file = filename.trim().split(separator); try { SBMLDocument document = readSBML(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { checkModelCompleteness(document); long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea .append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } SBMLWriter writer = new SBMLWriter(); writer .writeSBML(document, root + separator + file[file.length - 1]); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importBioModel) { if (root != null) { final BioModelsWSClient client = new BioModelsWSClient(); if (BioModelIds == null) { try { BioModelIds = client.getAllCuratedModelsId(); } catch (BioModelsWSException e2) { JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE); } } JPanel BioModelsPanel = new JPanel(new BorderLayout()); final JList ListOfBioModels = new JList(); sort(BioModelIds); ListOfBioModels.setListData(BioModelIds); ListOfBioModels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JLabel TextBioModels = new JLabel("List of BioModels"); JScrollPane ScrollBioModels = new JScrollPane(); ScrollBioModels.setMinimumSize(new Dimension(520, 250)); ScrollBioModels.setPreferredSize(new Dimension(552, 250)); ScrollBioModels.setViewportView(ListOfBioModels); JPanel GetButtons = new JPanel(); JButton GetNames = new JButton("Get Names"); JButton GetDescription = new JButton("Get Description"); JButton GetReference = new JButton("Get Reference"); GetNames.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < BioModelIds.length; i++) { try { BioModelIds[i] += " " + client.getModelNameById(BioModelIds[i]); } catch (BioModelsWSException e1) { JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE); } } ListOfBioModels.setListData(BioModelIds); } }); GetDescription.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String SelectedModel = ((String) ListOfBioModels.getSelectedValue()) .split(" ")[0]; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open http: + SelectedModel; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open http: + SelectedModel; } else { command = "cmd /c start http: + SelectedModel; } log.addText("Executing:\n" + command + "\n"); Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open model description.", "Error", JOptionPane.ERROR_MESSAGE); } } }); GetReference.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String SelectedModel = ((String) ListOfBioModels.getSelectedValue()) .split(" ")[0]; try { String Pub = (client.getSimpleModelById(SelectedModel)) .getPublicationId(); String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open http: + Pub; } else if (System.getProperty("os.name").toLowerCase().startsWith( "mac os")) { command = "open http: + Pub; } else { command = "cmd /c start http: + Pub; } log.addText("Executing:\n" + command + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command); } catch (BioModelsWSException e2) { JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open model description.", "Error", JOptionPane.ERROR_MESSAGE); } } }); GetButtons.add(GetNames); GetButtons.add(GetDescription); GetButtons.add(GetReference); BioModelsPanel.add(TextBioModels, "North"); BioModelsPanel.add(ScrollBioModels, "Center"); BioModelsPanel.add(GetButtons, "South"); Object[] options = { "OK", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, BioModelsPanel, "List of BioModels", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); /* * String modelNumber = JOptionPane.showInputDialog(frame, * "Enter BioModel Number:", "BioModel Number", * JOptionPane.PLAIN_MESSAGE); */ // if (modelNumber != null && !modelNumber.equals("")) { if (value == JOptionPane.YES_OPTION && ListOfBioModels.getSelectedValue() != null) { String BMurl = "http: String filename = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0]; /* * String filename = "BIOMD"; for (int i = 0; i < 10 - * modelNumber.length(); i++) { filename += "0"; } filename * += modelNumber + ".xml"; */ filename += ".xml"; try { URL url = new URL(BMurl + filename); /* * System.out.println("Opening connection to " + BMurl + * filename + "..."); */ URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); /* * System.out.println("Copying resource (type: " + * urlC.getContentType() + ")..."); System.out.flush(); */ if (overwrite(root + separator + filename, filename)) { FileOutputStream fos = null; fos = new FileOutputStream(root + separator + filename); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); // System.out.println(count + " byte(s) copied"); String[] file = filename.trim().split(separator); SBMLDocument document = readSBML(root + separator + filename.trim()); long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea .append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + file[file.length - 1]); refreshTree(); } } catch (MalformedURLException e1) { JOptionPane.showMessageDialog(frame, e1.toString(), "Error", JOptionPane.ERROR_MESSAGE); filename = ""; } catch (IOException e1) { JOptionPane.showMessageDialog(frame, filename + " not found.", "Error", JOptionPane.ERROR_MESSAGE); filename = ""; } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import dot menu item is selected else if (e.getSource() == importDot) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1); if (filename != null && !filename.trim().equals("")) { biosimrc.put("biosim.general.import_dir", filename.trim()); } if (new File(filename.trim()).isDirectory()) { for (String s : new File(filename.trim()).list()) { if (!(filename.trim() + separator + s).equals("") && (filename.trim() + separator + s).length() > 3 && (filename.trim() + separator + s).substring( (filename.trim() + separator + s).length() - 4, (filename.trim() + separator + s).length()).equals(".gcm")) { try { // GCMParser parser = new GCMParser((filename.trim() + separator + s)); if (overwrite(root + separator + s, s)) { FileOutputStream out = new FileOutputStream(new File(root + separator + s)); FileInputStream in = new FileInputStream(new File((filename .trim() + separator + s))); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { if (filename.trim().length() > 3 && !filename.trim().substring(filename.trim().length() - 4, filename.trim().length()).equals(".gcm")) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.trim().equals("")) { String[] file = filename.trim().split(separator); try { // GCMParser parser = new GCMParser(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename.trim())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import vhdl menu item is selected else if (e.getSource() == importVhdl) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import VHDL Model", -1); if (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals( ".vhd")) { JOptionPane.showMessageDialog(frame, "You must select a valid vhdl file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importS) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import Assembly File", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals( ".s")) { JOptionPane.showMessageDialog(frame, "You must select a valid assembly file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importInst) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import Instruction File", -1); if (filename.length() > 4 && !filename.substring(filename.length() - 5, filename.length()).equals( ".inst")) { JOptionPane.showMessageDialog(frame, "You must select a valid instruction file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importLpn) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import LPN", -1); if ((filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals(".g")) && (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals(".lpn"))) { JOptionPane.showMessageDialog(frame, "You must select a valid LPN file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { if (new File(filename).exists()) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); // log.addText(filename); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } if (filename.substring(filename.length() - 2, filename.length()).equals( ".g")) { // log.addText(filename + file[file.length - 1]); File work = new File(root); String oldName = root + separator + file[file.length - 1]; // String newName = oldName.replace(".lpn", // "_NEW.g"); Process atacs = Runtime.getRuntime().exec("atacs -lgsl " + oldName, null, work); atacs.waitFor(); String lpnName = oldName.replace(".g", ".lpn"); String newName = oldName.replace(".g", "_NEW.lpn"); atacs = Runtime.getRuntime().exec("atacs -llsl " + lpnName, null, work); atacs.waitFor(); FileOutputStream out = new FileOutputStream(new File(lpnName)); FileInputStream in = new FileInputStream(new File(newName)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); new File(newName).delete(); } refreshTree(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importG) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import Net", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals( ".g")) { JOptionPane.showMessageDialog(frame, "You must select a valid Petri net file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import csp menu item is selected else if (e.getSource() == importCsp) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import CSP", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".csp")) { JOptionPane.showMessageDialog(frame, "You must select a valid csp file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import hse menu item is selected else if (e.getSource() == importHse) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import HSE", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".hse")) { JOptionPane.showMessageDialog(frame, "You must select a valid handshaking expansion file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import unc menu item is selected else if (e.getSource() == importUnc) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import UNC", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".unc")) { JOptionPane.showMessageDialog(frame, "You must select a valid expanded burst mode machine file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import rsg menu item is selected else if (e.getSource() == importRsg) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import RSG", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".rsg")) { JOptionPane.showMessageDialog(frame, "You must select a valid rsg file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import spice menu item is selected else if (e.getSource() == importSpice) { if (root != null) { File importFile; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import Spice Circuit", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".cir")) { JOptionPane.showMessageDialog(frame, "You must select a valid spice circuit file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { biosimrc.put("biosim.general.import_dir", filename); String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the Graph data menu item is clicked else if (e.getSource() == graph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "Number of molecules", graphName.trim() .substring(0, graphName.length() - 4), "tsd.printer", root, "Time", this, null, log, graphName.trim(), true, false); addTab(graphName.trim(), g, "TSD Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == probGraph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Probability Graph:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "Number of Molecules", graphName.trim() .substring(0, graphName.length() - 4), "tsd.printer", root, "Time", this, null, log, graphName.trim(), false, false); addTab(graphName.trim(), g, "Probability Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLearn")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE); if (lrnName != null && !lrnName.trim().equals("")) { lrnName = lrnName.trim(); // try { if (overwrite(root + separator + lrnName, lrnName)) { new File(root + separator + lrnName).mkdir(); // new FileWriter(new File(root + separator + // lrnName + separator // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; if (sbmlFileNoPath.endsWith(".vhd")) { try { File work = new File(root); Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null, work); sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".lpn"); log.addText("atacs -lvsl " + sbmlFileNoPath + "\n"); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to generate LPN from VHDL file!", "Error Generating File", JOptionPane.ERROR_MESSAGE); } } try { FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn")); if (lema) { out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes()); } else { out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes()); } out.close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JTabbedPane lrnTab = new JTabbedPane(); lrnTab.addMouseListener(this); DataManager data = new DataManager(root + separator + lrnName, this, lema); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Data Manager"); if (lema) { LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } else { Learn learn = new Learn(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } // learn.addMouseListener(this); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph; tsdGraph = new Graph(null, "Number of molecules", lrnName + " data", "tsd.printer", root + separator + lrnName, "Time", this, null, log, null, true, false); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "TSD Graph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - * 1).setName("TSD Graph"); */ addTab(lrnName, lrnTab, null); } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Learn View directory.", "Error", // JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("viewState")) { if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(tree.getFile()); log.addText("Creating state graph."); StateGraph sg = new StateGraph(lhpnFile); sg.buildStateGraph(); sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), false); String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; log.addText("Executing:\n" + command + root + separator + (file.replace(".lpn", "_sg.dot")) + "\n"); Runtime exec = Runtime.getRuntime(); File work = new File(root); try { exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("markov")) { if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(tree.getFile()); log.addText("Creating state graph."); StateGraph sg = new StateGraph(lhpnFile); sg.buildStateGraph(); log.addText("Performing Markov Chain analysis."); sg.performMarkovianAnalysis(null); sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), true); String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; log.addText("Executing:\n" + command + root + separator + (file.replace(".lpn", "_sg.dot")) + "\n"); Runtime exec = Runtime.getRuntime(); File work = new File(root); try { exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("viewModel")) { try { if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPlgodpe " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String vhdFile = tree.getFile(); if (new File(vhdFile).exists()) { File vhdlAmsFile = new File(vhdFile); BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "VHDL-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view VHDL-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } /* * String filename = * tree.getFile().split(separator)[tree.getFile().split( * separator).length - 1]; String cmd = "atacs -lvslllodpl " * + filename; File work = new File(root); Runtime exec = * Runtime.getRuntime(); Process view = exec.exec(cmd, null, * work); log.addText("Executing:\n" + cmd); String[] * findTheFile = filename.split("\\."); view.waitFor(); // * String directory = ""; String theFile = findTheFile[0] + * ".dot"; if (new File(root + separator + * theFile).exists()) { String command = ""; if * (System.getProperty("os.name").contentEquals("Linux")) { * // directory = ENVVAR + "/docs/"; command = * "gnome-open "; } else if * (System.getProperty("os.name").toLowerCase * ().startsWith("mac os")) { // directory = ENVVAR + * "/docs/"; command = "open "; } else { // directory = * ENVVAR + "\\docs\\"; command = "dotty start "; } * log.addText(command + root + theFile + "\n"); * exec.exec(command + theFile, null, work); } else { File * log = new File(root + separator + "atacs.log"); * BufferedReader input = new BufferedReader(new * FileReader(log)); String line = null; JTextArea * messageArea = new JTextArea(); while ((line = * input.readLine()) != null) { messageArea.append(line); * messageArea.append(System.getProperty("line.separator")); * } input.close(); messageArea.setLineWrap(true); * messageArea.setWrapStyleWord(true); * messageArea.setEditable(false); JScrollPane scrolls = new * JScrollPane(); scrolls.setMinimumSize(new Dimension(500, * 500)); scrolls.setPreferredSize(new Dimension(500, 500)); * scrolls.setViewportView(messageArea); * JOptionPane.showMessageDialog(frame(), scrolls, "Log", * JOptionPane.INFORMATION_MESSAGE); } */ } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { try { String vamsFileName = tree.getFile(); if (new File(vamsFileName).exists()) { File vamsFile = new File(vamsFileName); BufferedReader input = new BufferedReader(new FileReader(vamsFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "Verilog-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view Verilog-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 3 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { try { String svFileName = tree.getFile(); if (new File(svFileName).exists()) { File svFile = new File(svFileName); BufferedReader input = new BufferedReader(new FileReader(svFile)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(800, 500)); scrolls.setPreferredSize(new Dimension(800, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(this.frame(), scrolls, "SystemVerilog Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this.frame(), "SystemVerilog model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(this.frame(), "Unable to view SystemVerilog model.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lcslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lhslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lxodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lsodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = ENVVAR + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = ENVVAR + "/docs/"; command = "open "; } else { // directory = ENVVAR + "\\docs\\"; command = "dotty start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException e2) { e2.printStackTrace(); } } else if (e.getActionCommand().equals("copy") || e.getSource() == copy) { if (!tree.getFile().equals(root)) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String modelID = null; String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } try { if (!copy.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".sbml") && !copy.substring(copy.length() - 4).equals(".xml")) { copy += ".xml"; } } else { copy += ".xml"; } if (copy.length() > 4) { if (copy.substring(copy.length() - 5).equals(".sbml")) { modelID = copy.substring(0, copy.length() - 5); } else { modelID = copy.substring(0, copy.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".vhd")) { copy += ".vhd"; } } else { copy += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".s")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".s")) { copy += ".s"; } } else { copy += ".s"; } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".inst")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".inst")) { copy += ".inst"; } } else { copy += ".inst"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".g")) { copy += ".g"; } } else { copy += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".lpn")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".lpn")) { copy += ".lpn"; } } else { copy += ".lpn"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".csp")) { copy += ".csp"; } } else { copy += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".hse")) { copy += ".hse"; } } else { copy += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".unc")) { copy += ".unc"; } } else { copy += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".rsg")) { copy += ".rsg"; } } else { copy += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".grf")) { copy += ".grf"; } } else { copy += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".prb")) { copy += ".prb"; } } else { copy += ".prb"; } } } if (copy .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + copy, copy)) { if (modelID != null) { SBMLDocument document = readSBML(tree.getFile()); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy); } else if ((tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".lpn") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc") || tree.getFile().substring( tree.getFile().length() - 4).equals(".rsg")) || (tree.getFile().length() >= 2 && tree.getFile().substring( tree.getFile().length() - 2).equals(".s")) || (tree.getFile().length() >= 5 && tree.getFile().substring( tree.getFile().length() - 5).equals(".inst")) || (tree.getFile().length() >= 2 && tree.getFile().substring( tree.getFile().length() - 2).equals(".g"))) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); FileInputStream in = new FileInputStream(new File(tree.getFile())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { new File(root + separator + copy).mkdir(); // new FileWriter(new File(root + separator + // copy + // separator + // ".sim")).close(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLDocument document = readSBML(tree.getFile() + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy + separator + ss); } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss .substring(ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } else { new File(root + separator + copy).mkdir(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss .substring(ss.length() - 4).equals(".lrn"))) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".lrn")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } } refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("rename") || e.getSource() == rename) { if (!tree.getFile().equals(root)) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) != 1) { return; } break; } } String modelID = null; String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".sbml") && !rename.substring(rename.length() - 4).equals(".xml")) { rename += ".xml"; } } else { rename += ".xml"; } if (rename.length() > 4) { if (rename.substring(rename.length() - 5).equals(".sbml")) { modelID = rename.substring(0, rename.length() - 5); } else { modelID = rename.substring(0, rename.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".gcm")) { rename += ".gcm"; } } else { rename += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".vhd")) { rename += ".vhd"; } } else { rename += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".g")) { rename += ".g"; } } else { rename += ".g"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".s")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".s")) { rename += ".s"; } } else { rename += ".s"; } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".inst")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".inst")) { rename += ".inst"; } } else { rename += ".inst"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".lpn")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".lpn")) { rename += ".lpn"; } } else { rename += ".lpn"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".csp")) { rename += ".csp"; } } else { rename += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".hse")) { rename += ".hse"; } } else { rename += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".unc")) { rename += ".unc"; } } else { rename += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".rsg")) { rename += ".rsg"; } } else { rename += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".grf")) { rename += ".grf"; } } else { rename += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".prb")) { rename += ".prb"; } } else { rename += ".prb"; } } if (rename.equals(tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + rename, rename)) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".xml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".gcm") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".lpn") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".vhd") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".csp") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".hse") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".unc") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".rsg")) { String oldName = tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]; reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm")) { String oldName = tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]; for (String s : new File(root).list()) { if (s.endsWith(".gcm")) { BufferedReader in = new BufferedReader(new FileReader(root + separator + s)); String line = null; String file = ""; while ((line = in.readLine()) != null) { line = line.replace(oldName, rename); file += line; file += "\n"; } in.close(); BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + s)); out.write(file); out.close(); } } } if (modelID != null) { SBMLDocument document = readSBML(root + separator + rename); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + rename); } if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".lpn") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".vhd") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".csp") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".hse") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".unc") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".rsg")) { updateAsyncViews(rename); } if (new File(root + separator + rename).isDirectory()) { if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } else if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn") .renameTo(new File(root + separator + rename + separator + rename + ".lrn")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".ver").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".ver") .renameTo(new File(root + separator + rename + separator + rename + ".ver")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf") .renameTo(new File(root + separator + rename + separator + rename + ".grf")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb") .renameTo(new File(root + separator + rename + separator + rename + ".prb")); } } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { if (tree.getFile().length() > 4 && tree.getFile() .substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".xml")) { ((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID); ((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && (tree.getFile().substring( tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring( tree.getFile().length() - 4).equals( ".prb"))) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".lpn")) { ((LHPNEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); tab.setTitleAt(i, rename); } else if (tab.getComponentAt(i) instanceof JTabbedPane) { JTabbedPane t = new JTabbedPane(); t.addMouseListener(this); int selected = ((JTabbedPane) tab.getComponentAt(i)) .getSelectedIndex(); boolean analysis = false; ArrayList<Component> comps = new ArrayList<Component>(); for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)) .getTabCount(); j++) { Component c = ((JTabbedPane) tab.getComponentAt(i)) .getComponent(j); comps.add(c); } for (Component c : comps) { if (c instanceof Reb2Sac) { ((Reb2Sac) c).setSim(rename); analysis = true; } else if (c instanceof SBML_Editor) { String properties = root + separator + rename + separator + rename + ".sim"; new File(properties).renameTo(new File(properties .replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) c).isDirty(); ((SBML_Editor) c).setParamFileAndSimDir(properties, root + separator + rename); ((SBML_Editor) c).save(false, "", true); ((SBML_Editor) c).updateSBML(i, 0); ((SBML_Editor) c).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")) .renameTo(new File(properties)); } else if (c instanceof Graph) { // c.addMouseListener(this); Graph g = ((Graph) c); g.setDirectory(root + separator + rename); if (g.isTSDGraph()) { g.setGraphName(rename + ".grf"); } else { g.setGraphName(rename + ".prb"); } } else if (c instanceof Learn) { Learn l = ((Learn) c); l.setDirectory(root + separator + rename); } else if (c instanceof DataManager) { DataManager d = ((DataManager) c); d.setDirectory(root + separator + rename); } if (analysis) { if (c instanceof Reb2Sac) { t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1) .setName("Simulate"); } else if (c instanceof SBML_Editor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("SBML Editor"); } else if (c instanceof GCM2SBMLEditor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("GCM Editor"); } else if (c instanceof Graph) { if (((Graph) c).isTSDGraph()) { t.addTab("TSD Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("TSD Graph"); } else { t.addTab("Probability Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("ProbGraph"); } } else { t.addTab("Abstraction Options", c); t.getComponentAt(t.getComponents().length - 1) .setName(""); } } } if (analysis) { t.setSelectedIndex(selected); tab.setComponentAt(i, t); } tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } else { tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } } } refreshTree(); // updateAsyncViews(rename); updateViewNames(tree.getFile(), rename); } } } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("openGraph")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .contains(".grf")) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Number of molecules", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile().split( separator)[tree.getFile().split(separator).length - 1], true, false), "TSD Graph"); } else { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Percent", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile().split(separator)[tree .getFile().split(separator).length - 1], false, false), "Probability Graph"); } } } enableTabMenu(tab.getSelectedIndex()); enableTreeMenu(); } public int getTab(String name) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { return i; } } return -1; } public void deleteDir(File dir) { int count = 0; do { File[] list = dir.listFiles(); System.gc(); for (int i = 0; i < list.length; i++) { if (list[i].isDirectory()) { deleteDir(list[i]); } else { list[i].delete(); } } count++; } while (!dir.delete() && count != 100); if (count == 100) { JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method adds a new project to recent list */ public void addRecentProject(String projDir) { // boolean newOne = true; for (int i = 0; i < numberRecentProj; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = 0; j <= i; j++) { String save = recentProjectPaths[j]; recentProjects[j] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } recentProjectPaths[j] = projDir; projDir = save; } for (int j = i + 1; j < numberRecentProj; j++) { if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } } return; } } if (numberRecentProj < 5) { numberRecentProj++; } for (int i = 0; i < numberRecentProj; i++) { String save = recentProjectPaths[i]; recentProjects[i] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[i]); } recentProjectPaths[i] = projDir; projDir = save; } } /** * This method refreshes the menu. */ public void refresh() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema, atacs); mainPanel.add(tree, "West"); mainPanel.validate(); } /** * This method refreshes the tree. */ public void refreshTree() { tree.fixTree(); updateGCM(); mainPanel.validate(); } /** * This method adds the given Component to a tab. */ public void addTab(String name, Component panel, String tabName) { tab.addTab(name, panel); // panel.addMouseListener(this); if (tabName != null) { tab.getComponentAt(tab.getTabCount() - 1).setName(tabName); } else { tab.getComponentAt(tab.getTabCount() - 1).setName(name); } tab.setSelectedIndex(tab.getTabCount() - 1); } /** * This method removes the given component from the tabs. */ public void removeTab(Component component) { tab.remove(component); } public JTabbedPane getTab() { return tab; } /** * Prompts the user to save work that has been done. */ public int save(int index, int autosave) { if (tab.getComponentAt(index).getName().contains(("GCM")) || tab.getComponentAt(index).getName().contains("LHPN")) { if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) { GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index); if (editor.isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { editor.save("gcm"); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { editor.save("gcm"); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { editor.save("gcm"); return 2; } else { return 3; } } } else if (tab.getComponentAt(index) instanceof LHPNEditor) { LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index); if (editor.isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { editor.save(); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { editor.save(); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { editor.save(); return 2; } else { return 3; } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } else if (tab.getComponentAt(index).getName().equals("SBML Editor")) { if (tab.getComponentAt(index) instanceof SBML_Editor) { if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 2; } else { return 3; } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } else if (tab.getComponentAt(index).getName().contains("Graph")) { if (tab.getComponentAt(index) instanceof Graph) { if (((Graph) tab.getComponentAt(index)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 1; } else if (value == NO_OPTION) { return 1; } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { ((Graph) tab.getComponentAt(index)).save(); return 2; } else { return 3; } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } else { if (tab.getComponentAt(index) instanceof JTabbedPane) { for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() != null) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() .equals("Simulate")) { if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save simulation option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("SBML Editor")) { if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("GCM Editor")) { if (((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).isDirty()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveParams(false, ""); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveParams(false, ""); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveParams(false, ""); } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { if (((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } } } if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) { if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)) .save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)) .save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().equals("Data Manager")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) { ((DataManager) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveChanges(tab.getTitleAt(index)); } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) .getName().contains("Graph")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { if (((Graph) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save graph changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)); g.save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)); g.save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (((JTabbedPane) tab.getComponentAt(index)) .getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab .getComponentAt(index)).getComponent(i)); g.save(); } } } } } } } } else if (tab.getComponentAt(index) instanceof JPanel) { if ((tab.getComponentAt(index)).getName().equals("Synthesis")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Synthesis) { if (((Synthesis) array[0]).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save synthesis option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } } } } } else if (tab.getComponentAt(index).getName().equals("Verification")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Verification) { if (((Verification) array[0]).hasChanged()) { if (autosave == 0) { int value = JOptionPane.showOptionDialog(frame, "Do you want to save verification option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]); if (value == YES_OPTION) { ((Verification) array[0]).save(); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((Verification) array[0]).save(); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((Verification) array[0]).save(); } } } } } if (autosave == 0) { return 1; } else if (autosave == 1) { return 2; } else { return 3; } } } /** * Saves a circuit from a learn view to the project view */ public void saveGcm(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Saves a circuit from a learn view to the project view */ public void saveLhpn(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + filename)); BufferedReader in = new BufferedReader(new FileReader(path)); String str; while ((str = in.readLine()) != null) { out.write(str + "\n"); } in.close(); out.close(); /* * out = new BufferedWriter(new FileWriter(root + separator + * filename.replace(".lpn", ".vhd"))); in = new * BufferedReader(new FileReader(path.replace(".lpn", ".vhd"))); * while ((str = in.readLine()) != null) { out.write(str + * "\n"); } in.close(); out.close(); out = new * BufferedWriter(new FileWriter(root + separator + * filename.replace(".lpn", ".vams"))); in = new * BufferedReader(new FileReader(path.replace(".lpn", * ".vams"))); while ((str = in.readLine()) != null) { * out.write(str + "\n"); } in.close(); out.close(); out = new * BufferedWriter(new FileWriter(root + separator + * filename.replace(".lpn", "_top.vams"))); String[] learnPath = * path.split(separator); String topVFile = * path.replace(learnPath[learnPath.length - 1], "top.vams"); * String[] cktPath = filename.split(separator); in = new * BufferedReader(new FileReader(topVFile)); while ((str = * in.readLine()) != null) { str = str.replace("module top", * "module " + cktPath[cktPath.length - 1].replace(".lpn", * "_top")); out.write(str + "\n"); } in.close(); out.close(); * out = new BufferedWriter(new FileWriter(root + separator + * filename.replace(".lpn", ".sv"))); in = new * BufferedReader(new FileReader(path.replace(".lpn", ".sv"))); * while ((str = in.readLine()) != null) { out.write(str + * "\n"); } in.close(); out.close(); */ // No top.sv file for now /* * out = new BufferedWriter(new FileWriter(root + separator + * filename.replace(".lpn", "_top.sv"))); learnPath = * path.split(separator); topVFile = * path.replace(learnPath[learnPath.length - 1], "top.sv"); * cktPath = filename.split(separator); in = new * BufferedReader(new FileReader(topVFile)); while ((str = * in.readLine()) != null) { str = str.replace("module top", * "module " + cktPath[cktPath.length - 1].replace(".lpn", * "_top")); out.write(str + "\n"); } in.close(); out.close(); */ refreshTree(); } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to save LPN.", "Error", JOptionPane.ERROR_MESSAGE); } } public void updateMenu(boolean logEnabled, boolean othersEnabled) { viewVHDL.setEnabled(othersEnabled); viewVerilog.setEnabled(othersEnabled); viewLHPN.setEnabled(othersEnabled); viewCoverage.setEnabled(othersEnabled); save.setEnabled(othersEnabled); viewLog.setEnabled(logEnabled); // Do saveas & save button too } /** * Returns the frame. */ public JFrame frame() { return frame; } public void mousePressed(MouseEvent e) { // log.addText(e.getSource().toString()); if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); frame.getGlassPane().setVisible(false); } } } else { executeMouseClickEvent(e); } } public void mouseReleased(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities .convertPoint(glassPane, glassPanePoint, container); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e .getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e .getClickCount(), e.isPopupTrigger())); if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); frame.getGlassPane().setVisible(false); } } catch (Exception e1) { e1.printStackTrace(); } } } else { executeMouseClickEvent(e); } } public void executeMouseClickEvent(MouseEvent e) { if (!(e.getSource() instanceof JTree)) { enableTabMenu(tab.getSelectedIndex()); // frame.getGlassPane().setVisible(true); } else if (e.getSource() instanceof JTree && tree.getFile() != null && e.isPopupTrigger()) { // frame.getGlassPane().setVisible(false); popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Model"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graphTree"); JMenuItem browse = new JMenuItem("View Model in Browser"); browse.addActionListener(this); browse.addMouseListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.addMouseListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.addMouseListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.addMouseListener(this); createSBML.setActionCommand("createSBML"); // JMenuItem createLHPN = new JMenuItem("Create LPN File"); // createLHPN.addActionListener(this); // createLHPN.addMouseListener(this); // createLHPN.setActionCommand("createLHPN"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Model"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graphTree"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); // popup.add(createLHPN); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (lema) { popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } } else if (tree.getFile().length() > 2 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (lema) { popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); // if (lema) { // popup.add(createLearn); popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); // //////// TODO JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createAnalysis"); // createAnalysis.setActionCommand("simulate"); // JMenuItem simulate = new // JMenuItem("Create Analysis View"); // simulate.addActionListener(this); // simulate.addMouseListener(this); // simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem convertToSBML = new JMenuItem("Convert To SBML"); convertToSBML.addActionListener(this); convertToSBML.addMouseListener(this); convertToSBML.setActionCommand("convertToSBML"); JMenuItem convertToVerilog = new JMenuItem("Convert To Verilog"); convertToVerilog.addActionListener(this); convertToVerilog.addMouseListener(this); convertToVerilog.setActionCommand("convertToVerilog"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem viewStateGraph = new JMenuItem("View State Graph"); viewStateGraph.addActionListener(this); viewStateGraph.addMouseListener(this); viewStateGraph.setActionCommand("viewState"); JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis"); markovAnalysis.addActionListener(this); markovAnalysis.addMouseListener(this); markovAnalysis.setActionCommand("markov"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } if (LPN2SBML) { popup.add(createAnalysis); } if (lema) { popup.add(createLearn); } if (atacs || lema) { popup.add(createVerification); } popup.addSeparator(); // popup.add(createAnalysis); // TODO popup.add(viewModel); // popup.add(viewStateGraph); if (!atacs && !lema && LPN2SBML) { popup.add(convertToSBML); // changed the order. SB } if (atacs || lema) { popup.add(convertToVerilog); } // popup.add(markovAnalysis); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) { // JMenuItem createAnalysis = new // JMenuItem("Create Analysis View"); // createAnalysis.addActionListener(this); // createAnalysis.addMouseListener(this); // createAnalysis.setActionCommand("createSim"); // JMenuItem createVerification = new // JMenuItem("Create Verification View"); // createVerification.addActionListener(this); // createVerification.addMouseListener(this); // createVerification.setActionCommand("createVerify"); // JMenuItem viewModel = new JMenuItem("View Model"); // viewModel.addActionListener(this); // viewModel.addMouseListener(this); // viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); // popup.add(createVerification); // popup.addSeparator(); // popup.add(viewModel); // popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) { // JMenuItem createAnalysis = new // JMenuItem("Create Analysis View"); // createAnalysis.addActionListener(this); // createAnalysis.addMouseListener(this); // createAnalysis.setActionCommand("createSim"); // JMenuItem createVerification = new // JMenuItem("Create Verification View"); // createVerification.addActionListener(this); // createVerification.addMouseListener(this); // createVerification.setActionCommand("createVerify"); // JMenuItem viewModel = new JMenuItem("View Model"); // viewModel.addActionListener(this); // viewModel.addMouseListener(this); // viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); // popup.add(createVerification); // popup.addSeparator(); // popup.add(viewModel); // popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.addMouseListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.addMouseListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.addMouseListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; boolean learn = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSim"); popup.add(open); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSynth"); popup.add(open); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openVerification"); popup.add(open); } else if (learn) { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openLearn"); popup.add(open); } if (sim || ver || synth || learn) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.addMouseListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.addMouseListener(this); rename.setActionCommand("rename"); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2 && e.getSource() instanceof JTree && tree.getFile() != null) { int index = tab.getSelectedIndex(); enableTabMenu(index); if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this, null, null); // sbml.addMouseListener(this); addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], sbml, "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "VHDL Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Assembly File Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this assembly file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Instruction File Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this instruction file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Verilog-AMS Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this Verilog-AMS file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 3 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "SystemVerilog Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this SystemVerilog file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Petri Net Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this .g file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } LhpnFile lhpn = new LhpnFile(log); // if (new File(directory + theFile).length() > 0) { // log.addText("here"); // lhpn.load(directory + theFile); // log.addText("there"); // log.addText("load completed"); File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { // log.addText("make Editor"); LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile, lhpn, this, log); // editor.addMouseListener(this); addTab(theFile, editor, "LHPN Editor"); // log.addText("Editor made"); } // String[] cmd = { "emacs", filename }; // Runtime.getRuntime().exec(cmd); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to view this LPN file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "CSP Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this csp file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "HSE Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this hse file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "UNC Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this unc file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "RSG Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (!viewer.equals("")) { String command = viewer + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Spice Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this spice file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Number of molecules", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile().split( separator)[tree.getFile().split(separator).length - 1], true, false), "TSD Graph"); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "Percent", "title", "tsd.printer", root, "Time", this, tree.getFile(), log, tree.getFile().split(separator)[tree .getFile().split(separator).length - 1], false, false), "Probability Graph"); } } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; boolean learn = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } if (sim) { openSim(); } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else if (learn) { if (lema) { openLearnLHPN(); } else { openLearn(); } } } } else { enableTreeMenu(); } } public void mouseMoved(MouseEvent e) { /* * Component glassPane = frame.getGlassPane(); Point glassPanePoint = * e.getPoint(); // Component component = e.getComponent(); Container * container = frame.getContentPane(); Point containerPoint = * SwingUtilities.convertPoint(glassPane, glassPanePoint, frame * .getContentPane()); if (containerPoint.y < 0) { // we're not in the * content pane if (containerPoint.y + menuBar.getHeight() >= 0) { * Component component = menuBar.getComponentAt(glassPanePoint); Point * componentPoint = SwingUtilities.convertPoint(glassPane, * glassPanePoint, component); component.dispatchEvent(new * MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), * componentPoint.x, componentPoint.y, e.getClickCount(), e * .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else * { Component deepComponent = * SwingUtilities.getDeepestComponentAt(container, containerPoint.x, * containerPoint.y); Point componentPoint = * SwingUtilities.convertPoint(glassPane, glassPanePoint, * deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { * // deepComponent = tab.findComponentAt(componentPoint); // } * deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), * e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, * e.getClickCount(), e .isPopupTrigger())); if (deepComponent * instanceof JComponent) { frame.getGlassPane().setVisible(false); } } */ } public void mouseWheelMoved(MouseWheelEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); } } public void windowGainedFocus(WindowEvent e) { setGlassPane(true); } private void simulate(int fileType) throws Exception { /* * if (fileType == 1) { String simName = * JOptionPane.showInputDialog(frame, "Enter Analysis ID:", * "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && * !simName.trim().equals("")) { simName = simName.trim(); if * (overwrite(root + separator + simName, simName)) { new File(root + * separator + simName).mkdir(); // new FileWriter(new File(root + * separator + simName + // separator + // ".sim")).close(); String[] * dot = tree.getFile().split(separator); String sbmlFile = root + * separator + simName + separator + (dot[dot.length - 1].substring(0, * dot[dot.length - 1].length() - 3) + "sbml"); GCMParser parser = new * GCMParser(tree.getFile()); GeneticNetwork network = * parser.buildNetwork(); GeneticNetwork.setRoot(root + separator); * network.mergeSBML(root + separator + simName + separator + sbmlFile); * try { FileOutputStream out = new FileOutputStream(new File(root + * separator + simName.trim() + separator + simName.trim() + ".sim")); * out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } * catch (IOException e1) { JOptionPane.showMessageDialog(frame, * "Unable to save parameter file!", "Error Saving File", * JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator * + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + * separator + (dot[dot.length - 1].substring(0, dot[dot.length - * 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); * Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, * simName.trim(), log, simTab, null, dot[dot.length - 1]); // * reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", * reb2sac); simTab.getComponentAt(simTab.getComponents().length - * 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); * // abstraction.addMouseListener(this); * simTab.addTab("Abstraction Options", abstraction); * simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); * // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // * simTab.getComponentAt(simTab.getComponents().length - // * 1).setName(""); if (dot[dot.length - 1].contains(".gcm")) { * GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, * dot[dot.length - 1], this, log, true, simName.trim(), root + * separator + simName.trim() + separator + simName.trim() + ".sim", * reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); * simTab.addTab("Parameter Editor", gcm); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("GCM Editor"); if (!gcm.getSBMLFile().equals("--none--")) * { SBML_Editor sbml = new SBML_Editor(root + separator + * gcm.getSBMLFile(), reb2sac, log, this, root + separator + * simName.trim(), root + separator + simName.trim() + separator + * simName.trim() + ".sim"); simTab.addTab("SBML Elements", * sbml.getElementsPanel()); * simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); * gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new * JScrollPane(); scroll.setViewportView(new JPanel()); * simTab.addTab("SBML Elements", scroll); * simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); * gcm.setSBMLParamFile(null); } } else { SBML_Editor sbml = new * SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + * simName.trim(), root + separator + simName.trim() + separator + * simName.trim() + ".sim"); reb2sac.setSbml(sbml); // * sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("SBML Editor"); simTab.addTab("SBML Elements", * sbml.getElementsPanel()); * simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); * } Graph tsdGraph = reb2sac.createGraph(null); // * tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", * tsdGraph); simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); Graph probGraph = * reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); * simTab.addTab("Probability Graph", probGraph); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); * * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); * * addTab(simName, simTab, null); } } } else if (fileType == 2) { String * simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", * "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && * !simName.trim().equals("")) { simName = simName.trim(); if * (overwrite(root + separator + simName, simName)) { new File(root + * separator + simName).mkdir(); // new FileWriter(new File(root + * separator + simName + // separator + // ".sim")).close(); String[] * dot = tree.getFile().split(separator); String sbmlFile = root + * separator + simName + separator + (dot[dot.length - 1].substring(0, * dot[dot.length - 1].length() - 3) + "sbml"); Translator t1 = new * Translator(); t1.BuildTemplate(tree.getFile()); t1.setFilename(root + * separator + simName + separator + sbmlFile); t1.outputSBML(); try { * FileOutputStream out = new FileOutputStream(new File(root + separator * + simName.trim() + separator + simName.trim() + ".sim")); * out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } * catch (IOException e1) { JOptionPane.showMessageDialog(frame, * "Unable to save parameter file!", "Error Saving File", * JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator * + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + * separator + (dot[dot.length - 1].substring(0, dot[dot.length - * 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); * Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, * simName.trim(), log, simTab, null, dot[dot.length - 1]); // * reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", * reb2sac); simTab.getComponentAt(simTab.getComponents().length - * 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); * // abstraction.addMouseListener(this); * simTab.addTab("Abstraction Options", abstraction); * simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); * // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // * simTab.getComponentAt(simTab.getComponents().length - // * 1).setName(""); Graph tsdGraph = reb2sac.createGraph(null); // * tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", * tsdGraph); simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); Graph probGraph = * reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); * simTab.addTab("Probability Graph", probGraph); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); addTab(simName, simTab, null); } } } else { */ for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) == 0) { return; } break; } } if (fileType == 0) { SBMLDocument document = readSBML(tree.getFile()); } String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String sbmlFile = tree.getFile(); String[] sbml1 = tree.getFile().split(separator); String sbmlFileProp; if (fileType == 1) { sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1] .length() - 3) + "sbml"); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + separator); network.mergeSBML(root + separator + simName + separator + sbmlFile); sbmlFileProp = root + separator + simName + separator + (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1] .length() - 3) + "sbml"); sbmlFile = sbmlFileProp; } else if (fileType == 2) { sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1] .length() - 3) + "sbml"); Translator t1 = new Translator(); t1.BuildTemplate(tree.getFile()); t1.setFilename(root + separator + simName + separator + sbmlFile); t1.outputSBML(); sbmlFileProp = root + separator + simName + separator + (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1] .length() - 3) + "sbml"); sbmlFile = sbmlFileProp; } else { sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1]; new FileOutputStream(new File(sbmlFileProp)).close(); } try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((sbml1[sbml1.length - 1] + "\n").getBytes()); out.close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } /* * try { FileOutputStream out = new FileOutputStream(new * File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); String * doc = writer.writeToString(document); byte[] output = * doc.getBytes(); out.write(output); out.close(); } catch * (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable * to copy sbml file to output location.", "Error", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); JTabbedPane simTab = new JTabbedPane(); simTab.addMouseListener(this); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(), log, simTab, null, sbml1[sbml1.length - 1], null); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); // abstraction.addMouseListener(this); if (fileType == 2) { simTab.addTab("Abstraction Options", new AbstPane(root, sbml1[sbml1.length - 1], log, this, false, false)); } else { // System.out.println(fileType); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); } simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName("");boolean if (sbml1[sbml1.length - 1].contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, sbml1[sbml1.length - 1], this, log, true, simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor"); if (!gcm.getSBMLFile().equals("--none SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); simTab.addTab("SBML Elements", scroll); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(null); } addModelViewTab(reb2sac, simTab, gcm); } else if (sbml1[sbml1.length - 1].contains(".sbml") || sbml1[sbml1.length - 1].contains(".xml")) { SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } private void openLearn() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); lrnTab.addMouseListener(this); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i, 0) == 0) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); Learn learn = new Learn(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "Number of molecules", tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "Time", this, open, log, null, true, true); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openLearnLHPN() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); lrnTab.addMouseListener(this); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i, 0) == 0) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "Number of molecules", tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "Time", this, open, log, null, true, true); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openSynth() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel synthPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String synthFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn"; String synthFile2 = tree.getFile() + separator + ".syn"; Properties load = new Properties(); String synthesisFile = ""; try { if (new File(synthFile2).exists()) { FileInputStream in = new FileInputStream(new File(synthFile2)); load.load(in); in.close(); new File(synthFile2).delete(); } if (new File(synthFile).exists()) { FileInputStream in = new FileInputStream(new File(synthFile)); load.load(in); in.close(); if (load.containsKey("synthesis.file")) { synthesisFile = load.getProperty("synthesis.file"); synthesisFile = synthesisFile.split(separator)[synthesisFile .split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(synthesisFile)); load.store(out, synthesisFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(synthesisFile)) { tab.setSelectedIndex(i); if (save(i, 0) == 0) { return; } break; } } if (!(new File(root + separator + synthesisFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this); // synth.addMouseListener(this); synthPanel.add(synth); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], synthPanel, "Synthesis"); } } private void openVerify() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { // JPanel verPanel = new JPanel(); // JPanel abstPanel = new JPanel(); // JPanel verTab = new JTabbedPane(); // String graphFile = ""; /* * if (new File(tree.getFile()).isDirectory()) { String[] list = new * File(tree.getFile()).list(); int run = 0; for (int i = 0; i < * list.length; i++) { if (!(new File(list[i]).isDirectory()) && * list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; * j++) { end = list[i].charAt(list[i].length() - j) + end; } if * (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) * { if (list[i].contains("run-")) { int tempNum = * Integer.parseInt(list[i].substring(4, list[i] .length() - * end.length())); if (tempNum > run) { run = tempNum; // graphFile * = tree.getFile() + separator + // list[i]; } } } } } } */ String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String verFile = tree.getFile() + separator + verName + ".ver"; Properties load = new Properties(); String verifyFile = ""; try { if (new File(verFile).exists()) { FileInputStream in = new FileInputStream(new File(verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1]; } } // FileOutputStream out = new FileOutputStream(new // File(verifyFile)); // load.store(out, verifyFile); // out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(verifyFile)) { tab.setSelectedIndex(i); if (save(i, 0) == 0) { return; } break; } } if (!(new File(verFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Verification ver = new Verification(root + separator + verName, verName, "flag", log, this, lema, atacs); // ver.addMouseListener(this); // verPanel.add(ver); // AbstPane abst = new AbstPane(root + separator + verName, ver, // "flag", log, this, lema, // atacs); // abstPanel.add(abst); // verTab.add("verify", verPanel); // verTab.add("abstract", abstPanel); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], ver, "Verification"); } } private void openSim() { String filename = tree.getFile(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( filename.split(separator)[filename.split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (filename != null && !filename.equals("")) { if (new File(filename).isDirectory()) { if (new File(filename + separator + ".sim").exists()) { new File(filename + separator + ".sim").delete(); } String[] list = new File(filename).list(); String getAFile = ""; // String probFile = ""; String openFile = ""; // String graphFile = ""; String open = null; String openProb = null; int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals("sbml")) { getAFile = filename + separator + list[i]; } else if (end.equals(".xml") && getAFile.equals("")) { getAFile = filename + separator + list[i]; } else if (end.equals(".txt") && list[i].contains("sim-rep")) { // probFile = filename + separator + list[i]; } else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) { openFile = filename + separator + list[i]; } else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = filename + separator + // list[i]; } } else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) { // graphFile = filename + separator + // list[i]; } else if (end.contains("=")) { // graphFile = filename + separator + // list[i]; } } else if (end.equals(".grf")) { open = filename + separator + list[i]; } else if (end.equals(".prb")) { openProb = filename + separator + list[i]; } } else if (new File(filename + separator + list[i]).isDirectory()) { String[] s = new File(filename + separator + list[i]).list(); for (int j = 0; j < s.length; j++) { if (s[j].contains("sim-rep")) { // probFile = filename + separator + list[i] // + separator + } else if (s[j].contains(".tsd")) { // graphFile = filename + separator + // list[i] + separator + } } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"; String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; if (new File(pmsFile).exists()) { if (new File(simFile).exists()) { new File(pmsFile).delete(); } else { new File(pmsFile).renameTo(new File(simFile)); } } String sbmlLoadFile = ""; String gcmFile = ""; if (new File(simFile).exists()) { try { Scanner s = new Scanner(new File(simFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; if (sbmlLoadFile.equals("")) { JOptionPane .showMessageDialog( frame, "Unable to open view because " + "the sbml linked to this view is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!(new File(root + separator + sbmlLoadFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else if (sbmlLoadFile.contains(".lpn")) { Translator t1 = new Translator(); t1.BuildTemplate(root + separator + sbmlLoadFile); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".lpn", ".sbml"); t1.setFilename(sbmlLoadFile); t1.outputSBML(); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (s.hasNextLine()) { s.nextLine(); } s.close(); File f = new File(sbmlLoadFile); if (!f.exists()) { sbmlLoadFile = root + separator + f.getName(); } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else { sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1]; if (!new File(sbmlLoadFile).exists()) { sbmlLoadFile = getAFile; /* * JOptionPane.showMessageDialog(frame, "Unable * to load sbml file.", "Error", * JOptionPane.ERROR_MESSAGE); return; */ } } if (!new File(sbmlLoadFile).exists()) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1] + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i, 0) == 0) { return; } break; } } JTabbedPane simTab = new JTabbedPane(); simTab.addMouseListener(this); AbstPane lhpnAbstraction = new AbstPane(root, gcmFile, log, this, false, false); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile, lhpnAbstraction); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1) .setName("Simulate"); if (gcmFile.contains(".lpn")) { simTab.addTab("Abstraction Options", lhpnAbstraction); } else { simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); } simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); if (!gcm.getSBMLFile().equals("--none SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1) .setName(""); gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); simTab.addTab("SBML Elements", scroll); simTab.getComponentAt(simTab.getComponents().length - 1) .setName(""); gcm.setSBMLParamFile(null); } addModelViewTab(reb2sac, simTab, gcm); } else if (gcmFile.contains(".sbml") || gcmFile.contains(".xml")) { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } // if (open != null) { Graph tsdGraph = reb2sac.createGraph(open); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "TSD Graph"); /* * } else if (!graphFile.equals("")) { * simTab.addTab("TSD Graph", * reb2sac.createGraph(open)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } / else { JLabel noData = * new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } */ // if (openProb != null) { Graph probGraph = reb2sac.createProbGraph(openProb); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "ProbGraph"); /* * } else if (!probFile.equals("")) { * simTab.addTab("Probability Graph", * reb2sac.createProbGraph(openProb)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } else { JLabel noData1 = * new JLabel("No data available"); Font font1 = * noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } /** * adds the tab for the modelview and the correct listener. * * @return */ private void addModelViewTab(Reb2Sac reb2sac, JTabbedPane tabPane, GCM2SBMLEditor gcm2sbml) { // Add the modelview tab // TODO: Add the modelview tab MovieContainer movieContainer = new MovieContainer(reb2sac, gcm2sbml.getGCM(), this, gcm2sbml); tabPane.addTab("Model View Movie", movieContainer); tabPane.getComponentAt(tabPane.getComponents().length - 1).setName("ModelViewMovie"); // When the Graphical View panel gets clicked on, tell it to display // itself. tabPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JTabbedPane selectedTab = (JTabbedPane) (e.getSource()); JPanel selectedPanel = (JPanel) selectedTab.getComponent(selectedTab .getSelectedIndex()); String className = selectedPanel.getClass().getName(); // if(selectedTab.getName().equals("ModelViewMovie")) // The new ModelView if (className.indexOf("MovieContainer") >= 0) { ((MovieContainer) selectedPanel).display(); } } }); } private class NewAction extends AbstractAction { NewAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(newProj); if (!async) { popup.add(newCircuit); popup.add(newModel); } else if (atacs) { popup.add(newVhdl); popup.add(newLhpn); popup.add(newCsp); popup.add(newHse); popup.add(newUnc); popup.add(newRsg); } else { popup.add(newVhdl); popup.add(newLhpn); popup.add(newSpice); } popup.add(graph); popup.add(probGraph); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class SaveAction extends AbstractAction { SaveAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(saveAsGcm); } else { popup.add(saveAsLhpn); } popup.add(saveAsGraph); if (!lema) { popup.add(saveAsSbml); popup.add(saveAsTemplate); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ImportAction extends AbstractAction { ImportAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(importDot); popup.add(importSbml); popup.add(importBioModel); } else if (atacs) { popup.add(importVhdl); popup.add(importLpn); popup.add(importCsp); popup.add(importHse); popup.add(importUnc); popup.add(importRsg); } else { popup.add(importVhdl); popup.add(importS); popup.add(importInst); popup.add(importLpn); popup.add(importSpice); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ExportAction extends AbstractAction { ExportAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(exportCsv); popup.add(exportDat); popup.add(exportEps); popup.add(exportJpg); popup.add(exportPdf); popup.add(exportPng); popup.add(exportSvg); popup.add(exportTsd); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ModelAction extends AbstractAction { ModelAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(viewModGraph); popup.add(viewModBrowser); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } public void mouseClicked(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); frame.getGlassPane().setVisible(false); } } } else { executeMouseClickEvent(e); } } public void mouseEntered(MouseEvent e) { // if (e.getSource() == tree.tree) { // setGlassPane(false); // else if (e.getSource() == popup) { // popupFlag = true; // setGlassPane(false); // else if (e.getSource() instanceof JMenuItem) { // menuFlag = true; // setGlassPane(false); } public void mouseExited(MouseEvent e) { // if (e.getSource() == tree.tree && !popupFlag && !menuFlag) { // setGlassPane(true); // else if (e.getSource() == popup) { // popupFlag = false; // if (!menuFlag) { // setGlassPane(true); // else if (e.getSource() instanceof JMenuItem) { // menuFlag = false; // if (!popupFlag) { // setGlassPane(true); } public void mouseDragged(MouseEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } catch (Exception e1) { } } } // public void componentHidden(ComponentEvent e) { // log.addText("hidden"); // setGlassPane(true); // public void componentResized(ComponentEvent e) { // log.addText("resized"); // public void componentMoved(ComponentEvent e) { // log.addText("moved"); // public void componentShown(ComponentEvent e) { // log.addText("shown"); public void windowLostFocus(WindowEvent e) { } // public void focusGained(FocusEvent e) { // public void focusLost(FocusEvent e) { // log.addText("focus lost"); public JMenuItem getExitButton() { return exit; } /** * This is the main method. It excecutes the BioSim GUI FrontEnd program. */ public static void main(String args[]) { boolean lemaFlag = false, atacsFlag = false, LPN2SBML = true; if (args.length > 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-lema")) { lemaFlag = true; } else if (args[i].equals("-atacs")) { atacsFlag = true; } } } if (!lemaFlag && !atacsFlag) { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the // classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname + " environment variable does not include\nthe" + " directory containing the libsbml library file."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment" + " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file."); System.exit(1); } catch (SecurityException e) { System.err.println("Could not load the libSBML library files due to a" + " security exception."); System.exit(1); } } else { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the // classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { LPN2SBML = false; } catch (ClassNotFoundException e) { LPN2SBML = false; } catch (SecurityException e) { LPN2SBML = false; } } new BioSim(lemaFlag, atacsFlag, LPN2SBML); } public void copySim(String newSim) { try { new File(root + separator + newSim).mkdir(); // new FileWriter(new File(root + separator + newSim + separator + // ".sim")).close(); String oldSim = tab.getTitleAt(tab.getSelectedIndex()); String[] s = new File(root + separator + oldSim).list(); String sbmlFile = ""; String propertiesFile = ""; String sbmlLoadFile = null; String gcmFile = null; for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLDocument document = readSBML(root + separator + oldSim + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + newSim + separator + ss); sbmlFile = root + separator + newSim + separator + ss; } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); propertiesFile = root + separator + newSim + separator + ss; } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring( ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else { out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); } FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); if (ss.substring(ss.length() - 4).equals(".pms")) { if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) { new File(root + separator + newSim + separator + ss).delete(); } else { new File(root + separator + newSim + separator + ss).renameTo(new File( root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim")); } ss = ss.substring(0, ss.length() - 4) + ".sim"; } if (ss.substring(ss.length() - 4).equals(".sim")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + separator); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (scan.hasNextLine()) { scan.nextLine(); } scan.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } refreshTree(); JTabbedPane simTab = new JTabbedPane(); simTab.addMouseListener(this); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile, gcmFile, null); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, newSim, root + separator + newSim + separator + newSim + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor"); if (!gcm.getSBMLFile().equals("--none SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); simTab.addTab("SBML Elements", scroll); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); gcm.setSBMLParamFile(null); } addModelViewTab(reb2sac, simTab, gcm); } else { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ tab.setComponentAt(tab.getSelectedIndex(), simTab); tab.setTitleAt(tab.getSelectedIndex(), newSim); tab.getComponentAt(tab.getSelectedIndex()).setName(newSim); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } public void refreshLearn(String learnName, boolean data) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnName)) { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals( "TSD Graph")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) { ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)) .refresh(); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null, "Number of molecules", learnName + " data", "tsd.printer", root + separator + learnName, "Time", this, null, log, null, true, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName( "TSD Graph"); } /* * } else { JLabel noData1 = new * JLabel("No data available"); Font font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData1); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("TSD Graph"); } */ } else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) { } else { if (lema) { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnLHPN(root + separator + learnName, log, this)); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn( root + separator + learnName, log, this)); } ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) .setName("Learn"); } /* * } else { JLabel noData = new * JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("Learn"); } */ } } } } } private void updateGCM() { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles(); tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename()); } } } public void updateAsyncViews(String updatedFile) { // log.addText(updatedFile); for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".ver"; String properties1 = root + separator + tab + separator + tab + ".synth"; String properties2 = root + separator + tab + separator + tab + ".lrn"; // log.addText(properties + "\n" + properties1 + "\n" + properties2 if (new File(properties).exists()) { // String check = ""; // try { // Scanner s = new Scanner(new File(properties)); // if (s.hasNextLine()) { // check = s.nextLine(); // check = check.split(separator)[check.split(separator).length // s.close(); // catch (Exception e) { // if (check.equals(updatedFile)) { Verification verify = ((Verification) (this.tab.getComponentAt(i))); verify.reload(updatedFile); } if (new File(properties1).exists()) { // String check = ""; // try { // Scanner s = new Scanner(new File(properties1)); // if (s.hasNextLine()) { // check = s.nextLine(); // check = check.split(separator)[check.split(separator).length // s.close(); // catch (Exception e) { // if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("Synthesis")) { // new File(properties).renameTo(new // File(properties.replace(".synth", // ".temp"))); // boolean dirty = ((SBML_Editor) // (sim.getComponentAt(j))).isDirty(); ((Synthesis) (sim.getComponentAt(j))).reload(updatedFile); // if (updatedFile.contains(".g")) { // GCMParser parser = new GCMParser(root + separator + // updatedFile); // GeneticNetwork network = parser.buildNetwork(); // GeneticNetwork.setRoot(root + File.separator); // network.mergeSBML(root + separator + tab + separator // + updatedFile.replace(".g", ".vhd")); // ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, // j, root // + separator + tab + separator // + updatedFile.replace(".g", ".vhd")); // else { // ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, // j, root // + separator + updatedFile); // ((SBML_Editor) // (sim.getComponentAt(j))).setDirty(dirty); // new File(properties).delete(); // new File(properties.replace(".synth", // ".temp")).renameTo(new // File( // properties)); // sim.setComponentAt(j + 1, ((SBML_Editor) // (sim.getComponentAt(j))) // .getElementsPanel()); // sim.getComponentAt(j + 1).setName(""); } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((LearnLHPN) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); ((LearnLHPN) (learn.getComponentAt(j))).reload(updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } } } public void updateViews(String updatedFile) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".sim"; String properties2 = root + separator + tab + separator + tab + ".lrn"; if (new File(properties).exists()) { String check = ""; try { Scanner s = new Scanner(new File(properties)); if (s.hasNextLine()) { check = s.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } s.close(); } catch (Exception e) { } if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("SBML Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty(); ((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true); if (updatedFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + updatedFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + separator); network.mergeSBML(root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); } else { ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile); } ((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File( properties)); sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j))) .getElementsPanel()); sim.getComponentAt(j + 1).setName(""); } else if (sim.getComponentAt(j).getName().equals("GCM Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((GCM2SBMLEditor) (sim.getComponentAt(j))).isDirty(); ((GCM2SBMLEditor) (sim.getComponentAt(j))).saveParams(false, ""); ((GCM2SBMLEditor) (sim.getComponentAt(j))).reload(check.replace(".gcm", "")); ((GCM2SBMLEditor) (sim.getComponentAt(j))).refresh(); ((GCM2SBMLEditor) (sim.getComponentAt(j))).loadParams(); ((GCM2SBMLEditor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File( properties)); if (!((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile().equals( "--none SBML_Editor sbml = new SBML_Editor(root + separator + ((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile(), ((Reb2Sac) sim.getComponentAt(0)), log, this, root + separator + tab, root + separator + tab + separator + tab + ".sim"); sim.setComponentAt(j + 1, sbml.getElementsPanel()); sim.getComponentAt(j + 1).setName(""); ((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(sbml); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); sim.setComponentAt(j + 1, scroll); sim.getComponentAt(j + 1).setName(""); ((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(null); } } } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } ArrayList<String> saved = new ArrayList<String>(); if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { saved.add(this.tab.getTitleAt(i)); GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i); if (gcm.getSBMLFile().equals(updatedFile)) { gcm.save("save"); } } String[] files = new File(root).list(); for (String s : files) { if (s.contains(".gcm") && !saved.contains(s)) { GCMFile gcm = new GCMFile(root); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(updatedFile)) { updateViews(s); } } } } } private void updateViewNames(String oldname, String newname) { File work = new File(root); String[] fileList = work.list(); String[] temp = oldname.split(separator); oldname = temp[temp.length - 1]; for (int i = 0; i < fileList.length; i++) { String tabTitle = fileList[i]; String properties = root + separator + tabTitle + separator + tabTitle + ".ver"; String properties1 = root + separator + tabTitle + separator + tabTitle + ".synth"; String properties2 = root + separator + tabTitle + separator + tabTitle + ".lrn"; if (new File(properties).exists()) { String check; Properties p = new Properties(); try { FileInputStream load = new FileInputStream(new File(properties)); p.load(load); load.close(); if (p.containsKey("verification.file")) { String[] getProp = p.getProperty("verification.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } if (check.equals(oldname)) { p.setProperty("verification.file", newname); FileOutputStream out = new FileOutputStream(new File(properties)); p.store(out, properties); } } catch (Exception e) { // log.addText("verification"); // e.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } } if (new File(properties1).exists()) { String check; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties1)); p.load(load); load.close(); if (p.containsKey("synthesis.file")) { String[] getProp = p.getProperty("synthesis.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } if (check.equals(oldname)) { p.setProperty("synthesis.file", newname); FileOutputStream out = new FileOutputStream(new File(properties1)); p.store(out, properties1); } } catch (Exception e) { // log.addText("synthesis"); // e.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } if (check.equals(oldname)) { p.setProperty("learn.file", newname); FileOutputStream out = new FileOutputStream(new File(properties2)); p.store(out, properties2); } } catch (Exception e) { // e.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } } } updateAsyncViews(newname); } public void enableTabMenu(int selectedTab) { treeSelected = false; // log.addText("tab menu"); if (selectedTab != -1) { tab.setSelectedIndex(selectedTab); } Component comp = tab.getSelectedComponent(); // if (comp != null) { // log.addText(comp.toString()); /* * viewModel.setEnabled(false); viewModGraph.setEnabled(false); * viewModBrowser.setEnabled(false); viewSG.setEnabled(false); * createAnal.setEnabled(false); createLearn.setEnabled(false); * createSbml.setEnabled(false); createSynth.setEnabled(false); * createVer.setEnabled(false); */ if (comp instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(true); // saveGcmAsLhpn.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); // viewModGraph.setEnabled(true); } else if (comp instanceof LHPNEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(true); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(true); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); // viewModGraph.setEnabled(true); } else if (comp instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(true); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); // viewModGraph.setEnabled(true); // viewModBrowser.setEnabled(true); } else if (comp instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(true); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) comp).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); Boolean learn = false; for (String s : new File(root + separator + tab.getTitleAt(tab.getSelectedIndex())) .list()) { if (s.contains("_sg.dot")) { viewSG.setEnabled(true); } } for (Component c : ((JTabbedPane) comp).getComponents()) { if (c instanceof Learn) { learn = true; } } // int index = tab.getSelectedIndex(); if (component instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); if (learn) { runButton.setEnabled(false); } else { runButton.setEnabled(true); } refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); if (learn) { run.setEnabled(false); saveModel.setEnabled(true); } else { run.setEnabled(true); saveModel.setEnabled(false); } saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) component).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Reb2Sac) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(true); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(true); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(true); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { // if (((Learn) component).isComboSelected()) { // frame.getGlassPane().setVisible(false); // saveButton.setEnabled(((Learn) // component).getSaveGcmEnabled()); saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // save.setEnabled(((Learn) component).getSaveGcmEnabled()); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); // viewModel.setEnabled(true); // viewModGraph.setEnabled(((Learn) // component).getViewGcmEnabled()); viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((Learn) component).getViewLogEnabled()); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // viewCoverage.setEnabled(((Learn) // component).getViewCoverageEnabled()); // SB // saveParam.setEnabled(true); saveModel.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof LearnLHPN) { // if (((LearnLHPN) component).isComboSelected()) { // frame.getGlassPane().setVisible(false); // saveButton.setEnabled(((LearnLHPN) // component).getSaveLhpnEnabled()); saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // save.setEnabled(((LearnLHPN) // component).getSaveLhpnEnabled()); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); // viewModel.setEnabled(true); viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled()); viewVHDL.setEnabled(((LearnLHPN) component).getViewVHDLEnabled()); viewVerilog.setEnabled(((LearnLHPN) component).getViewVerilogEnabled()); viewLHPN.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); // saveParam.setEnabled(true); saveModel.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof DataManager) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // /saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JPanel) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(true); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(true); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); // viewModel.setEnabled(true); // viewModGraph.setEnabled(true); // viewModBrowser.setEnabled(true); viewRules.setEnabled(false); // always false?? // viewTrace.setEnabled(((Verification) // comp).getViewTraceEnabled()); viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); // Should // true // only // verification // Result // available??? viewCircuit.setEnabled(false); // always true??? // viewLog.setEnabled(((Verification) // comp).getViewLogEnabled()); viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); // Should // true // only // log // available??? viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(true); saveModel.setEnabled(false); } else if (comp.getName().equals("Synthesis")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); // viewModel.setEnabled(true); // always true?? // viewModGraph.setEnabled(true); // viewModBrowser.setEnabled(true); // viewRules.setEnabled(((Synthesis) // comp).getViewRulesEnabled()); // viewTrace.setEnabled(((Synthesis) // comp).getViewTraceEnabled()); // viewCircuit.setEnabled(((Synthesis) // comp).getViewCircuitEnabled()); // viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled()); viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); // Always viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); // Always viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); } } else if (comp instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(true); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else { saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); // /saveGcmAsLhpn.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } // copy.setEnabled(false); // rename.setEnabled(false); // delete.setEnabled(false); } private void enableTreeMenu() { treeSelected = true; // log.addText(tree.getFile()); /* * saveButton.setEnabled(false); saveasButton.setEnabled(false); * runButton.setEnabled(false); refreshButton.setEnabled(false); * checkButton.setEnabled(false); exportButton.setEnabled(false); * exportMenu.setEnabled(false); save.setEnabled(false); * run.setEnabled(false); saveAs.setEnabled(false); * saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); * saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); * saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); */ // saveGcmAsLhpn.setEnabled(false); // viewSG.setEnabled(false); if (tree.getFile() != null) { if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { viewModGraph.setEnabled(true); viewModGraph.setActionCommand("graph"); viewModBrowser.setEnabled(true); createAnal.setEnabled(true); createAnal.setActionCommand("simulate"); createLearn.setEnabled(true); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { viewModGraph.setEnabled(true); // viewModGraph.setActionCommand("graphDot"); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSbml.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // /saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(true); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // save.setEnabled(true); // SB should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { viewModel.setEnabled(true); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createAnal.setActionCommand("createSim"); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(true); viewLHPN.setEnabled(false); // save.setEnabled(true); // SB should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 2 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { viewModel.setEnabled(true); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createAnal.setActionCommand("createSim"); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(true); viewLHPN.setEnabled(false); // save.setEnabled(true); // SB should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); if (new File(root + separator + "atacs.log").exists()) { viewLog.setEnabled(true); } else { viewLog.setEnabled(false); } viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); if (new File(root + separator + "atacs.log").exists()) { viewLog.setEnabled(true); } else { viewLog.setEnabled(false); } // not displaying the correct log too ????? SB viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(true); // SB true ??? since lpn // save.setEnabled(true); // SB should exist ??? // saveas too??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; boolean learn = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } if (sim || synth || ver || learn) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewVHDL.setEnabled(false); viewVerilog.setEnabled(false); viewLHPN.setEnabled(false); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } } public String getRoot() { return root; } public void setGlassPane(boolean visible) { // frame.getGlassPane().setVisible(visible); } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { String[] views = canDelete(name); Object[] options = { "Overwrite", "Cancel" }; int value; if (views.length == 0) { value = JOptionPane.showOptionDialog(frame, name + " already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "The file, " + name + ", aleeady exists, and\nit is linked to the following views:\n\n" + view + "\n\nAre you sure you want to overwrite?"; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); value = JOptionPane.showOptionDialog(frame, scroll, "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); /* * JOptionPane.showMessageDialog(frame, scroll, * "Unable To Overwrite File", JOptionPane.ERROR_MESSAGE); */ } if (value == JOptionPane.YES_OPTION) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { tab.remove(i); } } File dir = new File(fullPath); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } return true; } else { return false; } } else { return true; } } public boolean updateOpenSBML(String sbmlName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (sbmlName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof SBML_Editor) { SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null); this.tab.setComponentAt(i, newSBML); this.tab.getComponentAt(i).setName("SBML Editor"); newSBML.save(false, "", false); return true; } } } return false; } public boolean updateOpenLHPN(String lhpnName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (lhpnName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof LHPNEditor) { LHPNEditor newLHPN = new LHPNEditor(root, lhpnName, null, this, log); this.tab.setComponentAt(i, newLHPN); this.tab.getComponentAt(i).setName("LHPN Editor"); return true; } } } return false; } private String[] canDelete(String filename) { ArrayList<String> views = new ArrayList<String>(); String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } scan.close(); } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } else if (new File(root + separator + s + separator + s + ".ver").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("verification.file")) { String[] getProp = p.getProperty("verification.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } else if (new File(root + separator + s + separator + s + ".synth").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("synthesis.file")) { String[] getProp = p.getProperty("synthesis.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } if (check.equals(filename)) { views.add(s); } } } String[] usingViews = views.toArray(new String[0]); sort(usingViews); return usingViews; } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } private void reassignViews(String oldName, String newName) { String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { ArrayList<String> copy = new ArrayList<String>(); Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; if (check.equals(oldName)) { while (scan.hasNextLine()) { copy.add(scan.nextLine()); } scan.close(); FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim")); out.write((newName + "\n").getBytes()); for (String cop : copy) { out.write((cop + "\n").getBytes()); } out.close(); } else { scan.close(); } } } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; if (check.equals(oldName)) { p.setProperty("genenet.file", newName); FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn")); p.store(store, "Learn File Data"); store.close(); } } } catch (Exception e) { } } } } } protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText, String altText) { // URL imageURL = BioSim.class.getResource(imageName); // Create and initialize the button. JButton button = new JButton(); button.setActionCommand(actionCommand); button.setToolTipText(toolTipText); button.addActionListener(this); button.setIcon(new ImageIcon(imageName)); // if (imageURL != null) { //image found // button.setIcon(new ImageIcon(imageURL, altText)); // } else { //no image found // button.setText(altText); // System.err.println("Resource not found: " // + imageName); return button; } public static SBMLDocument readSBML(String filename) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename); JTextArea messageArea = new JTextArea(); messageArea.append("Conversion to SBML level " + SBML_LEVEL + " version " + SBML_VERSION + " produced the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; long numErrors = document.checkL2v4Compatibility(); if (numErrors > 0) { display = true; messageArea .append(" messageArea.append(filename); messageArea .append("\n for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); messageArea.append(i + ":" + error + "\n"); } } if (display) { final JFrame f = new JFrame("SBML Conversion Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION); return document; } public static void checkModelCompleteness(SBMLDocument document) { JTextArea messageArea = new JTextArea(); messageArea .append("Model is incomplete. Cannot be simulated until the following information is provided.\n"); boolean display = false; Model model = document.getModel(); ListOf list = model.getListOfCompartments(); for (int i = 0; i < model.getNumCompartments(); i++) { Compartment compartment = (Compartment) list.get(i); if (!compartment.isSetSize()) { messageArea .append(" messageArea.append("Compartment " + compartment.getId() + " needs a size.\n"); display = true; } } list = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { Species species = (Species) list.get(i); if (!(species.isSetInitialAmount()) && !(species.isSetInitialConcentration())) { messageArea .append(" messageArea.append("Species " + species.getId() + " needs an initial amount or concentration.\n"); display = true; } } list = model.getListOfParameters(); for (int i = 0; i < model.getNumParameters(); i++) { Parameter parameter = (Parameter) list.get(i); if (!(parameter.isSetValue())) { messageArea .append(" messageArea.append("Parameter " + parameter.getId() + " needs an initial value.\n"); display = true; } } list = model.getListOfReactions(); for (int i = 0; i < model.getNumReactions(); i++) { Reaction reaction = (Reaction) list.get(i); if (!(reaction.isSetKineticLaw())) { messageArea .append(" messageArea.append("Reaction " + reaction.getId() + " needs a kinetic law.\n"); display = true; } else { ListOf params = reaction.getKineticLaw().getListOfParameters(); for (int j = 0; j < reaction.getKineticLaw().getNumParameters(); j++) { Parameter param = (Parameter) params.get(j); if (!(param.isSetValue())) { messageArea .append(" messageArea.append("Local parameter " + param.getId() + " for reaction " + reaction.getId() + " needs an initial value.\n"); display = true; } } } } if (display) { final JFrame f = new JFrame("SBML Model Completeness Errors"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } }
package modules; import config.ShooterConfig; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.PIDOutput; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.Watchdog; /** * controls the shooter * @author Ben Evans * @author Michael Chin */ public class ShooterModule extends Module{ private Solenoid lifter; private Solenoid shifter; private Victor winch1, winch2; private DigitalInput winchSensor; private Encoder winchEncoder; private PIDController winchController; //TODO enums? public static int READY = 0; public static int LIFTING_PNEUMATIC = 1; public static int SHOOTING = 2; public static int RELOADING = 3; private int mode; private boolean manual = true; private double winchPower = 0; private boolean shifterGear = true; /** * the constructor for this class * @param lift * @param shift * @param win1 * @param win2 * @param button */ public ShooterModule(int lift, int shift, int win1, int win2, int button, int encA, int encB){ lifter = new Solenoid(lift); shifter = new Solenoid(shift); winch1 = new Victor(win1); winch2 = new Victor(win2); winchSensor = new DigitalInput(button); winchEncoder = new Encoder(encA, encB); mode = READY; winchController = new PIDController(ShooterConfig.KP, ShooterConfig.KI, ShooterConfig.KD, winchEncoder, new PIDOutput() { public void pidWrite(double d) { winch1.set(d); winch2.set(d); } }); } /** * shoots, lifts Pneumatic */ public void shoot(){ if(mode == READY) mode = LIFTING_PNEUMATIC; } /** * * @return mode */ public int getMode(){ return mode; } /** * * @return mode == Ready */ public boolean isReady(){ return mode == READY; } public void setIntake(boolean up){ lifter.set(up); } public synchronized void setManual(boolean man){ this.manual = man; } public synchronized void setWinchPower(double power){ this.winchPower = power; } public synchronized void setGear(boolean engaged){ this.shifterGear = engaged; } public void setPID(double p, double i, double d){ winchController.setPID(p, i, d); } /** * handles shooter state */ public void run(){ long stateTimer = 0; while(true){ if(enabled){ if(manual){ winchController.disable(); }else{ //state machine winchController.enable(); if(mode == READY){ stateTimer = System.currentTimeMillis(); }else if(mode == LIFTING_PNEUMATIC){ lifter.set(true); if((System.currentTimeMillis() - stateTimer) > 1000){ mode = SHOOTING; stateTimer = System.currentTimeMillis(); } }else if(mode == SHOOTING){ shifter.set(false); if((System.currentTimeMillis() - stateTimer) > 1000){ shifter.set(true); mode = RELOADING; stateTimer = System.currentTimeMillis(); } }else if(mode == RELOADING){ lifter.set(false); winchController.setSetpoint(ShooterConfig.LOADED_TICKS); if(winchSensor.get()) mode = READY; }else{ //problem } } if(winchSensor.get()){ winchPower = 0; } winch1.set(winchPower); winch2.set(winchPower); shifter.set(shifterGear); } Timer.delay(0.05); } } /** * * @return winch charge status and state */ public String toString() { return "Winch Charge Status: " + winchSensor.get() + " State: " + getState() + " Winch: " + winchPower; } public String getLogData(){ String line1 = "\t\t<data name=\"lifter\" value=\""+(lifter.get() ? "ON" : "OFF")+"\">\n"; String line2 = "\t\t<data name=\"dog\" value=\""+(shifter.get() ? "ON" : "OFF")+"\">\n"; String line3 = "\t\t<data name=\"winch\" value=\""+winch1.get()+"\">\n"; String line4 = "\t\t<data name=\"state\" value=\""+getState()+"\">"; return line1+line2+line3+line4; } /** * * @return state */ public String getState(){ if (mode == READY){ return "SHOOTER_READY"; }else if(mode == LIFTING_PNEUMATIC){ return "LIFTING_PNEUMATIC"; }else if(mode == SHOOTING){ return "FIRING_BALLZ"; }else if(mode == RELOADING){ return "RELOADING"; }else{ return "NOT_READY"; } } }
package model; public class Categoria { String nome; }
// RMG - Reaction Mechanism Generator // RMG Team (rmg_dev@mit.edu) // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. package jing.rxnSys; import java.io.*; import jing.rxnSys.ReactionSystem; import jing.rxn.*; import jing.chem.*; import java.util.*; import jing.mathTool.UncertainDouble; import jing.param.*; import jing.chemUtil.*; import jing.chemParser.*; //## package jing::rxnSys // jing\rxnSys\ReactionModelGenerator.java //## class ReactionModelGenerator public class ReactionModelGenerator { protected LinkedList timeStep; //## attribute timeStep protected ReactionModel reactionModel; //gmagoon 9/24/07 protected String workingDirectory; //## attribute workingDirectory // protected ReactionSystem reactionSystem; protected LinkedList reactionSystemList; //10/24/07 gmagoon: changed from reactionSystem to reactionSystemList protected int paraInfor;//svp protected boolean error;//svp protected boolean sensitivity;//svp protected LinkedList species;//svp // protected InitialStatus initialStatus;//svp protected LinkedList initialStatusList; //10/23/07 gmagoon: changed from initialStatus to initialStatusList protected double rtol;//svp protected static double atol; protected PrimaryReactionLibrary primaryReactionLibrary;//9/24/07 gmagoon protected ReactionModelEnlarger reactionModelEnlarger;//9/24/07 gmagoon protected LinkedHashSet speciesSeed;//9/24/07 gmagoon; protected ReactionGenerator reactionGenerator;//9/24/07 gmagoon protected LibraryReactionGenerator lrg;// = new LibraryReactionGenerator();//9/24/07 gmagoon: moved from ReactionSystem.java;10/4/07 gmagoon: postponed initialization of lrg til later //10/23/07 gmagoon: added additional variables protected LinkedList tempList; protected LinkedList presList; protected LinkedList validList;//10/24/07 gmagoon: added //10/25/07 gmagoon: moved variables from modelGeneration() protected LinkedList initList = new LinkedList(); protected LinkedList beginList = new LinkedList(); protected LinkedList endList = new LinkedList(); protected LinkedList lastTList = new LinkedList(); protected LinkedList currentTList = new LinkedList(); protected LinkedList lastPList = new LinkedList(); protected LinkedList currentPList = new LinkedList(); protected LinkedList conditionChangedList = new LinkedList(); protected LinkedList reactionChangedList = new LinkedList(); protected int numConversions;//5/6/08 gmagoon: moved from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator() protected String equationOfState; // 24Jun2009 MRH: variable stores the first temperature encountered in the condition.txt file // This temperature is used to select the "best" kinetics from the rxn library protected static Temperature temp4BestKinetics; // This is the new "PrimaryReactionLibrary" protected SeedMechanism seedMechanism; protected PrimaryThermoLibrary primaryThermoLibrary; protected boolean restart = false; protected boolean readrestart = false; protected boolean writerestart = false; protected LinkedHashSet restartCoreSpcs = new LinkedHashSet(); protected LinkedHashSet restartEdgeSpcs = new LinkedHashSet(); protected LinkedHashSet restartCoreRxns = new LinkedHashSet(); protected LinkedHashSet restartEdgeRxns = new LinkedHashSet(); // Constructors private HashSet specs = new HashSet(); //public static native long getCpuTime(); //static {System.loadLibrary("cpuTime");} //## operation ReactionModelGenerator() public ReactionModelGenerator() { //#[ operation ReactionModelGenerator() workingDirectory = System.getProperty("RMG.workingDirectory"); // } //## operation initializeReactionSystem() //10/24/07 gmagoon: changed name to initializeReactionSystems public void initializeReactionSystems() throws InvalidSymbolException, IOException { //#[ operation initializeReactionSystem() try { String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile"); if (initialConditionFile == null) { System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile"); System.exit(0); } //double sandeep = getCpuTime(); //System.out.println(getCpuTime()/1e9/60); FileReader in = new FileReader(initialConditionFile); BufferedReader reader = new BufferedReader(in); //TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out //PressureModel pressureModel = null;//10/27/07 gmagoon: commented out // ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems FinishController finishController = null; //DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line LinkedList dynamicSimulatorList = new LinkedList(); //PrimaryReactionLibrary primaryReactionLibrary = null;//10/14/07 gmagoon: see below setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary double [] conversionSet = new double[50]; String line = ChemParser.readMeaningfulLine(reader); /*if (line.startsWith("Restart")){ StringTokenizer st = new StringTokenizer(line); String token = st.nextToken(); token = st.nextToken(); if (token.equalsIgnoreCase("true")) { //Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt"); //Runtime.getRuntime().exec("echo >> allSpecies.txt"); restart = true; } else if (token.equalsIgnoreCase("false")) { Runtime.getRuntime().exec("rm Restart/allSpecies.txt"); restart = false; } else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:"); } else throw new InvalidSymbolException("Can't find Restart!");*/ //line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Database")){//svp line = ChemParser.readMeaningfulLine(reader); } else throw new InvalidSymbolException("Can't find database!"); // if (line.startsWith("PrimaryThermoLibrary")){//svp // line = ChemParser.readMeaningfulLine(reader); // else throw new InvalidSymbolException("Can't find primary thermo library!"); /* * Added by MRH on 15-Jun-2009 * Give user the option to change the maximum carbon, oxygen, * and/or radical number for all species. These lines will be * optional in the condition.txt file. Values are hard- * coded into RMG (in ChemGraph.java), but any user- * defined input will override these values. */ /* * Moved from before InitialStatus to before PrimaryThermoLibary * by MRH on 27-Oct-2009 * Overriding default values of maximum number of "X" per * chemgraph should come before RMG attempts to make any * chemgraph. The first instance RMG will attempt to make a * chemgraph is in reading the primary thermo library. */ if (line.startsWith("MaxCarbonNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:" int maxCNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxCarbonNumber(maxCNum); System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum); line = ChemParser.readMeaningfulLine(reader); } if (line.startsWith("MaxOxygenNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:" int maxONum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxOxygenNumber(maxONum); System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum); line = ChemParser.readMeaningfulLine(reader); } if (line.startsWith("MaxRadicalNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:" int maxRadNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxRadicalNumber(maxRadNum); System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum); line = ChemParser.readMeaningfulLine(reader); } if (line.startsWith("MaxSulfurNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:" int maxSNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxSulfurNumber(maxSNum); System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum); line = ChemParser.readMeaningfulLine(reader); } if (line.startsWith("MaxSiliconNumber")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:" int maxSiNum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxSiliconNumber(maxSiNum); System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum); line = ChemParser.readMeaningfulLine(reader); } if (line.startsWith("MaxHeavyAtom")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:" int maxHANum = Integer.parseInt(st.nextToken()); ChemGraph.setMaxHeavyAtomNumber(maxHANum); System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum); line = ChemParser.readMeaningfulLine(reader); } /* * Read in the Primary Thermo Library * MRH 7-Jul-2009 */ if (line.startsWith("PrimaryThermoLibrary:")) { int numPTLs = 0; line = ChemParser.readMeaningfulLine(reader); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader); tempString = line.split("Location: "); String path = tempString[tempString.length-1].trim(); if (numPTLs==0) { setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path)); ++numPTLs; } else { getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path); ++numPTLs; } line = ChemParser.readMeaningfulLine(reader); } if (numPTLs == 0) setPrimaryThermoLibrary(null); } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate PrimaryThermoLibrary field"); line = ChemParser.readMeaningfulLine(reader); if (line.toLowerCase().startsWith("readrestart")) { StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); // "ReadRestart:" tempString = st.nextToken(); if (tempString.toLowerCase().equals("yes")) { readrestart = true; readRestartSpecies(); } else readrestart = false; line = ChemParser.readMeaningfulLine(reader); } else throw new InvalidSymbolException("Cannot locate ReadRestart field"); if (line.toLowerCase().startsWith("writerestart")) { StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); // "WriteRestart:" tempString = st.nextToken(); if (tempString.toLowerCase().equals("yes")) writerestart = true; else writerestart = false; line = ChemParser.readMeaningfulLine(reader); } else throw new InvalidSymbolException("Cannot locate WriteRestart field"); // read temperature model //gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt if (line.startsWith("TemperatureModel:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String modelType = st.nextToken(); //String t = st.nextToken(); String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); if (modelType.equals("Constant")) { tempList = new LinkedList(); //read first temperature double t = Double.parseDouble(st.nextToken()); tempList.add(new ConstantTM(t, unit)); Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature Global.lowTemperature = (Temperature)temp.clone(); Global.highTemperature = (Temperature)temp.clone(); //read remaining temperatures while (st.hasMoreTokens()) { t = Double.parseDouble(st.nextToken()); tempList.add(new ConstantTM(t, unit)); temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature if(temp.getK() < Global.lowTemperature.getK()) Global.lowTemperature = (Temperature)temp.clone(); if(temp.getK() > Global.highTemperature.getK()) Global.highTemperature = (Temperature)temp.clone(); } // Global.temperature = new Temperature(t,unit); } //10/23/07 gmagoon: commenting out; further updates needed to get this to work //else if (modelType.equals("Curved")) { // String t = st.nextToken(); // // add reading curved temperature function here // temperatureModel = new CurvedTM(new LinkedList()); else { throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType); } } else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!"); // read in pressure model line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("PressureModel:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String modelType = st.nextToken(); //String p = st.nextToken(); String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); if (modelType.equals("Constant")) { presList = new LinkedList(); //read first pressure double p = Double.parseDouble(st.nextToken()); presList.add(new ConstantPM(p, unit)); //read remaining temperatures while (st.hasMoreTokens()) { p = Double.parseDouble(st.nextToken()); presList.add(new ConstantPM(p, unit)); } //Global.pressure = new Pressure(p, unit); } //10/23/07 gmagoon: commenting out; further updates needed to get this to work //else if (modelType.equals("Curved")) { // // add reading curved pressure function here // pressureModel = new CurvedPM(new LinkedList()); else { throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType); } } else throw new InvalidSymbolException("condition.txt: can't find PressureModel!"); // after PressureModel comes an optional line EquationOfState // if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct // if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law) line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("EquationOfState")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String eosType = st.nextToken(); if (eosType.equals("Liquid")) { equationOfState="Liquid"; System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT"); } line = ChemParser.readMeaningfulLine(reader); } // Read in InChI generation if (line.startsWith("InChIGeneration:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String inchiOnOff = st.nextToken().toLowerCase(); if (inchiOnOff.equals("on")) { Species.useInChI = true; } else if (inchiOnOff.equals("off")) { Species.useInChI = false; } else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff); line = ChemParser.readMeaningfulLine(reader); } // Read in Solvation effects if (line.startsWith("Solvation:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String solvationOnOff = st.nextToken().toLowerCase(); if (solvationOnOff.equals("on")) { Species.useSolvation = true; } else if (solvationOnOff.equals("off")) { Species.useSolvation = false; } else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff); line = ChemParser.readMeaningfulLine(reader); } //line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line // Read in optional QM thermo generation if (line.startsWith("ThermoMethod:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String thermoMethod = st.nextToken().toLowerCase(); if (thermoMethod.equals("qm")) { ChemGraph.useQM = true; line=ChemParser.readMeaningfulLine(reader); if(line.startsWith("QMForCyclicsOnly:")){ StringTokenizer st2 = new StringTokenizer(line); String nameCyc = st2.nextToken(); String option = st2.nextToken().toLowerCase(); if (option.equals("on")) { ChemGraph.useQMonCyclicsOnly = true; } } else{ System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field"); System.exit(0); } line=ChemParser.readMeaningfulLine(reader); if(line.startsWith("MaxRadNumForQM:")){ StringTokenizer st3 = new StringTokenizer(line); String nameRadNum = st3.nextToken(); Global.maxRadNumForQM = Integer.parseInt(st3.nextToken()); } else{ System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field"); System.exit(0); } }//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used line = ChemParser.readMeaningfulLine(reader);//read in reactants } // // Read in Solvation effects // if (line.startsWith("Solvation:")) { // StringTokenizer st = new StringTokenizer(line); // String name = st.nextToken(); // String solvationOnOff = st.nextToken().toLowerCase(); // if (solvationOnOff.equals("on")) { // Species.useSolvation = true; // } else if (solvationOnOff.equals("off")) { // Species.useSolvation = false; // else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff); // else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag."); // read in reactants //10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel //LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed //setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added LinkedHashMap speciesSet = new LinkedHashMap(); LinkedHashMap speciesStatus = new LinkedHashMap(); int speciesnum = 1; //System.out.println(line); if (line.startsWith("InitialStatus")) { line = ChemParser.readMeaningfulLine(reader); while (!line.equals("END")) { StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); String name = null; if (!index.startsWith("(")) name = index; else name = st.nextToken(); //if (restart) name += "("+speciesnum+")"; // 24Jun2009: MRH // Check if the species name begins with a number. // If so, terminate the program and inform the user to choose // a different name. This is implemented so that the chem.inp // file generated will be valid when run in Chemkin try { int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1)); System.out.println("\nA species name should not begin with a number." + " Please rename species: " + name + "\n"); System.exit(0); } catch (NumberFormatException e) { // We're good } speciesnum ++; String conc = st.nextToken(); double concentration = Double.parseDouble(conc); String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) { concentration /= 1000; unit = "mol/cm3"; } else if (unit.equals("mole/m3") || unit.equals("mol/m3")) { concentration /= 1000000; unit = "mol/cm3"; } else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) { concentration /= 6.022e23; } else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) { throw new InvalidUnitException("Species Concentration in condition.txt!"); } //GJB to allow "unreactive" species that only follow user-defined library reactions. // They will not react according to RMG reaction families boolean IsReactive = true; boolean IsConstantConcentration = false; while (st.hasMoreTokens()) { String reactive = st.nextToken().trim(); if (reactive.equalsIgnoreCase("unreactive")) IsReactive = false; if (reactive.equalsIgnoreCase("constantconcentration")) IsConstantConcentration=true; } Graph g = ChemParser.readChemGraph(reader); ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { System.out.println("Forbidden Structure:\n" + e.getMessage()); System.exit(0); } //System.out.println(name); Species species = Species.make(name,cg); species.setReactivity(IsReactive); // GJB species.setConstantConcentration(IsConstantConcentration); speciesSet.put(name, species); getSpeciesSeed().add(species); double flux = 0; int species_type = 1; // reacted species SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux); speciesStatus.put(species, ss); line = ChemParser.readMeaningfulLine(reader); } ReactionTime initial = new ReactionTime(0,"S"); //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem initialStatusList = new LinkedList(); for (Iterator iter = tempList.iterator(); iter.hasNext(); ) { TemperatureModel tm = (TemperatureModel)iter.next(); for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){ PressureModel pm = (PressureModel)iter2.next(); // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all) Set ks = speciesStatus.keySet(); LinkedHashMap speStat = new LinkedHashMap(); for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?) SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next()); speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux())); } initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial))); } } } else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!"); // read in inert gas concentration line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("InertGas:")) { line = ChemParser.readMeaningfulLine(reader); while (!line.equals("END")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken().trim(); String conc = st.nextToken(); double inertConc = Double.parseDouble(conc); String unit = st.nextToken(); unit = ChemParser.removeBrace(unit); if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) { inertConc /= 1000; unit = "mol/cm3"; } else if (unit.equals("mole/m3") || unit.equals("mol/m3")) { inertConc /= 1000000; unit = "mol/cm3"; } else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) { inertConc /= 6.022e23; unit = "mol/cm3"; } else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) { throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit); } //SystemSnapshot.putInertGas(name,inertConc); for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc ((InitialStatus)iter.next()).putInertGas(name,inertConc); } line = ChemParser.readMeaningfulLine(reader); } } else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!"); // read in spectroscopic data estimator line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("SpectroscopicDataEstimator:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String sdeType = st.nextToken().toLowerCase(); if (sdeType.equals("frequencygroups") || sdeType.equals("default")) { SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS; } else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) { SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY; } else if (sdeType.equals("off") || sdeType.equals("none")) { SpectroscopicData.mode = SpectroscopicData.Mode.OFF; } else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType); } else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!"); // pressure dependence flag line = ChemParser.readMeaningfulLine(reader); if (line.toLowerCase().startsWith("pressuredependence:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String pDepType = st.nextToken(); if (pDepType.toLowerCase().equals("modifiedstrongcollision") || pDepType.toLowerCase().equals("reservoirstate") || pDepType.toLowerCase().equals("chemdis")) { reactionModelEnlarger = new RateBasedPDepRME(); PDepNetwork.generateNetworks = true; if (pDepType.toLowerCase().equals("reservoirstate")) { ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE)); if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) { System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups."); SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS; } } else if (pDepType.toLowerCase().equals("modifiedstrongcollision")) { ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION)); if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) { System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups."); SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS; } } else if (pDepType.toLowerCase().equals("chemdis")) { ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis()); if (SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) { System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model."); SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY; } } else { throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsEstimator = " + pDepType); } // Set temperatures and pressures to use in PDep kinetics estimation Temperature[] temperatures = new Temperature[8]; temperatures[0] = new Temperature(300, "K"); temperatures[1] = new Temperature(400, "K"); temperatures[2] = new Temperature(600, "K"); temperatures[3] = new Temperature(900, "K"); temperatures[4] = new Temperature(1200, "K"); temperatures[5] = new Temperature(1500, "K"); temperatures[6] = new Temperature(1800, "K"); temperatures[7] = new Temperature(2100, "K"); FastMasterEqn.setTemperatures(temperatures); PDepRateConstant.setTemperatures(temperatures); ChebyshevPolynomials.setTlow(temperatures[0]); ChebyshevPolynomials.setTup(temperatures[7]); Pressure[] pressures = new Pressure[5]; pressures[0] = new Pressure(0.01, "bar"); pressures[1] = new Pressure(0.1, "bar"); pressures[2] = new Pressure(1, "bar"); pressures[3] = new Pressure(10, "bar"); pressures[4] = new Pressure(100, "bar"); FastMasterEqn.setPressures(pressures); PDepRateConstant.setPressures(pressures); ChebyshevPolynomials.setPlow(pressures[0]); ChebyshevPolynomials.setPup(pressures[4]); } else if (pDepType.toLowerCase().equals("off")) { // No pressure dependence reactionModelEnlarger = new RateBasedRME(); PDepNetwork.generateNetworks = false; } else { throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType); } } else throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!"); // pressure dependence flag if (reactionModelEnlarger instanceof RateBasedPDepRME) { line = ChemParser.readMeaningfulLine(reader); if (line.toLowerCase().startsWith("pdepkineticsmodel:")) { StringTokenizer st = new StringTokenizer(line); String name = st.nextToken(); String pDepKinType = st.nextToken(); if (pDepKinType.toLowerCase().equals("chebyshev") || pDepKinType.toLowerCase().equals("pdeparrhenius") || pDepKinType.toLowerCase().equals("rate")) { if (pDepKinType.toLowerCase().equals("chebyshev")) { PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV); line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("TRange")) { st = new StringTokenizer(line); String temp = st.nextToken(); // Should be "TRange:" String TUNITS = ChemParser.removeBrace(st.nextToken()); double tLow = Double.parseDouble(st.nextToken()); Temperature TMIN = new Temperature(tLow,TUNITS); ChebyshevPolynomials.setTlow(TMIN); double tHigh = Double.parseDouble(st.nextToken()); if (tHigh <= tLow) { System.err.println("Tmax is less than or equal to Tmin"); System.exit(0); } Temperature TMAX = new Temperature(tHigh,TUNITS); ChebyshevPolynomials.setTup(TMAX); int tResolution = Integer.parseInt(st.nextToken()); int tbasisFuncs = Integer.parseInt(st.nextToken()); if (tbasisFuncs > tResolution) { System.err.println("The number of basis functions cannot exceed the number of grid points"); System.exit(0); } FastMasterEqn.setNumTBasisFuncs(tbasisFuncs); line = ChemParser.readMeaningfulLine(reader); String PUNITS = ""; Pressure PMIN = new Pressure(); Pressure PMAX = new Pressure(); int pResolution = 0; int pbasisFuncs = 0; if (line.startsWith("PRange")) { st = new StringTokenizer(line); temp = st.nextToken(); // Should be "PRange:" PUNITS = ChemParser.removeBrace(st.nextToken()); double pLow = Double.parseDouble(st.nextToken()); PMIN = new Pressure(pLow,PUNITS); ChebyshevPolynomials.setPlow(PMIN); double pHigh = Double.parseDouble(st.nextToken()); if (pHigh <= pLow) { System.err.println("Pmax is less than or equal to Pmin"); System.exit(0); } PMAX = new Pressure(pHigh,PUNITS); ChebyshevPolynomials.setPup(PMAX); pResolution = Integer.parseInt(st.nextToken()); pbasisFuncs = Integer.parseInt(st.nextToken()); if (pbasisFuncs > pResolution) { System.err.println("The number of basis functions cannot exceed the number of grid points"); System.exit(0); } FastMasterEqn.setNumPBasisFuncs(pbasisFuncs); } else { System.err.println("RMG cannot locate PRange field for Chebyshev polynomials."); System.exit(0); } // Set temperatures and pressures to use in PDep kinetics estimation Temperature[] temperatures = new Temperature[tResolution]; for (int i=0; i<temperatures.length; i++) { double tempValueTilda = Math.cos((2*(i+1)-1)*Math.PI/(2*temperatures.length)); double tempValue = 2 / (tempValueTilda * ((1/TMAX.getK()) - (1/TMIN.getK())) + (1/TMIN.getK()) + (1/TMAX.getK())); temperatures[temperatures.length-i-1] = new Temperature(tempValue,TUNITS); } FastMasterEqn.setTemperatures(temperatures); PDepRateConstant.setTemperatures(temperatures); Pressure[] pressures = new Pressure[pResolution]; for (int j=0; j<pressures.length; j++) { double pressValueTilda = Math.cos((2*(j+1)-1)*Math.PI/(2*pressures.length)); double pressValue = Math.pow(10,(pressValueTilda*(Math.log10(PMAX.getBar())-Math.log10(PMIN.getBar()))+Math.log10(PMIN.getBar())+Math.log10(PMAX.getBar()))/2); pressures[pressures.length-j-1] = new Pressure(pressValue,PUNITS); } FastMasterEqn.setPressures(pressures); PDepRateConstant.setPressures(pressures); line = ChemParser.readMeaningfulLine(reader); } } else if (pDepKinType.toLowerCase().equals("pdeparrhenius")) { //PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS); /* * Updated by MRH on 10Feb2010 * Allow user to specify # of T's/P's solved for in fame & * # of PLOG's to report */ PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS); line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("TRange")) { st = new StringTokenizer(line); String temp = st.nextToken(); // Should be "TRange:" String TUNITS = ChemParser.removeBrace(st.nextToken()); int numT = Integer.parseInt(st.nextToken()); Temperature[] listOfTs = new Temperature[numT]; int counter = 0; while (st.hasMoreTokens()) { listOfTs[counter] = new Temperature(Double.parseDouble(st.nextToken()),TUNITS); ++counter; } if (counter != numT) { System.out.println("Warning in TRange field of PressureDependence:\n" + "The stated number of temperatures is: " + numT + "but the length of the temperature list is: " + counter); } line = ChemParser.readMeaningfulLine(reader); String PUNITS = ""; if (line.startsWith("PRange")) { st = new StringTokenizer(line); temp = st.nextToken(); // Should be "PRange:" PUNITS = ChemParser.removeBrace(st.nextToken()); int numP = Integer.parseInt(st.nextToken()); Pressure[] listOfPs = new Pressure[numP]; counter = 0; while (st.hasMoreTokens()) { listOfPs[counter] = new Pressure(Double.parseDouble(st.nextToken()),PUNITS); ++counter; } if (counter != numP) { System.out.println("Warning in PRange field of PressureDependence:\n" + "The stated number of pressures is: " + numT + "but the length of the pressure list is: " + counter); } FastMasterEqn.setTemperatures(listOfTs); PDepRateConstant.setTemperatures(listOfTs); FastMasterEqn.setPressures(listOfPs); PDepRateConstant.setPressures(listOfPs); PDepArrheniusKinetics.setNumPressures(numP); PDepArrheniusKinetics.setPressures(listOfPs); } else { System.err.println("RMG cannot locate PRange field for PDepArrhenius."); System.exit(0); } line = ChemParser.readMeaningfulLine(reader); } } // 6Jul2009-MRH: // RATE mode reports p-dep rxn kinetics as: A 0.0 0.0 // where A is k(T,P) evaluated at the single temperature // and pressure given in the condition.txt file else if (pDepKinType.toLowerCase().equals("rate")) PDepRateConstant.setMode(PDepRateConstant.Mode.RATE); } else { throw new InvalidSymbolException("condition.txt: Unknown PDepKinetics = " + pDepKinType); } } else throw new InvalidSymbolException("condition.txt: can't find PDepKinetics flag!"); } // include species (optional) if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") && !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS")) line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("IncludeSpecies")) { StringTokenizer st = new StringTokenizer(line); String iS = st.nextToken(); String fileName = st.nextToken(); HashSet includeSpecies = readIncludeSpecies(fileName); ((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies); line = ChemParser.readMeaningfulLine(reader); } // read in finish controller if (line.startsWith("FinishController")) { line = ChemParser.readMeaningfulLine(reader); StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); String goal = st.nextToken(); String type = st.nextToken(); TerminationTester tt; if (type.startsWith("Conversion")) { LinkedList spc = new LinkedList(); while (st.hasMoreTokens()) { String name = st.nextToken(); Species spe = (Species)speciesSet.get(name); if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name); String conv = st.nextToken(); double conversion; try { if (conv.endsWith("%")) { conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100; } else { conversion = Double.parseDouble(conv); } conversionSet[49] = conversion; } catch (NumberFormatException e) { throw new NumberFormatException("wrong number format for conversion in initial condition file!"); } SpeciesConversion sc = new SpeciesConversion(spe, conversion); spc.add(sc); } tt = new ConversionTT(spc); } else if (type.startsWith("ReactionTime")) { double time = Double.parseDouble(st.nextToken()); String unit = ChemParser.removeBrace(st.nextToken()); ReactionTime rt = new ReactionTime(time, unit); tt = new ReactionTimeTT(rt); } else { throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type); } line = ChemParser.readMeaningfulLine(reader); st = new StringTokenizer(line, ":"); String temp = st.nextToken(); String tol = st.nextToken(); double tolerance; try { if (tol.endsWith("%")) { tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100; } else { tolerance = Double.parseDouble(tol); } } catch (NumberFormatException e) { throw new NumberFormatException("wrong number format for conversion in initial condition file!"); } ValidityTester vt = null; if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance); else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance); else throw new InvalidReactionModelEnlargerException(); finishController = new FinishController(tt, vt); } else throw new InvalidSymbolException("condition.txt: can't find FinishController!"); // read in dynamic simulator line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("DynamicSimulator")) { StringTokenizer st = new StringTokenizer(line,":"); String temp = st.nextToken(); String simulator = st.nextToken().trim(); //read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative" if (st.hasMoreTokens()){ if (st.nextToken().trim().toLowerCase().equals("non-negative")){ if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true; else{ System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option."); System.exit(0); } } } numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator() //int numConversions = 0; boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line // read in time step line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) { st = new StringTokenizer(line); temp = st.nextToken(); while (st.hasMoreTokens()) { temp = st.nextToken(); if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO") autoflag=true; } else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO" double tStep = Double.parseDouble(temp); String unit = "sec"; setTimeStep(new ReactionTime(tStep, unit)); } } ((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep); } else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){ st = new StringTokenizer(line); temp = st.nextToken(); int i=0; SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0); Species convSpecies = sc.species; Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen double initialConc = 0; while (iter.hasNext()){ SpeciesStatus sps = (SpeciesStatus)iter.next(); if (sps.species.equals(convSpecies)) initialConc = sps.concentration; } while (st.hasMoreTokens()){ temp=st.nextToken(); if (temp.startsWith("AUTO")){ autoflag=true; } else if (!autoflag){ double conv = Double.parseDouble(temp); conversionSet[i] = (1-conv) * initialConc; i++; } } conversionSet[i] = (1 - conversionSet[49])* initialConc; numConversions = i+1; } else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!"); // read in atol line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Atol:")) { st = new StringTokenizer(line); temp = st.nextToken(); atol = Double.parseDouble(st.nextToken()); } else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!"); // read in rtol line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Rtol:")) { st = new StringTokenizer(line); temp = st.nextToken(); String rel_tol = st.nextToken(); if (rel_tol.endsWith("%")) rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1)); else rtol = Double.parseDouble(rel_tol); } else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!"); if (simulator.equals("DASPK")) { paraInfor = 0;//svp // read in SA line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Error bars")) {//svp st = new StringTokenizer(line,":"); temp = st.nextToken(); String sa = st.nextToken().trim(); if (sa.compareToIgnoreCase("on")==0) { paraInfor = 1; error = true; } else if (sa.compareToIgnoreCase("off")==0) { paraInfor = 0; error = false; } else throw new InvalidSymbolException("condition.txt: can't find error on/off information!"); } else throw new InvalidSymbolException("condition.txt: can't find SA information!"); line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Display sensitivity coefficients")){//svp st = new StringTokenizer(line,":"); temp = st.nextToken(); String sa = st.nextToken().trim(); if (sa.compareToIgnoreCase("on")==0){ paraInfor = 1; sensitivity = true; } else if (sa.compareToIgnoreCase("off")==0){ if (paraInfor != 1){ paraInfor = 0; } sensitivity = false; } else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!"); //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList //6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL //6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null? for (int i = 0;i < initialStatusList.size();i++) { dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag)); } } species = new LinkedList(); line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Display sensitivity information") ){ line = ChemParser.readMeaningfulLine(reader); System.out.println(line); while (!line.equals("END")){ st = new StringTokenizer(line); String name = st.nextToken(); if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything species.add(name); line = ChemParser.readMeaningfulLine(reader); } } } else if (simulator.equals("DASSL")) { //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList // for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) { // dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next())); //11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i //5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null? for (int i = 0;i < initialStatusList.size();i++) { dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag)); } } else if (simulator.equals("Chemkin")) { line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("ReactorType")) { st = new StringTokenizer(line, ":"); temp = st.nextToken(); String reactorType = st.nextToken().trim(); //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) { //dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next())); dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error } } } else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator); //10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) { double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used ((DynamicSimulator)(iter.next())).addConversion(cs, numConversions); } } else throw new InvalidSymbolException("condition.txt: can't find DynamicSimulator!"); // read in reaction model enlarger /* Read in the Primary Reaction Library * MRH 12-Jun-2009 * * I've made minor changes to this piece of code. In particular, I've * eliminated the on/off flag. The user can specify as many PRLs, * including none, as they like. */ line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("PrimaryReactionLibrary:")) { // GJB modified to allow multiple primary reaction libraries int Ilib = 0; line = ChemParser.readMeaningfulLine(reader); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader); tempString = line.split("Location: "); String path = tempString[tempString.length-1].trim(); if (Ilib==0) { //primaryReactionLibrary = new PrimaryReactionLibrary(name, path); setPrimaryReactionLibrary(new PrimaryReactionLibrary(name, path));//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary Ilib++; } else { //primaryReactionLibrary.appendPrimaryReactionLibrary(name,path); getPrimaryReactionLibrary().appendPrimaryReactionLibrary(name,path);//10/14/07 gmagoon: changed to use getPrimaryReactionLibrary; check to make sure this is valid Ilib++;//just in case anybody wants to track how many are processed } line = ChemParser.readMeaningfulLine(reader); } // System.out.println("Primary Reaction Libraries in use: " +getPrimaryReactionLibrary().getName());//10/14/07 gmagoon: changed to use getPrimaryReactionLibrary if (Ilib==0) { //primaryReactionLibrary = null; setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary; check to make sure this is valid } else System.out.println("Primary Reaction Libraries in use: " + getPrimaryReactionLibrary().getName()); } else throw new InvalidSymbolException("condition.txt: can't find PrimaryReactionLibrary!"); /* * Added by MRH 12-Jun-2009 * * The SeedMechanism acts almost exactly as the old * PrimaryReactionLibrary did. Whatever is in the SeedMechanism * will be placed in the core at the beginning of the simulation. * The user can specify as many seed mechanisms as they like, with * the priority (in the case of duplicates) given to the first * instance. There is no on/off flag. */ line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("SeedMechanism:")) { int numMechs = 0; line = ChemParser.readMeaningfulLine(reader); while (!line.equals("END")) { String[] tempString = line.split("Name: "); String name = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader); tempString = line.split("Location: "); String path = tempString[tempString.length-1].trim(); line = ChemParser.readMeaningfulLine(reader); tempString = line.split("GenerateReactions: "); String generateStr = tempString[tempString.length-1].trim(); boolean generate = true; if (generateStr.equalsIgnoreCase("yes") || generateStr.equalsIgnoreCase("on") || generateStr.equalsIgnoreCase("true")){ generate = true; System.out.println("Will generate cross-reactions between species in seed mechanism " + name); } else if(generateStr.equalsIgnoreCase("no") || generateStr.equalsIgnoreCase("off") || generateStr.equalsIgnoreCase("false")) { generate = false; System.out.println("Will NOT initially generate cross-reactions between species in seed mechanism "+ name); System.out.println("This may have unintended consequences"); } else { System.err.println("Input file invalid"); System.err.println("Please include a 'GenerateReactions: yes/no' line for seed mechanism "+name); System.exit(0); } if (numMechs==0) { setSeedMechanism(new SeedMechanism(name, path, generate)); ++numMechs; } else { getSeedMechanism().appendSeedMechanism(name, path, generate); ++numMechs; } line = ChemParser.readMeaningfulLine(reader); } if (numMechs != 0) System.out.println("Seed Mechanisms in use: " + getSeedMechanism().getName()); else setSeedMechanism(null); } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate SeedMechanism field"); line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("ChemkinUnits")) { line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Verbose:")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); String OnOff = st.nextToken().toLowerCase(); if (OnOff.equals("off")) { ArrheniusKinetics.setVerbose(false); } else if (OnOff.equals("on")) { ArrheniusKinetics.setVerbose(true); } line = ChemParser.readMeaningfulLine(reader); } if (line.startsWith("A")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // Should be "A:" String units = st.nextToken(); if (units.equals("moles") || units.equals("molecules")) ArrheniusKinetics.setAUnits(units); else { System.err.println("Units for A were not recognized: " + units); System.exit(0); } } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate Chemkin units A field."); line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Ea")) { StringTokenizer st = new StringTokenizer(line); String dummyString = st.nextToken(); // Should be "Ea:" String units = st.nextToken(); if (units.equals("kcal/mol") || units.equals("cal/mol") || units.equals("kJ/mol") || units.equals("J/mol") || units.equals("Kelvins")) ArrheniusKinetics.setEaUnits(units); else { System.err.println("Units for Ea were not recognized: " + units); System.exit(0); } } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate Chemkin units Ea field."); } else throw new InvalidSymbolException("Error reading condition.txt file: " + "Could not locate ChemkinUnits field."); in.close(); // LinkedList temperatureArray = new LinkedList(); // LinkedList pressureArray = new LinkedList(); // Iterator iterIS = initialStatusList.iterator(); // for (Iterator iter = tempList.iterator(); iter.hasNext(); ) { // TemperatureModel tm = (TemperatureModel)iter.next(); // for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){ // PressureModel pm = (PressureModel)iter2.next(); // InitialStatus is = (InitialStatus)iterIS.next(); // temperatureArray.add(tm.getTemperature(is.getTime())); // pressureArray.add(pm.getPressure(is.getTime())); // PDepNetwork.setTemperatureArray(temperatureArray); // PDepNetwork.setPressureArray(pressureArray); //10/4/07 gmagoon: moved to modelGeneration() //ReactionGenerator p_reactionGenerator = new TemplateReactionGenerator();//10/4/07 gmagoon: changed to p_reactionGenerator from reactionGenerator // setReactionGenerator(p_reactionGenerator);//10/4/07 gmagoon: added /* * MRH 12-Jun-2009 * A TemplateReactionGenerator now requires a Temperature be passed to it. * This allows RMG to determine the "best" kinetic parameters to use * in the mechanism generation. For now, I choose to pass the first * temperature in the list of temperatures. RMG only outputs one mechanism, * even for multiple temperature/pressure systems, so we can only have one * set of kinetics. */ Temperature t = new Temperature(300,"K"); for (Iterator iter = tempList.iterator(); iter.hasNext();) { TemperatureModel tm = (TemperatureModel)iter.next(); t = tm.getTemperature(new ReactionTime(0,"sec")); setTemp4BestKinetics(t); break; } setReactionGenerator(new TemplateReactionGenerator()); //11/4/07 gmagoon: moved from modelGeneration; mysteriously, moving this later moves "Father" lines up in output at runtime, immediately after condition file (as in original code); previously, these Father lines were just before "Can't read primary reaction library files!" lrg = new LibraryReactionGenerator();//10/10/07 gmagoon: moved from modelGeneration (sequence lrg increases species id, and the different sequence was causing problems as main species id was 6 instead of 1); //10/31/07 gmagoon: restored this line from 10/10/07 backup: somehow it got lost along the way; 11/5/07 gmagoon: changed to use "lrg =" instead of setLibraryReactionGenerator //10/24/07 gmagoon: updated to use multiple reactionSystem variables reactionSystemList = new LinkedList(); // LinkedList temperatureArray = new LinkedList();//10/30/07 gmagoon: added temperatureArray variable for passing to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg; Iterator iter3 = initialStatusList.iterator(); Iterator iter4 = dynamicSimulatorList.iterator(); int i = 0;//10/30/07 gmagoon: added for (Iterator iter = tempList.iterator(); iter.hasNext(); ) { TemperatureModel tm = (TemperatureModel)iter.next(); //InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: fixing apparent bug by moving these inside inner "for loop" //DynamicSimulator ds = (DynamicSimulator)iter4.next(); for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){ PressureModel pm = (PressureModel)iter2.next(); InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: moved from outer "for loop"" DynamicSimulator ds = (DynamicSimulator)iter4.next(); // temperatureArray.add(tm.getTemperature(is.getTime()));//10/30/07 gmagoon: added; //10/31/07 added .getTemperature(is.getTime()); 11/6/07 gmagoon: moved before initialization of lrg; //11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT // TerminationTester termTestCopy; // if (finishController.getTerminationTester() instanceof ConversionTT){ // ConversionTT termTest = (ConversionTT)finishController.getTerminationTester(); // LinkedList spcCopy = (LinkedList)(termTest.getSpeciesGoalConversionSetList().clone()); // termTestCopy = new ConversionTT(spcCopy); // else{ // termTestCopy = finishController.getTerminationTester(); FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester());//10/31/07 gmagoon: changed to create new finishController instance in each case (apparently, the finish controller becomes associated with reactionSystem in setFinishController within ReactionSystem); alteratively, could use clone, but might need to change FinishController to be "cloneable" // FinishController fc = new FinishController(termTestCopy, finishController.getValidityTester()); reactionSystemList.add(new ReactionSystem(tm, pm, reactionModelEnlarger, fc, ds, getPrimaryReactionLibrary(), getReactionGenerator(), getSpeciesSeed(), is, getReactionModel(),lrg, i, equationOfState)); i++;//10/30/07 gmagoon: added System.out.println("Created reaction system "+i+"\n"); } } // PDepNetwork.setTemperatureArray(temperatureArray);//10/30/07 gmagoon: passing temperatureArray to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg; } catch (IOException e) { System.err.println("Error in read in reaction system initialization file!"); throw new IOException("Reaction System Initialization: " + e.getMessage()); } } public void setReactionModel(ReactionModel p_ReactionModel) { reactionModel = p_ReactionModel; } public void modelGeneration() { //long begin_t = System.currentTimeMillis(); try{ ChemGraph.readForbiddenStructure(); setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon moved from initializeCoreEdgeReactionModel // setReactionGenerator(new TemplateReactionGenerator());//10/4/07 gmagoon: moved inside initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 (although I have not investigated this change in detail); //11/4/07 gmagoon: moved inside initializeReactionSystems // setLibraryReactionGenerator(new LibraryReactionGenerator());//10/10/07 gmagoon: moved after initializeReactionSystem // initializeCoreEdgeReactionModel();//10/4/07 gmagoon moved from below to run initializeCoreEdgeReactionModel before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 initializeReactionSystems(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(0); } catch (InvalidSymbolException e) { System.err.println(e.getMessage()); System.exit(0); } //10/31/07 gmagoon: initialize validList (to false) before initializeCoreEdgeReactionModel is called validList = new LinkedList(); for (Integer i = 0; i<reactionSystemList.size();i++) { validList.add(false); } initializeCoreEdgeReactionModel();//10/4/07 gmagoon: moved before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 //10/24/07 gmagoon: changed to use reactionSystemList // LinkedList initList = new LinkedList();//10/25/07 gmagoon: moved these variables to apply to entire class // LinkedList beginList = new LinkedList(); // LinkedList endList = new LinkedList(); // LinkedList lastTList = new LinkedList(); // LinkedList currentTList = new LinkedList(); // LinkedList lastPList = new LinkedList(); // LinkedList currentPList = new LinkedList(); // LinkedList conditionChangedList = new LinkedList(); // LinkedList reactionChangedList = new LinkedList(); //5/6/08 gmagoon: determine whether there are intermediate time/conversion steps, type of termination tester is based on characteristics of 1st reaction system (it is assumed that they are all identical in terms of type of termination tester) boolean intermediateSteps = true; ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0); if (rs0.finishController.terminationTester instanceof ReactionTimeTT){ if (timeStep == null){ intermediateSteps = false; } } else if (numConversions==1){ //if we get to this block, we presumably have a conversion terminationTester; this required moving numConversions to be attribute...alternative to using numConversions is to access one of the DynamicSimulators and determine conversion length intermediateSteps=false; } //10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) { ReactionSystem rs = (ReactionSystem)iter.next(); if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases rs.initializePDepNetwork(); } ReactionTime init = rs.getInitialReactionTime(); initList.add(init); ReactionTime begin = init; beginList.add(begin); ReactionTime end; if (rs.finishController.terminationTester instanceof ReactionTimeTT){ //5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified if (!(timeStep==null)){ end = (ReactionTime)timeStep.get(0); } else{ end= ((ReactionTimeTT)rs.finishController.terminationTester).finalTime; } //end = (ReactionTime)timeStep.get(0); endList.add(end); } else{ end = new ReactionTime(1e6,"sec"); endList.add(end); } // int iterationNumber = 1; lastTList.add(rs.getTemperature(init)); currentTList.add(rs.getTemperature(init)); lastPList.add(rs.getPressure(init)); currentPList.add(rs.getPressure(init)); conditionChangedList.add(false); reactionChangedList.add(false);//10/31/07 gmagoon: added //Chemkin.writeChemkinInputFile(reactionSystem.getReactionModel(),reactionSystem.getPresentStatus()); } int iterationNumber = 1; LinkedList terminatedList = new LinkedList();//10/24/07 gmagoon: this may not be necessary, as if one reactionSystem is terminated, I think all should be terminated //validList = new LinkedList();//10/31/07 gmagoon: moved before initializeCoreEdgeReactionModel //10/24/07 gmagoon: initialize allTerminated and allValid to true; these variables keep track of whether all the reactionSystem variables satisfy termination and validity, respectively boolean allTerminated = true; boolean allValid = true; // IF RESTART IS TURNED ON // Update the systemSnapshot for each ReactionSystem in the reactionSystemList if (readrestart) { for (Integer i=0; i<reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); InitialStatus is = rs.getInitialStatus(); putRestartSpeciesInInitialStatus(is,i); rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature()); } } //10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); endList.set(i,rs.solveReactionSystem(begin, end, true, true, true, iterationNumber-1)); Chemkin.writeChemkinInputFile(rs); boolean terminated = rs.isReactionTerminated(); terminatedList.add(terminated); if(!terminated) allTerminated = false; boolean valid = rs.isModelValid(); //validList.add(valid); validList.set(i, valid);//10/31/07 gmagoon: validList initialization moved before initializeCoreEdgeReactionModel if(!valid) allValid = false; reactionChangedList.set(i,false); } //9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey if (ChemGraph.useQM){ writeInChIs(getReactionModel()); } writeDictionary(getReactionModel()); //System.exit(0); System.out.println("The model core has " + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); System.out.println("The model edge has " + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + " species."); StringBuilder print_info = Global.diagnosticInfo; print_info.append("\nMolecule \t Flux\t\tTime\t \t\t \t Core \t \t Edge \t \t memory\n"); print_info.append(" \t moleular \t characteristic \t findspecies \t moveUnreactedToReacted \t enlarger \t restart1 \t totalEnlarger \t resetSystem \t readSolverFile\t writeSolverFile \t justSolver \t SolverIterations \t solverSpeciesStatus \t Totalsolver \t gc \t restart+diagnosis \t chemkin thermo \t chemkin reactions \t validitytester \t Species \t Reactions\t Species\t Reactions \t memory used \t allSpecies \t TotalTime \t findRateConstant\t identifyReactedSites \t reactChemGraph \t makespecies\t CheckReverseReaction \t makeTemplateReaction \t getReactionfromStruc \t genReverseFromReac"); print_info.append("\t\t\t\t\t\t\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t"+Global.makeSpecies+"\n"); double solverMin = 0; double vTester = 0; /*if (!restart){ writeRestartFile(); writeCoreReactions(); writeAllReactions(); }*/ //System.exit(0); SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); System.out.println("Species dictionary size: "+dictionary.size()); double tAtInitialization = Global.tAtInitialization; //10/24/07: changed to use allTerminated and allValid // step 2: iteratively grow reaction system while (!allTerminated || !allValid) { while (!allValid) { //writeCoreSpecies(); double pt = System.currentTimeMillis(); // ENLARGE THE MODEL!!! (this is where the good stuff happens) enlargeReactionModel();//10/24/07 gmagoon: need to adjust this function double totalEnlarger = (System.currentTimeMillis() - pt)/1000/60; //PDepNetwork.completeNetwork(reactionSystem.reactionModel.getSpeciesSet()); //10/24/07 gmagoon: changed to use reactionSystemList if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) { ReactionSystem rs = (ReactionSystem)iter.next(); rs.initializePDepNetwork(); } //reactionSystem.initializePDepNetwork(); } pt = System.currentTimeMillis(); //10/24/07 gmagoon: changed to use reactionSystemList for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) { ReactionSystem rs = (ReactionSystem)iter.next(); rs.resetSystemSnapshot(); } //reactionSystem.resetSystemSnapshot(); double resetSystem = (System.currentTimeMillis() - pt)/1000/60; //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { //reactionChanged = true; ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); reactionChangedList.set(i,true); // begin = init; beginList.set(i, (ReactionTime)initList.get(i)); if (rs.finishController.terminationTester instanceof ReactionTimeTT){ //5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified if (!(timeStep==null)){ endList.set(i,(ReactionTime)timeStep.get(0)); } else{ endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime); } // endList.set(i, (ReactionTime)timeStep.get(0)); //end = (ReactionTime)timeStep.get(0); } else endList.set(i, new ReactionTime(1e6,"sec")); //end = new ReactionTime(1e6,"sec"); // iterationNumber = 1;//10/24/07 gmagoon: moved outside of loop currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i))); currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i))); conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i)))); //currentT = reactionSystem.getTemperature(begin); //currentP = reactionSystem.getPressure(begin); //conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP)); } iterationNumber = 1; double startTime = System.currentTimeMillis(); //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean reactionChanged = (Boolean)reactionChangedList.get(i); boolean conditionChanged = (Boolean)conditionChangedList.get(i); ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1)); //end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1); } solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60; startTime = System.currentTimeMillis(); //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); Chemkin.writeChemkinInputFile(rs); //Chemkin.writeChemkinInputFile(reactionSystem); } //9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey if (ChemGraph.useQM){ writeInChIs(getReactionModel()); } writeDictionary(getReactionModel()); double chemkint = (System.currentTimeMillis()-startTime)/1000/60; if (writerestart) { writeCoreSpecies(); writeCoreReactions(); writeEdgeSpecies(); writeEdgeReactions(); if (PDepNetwork.generateNetworks == true) writePDepNetworks(); } //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size()); System.out.println("At this time: " + ((ReactionTime)endList.get(i)).toString()); Species spe = SpeciesDictionary.getSpeciesFromID(1); double conv = rs.getPresentConversion(spe); System.out.print("Conversion of " + spe.getName() + " is:"); System.out.println(conv); } System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis()-tAtInitialization)/1000/60) + " minutes."); System.out.println("The model edge has " + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + " species."); //10/24/07 gmagoon: note: all reaction systems should use the same core, but I will display for each reactionSystem for testing purposes: for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size()); if (rs.getDynamicSimulator() instanceof JDASPK){ JDASPK solver = (JDASPK)rs.getDynamicSimulator(); System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); } else{ JDASSL solver = (JDASSL)rs.getDynamicSimulator(); System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); } } // if (reactionSystem.getDynamicSimulator() instanceof JDASPK){ // JDASPK solver = (JDASPK)reactionSystem.getDynamicSimulator(); // System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); //else{ // JDASSL solver = (JDASSL)reactionSystem.getDynamicSimulator(); // System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); startTime = System.currentTimeMillis(); double mU = memoryUsed(); double gc = (System.currentTimeMillis()-startTime)/1000/60; startTime = System.currentTimeMillis(); //10/24/07 gmagoon: updating to use reactionSystemList allValid = true; for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean valid = rs.isModelValid(); if(!valid) allValid = false; validList.set(i,valid); //valid = reactionSystem.isModelValid(); } vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60; startTime = System.currentTimeMillis(); writeDiagnosticInfo(); writeEnlargerInfo(); double restart2 = (System.currentTimeMillis()-startTime)/1000/60; int allSpecies, allReactions; allSpecies = SpeciesDictionary.getInstance().size(); print_info.append(totalEnlarger + "\t" + resetSystem + "\t" + Global.readSolverFile + "\t" + Global.writeSolverFile + "\t" + Global.solvertime + "\t" + Global.solverIterations + "\t" + Global.speciesStatusGenerator + "\t" + solverMin + "\t" + gc + "\t" + restart2 + "\t" + Global.chemkinThermo + '\t' + Global.chemkinReaction + "\t" + vTester + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t" + mU + "\t" + allSpecies + "\t" + (System.currentTimeMillis()-Global.tAtInitialization)/1000/60 + "\t"+ String.valueOf(Global.RT_findRateConstant)+"\t"+Global.RT_identifyReactedSites+"\t"+Global.RT_reactChemGraph+"\t"+Global.makeSpecies+"\t"+Global.checkReactionReverse+"\t"+Global.makeTR+ "\t" + Global.getReacFromStruc + "\t" + Global.generateReverse+"\n"); } //5/6/08 gmagoon: in order to handle cases where no intermediate time/conversion steps are used, only evaluate the next block of code when there are intermediate time/conversion steps double startTime = System.currentTimeMillis(); if(intermediateSteps){ for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); reactionChangedList.set(i, false); //reactionChanged = false; Temperature currentT = (Temperature)currentTList.get(i); Pressure currentP = (Pressure)currentPList.get(i); lastTList.set(i,(Temperature)currentT.clone()) ; lastPList.set(i,(Pressure)currentP.clone()); //lastT = (Temperature)currentT.clone(); //lastP = (Pressure)currentP.clone(); currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i))); currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i))); conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i)))); //currentP = reactionSystem.getPressure(begin); //conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP)); beginList.set(i,((SystemSnapshot)(rs.getSystemSnapshotEnd().next())).time); // begin=((SystemSnapshot)(reactionSystem.getSystemSnapshotEnd().next())).time; if (rs.finishController.terminationTester instanceof ReactionTimeTT){ if (iterationNumber < timeStep.size()){ endList.set(i,(ReactionTime)timeStep.get(iterationNumber)); //end = (ReactionTime)timeStep.get(iterationNumber); } else endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime); //end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime; } else endList.set(i,new ReactionTime(1e6,"sec")); //end = new ReactionTime(1e6,"sec"); } iterationNumber++; startTime = System.currentTimeMillis();//5/6/08 gmagoon: moved declaration outside of if statement so it can be accessed in subsequent vTester line; previous steps are probably so fast that I could eliminate this line without much effect on normal operation with intermediate steps //double startTime = System.currentTimeMillis(); //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean reactionChanged = (Boolean)reactionChangedList.get(i); boolean conditionChanged = (Boolean)conditionChangedList.get(i); ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1)); // end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1); } solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60; startTime = System.currentTimeMillis(); //5/6/08 gmagoon: changed to separate validity and termination testing, and termination testing is done last...termination testing should be done even if there are no intermediate conversions; however, validity is guaranteed if there are no intermediate conversions based on previous conditional if statement allValid = true; for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean valid = rs.isModelValid(); validList.set(i,valid); if(!valid) allValid = false; } }//5/6/08 gmagoon: end of block for intermediateSteps allTerminated = true; for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); boolean terminated = rs.isReactionTerminated(); terminatedList.set(i,terminated); if(!terminated){ allTerminated = false; System.out.println("Reaction System "+(i+1)+" has not reached its termination criterion"); if (rs.isModelValid()&& runKillableToPreventInfiniteLoop(intermediateSteps, iterationNumber)) { System.out.println("although it seems to be valid (complete), so it was not interrupted for being invalid."); System.out.println("This probably means there was an error with the ODE solver, and we risk entering an endless loop."); System.out.println("Stopping."); throw new Error(); } } } // //10/24/07 gmagoon: changed to use reactionSystemList // allTerminated = true; // allValid = true; // for (Integer i = 0; i<reactionSystemList.size();i++) { // ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); // boolean terminated = rs.isReactionTerminated(); // terminatedList.set(i,terminated); // if(!terminated) // allTerminated = false; // boolean valid = rs.isModelValid(); // validList.set(i,valid); // if(!valid) // allValid = false; // //terminated = reactionSystem.isReactionTerminated(); // //valid = reactionSystem.isModelValid(); //10/24/07 gmagoon: changed to use reactionSystemList, allValid if (allValid) { //10/24/07 gmagoon: changed to use reactionSystemList for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size()); System.out.println("At this reaction time: " + ((ReactionTime)endList.get(i)).toString()); Species spe = SpeciesDictionary.getSpeciesFromID(1); double conv = rs.getPresentConversion(spe); System.out.print("Conversion of " + spe.getName() + " is:"); System.out.println(conv); } //System.out.println("At this time: " + end.toString()); //Species spe = SpeciesDictionary.getSpeciesFromID(1); //double conv = reactionSystem.getPresentConversion(spe); //System.out.print("current conversion = "); //System.out.println(conv); Runtime runTime = Runtime.getRuntime(); System.out.print("Memory used: "); System.out.println(runTime.totalMemory()); System.out.print("Free memory: "); System.out.println(runTime.freeMemory()); //runTime.gc(); /* if we're not calling runTime.gc() then don't bother printing this: System.out.println("After garbage collection:"); System.out.print("Memory used: "); System.out.println(runTime.totalMemory()); System.out.print("Free memory: "); System.out.println(runTime.freeMemory()); */ //10/24/07 gmagoon: note: all reaction systems should use the same core, but I will display for each reactionSystem for testing purposes: for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size()); if (rs.getDynamicSimulator() instanceof JDASPK){ JDASPK solver = (JDASPK)rs.getDynamicSimulator(); System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); } else{ JDASSL solver = (JDASSL)rs.getDynamicSimulator(); System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); System.out.println("(although rs.getReactionModel().getReactionNumber() returns "+rs.getReactionModel().getReactionNumber()+")"); } } // if (reactionSystem.getDynamicSimulator() instanceof JDASPK){ // JDASPK solver = (JDASPK)reactionSystem.getDynamicSimulator(); // System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); // else{ // JDASSL solver = (JDASSL)reactionSystem.getDynamicSimulator(); // System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species."); } vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;//5/6/08 gmagoon: for case where intermediateSteps = false, this will use startTime declared just before intermediateSteps loop, and will only include termination testing, but no validity testing } //System.out.println("Performing model reduction"); if (paraInfor != 0){ System.out.println("Model Generation performed. Now generating sensitivity data."); //10/24/07 gmagoon: updated to use reactionSystemList LinkedList dynamicSimulator2List = new LinkedList(); for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); //6/25/08 gmagoon: updated to pass index i //6/25/08 gmagoon: updated to pass (dummy) finishController and autoflag (set to false here); dynamicSimulator2List.add(new JDASPK(rtol, atol, paraInfor, (InitialStatus)initialStatusList.get(i),i)); //DynamicSimulator dynamicSimulator2 = new JDASPK(rtol, atol, paraInfor, initialStatus); ((DynamicSimulator)dynamicSimulator2List.get(i)).addConversion(((JDASPK)rs.dynamicSimulator).conversionSet, ((JDASPK)rs.dynamicSimulator).conversionSet.length); //dynamicSimulator2.addConversion(((JDASPK)reactionSystem.dynamicSimulator).conversionSet, ((JDASPK)reactionSystem.dynamicSimulator).conversionSet.length); rs.setDynamicSimulator((DynamicSimulator)dynamicSimulator2List.get(i)); //reactionSystem.setDynamicSimulator(dynamicSimulator2); int numSteps = rs.systemSnapshot.size() -1; rs.resetSystemSnapshot(); beginList.set(i, (ReactionTime)initList.get(i)); //begin = init; if (rs.finishController.terminationTester instanceof ReactionTimeTT){ endList.set(i,((ReactionTimeTT)rs.finishController.terminationTester).finalTime); //end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime; } else{ ReactionTime end = (ReactionTime)endList.get(i); endList.set(i, end.add(end)); //end = end.add(end); } terminatedList.set(i, false); //terminated = false; ReactionTime begin = (ReactionTime)beginList.get(i); ReactionTime end = (ReactionTime)endList.get(i); rs.solveReactionSystemwithSEN(begin, end, true, false, false); //reactionSystem.solveReactionSystemwithSEN(begin, end, true, false, false); } } for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus()); } //9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey if (ChemGraph.useQM){ writeInChIs(getReactionModel()); } writeDictionary(getReactionModel()); System.out.println("Model Generation Completed"); return; } //9/1/09 gmagoon: this function writes a "dictionary" with Chemkin name, RMG name, (modified) InChI, and InChIKey //this is based off of writeChemkinFile in ChemkinInputFile.java private void writeInChIs(ReactionModel p_reactionModel) { StringBuilder result=new StringBuilder(); for (Iterator iter = ((CoreEdgeReactionModel)p_reactionModel).core.getSpecies(); iter.hasNext(); ) { Species species = (Species) iter.next(); result.append(species.getChemkinName() + "\t"+species.getName() + "\t" + species.getChemGraph().getModifiedInChIAnew() + "\t" + species.getChemGraph().getModifiedInChIKeyAnew()+ "\n"); } String file = "inchiDictionary.txt"; try { FileWriter fw = new FileWriter(file); fw.write(result.toString()); fw.close(); } catch (Exception e) { System.out.println("Error in writing InChI file inchiDictionary.txt!"); System.out.println(e.getMessage()); System.exit(0); } } //9/14/09 gmagoon: function to write dictionary, based on code copied from RMG.java private void writeDictionary(ReactionModel rm){ CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm; //Write core species to RMG_Dictionary.txt String coreSpecies =""; Iterator iter = cerm.getSpecies(); if (Species.useInChI) { while (iter.hasNext()){ int i=1; Species spe = (Species) iter.next(); coreSpecies = coreSpecies + spe.getChemkinName() + " " + spe.getInChI() + "\n"+spe.getChemGraph().toString(i)+"\n\n"; } } else { while (iter.hasNext()){ int i=1; Species spe = (Species) iter.next(); coreSpecies = coreSpecies + spe.getChemkinName() + "\n"+spe.getChemGraph().toString(i)+"\n\n"; } } try{ File rmgDictionary = new File("RMG_Dictionary.txt"); FileWriter fw = new FileWriter(rmgDictionary); fw.write(coreSpecies); fw.close(); } catch (IOException e) { System.out.println("Could not write RMG_Dictionary.txt"); System.exit(0); } } private void parseRestartFiles() { parseAllSpecies(); parseCoreSpecies(); parseEdgeSpecies(); parseAllReactions(); parseCoreReactions(); } private void parseEdgeReactions() { SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); //HasMap speciesMap = dictionary.dictionary; try{ File coreReactions = new File("Restart/edgeReactions.txt"); FileReader fr = new FileReader(coreReactions); BufferedReader reader = new BufferedReader(fr); String line = ChemParser.readMeaningfulLine(reader); boolean found = false; LinkedHashSet reactionSet = new LinkedHashSet(); while (line != null){ Reaction reaction = ChemParser.parseEdgeArrheniusReaction(dictionary,line,1,1); boolean added = reactionSet.add(reaction); if (!added){ if (reaction.hasResonanceIsomerAsReactant()){ //Structure reactionStructure = reaction.getStructure(); found = getResonanceStructure(reaction,"reactants", reactionSet); } if (reaction.hasResonanceIsomerAsProduct() && !found){ //Structure reactionStructure = reaction.getStructure(); found = getResonanceStructure(reaction,"products", reactionSet); } if (!found){ System.out.println("Cannot add reaction "+line+" to the Reaction Edge. All resonance isomers have already been added"); System.exit(0); } else found = false; } //Reaction reverse = reaction.getReverseReaction(); //if (reverse != null) reactionSet.add(reverse); line = ChemParser.readMeaningfulLine(reader); } ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet); } catch (IOException e){ System.out.println("Could not read the corespecies restart file"); System.exit(0); } } public void parseCoreReactions() { SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); int i=1; //HasMap speciesMap = dictionary.dictionary; try{ File coreReactions = new File("Restart/coreReactions.txt"); FileReader fr = new FileReader(coreReactions); BufferedReader reader = new BufferedReader(fr); String line = ChemParser.readMeaningfulLine(reader); boolean found = false; LinkedHashSet reactionSet = new LinkedHashSet(); while (line != null){ Reaction reaction = ChemParser.parseCoreArrheniusReaction(dictionary,line,1,1);//,((CoreEdgeReactionModel)reactionSystem.reactionModel)); boolean added = reactionSet.add(reaction); if (!added){ if (reaction.hasResonanceIsomerAsReactant()){ //Structure reactionStructure = reaction.getStructure(); found = getResonanceStructure(reaction,"reactants", reactionSet); } if (reaction.hasResonanceIsomerAsProduct() && !found){ //Structure reactionStructure = reaction.getStructure(); found = getResonanceStructure(reaction,"products", reactionSet); } if (!found){ System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added"); //System.exit(0); } else found = false; } Reaction reverse = reaction.getReverseReaction(); if (reverse != null) { reactionSet.add(reverse); //System.out.println(2 + "\t " + line); } //else System.out.println(1 + "\t" + line); line = ChemParser.readMeaningfulLine(reader); i=i+1; } ((CoreEdgeReactionModel)getReactionModel()).addReactedReactionSet(reactionSet); } catch (IOException e){ System.out.println("Could not read the coreReactions restart file"); System.exit(0); } } private void parseAllReactions() { SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); int i=1; //HasMap speciesMap = dictionary.dictionary; try{ File allReactions = new File("Restart/allReactions.txt"); FileReader fr = new FileReader(allReactions); BufferedReader reader = new BufferedReader(fr); String line = ChemParser.readMeaningfulLine(reader); boolean found = false; LinkedHashSet reactionSet = new LinkedHashSet(); OuterLoop: while (line != null){ Reaction reaction = ChemParser.parseArrheniusReaction(dictionary,line,1,1,((CoreEdgeReactionModel)getReactionModel())); if (((CoreEdgeReactionModel)getReactionModel()).categorizeReaction(reaction)==-1){ boolean added = reactionSet.add(reaction); if (!added){ found = false; if (reaction.hasResonanceIsomerAsReactant()){ //Structure reactionStructure = reaction.getStructure(); found = getResonanceStructure(reaction,"reactants", reactionSet); } if (reaction.hasResonanceIsomerAsProduct() && !found){ //Structure reactionStructure = reaction.getStructure(); found = getResonanceStructure(reaction,"products", reactionSet); } if (!found){ Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction reacTemp = (Reaction)iter.next(); if (reacTemp.equals(reaction)){ reactionSet.remove(reacTemp); reactionSet.add(reaction); break; } } //System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added"); //System.exit(0); } //else found = false; } } /*Reaction reverse = reaction.getReverseReaction(); if (reverse != null && ((CoreEdgeReactionModel)reactionSystem.reactionModel).isReactedReaction(reaction)) { reactionSet.add(reverse); //System.out.println(2 + "\t " + line); }*/ //else System.out.println(1 + "\t" + line); i=i+1; line = ChemParser.readMeaningfulLine(reader); } ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet); } catch (IOException e){ System.out.println("Could not read the corespecies restart file"); System.exit(0); } } private boolean getResonanceStructure(Reaction p_Reaction, String rOrP, LinkedHashSet reactionSet) { Structure reactionStructure = p_Reaction.getStructure(); //Structure tempreactionStructure = new Structure(reactionStructure.getReactantList(),reactionStructure.getProductList()); boolean found = false; if (rOrP.equals("reactants")){ Iterator originalreactants = reactionStructure.getReactants(); HashSet tempHashSet = new HashSet(); while(originalreactants.hasNext()){ tempHashSet.add(originalreactants.next()); } Iterator reactants = tempHashSet.iterator(); while(reactants.hasNext() && !found){ ChemGraph reactant = (ChemGraph)reactants.next(); if (reactant.getSpecies().hasResonanceIsomers()){ Iterator chemGraphIterator = reactant.getSpecies().getResonanceIsomers(); ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next(); while(chemGraphIterator.hasNext() && !found){ newChemGraph = (ChemGraph)chemGraphIterator.next(); reactionStructure.removeReactants(reactant); reactionStructure.addReactants(newChemGraph); reactant = newChemGraph; if (reactionSet.add(p_Reaction)){ found = true; } } } } } else{ Iterator originalproducts = reactionStructure.getProducts(); HashSet tempHashSet = new HashSet(); while(originalproducts.hasNext()){ tempHashSet.add(originalproducts.next()); } Iterator products = tempHashSet.iterator(); while(products.hasNext() && !found){ ChemGraph product = (ChemGraph)products.next(); if (product.getSpecies().hasResonanceIsomers()){ Iterator chemGraphIterator = product.getSpecies().getResonanceIsomers(); ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next(); while(chemGraphIterator.hasNext() && !found){ newChemGraph = (ChemGraph)chemGraphIterator.next(); reactionStructure.removeProducts(product); reactionStructure.addProducts(newChemGraph); product = newChemGraph; if (reactionSet.add(p_Reaction)){ found = true; } } } } } return found; } public void parseCoreSpecies() { // String restartFileContent =""; //int speciesCount = 0; //boolean added; SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); try{ File coreSpecies = new File ("Restart/coreSpecies.txt"); FileReader fr = new FileReader(coreSpecies); BufferedReader reader = new BufferedReader(fr); String line = ChemParser.readMeaningfulLine(reader); //HashSet speciesSet = new HashSet(); // if (reactionSystem == null){//10/24/07 gmagoon: commenting out since contents of if was already commented out anyway // //ReactionSystem reactionSystem = new ReactionSystem(); setReactionModel(new CoreEdgeReactionModel());//10/4/07 gmagoon:changed to setReactionModel while (line!=null) { StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); int ID = Integer.parseInt(index); Species spe = dictionary.getSpeciesFromID(ID); if (spe == null) System.out.println("There was no species with ID "+ID +" in the species dictionary"); ((CoreEdgeReactionModel)getReactionModel()).addReactedSpecies(spe); line = ChemParser.readMeaningfulLine(reader); } } catch (IOException e){ System.out.println("Could not read the corespecies restart file"); System.exit(0); } } public static void garbageCollect(){ System.gc(); } public static long memoryUsed(){ garbageCollect(); Runtime rT = Runtime.getRuntime(); long uM, tM, fM; tM = rT.totalMemory(); fM = rT.freeMemory(); uM = tM - fM; System.out.println("After garbage collection:"); System.out.print("Memory used: "); System.out.println(tM); System.out.print("Free memory: "); System.out.println(fM); return uM; } private HashSet readIncludeSpecies(String fileName) { HashSet speciesSet = new HashSet(); try { File includeSpecies = new File (fileName); FileReader fr = new FileReader(includeSpecies); BufferedReader reader = new BufferedReader(fr); String line = ChemParser.readMeaningfulLine(reader); while (line!=null) { StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); String name = null; if (!index.startsWith("(")) name = index; else name = st.nextToken().trim(); Graph g = ChemParser.readChemGraph(reader); ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { System.out.println("Forbidden Structure:\n" + e.getMessage()); System.exit(0); } Species species = Species.make(name,cg); //speciesSet.put(name, species); speciesSet.add(species); line = ChemParser.readMeaningfulLine(reader); System.out.println(line); } } catch (IOException e){ System.out.println("Could not read the included species file"); System.exit(0); } return speciesSet; } public LinkedHashSet parseAllSpecies() { // String restartFileContent =""; int speciesCount = 0; LinkedHashSet speciesSet = new LinkedHashSet(); boolean added; try{ long initialTime = System.currentTimeMillis(); File coreSpecies = new File ("allSpecies.txt"); BufferedReader reader = new BufferedReader(new FileReader(coreSpecies)); String line = ChemParser.readMeaningfulLine(reader); int i=0; while (line!=null) { i++; StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); String name = null; if (!index.startsWith("(")) name = index; else name = st.nextToken().trim(); int ID = getID(name); name = getName(name); Graph g = ChemParser.readChemGraph(reader); ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { System.out.println("Forbidden Structure:\n" + e.getMessage()); System.exit(0); } Species species; if (ID == 0) species = Species.make(name,cg); else species = Species.make(name,cg,ID); speciesSet.add(species); double flux = 0; int species_type = 1; line = ChemParser.readMeaningfulLine(reader); System.out.println(line); } } catch (IOException e){ System.out.println("Could not read the allSpecies restart file"); System.exit(0); } return speciesSet; } private String getName(String name) { //int id; String number = ""; int index=0; if (!name.endsWith(")")) return name; else { char [] nameChars = name.toCharArray(); String temp = String.copyValueOf(nameChars); int i=name.length()-2; //char test = "("; while (i>0){ if (name.charAt(i)== '(') { index=i; i=0; } else i = i-1; } } number = name.substring(0,index); return number; } private int getID(String name) { int id; String number = ""; if (!name.endsWith(")")) return 0; else { char [] nameChars = name.toCharArray(); int i=name.length()-2; //char test = "("; while (i>0){ if (name.charAt(i)== '(') i=0; else{ number = name.charAt(i)+number; i = i-1; } } } id = Integer.parseInt(number); return id; } private void parseEdgeSpecies() { // String restartFileContent =""; SpeciesDictionary dictionary = SpeciesDictionary.getInstance(); try{ File edgeSpecies = new File ("Restart/edgeSpecies.txt"); FileReader fr = new FileReader(edgeSpecies); BufferedReader reader = new BufferedReader(fr); String line = ChemParser.readMeaningfulLine(reader); //HashSet speciesSet = new HashSet(); while (line!=null) { StringTokenizer st = new StringTokenizer(line); String index = st.nextToken(); int ID = Integer.parseInt(index); Species spe = dictionary.getSpeciesFromID(ID); if (spe == null) System.out.println("There was no species with ID "+ID +" in the species dictionary"); //reactionSystem.reactionModel = new CoreEdgeReactionModel(); ((CoreEdgeReactionModel)getReactionModel()).addUnreactedSpecies(spe); line = ChemParser.readMeaningfulLine(reader); } } catch (IOException e){ System.out.println("Could not read the edgepecies restart file"); System.exit(0); } } /*private int calculateAllReactionsinReactionTemplate() { int totalnum = 0; TemplateReactionGenerator trg = (TemplateReactionGenerator)reactionSystem.reactionGenerator; Iterator iter = trg.getReactionTemplateLibrary().getReactionTemplate(); while (iter.hasNext()){ ReactionTemplate rt = (ReactionTemplate)iter.next(); totalnum += rt.getNumberOfReactions(); } return totalnum; }*/ private void writeEnlargerInfo() { try { File diagnosis = new File("enlarger.xls"); FileWriter fw = new FileWriter(diagnosis); fw.write(Global.enlargerInfo.toString()); fw.close(); } catch (IOException e) { System.out.println("Cannot write enlarger file"); System.exit(0); } } private void writeDiagnosticInfo() { try { File diagnosis = new File("diagnosis.xls"); FileWriter fw = new FileWriter(diagnosis); fw.write(Global.diagnosticInfo.toString()); fw.close(); } catch (IOException e) { System.out.println("Cannot write diagnosis file"); System.exit(0); } } //10/25/07 gmagoon: I don't think this is used, but I will update to use reactionSystem and reactionTime as parameter to access temperature; commented-out usage of writeRestartFile will need to be modified //Is still incomplete. public void writeRestartFile(ReactionSystem p_rs, ReactionTime p_time ) { //writeCoreSpecies(p_rs); //writeCoreReactions(p_rs, p_time); //writeEdgeSpecies(); //writeAllReactions(p_rs, p_time); //writeEdgeReactions(p_rs, p_time); //String restartFileName; //String restartFileContent=""; } /*Only write the forward reactions in the model core. The reverse reactions are generated from the forward reactions.*/ //10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature private void writeEdgeReactions(ReactionSystem p_rs, ReactionTime p_time) { StringBuilder restartFileContent =new StringBuilder(); int reactionCount = 1; try{ File coreSpecies = new File ("Restart/edgeReactions.txt"); FileWriter fw = new FileWriter(coreSpecies); for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); //if (reaction.getDirection()==1){ //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); reactionCount = reactionCount + 1; } //restartFileContent += "\nEND"; fw.write(restartFileContent.toString()); fw.close(); } catch (IOException e){ System.out.println("Could not write the restart edgereactions file"); System.exit(0); } } //10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature private void writeAllReactions(ReactionSystem p_rs, ReactionTime p_time) { StringBuilder restartFileContent = new StringBuilder(); int reactionCount = 1; try{ File allReactions = new File ("Restart/allReactions.txt"); FileWriter fw = new FileWriter(allReactions); for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); } for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); //if (reaction.getDirection()==1){ //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); } //restartFileContent += "\nEND"; fw.write(restartFileContent.toString()); fw.close(); } catch (IOException e){ System.out.println("Could not write the restart edgereactions file"); System.exit(0); } } private void writeEdgeSpecies() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/edgeSpecies.txt")); for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().iterator();iter.hasNext();){ Species species = (Species) iter.next(); bw.write(species.getChemkinName()); bw.newLine(); int dummyInt = 0; bw.write(species.getChemGraph().toString(dummyInt)); bw.newLine(); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } //10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature private void writeCoreReactions(ReactionSystem p_rs, ReactionTime p_time) { StringBuilder restartFileContent = new StringBuilder(); int reactionCount = 0; try{ File coreSpecies = new File ("Restart/coreReactions.txt"); FileWriter fw = new FileWriter(coreSpecies); for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); if (reaction.getDirection()==1){ //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n"; restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n"); reactionCount = reactionCount + 1; } } //restartFileContent += "\nEND"; fw.write(restartFileContent.toString()); fw.close(); } catch (IOException e){ System.out.println("Could not write the restart corereactions file"); System.exit(0); } } private void writeCoreSpecies() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/coreSpecies.txt")); for(Iterator iter=getReactionModel().getSpecies();iter.hasNext();){ Species species = (Species) iter.next(); bw.write(species.getChemkinName()); bw.newLine(); int dummyInt = 0; bw.write(species.getChemGraph().toString(dummyInt)); bw.newLine(); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } private void writeCoreReactions() { BufferedWriter bw_rxns = null; BufferedWriter bw_troe = null; BufferedWriter bw_lindemann = null; BufferedWriter bw_thirdbody = null; try { bw_rxns = new BufferedWriter(new FileWriter("Restart/coreReactions.txt")); bw_troe = new BufferedWriter(new FileWriter("Restart/troeReactions.txt")); bw_lindemann = new BufferedWriter(new FileWriter("Restart/lindemannReactions.txt")); bw_thirdbody = new BufferedWriter(new FileWriter("Restart/thirdBodyReactions.txt")); String EaUnits = ArrheniusKinetics.getEaUnits(); String AUnits = ArrheniusKinetics.getAUnits(); bw_rxns.write("UnitsOfEa: " + EaUnits); bw_rxns.newLine(); bw_troe.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:"); bw_troe.newLine(); bw_lindemann.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:"); bw_lindemann.newLine(); bw_thirdbody.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions :"); bw_thirdbody.newLine(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel(); LinkedHashSet allcoreRxns = cerm.core.reaction; for(Iterator iter=allcoreRxns.iterator(); iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); if (reaction.isForward()) { if (reaction instanceof TROEReaction) { TROEReaction troeRxn = (TROEReaction) reaction; bw_troe.write(troeRxn.toRestartString(new Temperature(298,"K"))); bw_troe.newLine(); } else if (reaction instanceof LindemannReaction) { LindemannReaction lindeRxn = (LindemannReaction) reaction; bw_lindemann.write(lindeRxn.toRestartString(new Temperature(298,"K"))); bw_lindemann.newLine(); } else if (reaction instanceof ThirdBodyReaction) { ThirdBodyReaction tbRxn = (ThirdBodyReaction) reaction; bw_thirdbody.write(tbRxn.toRestartString(new Temperature(298,"K"))); bw_thirdbody.newLine(); } else { //bw.write(reaction.toChemkinString(new Temperature(298,"K"))); bw_rxns.write(reaction.toRestartString(new Temperature(298,"K"))); bw_rxns.newLine(); } } } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (bw_rxns != null) { bw_rxns.flush(); bw_rxns.close(); } if (bw_troe != null) { bw_troe.flush(); bw_troe.close(); } if (bw_lindemann != null) { bw_lindemann.flush(); bw_lindemann.close(); } if (bw_thirdbody != null) { bw_thirdbody.flush(); bw_thirdbody.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } private void writeEdgeReactions() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/edgeReactions.txt")); String EaUnits = ArrheniusKinetics.getEaUnits(); bw.write("UnitsOfEa: " + EaUnits); bw.newLine(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel(); LinkedHashSet alledgeRxns = cerm.edge.reaction; for(Iterator iter=alledgeRxns.iterator(); iter.hasNext();){ Reaction reaction = (Reaction) iter.next(); if (reaction.isForward()) { //bw.write(reaction.toChemkinString(new Temperature(298,"K"))); bw.write(reaction.toRestartString(new Temperature(298,"K"))); bw.newLine(); } else if (reaction.getReverseReaction().isForward()) { //bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K"))); bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K"))); bw.newLine(); } else System.out.println("Could not determine forward direction for following rxn: " + reaction.toString()); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } private void writePDepNetworks() { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("Restart/pdepnetworks.txt")); int numFameTemps = PDepRateConstant.getTemperatures().length; int numFamePress = PDepRateConstant.getPressures().length; int numChebyTemps = ChebyshevPolynomials.getNT(); int numChebyPress = ChebyshevPolynomials.getNP(); int numPlog = PDepArrheniusKinetics.getNumPressures(); String EaUnits = ArrheniusKinetics.getEaUnits(); bw.write("UnitsOfEa: " + EaUnits); bw.newLine(); bw.write("NumberOfFameTemps: " + numFameTemps); bw.newLine(); bw.write("NumberOfFamePress: " + numFamePress); bw.newLine(); bw.write("NumberOfChebyTemps: " + numChebyTemps); bw.newLine(); bw.write("NumberOfChebyPress: " + numChebyPress); bw.newLine(); bw.write("NumberOfPLogs: " + numPlog); bw.newLine(); bw.newLine(); LinkedList allNets = PDepNetwork.getNetworks(); int netCounter = 0; for(Iterator iter=allNets.iterator(); iter.hasNext();){ PDepNetwork pdepnet = (PDepNetwork) iter.next(); ++netCounter; bw.write("PDepNetwork #" + netCounter); bw.newLine(); // Write netReactionList LinkedList netRxns = pdepnet.getNetReactions(); bw.write("netReactionList:"); bw.newLine(); for (Iterator iter2=netRxns.iterator(); iter2.hasNext();) { PDepReaction currentPDepRxn = (PDepReaction)iter2.next(); bw.write(currentPDepRxn.toString()); bw.newLine(); bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps, numFamePress,numChebyTemps,numChebyPress,numPlog)); PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction(); bw.write(currentPDepReverseRxn.toString()); bw.newLine(); bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps, numFamePress,numChebyTemps,numChebyPress,numPlog)); } // Write nonincludedReactionList LinkedList nonIncludeRxns = pdepnet.getNonincludedReactions(); bw.write("nonIncludedReactionList:"); bw.newLine(); for (Iterator iter2=nonIncludeRxns.iterator(); iter2.hasNext();) { PDepReaction currentPDepRxn = (PDepReaction)iter2.next(); bw.write(currentPDepRxn.toString()); bw.newLine(); bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps, numFamePress,numChebyTemps,numChebyPress,numPlog)); PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction(); bw.write(currentPDepReverseRxn.toString()); bw.newLine(); bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps, numFamePress,numChebyTemps,numChebyPress,numPlog)); } // Write pathReactionList LinkedList pathRxns = pdepnet.getPathReactions(); bw.write("pathReactionList:"); bw.newLine(); for (Iterator iter2=pathRxns.iterator(); iter2.hasNext();) { PDepReaction currentPDepRxn = (PDepReaction)iter2.next(); bw.write(currentPDepRxn.getDirection() + "\t" + currentPDepRxn.toChemkinString(new Temperature(298,"K"))); bw.newLine(); } bw.newLine(); bw.newLine(); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } public String writeRatesAndParameters(PDepReaction pdeprxn, int numFameTemps, int numFamePress, int numChebyTemps, int numChebyPress, int numPlog) { StringBuilder sb = new StringBuilder(); // Write the rate coefficients double[][] rateConstants = pdeprxn.getPDepRate().getRateConstants(); for (int i=0; i<numFameTemps; i++) { for (int j=0; j<numFamePress; j++) { sb.append(rateConstants[i][j] + "\t"); } sb.append("\n"); } sb.append("\n"); // If chebyshev polynomials are present, write them if (numChebyTemps != 0) { ChebyshevPolynomials chebyPolys = pdeprxn.getPDepRate().getChebyshev(); for (int i=0; i<numChebyTemps; i++) { for (int j=0; j<numChebyPress; j++) { sb.append(chebyPolys.getAlpha(i,j) + "\t"); } sb.append("\n"); } sb.append("\n"); } // If plog parameters are present, write them else if (numPlog != 0) { PDepArrheniusKinetics kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics(); for (int i=0; i<numPlog; i++) { double Hrxn = pdeprxn.calculateHrxn(new Temperature(298,"K")); sb.append(kinetics.pressures[i].getPa() + "\t" + kinetics.getKinetics(i).toChemkinString(Hrxn,new Temperature(298,"K"),false) + "\n"); } sb.append("\n"); } return sb.toString(); } public LinkedList getTimeStep() { return timeStep; } public void setTimeStep(ReactionTime p_timeStep) { if (timeStep == null) timeStep = new LinkedList(); timeStep.add(p_timeStep); } public String getWorkingDirectory() { return workingDirectory; } public void setWorkingDirectory(String p_workingDirectory) { workingDirectory = p_workingDirectory; } //svp public boolean getError(){ return error; } //svp public boolean getSensitivity(){ return sensitivity; } public LinkedList getSpeciesList() { return species; } //gmagoon 10/24/07: commented out getReactionSystem and setReactionSystem // public ReactionSystem getReactionSystem() { // return reactionSystem; //11/2/07 gmagoon: adding accessor method for reactionSystemList public LinkedList getReactionSystemList(){ return reactionSystemList; } //added by gmagoon 9/24/07 // public void setReactionSystem(ReactionSystem p_ReactionSystem) { // reactionSystem = p_ReactionSystem; //copied from ReactionSystem.java by gmagoon 9/24/07 public ReactionModel getReactionModel() { return reactionModel; } public void readRestartSpecies() { // Read in core species -- NOTE code is almost duplicated in Read in edge species (second part of procedure) try { FileReader in = new FileReader("Restart/coreSpecies.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Make the species int intLocation = totalSpeciesName.indexOf("(" + splitString2[0] + ")"); Species species = Species.make(totalSpeciesName.substring(0,intLocation),cg,Integer.parseInt(splitString2[0])); // Add the new species to the set of species restartCoreSpcs.add(species); /*int species_type = 1; // reacted species for (int i=0; i<numRxnSystems; i++) { SpeciesStatus ss = new SpeciesStatus(species,species_type,y[i],yprime[i]); speciesStatus[i].put(species, ss); }*/ line = ChemParser.readMeaningfulLine(reader); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Read in edge species try { FileReader in = new FileReader("Restart/edgeSpecies.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // Change JDM to reflect MRH 2-11-2010 // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Make the species Species species = Species.make(splitString1[0],cg,Integer.parseInt(splitString2[0])); // Add the new species to the set of species restartEdgeSpcs.add(species); line = ChemParser.readMeaningfulLine(reader); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void readRestartReactions() { // Grab the IDs from the core species int[] coreSpcsIds = new int[restartCoreSpcs.size()]; int i = 0; for (Iterator iter = restartCoreSpcs.iterator(); iter.hasNext();) { Species spcs = (Species)iter.next(); coreSpcsIds[i] = spcs.getID(); ++i; } // Read in core reactions try { FileReader in = new FileReader("Restart/coreReactions.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader); // Determine units of Ea StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); String EaUnits = st.nextToken(); line = ChemParser.readMeaningfulLine(reader); while (line != null) { if (!line.trim().equals("DUP")) { Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"core",EaUnits); Iterator rxnIter = restartCoreRxns.iterator(); boolean foundRxn = false; while (rxnIter.hasNext()) { Reaction old = (Reaction)rxnIter.next(); if (old.equals(r)) { old.addAdditionalKinetics(r.getKinetics(),1); foundRxn = true; break; } } if (!foundRxn) { if (r.hasReverseReaction()) r.generateReverseReaction(); restartCoreRxns.add(r); } } line = ChemParser.readMeaningfulLine(reader); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { SeedMechanism.readThirdBodyReactions("Restart/thirdBodyReactions.txt"); } catch (IOException e1) { e1.printStackTrace(); } try { SeedMechanism.readLindemannReactions("Restart/lindemannReactions.txt"); } catch (IOException e1) { e1.printStackTrace(); } try { SeedMechanism.readTroeReactions("Restart/troeReactions.txt"); } catch (IOException e1) { e1.printStackTrace(); } restartCoreRxns.addAll(SeedMechanism.reactionSet); // Read in edge reactions try { FileReader in = new FileReader("Restart/edgeReactions.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader); // Determine units of Ea StringTokenizer st = new StringTokenizer(line); String tempString = st.nextToken(); String EaUnits = st.nextToken(); line = ChemParser.readMeaningfulLine(reader); while (line != null) { if (!line.trim().equals("DUP")) { Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"edge",EaUnits); Iterator rxnIter = restartEdgeRxns.iterator(); boolean foundRxn = false; while (rxnIter.hasNext()) { Reaction old = (Reaction)rxnIter.next(); if (old.equals(r)) { old.addAdditionalKinetics(r.getKinetics(),1); foundRxn = true; break; } } if (!foundRxn) { r.generateReverseReaction(); restartEdgeRxns.add(r); } } line = ChemParser.readMeaningfulLine(reader); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public LinkedHashMap getRestartSpeciesStatus(int i) { LinkedHashMap speciesStatus = new LinkedHashMap(); try { FileReader in = new FileReader("Restart/coreSpecies.txt"); BufferedReader reader = new BufferedReader(in); Integer numRxnSystems = Integer.parseInt(ChemParser.readMeaningfulLine(reader)); String line = ChemParser.readMeaningfulLine(reader); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[1].split("[)]"); double y = 0.0; double yprime = 0.0; for (int j=0; j<numRxnSystems; j++) { StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); if (j == i) { y = Double.parseDouble(st.nextToken()); yprime = Double.parseDouble(st.nextToken()); } } // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Make the species Species species = Species.make(splitString1[0],cg); // Add the new species to the set of species //restartCoreSpcs.add(species); int species_type = 1; // reacted species SpeciesStatus ss = new SpeciesStatus(species,species_type,y,yprime); speciesStatus.put(species, ss); line = ChemParser.readMeaningfulLine(reader); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return speciesStatus; } public void putRestartSpeciesInInitialStatus(InitialStatus is, int i) { try { FileReader in = new FileReader("Restart/coreSpecies.txt"); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader); while (line != null) { // The first line of a new species is the user-defined name String totalSpeciesName = line; String[] splitString1 = totalSpeciesName.split("[(]"); String[] splitString2 = splitString1[1].split("[)]"); // The remaining lines are the graph Graph g = ChemParser.readChemGraph(reader); // Make the ChemGraph, assuming it does not contain a forbidden structure ChemGraph cg = null; try { cg = ChemGraph.make(g); } catch (ForbiddenStructureException e) { System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString()); System.exit(0); } // Make the species Species species = Species.make(splitString1[0],cg); // Add the new species to the set of species //restartCoreSpcs.add(species); if (is.getSpeciesStatus(species) == null) { SpeciesStatus ss = new SpeciesStatus(species,1,0.0,0.0); is.putSpeciesStatus(ss); } line = ChemParser.readMeaningfulLine(reader); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void readPDepNetworks() { SpeciesDictionary sd = SpeciesDictionary.getInstance(); LinkedList allNetworks = PDepNetwork.getNetworks(); try { FileReader in = new FileReader("Restart/pdepnetworks.txt"); BufferedReader reader = new BufferedReader(in); StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); String tempString = st.nextToken(); String EaUnits = st.nextToken(); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); tempString = st.nextToken(); int numFameTs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); tempString = st.nextToken(); int numFamePs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); tempString = st.nextToken(); int numChebyTs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); tempString = st.nextToken(); int numChebyPs = Integer.parseInt(st.nextToken()); st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); tempString = st.nextToken(); int numPlogs = Integer.parseInt(st.nextToken()); double[][] rateCoefficients = new double[numFameTs][numFamePs]; double[][] chebyPolys = new double[numChebyTs][numChebyPs]; Kinetics[] plogKinetics = new Kinetics[numPlogs]; String line = ChemParser.readMeaningfulLine(reader); // line should be "PDepNetwork while (line != null) { line = ChemParser.readMeaningfulLine(reader); // line should now be "netReactionList:" PDepNetwork newNetwork = new PDepNetwork(); LinkedList netRxns = newNetwork.getNetReactions(); LinkedList nonincludeRxns = newNetwork.getNonincludedReactions(); line = ChemParser.readMeaningfulLine(reader); // line is either data or "nonIncludedReactionList" // If line is "nonincludedreactionlist", we need to skip over this while loop if (!line.toLowerCase().startsWith("nonincludedreactionlist")) { while (!line.toLowerCase().startsWith("nonincludedreactionlist")) { // Read in the forward rxn String[] reactsANDprods = line.split("\\ PDepIsomer Reactants = null; String reacts = reactsANDprods[0].trim(); if (reacts.contains("+")) { String[] indivReacts = reacts.split("[+]"); String name = indivReacts[0].trim(); Species spc1 = sd.getSpeciesFromChemkinName(name); if (spc1 == null) { spc1 = getSpeciesBySPCName(name,sd); } name = indivReacts[1].trim(); Species spc2 = sd.getSpeciesFromChemkinName(name); if (spc2 == null) { spc2 = getSpeciesBySPCName(name,sd); } Reactants = new PDepIsomer(spc1,spc2); } else { String name = reacts.trim(); Species spc = sd.getSpeciesFromChemkinName(name); if (spc == null) { spc = getSpeciesBySPCName(name,sd); } Reactants = new PDepIsomer(spc); } PDepIsomer Products = null; String prods = reactsANDprods[1].trim(); if (prods.contains("+")) { String[] indivProds = prods.split("[+]"); String name = indivProds[0].trim(); Species spc1 = sd.getSpeciesFromChemkinName(name); if (spc1 == null) { spc1 = getSpeciesBySPCName(name,sd); } name = indivProds[1].trim(); Species spc2 = sd.getSpeciesFromChemkinName(name); if (spc2 == null) { spc2 = getSpeciesBySPCName(name,sd); } Products = new PDepIsomer(spc1,spc2); } else { String name = prods.trim(); Species spc = sd.getSpeciesFromChemkinName(name); if (spc == null) { spc = getSpeciesBySPCName(name,sd); } Products = new PDepIsomer(spc); } newNetwork.addIsomer(Reactants); newNetwork.addIsomer(Products); for (int i=0; i<numFameTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numFamePs; j++) { rateCoefficients[i][j] = Double.parseDouble(st.nextToken()); } } PDepRateConstant pdepk = null; if (numChebyTs > 0) { for (int i=0; i<numChebyTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numChebyPs; j++) { chebyPolys[i][j] = Double.parseDouble(st.nextToken()); } } ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs, ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(), numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(), chebyPolys); pdepk = new PDepRateConstant(rateCoefficients,chebyshev); } else if (numPlogs > 0) { for (int i=0; i<numPlogs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa"); UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); double Ea = Double.parseDouble(st.nextToken()); if (EaUnits.equals("cal/mol")) Ea = Ea / 1000; else if (EaUnits.equals("J/mol")) Ea = Ea / 4.184 / 1000; else if (EaUnits.equals("kJ/mol")) Ea = Ea / 4.184; else if (EaUnits.equals("Kelvins")) Ea = Ea * 1.987; UncertainDouble dE = new UncertainDouble(Ea,0.0,"A"); ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", ""); PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i); pdepAK.setKinetics(i, p, k); pdepk = new PDepRateConstant(rateCoefficients,pdepAK); } } PDepReaction forward = new PDepReaction(Reactants, Products, pdepk); // Read in the reverse reaction line = ChemParser.readMeaningfulLine(reader); for (int i=0; i<numFameTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numFamePs; j++) { rateCoefficients[i][j] = Double.parseDouble(st.nextToken()); } } pdepk = null; if (numChebyTs > 0) { for (int i=0; i<numChebyTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numChebyPs; j++) { chebyPolys[i][j] = Double.parseDouble(st.nextToken()); } } ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs, ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(), numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(), chebyPolys); pdepk = new PDepRateConstant(rateCoefficients,chebyshev); } else if (numPlogs > 0) { for (int i=0; i<numPlogs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa"); UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); double Ea = Double.parseDouble(st.nextToken()); if (EaUnits.equals("cal/mol")) Ea = Ea / 1000; else if (EaUnits.equals("J/mol")) Ea = Ea / 4.184 / 1000; else if (EaUnits.equals("kJ/mol")) Ea = Ea / 4.184; else if (EaUnits.equals("Kelvins")) Ea = Ea * 1.987; UncertainDouble dE = new UncertainDouble(Ea,0.0,"A"); ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", ""); PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i); pdepAK.setKinetics(i, p, k); pdepk = new PDepRateConstant(rateCoefficients,pdepAK); } } PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk); reverse.setReverseReaction(forward); forward.setReverseReaction(reverse); netRxns.add(forward); line = ChemParser.readMeaningfulLine(reader); } } // This loop ends once line == "nonIncludedReactionList" line = ChemParser.readMeaningfulLine(reader); // line is either data or "pathReactionList" if (!line.toLowerCase().startsWith("pathreactionList")) { while (!line.toLowerCase().startsWith("pathreactionlist")) { // Read in the forward rxn String[] reactsANDprods = line.split("\\ PDepIsomer Reactants = null; String reacts = reactsANDprods[0].trim(); if (reacts.contains("+")) { String[] indivReacts = reacts.split("[+]"); String name = indivReacts[0].trim(); Species spc1 = sd.getSpeciesFromChemkinName(name); if (spc1 == null) { spc1 = getSpeciesBySPCName(name,sd); } name = indivReacts[1].trim(); Species spc2 = sd.getSpeciesFromChemkinName(name); if (spc2 == null) { spc2 = getSpeciesBySPCName(name,sd); } Reactants = new PDepIsomer(spc1,spc2); } else { String name = reacts.trim(); Species spc = sd.getSpeciesFromChemkinName(name); if (spc == null) { spc = getSpeciesBySPCName(name,sd); } Reactants = new PDepIsomer(spc); } PDepIsomer Products = null; String prods = reactsANDprods[1].trim(); if (prods.contains("+")) { String[] indivProds = prods.split("[+]"); String name = indivProds[0].trim(); Species spc1 = sd.getSpeciesFromChemkinName(name); if (spc1 == null) { spc1 = getSpeciesBySPCName(name,sd); } name = indivProds[1].trim(); Species spc2 = sd.getSpeciesFromChemkinName(name); if (spc2 == null) { spc2 = getSpeciesBySPCName(name,sd); } Products = new PDepIsomer(spc1,spc2); } else { String name = prods.trim(); Species spc = sd.getSpeciesFromChemkinName(name); if (spc == null) { spc = getSpeciesBySPCName(name,sd); } Products = new PDepIsomer(spc); } newNetwork.addIsomer(Reactants); newNetwork.addIsomer(Products); for (int i=0; i<numFameTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numFamePs; j++) { rateCoefficients[i][j] = Double.parseDouble(st.nextToken()); } } PDepRateConstant pdepk = null; if (numChebyTs > 0) { for (int i=0; i<numChebyTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numChebyPs; j++) { chebyPolys[i][j] = Double.parseDouble(st.nextToken()); } } ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs, ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(), numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(), chebyPolys); pdepk = new PDepRateConstant(rateCoefficients,chebyshev); } else if (numPlogs > 0) { for (int i=0; i<numPlogs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa"); UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); double Ea = Double.parseDouble(st.nextToken()); if (EaUnits.equals("cal/mol")) Ea = Ea / 1000; else if (EaUnits.equals("J/mol")) Ea = Ea / 4.184 / 1000; else if (EaUnits.equals("kJ/mol")) Ea = Ea / 4.184; else if (EaUnits.equals("Kelvins")) Ea = Ea * 1.987; UncertainDouble dE = new UncertainDouble(Ea,0.0,"A"); ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", ""); PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i); pdepAK.setKinetics(i, p, k); pdepk = new PDepRateConstant(rateCoefficients,pdepAK); } } PDepReaction forward = new PDepReaction(Reactants, Products, pdepk); // Read in the reverse reaction line = ChemParser.readMeaningfulLine(reader); for (int i=0; i<numFameTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numFamePs; j++) { rateCoefficients[i][j] = Double.parseDouble(st.nextToken()); } } pdepk = null; if (numChebyTs > 0) { for (int i=0; i<numChebyTs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); for (int j=0; j<numChebyPs; j++) { chebyPolys[i][j] = Double.parseDouble(st.nextToken()); } } ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs, ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(), numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(), chebyPolys); pdepk = new PDepRateConstant(rateCoefficients,chebyshev); } else if (numPlogs > 0) { for (int i=0; i<numPlogs; i++) { st = new StringTokenizer(ChemParser.readMeaningfulLine(reader)); Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa"); UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A"); double Ea = Double.parseDouble(st.nextToken()); if (EaUnits.equals("cal/mol")) Ea = Ea / 1000; else if (EaUnits.equals("J/mol")) Ea = Ea / 4.184 / 1000; else if (EaUnits.equals("kJ/mol")) Ea = Ea / 4.184; else if (EaUnits.equals("Kelvins")) Ea = Ea * 1.987; UncertainDouble dE = new UncertainDouble(Ea,0.0,"A"); ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", ""); PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i); pdepAK.setKinetics(i, p, k); pdepk = new PDepRateConstant(rateCoefficients,pdepAK); } } PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk); reverse.setReverseReaction(forward); forward.setReverseReaction(reverse); nonincludeRxns.add(forward); line = ChemParser.readMeaningfulLine(reader); } } // This loop ends once line == "pathReactionList" line = ChemParser.readMeaningfulLine(reader); // line is either data or "PDepNetwork #_" or null (end of file) while (line != null && !line.toLowerCase().startsWith("pdepnetwork")) { st = new StringTokenizer(line); int direction = Integer.parseInt(st.nextToken()); // First token is the rxn structure: A+B=C+D // Note: Up to 3 reactants/products allowed // : Either "=" or "=>" will separate reactants and products String structure = st.nextToken(); // Separate the reactants from the products boolean generateReverse = false; String[] reactsANDprods = structure.split("\\=>"); if (reactsANDprods.length == 1) { reactsANDprods = structure.split("[=]"); generateReverse = true; } sd = SpeciesDictionary.getInstance(); LinkedList r = ChemParser.parseReactionSpecies(sd, reactsANDprods[0]); LinkedList p = ChemParser.parseReactionSpecies(sd, reactsANDprods[1]); Structure s = new Structure(r,p); s.setDirection(direction); // Next three tokens are the modified Arrhenius parameters double rxn_A = Double.parseDouble(st.nextToken()); double rxn_n = Double.parseDouble(st.nextToken()); double rxn_E = Double.parseDouble(st.nextToken()); if (EaUnits.equals("cal/mol")) rxn_E = rxn_E / 1000; else if (EaUnits.equals("J/mol")) rxn_E = rxn_E / 4.184 / 1000; else if (EaUnits.equals("kJ/mol")) rxn_E = rxn_E / 4.184; else if (EaUnits.equals("Kelvins")) rxn_E = rxn_E * 1.987; UncertainDouble uA = new UncertainDouble(rxn_A,0.0,"A"); UncertainDouble un = new UncertainDouble(rxn_n,0.0,"A"); UncertainDouble uE = new UncertainDouble(rxn_E,0.0,"A"); // The remaining tokens are comments String comments = ""; while (st.hasMoreTokens()) { comments += st.nextToken(); } ArrheniusKinetics k = new ArrheniusKinetics(uA,un,uE,"",1,"",comments); Reaction pathRxn = new Reaction(); // if (direction == 1) // pathRxn = Reaction.makeReaction(s,k,generateReverse); // else // pathRxn = Reaction.makeReaction(s.generateReverseStructure(),k,generateReverse); pathRxn = Reaction.makeReaction(s,k,generateReverse); PDepIsomer Reactants = new PDepIsomer(r); PDepIsomer Products = new PDepIsomer(p); PDepReaction pdeppathrxn = new PDepReaction(Reactants,Products,pathRxn); newNetwork.addReaction(pdeppathrxn); line = ChemParser.readMeaningfulLine(reader); } PDepNetwork.getNetworks().add(newNetwork); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * MRH 14Jan2010 * * getSpeciesBySPCName * * Input: String name - Name of species, normally chemical formula followed * by "J"s for radicals, and then (#) * SpeciesDictionary sd * * This method was originally written as a complement to the method readPDepNetworks. * jdmo found a bug with the readrestart option. The bug was that the method was * attempting to add a null species to the Isomer list. The null species resulted * from searching the SpeciesDictionary by chemkinName (e.g. C4H8OJJ(48)), when the * chemkinName present in the dictionary was SPC(48). * */ public Species getSpeciesBySPCName(String name, SpeciesDictionary sd) { String[] nameFromNumber = name.split("\\("); String newName = "SPC(" + nameFromNumber[1]; return sd.getSpeciesFromChemkinName(newName); } /** * MRH 12-Jun-2009 * * Function initializes the model's core and edge. * The initial core species always consists of the species contained * in the condition.txt file. If seed mechanisms exist, those species * (and the reactions given in the seed mechanism) are also added to * the core. * The initial edge species/reactions are determined by reacting the core * species by one full iteration. */ public void initializeCoreEdgeModel() { LinkedHashSet allInitialCoreSpecies = new LinkedHashSet(); LinkedHashSet allInitialCoreRxns = new LinkedHashSet(); if (readrestart) { readRestartReactions(); if (PDepNetwork.generateNetworks) readPDepNetworks(); allInitialCoreSpecies.addAll(restartCoreSpcs); allInitialCoreRxns.addAll(restartCoreRxns); } // Add the species from the condition.txt (input) file allInitialCoreSpecies.addAll(getSpeciesSeed()); // Add the species from the seed mechanisms, if they exist if (hasSeedMechanisms()) { allInitialCoreSpecies.addAll(getSeedMechanism().getSpeciesSet()); allInitialCoreRxns.addAll(getSeedMechanism().getReactionSet()); } CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(allInitialCoreSpecies, allInitialCoreRxns); if (readrestart) { cerm.addUnreactedSpeciesSet(restartEdgeSpcs); cerm.addUnreactedReactionSet(restartEdgeRxns); } setReactionModel(cerm); PDepNetwork.reactionModel = getReactionModel(); PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0); // Determine initial set of reactions and edge species using only the // species enumerated in the input file and the seed mechanisms as the core if (!readrestart) { LinkedHashSet reactionSet; if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) { reactionSet = getReactionGenerator().react(allInitialCoreSpecies); } else { reactionSet = new LinkedHashSet(); for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) { Species spec = (Species) iter.next(); reactionSet.addAll(getReactionGenerator().react(allInitialCoreSpecies, spec)); } } reactionSet.addAll(getLibraryReactionGenerator().react(allInitialCoreSpecies)); // Set initial core-edge reaction model based on above results if (reactionModelEnlarger instanceof RateBasedRME) { Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); cerm.addReaction(r); } } else { // Only keep the reactions involving bimolecular reactants and bimolecular products Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){ cerm.addReaction(r); } else { cerm.categorizeReaction(r.getStructure()); PDepNetwork.addReactionToNetworks(r); } } } } for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } // We cannot return a system with no core reactions, so if this is a case we must add to the core while (getReactionModel().isEmpty() && !PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) { for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); if (reactionModelEnlarger instanceof RateBasedPDepRME) rs.initializePDepNetwork(); rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature()); } enlargeReactionModel(); } for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } return; } //## operation initializeCoreEdgeModelWithPRL() //9/24/07 gmagoon: moved from ReactionSystem.java public void initializeCoreEdgeModelWithPRL() { //#[ operation initializeCoreEdgeModelWithPRL() initializeCoreEdgeModelWithoutPRL(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel(); LinkedHashSet primarySpeciesSet = getPrimaryReactionLibrary().getSpeciesSet(); //10/14/07 gmagoon: changed to use getPrimaryReactionLibrary LinkedHashSet primaryReactionSet = getPrimaryReactionLibrary().getReactionSet(); cerm.addReactedSpeciesSet(primarySpeciesSet); cerm.addPrimaryReactionSet(primaryReactionSet); LinkedHashSet newReactions = getReactionGenerator().react(cerm.getReactedSpeciesSet()); if (reactionModelEnlarger instanceof RateBasedRME) cerm.addReactionSet(newReactions); else { Iterator iter = newReactions.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); if (r.getReactantNumber() == 2 && r.getProductNumber() == 2){ cerm.addReaction(r); } } } return; // } //## operation initializeCoreEdgeModelWithoutPRL() //9/24/07 gmagoon: moved from ReactionSystem.java protected void initializeCoreEdgeModelWithoutPRL() { //#[ operation initializeCoreEdgeModelWithoutPRL() CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(new LinkedHashSet(getSpeciesSeed())); setReactionModel(cerm); PDepNetwork.reactionModel = getReactionModel(); PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0); // Determine initial set of reactions and edge species using only the // species enumerated in the input file as the core LinkedHashSet reactionSet = getReactionGenerator().react(getSpeciesSeed()); reactionSet.addAll(getLibraryReactionGenerator().react(getSpeciesSeed())); // Set initial core-edge reaction model based on above results if (reactionModelEnlarger instanceof RateBasedRME) { // Only keep the reactions involving bimolecular reactants and bimolecular products Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); cerm.addReaction(r); } } else { // Only keep the reactions involving bimolecular reactants and bimolecular products Iterator iter = reactionSet.iterator(); while (iter.hasNext()){ Reaction r = (Reaction)iter.next(); if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){ cerm.addReaction(r); } else { cerm.categorizeReaction(r.getStructure()); PDepNetwork.addReactionToNetworks(r); } } } //10/9/07 gmagoon: copy reactionModel to reactionSystem; there may still be scope problems, particularly in above elseif statement //10/24/07 gmagoon: want to copy same reaction model to all reactionSystem variables; should probably also make similar modifications elsewhere; may or may not need to copy in ...WithPRL function for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } //reactionSystem.setReactionModel(getReactionModel()); // We cannot return a system with no core reactions, so if this is a case we must add to the core while (getReactionModel().isEmpty()&&!PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) { for (Integer i = 0; i < reactionSystemList.size(); i++) { ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i); if (reactionModelEnlarger instanceof RateBasedPDepRME) rs.initializePDepNetwork(); rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature()); } enlargeReactionModel(); } for (Integer i = 0; i<reactionSystemList.size();i++) { ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i); rs.setReactionModel(getReactionModel()); } return; // } //## operation initializeCoreEdgeReactionModel() //9/24/07 gmagoon: moved from ReactionSystem.java public void initializeCoreEdgeReactionModel() { System.out.println("\nInitializing core-edge reaction model"); // setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon:moved from initializeReactionSystem; later moved to modelGeneration() //#[ operation initializeCoreEdgeReactionModel() // if (hasPrimaryReactionLibrary()) initializeCoreEdgeModelWithPRL(); // else initializeCoreEdgeModelWithoutPRL(); /* * MRH 12-Jun-2009 * * I've lumped the initializeCoreEdgeModel w/ and w/o a seed mechanism * (which used to be the PRL) into one function. Before, RMG would * complete one iteration (construct the edge species/rxns) before adding * the seed mechanism to the rxn, thereby possibly estimating kinetic * parameters for a rxn that exists in a seed mechanism */ initializeCoreEdgeModel(); // } //9/24/07 gmagoon: copied from ReactionSystem.java public ReactionGenerator getReactionGenerator() { return reactionGenerator; } //10/4/07 gmagoon: moved from ReactionSystem.java public void setReactionGenerator(ReactionGenerator p_ReactionGenerator) { reactionGenerator = p_ReactionGenerator; } //9/25/07 gmagoon: moved from ReactionSystem.java //10/24/07 gmagoon: changed to use reactionSystemList //## operation enlargeReactionModel() public void enlargeReactionModel() { //#[ operation enlargeReactionModel() if (reactionModelEnlarger == null) throw new NullPointerException("ReactionModelEnlarger"); System.out.println("\nEnlarging reaction model"); reactionModelEnlarger.enlargeReactionModel(reactionSystemList, reactionModel, validList); return; // } //9/25/07 gmagoon: moved from ReactionSystem.java //## operation hasPrimaryReactionLibrary() public boolean hasPrimaryReactionLibrary() { //#[ operation hasPrimaryReactionLibrary() if (primaryReactionLibrary == null) return false; return (primaryReactionLibrary.size() > 0); // } public boolean hasSeedMechanisms() { if (getSeedMechanism() == null) return false; return (seedMechanism.size() > 0); } //9/25/07 gmagoon: moved from ReactionSystem.java public PrimaryReactionLibrary getPrimaryReactionLibrary() { return primaryReactionLibrary; } //9/25/07 gmagoon: moved from ReactionSystem.java public void setPrimaryReactionLibrary(PrimaryReactionLibrary p_PrimaryReactionLibrary) { primaryReactionLibrary = p_PrimaryReactionLibrary; } //10/4/07 gmagoon: added public LinkedHashSet getSpeciesSeed() { return speciesSeed; } //10/4/07 gmagoon: added public void setSpeciesSeed(LinkedHashSet p_speciesSeed) { speciesSeed = p_speciesSeed; } //10/4/07 gmagoon: added public LibraryReactionGenerator getLibraryReactionGenerator() { return lrg; } //10/4/07 gmagoon: added public void setLibraryReactionGenerator(LibraryReactionGenerator p_lrg) { lrg = p_lrg; } public static Temperature getTemp4BestKinetics() { return temp4BestKinetics; } public static void setTemp4BestKinetics(Temperature firstSysTemp) { temp4BestKinetics = firstSysTemp; } public SeedMechanism getSeedMechanism() { return seedMechanism; } public void setSeedMechanism(SeedMechanism p_seedMechanism) { seedMechanism = p_seedMechanism; } public PrimaryThermoLibrary getPrimaryThermoLibrary() { return primaryThermoLibrary; } public void setPrimaryThermoLibrary(PrimaryThermoLibrary p_primaryThermoLibrary) { primaryThermoLibrary = p_primaryThermoLibrary; } public static double getAtol(){ return atol; } public boolean runKillableToPreventInfiniteLoop(boolean intermediateSteps, int iterationNumber) { ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0); if (!intermediateSteps)//if there are no intermediate steps (for example when using AUTO method), return true; return true; //if there are intermediate steps, the run is killable if the iteration number exceeds the number of time steps / conversions else if (rs0.finishController.terminationTester instanceof ReactionTimeTT){ if (iterationNumber - 1 > timeStep.size()){ //-1 correction needed since when this is called, iteration number has been incremented return true; } } else //the case where intermediate conversions are specified if (iterationNumber - 1 > numConversions){ //see above; it is possible there is an off-by-one error here, so further testing will be needed return true; } return false; //return false if none of the above criteria are met } }
package gnu.mapping; /** A Binding is a Location in an Environment object. */ public final class Binding extends Location // implements java.util.Map.Entry { /** The current value of the binding. */ Object value; Constraint constraint; public final Object get () { return constraint.get(this); } public final Procedure getProcedure () { return constraint.getProcedure(this); } public final void set (Object value) { constraint.set(this, value); } public final void setConstraint (Constraint constraint) { this.constraint = constraint; } public boolean isBound () { return ! (constraint instanceof UnboundConstraint); // FIXME } // The compiler emits calls to this method. public static Binding make (Object init, String name) { Binding binding = new Binding(); binding.value = init; binding.setName(name); binding.constraint = new TrivialConstraint(null); return binding; } /** Used to chain multiple Bindings in the same hash bucket. * Note that there can be multiple Bindings with the same name; * in that case, the newest comes first. */ Binding chain; /** The "time" the binding was created. * If the binding is newer than the current thread, it does not count. */ int time_stamp; public void print(java.io.PrintWriter ps) { ps.print ("#<binding "); String name = getName(); if (name != null) ps.print(name); if (isBound()) { ps.print(" -> "); SFormat.print(get(), ps); } else ps.print("(unbound)"); ps.print ('>'); } // Methods that implement java.util.Map.Entry: public final Object getKey () { return getName(); } public final Object getValue () { return constraint.get(this); } public final Object setValue (Object value) { Object old = constraint.get(this); constraint.set(this, value); return old; } public boolean equals (Object o) { if (! (o instanceof Binding)) return false; Binding e2 = (Binding) o; String e1Key = getName(); String e2Key = e2.getName(); // This is quite following the Collections spec, but we assume keys // are interned, or if they are not, that they are seen as unequal. if (e1Key != e2Key) return false; Object e1Value = constraint.get(this); Object e2Value = e2.constraint.get(e2); return e1Value == null ? e2Value == null : e1Value.equals(e2Value); } public int hashCode () { Object value = constraint.get(this); return getName().hashCode() ^ (value == null ? 0 : value.hashCode()); } }
package novice; import static edu.mines.jtk.util.ArrayMath.*; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.filechooser.*; import edu.mines.jtk.awt.*; import edu.mines.jtk.dsp.Sampling; import edu.mines.jtk.mosaic.*; import static novice.Segd.*; import static novice.Waypoints.*; import static novice.NedFileReader.*; /** * The Class SeisPlot. * * <p> The main container class for the program. Controls the contained class for plot, * data imports and other subroutines. Takes calls from contained classes * and updates them accordingly. * * @author Colton Kohnke, Colorado School of Mines * @version 1.0 * @since April 13, 2014 * */ public class SeisPlot { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new SeisPlot(); } }); } // Location and size of overlay plot. /** The Constant M_X. */ private static final int M_X = 0; /** The Constant M_Y. */ private static final int M_Y = 0; /** The Constant M_WIDTH. */ private static final int M_WIDTH = 500; /** The Constant M_HEIGHT. */ private static final int M_HEIGHT = 500; /** The _gps. */ public static ArrayList<MPoint> _gps; /** The _segd. */ public ArrayList<Segdata> _segd; /** The _ned files. */ public ArrayList<NedFile> _nedFiles; /** The _bp. */ public BasePlot _bp; /** The _rp. */ public ResponsePlot _rp; /** The _elev. */ public ElevPlot _elev; // Sliders /** The gain slider. */ public JSlider gainSlider; /** The lowpass slider. */ public JSlider lowpassSlider; /** The tpow slider. */ public JSlider tpowSlider; /** * Instantiates a new plot test. * Initiates the plots */ private SeisPlot() { // _shots = new ArrayList<MPoint>(0); // _gps = new ArrayList<MPoint>(0); // _segd = new ArrayList<Segdata>(0); _bp = new BasePlot(); _rp = new ResponsePlot(); _elev = new ElevPlot(); } /** * The Class BasePlot. * * <p> Class for controlling the base map view. * * @author Colton Kohnke, Colorado School of Mines * @version 1.0 * @since April 13, 2014 * */ private class BasePlot { /** The _plot frame. */ private PlotFrame _plotFrame; /** The _plot panel. */ private PlotPanel _plotPanel; /** The _base view. */ private PointsView _baseView; /** The _red view. */ private PointsView _redView; /** The _blue view. */ private PointsView _blueView; /** The _green view. */ private PointsView _greenView; /** The _circle view. */ private PointsView _circleView; /** * Instantiates a new base plot. */ private BasePlot() { // The plot panel. _plotPanel = new PlotPanel(); _plotPanel.setTitle("Base Plot"); _plotPanel.setHLabel("Easting (m) (UTM)"); _plotPanel.setVLabel("Northing (m) (UTM)"); _plotPanel.setHLimits(317600, 320600); _plotPanel.setVLimits(4121800, 4123600); _plotPanel.setHFormat("%s"); _plotPanel.setVFormat("%s"); _plotPanel.addGrid("H-.V-."); // A grid view for horizontal and vertical lines (axes). _plotPanel.addGrid("H0-V0-"); // A plot frame has a mode for zooming in tiles or tile axes. _plotFrame = new PlotFrame(_plotPanel); _plotFrame.setTitle("Base Plot"); TileZoomMode tzm = _plotFrame.getTileZoomMode(); // Modes for Base plot ModeManager mm = _plotFrame.getModeManager(); RoamMode rm = new RoamMode(mm); // roam and plot CircleMode om = new CircleMode(mm); ChannelMode cm = new ChannelMode(mm); NoGPSMode gm = new NoGPSMode(mm); // The menu bar includes a mode menu for selecting a mode. JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); fileMenu.add(new SaveAsPngAction(_plotFrame)).setMnemonic('a'); fileMenu.add(new ExitAction()).setMnemonic('x'); JMenu modeMenu = new JMenu("Mode"); modeMenu.setMnemonic('M'); modeMenu.add(new ModeMenuItem(tzm)); modeMenu.add(new ModeMenuItem(rm)); modeMenu.add(new ModeMenuItem(om)); modeMenu.add(new ModeMenuItem(cm)); modeMenu.add(new ModeMenuItem(gm)); JMenu gpsMenu = new JMenu("GPS Tools"); gpsMenu.add(new GetFlagsFromHH()).setMnemonic('f'); gpsMenu.add(new GetDEM(_plotPanel)).setMnemonic('g'); gpsMenu.add(new ReadNedElevation(_plotPanel)); gpsMenu.add(new ExportFlagsToCSV()).setMnemonic('e'); JMenu segdMenu = new JMenu("SEGD Tools"); segdMenu.add(new ImportSegdDir()).setMnemonic('s'); segdMenu.add(new ImportSegdFile()).setMnemonic('d'); JMenu testMenu = new JMenu("Dev"); testMenu.setMnemonic('E'); testMenu.add(new ClearData()).setMnemonic('c'); testMenu.add(new DownloadNedFile()).setMnemonic('d'); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(modeMenu); menuBar.add(gpsMenu); menuBar.add(segdMenu); menuBar.add(testMenu); _plotFrame.setJMenuBar(menuBar); // The tool bar includes toggle buttons for selecting a mode. JToolBar toolBar = new JToolBar(SwingConstants.VERTICAL); toolBar.setRollover(true); toolBar.add(new ModeToggleButton(tzm)); toolBar.add(new ModeToggleButton(rm)); toolBar.add(new ModeToggleButton(om)); toolBar.add(new ModeToggleButton(cm)); toolBar.add(new ModeToggleButton(gm)); _plotFrame.add(toolBar, BorderLayout.WEST); // Make the plot frame visible. _plotFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); _plotFrame.setLocation(M_X, M_Y); _plotFrame.setSize(M_WIDTH, M_HEIGHT); _plotFrame.setFontSizeForPrint(8, 240); _plotFrame.setVisible(true); } // Makes points visible /** * Update bp view. */ private void updateBPView() { if(_gps != null){ int np = _gps.size(); float[] xp = new float[np]; float[] yp = new float[np]; for (int ip = 0; ip < np; ++ip) { MPoint p = _gps.get(ip); xp[ip] = (float) p.getUTMX(); yp[ip] = (float) p.getUTMY(); } _plotPanel.setHLimits(min(xp) - 25, max(xp) + 25); _plotPanel.setVLimits(min(yp) - 25, max(yp) + 25); if (_baseView == null) { _baseView = _plotPanel.addPoints(xp, yp); _baseView.setMarkStyle(PointsView.Mark.CROSS); _baseView.setLineStyle(PointsView.Line.NONE); } else { _baseView.set(xp, yp); } } } /** * Draw current gps. * * @param p the p */ private void drawCurrentGPS(MPoint p){ float[] xp = new float[1]; float[] yp = new float[1]; xp[0] = (float) p.getUTMX(); yp[0] = (float) p.getUTMY(); if(_redView == null){ _redView = _plotPanel.addPoints(xp, yp); _redView.setMarkStyle(PointsView.Mark.CROSS); _redView.setLineStyle(PointsView.Line.NONE); _redView.setMarkColor(Color.RED); } else{ _redView.set(xp, yp); } } /** * Draw current gps. * * @param p the p */ private void drawCurrentGPS(ArrayList<MPoint> p){ if(p.size() > 0){ int np = p.size(); float[] xp = new float[np]; float[] yp = new float[np]; for (int ip = 0; ip < np; ++ip) { MPoint m = p.get(ip); xp[ip] = (float) m.getUTMX(); yp[ip] = (float) m.getUTMY(); } if(_redView == null){ _redView = _plotPanel.addPoints(xp, yp); _redView.setMarkStyle(PointsView.Mark.CROSS); _redView.setLineStyle(PointsView.Line.NONE); _redView.setMarkColor(Color.RED); } else{ _redView.set(xp, yp); } } } /** * Draw current seg. * * @param s the s */ private void drawCurrentSeg(Segdata s){ int g = s.getSP(); MPoint p = getNearestGPSFromSegdata(s); float[] xp = new float[1]; float[] yp = new float[1]; xp[0] = (float) p.getUTMX(); yp[0] = (float) p.getUTMY(); if(_blueView == null){ _blueView = _plotPanel.addPoints(xp, yp); _blueView.setMarkStyle(PointsView.Mark.HOLLOW_CIRCLE); _blueView.setLineStyle(PointsView.Line.NONE); _blueView.setMarkColor(Color.BLUE); } else{ _blueView.set(xp, yp); } } /** * Draw current seg. * * @param s the s */ private void drawCurrentSeg(ArrayList<Segdata> s){ if(s.size() > 0){ int np = s.size(); float[] xp = new float[np]; float[] yp = new float[np]; for (int ip = 0; ip < np; ++ip) { Segdata m = s.get(ip); MPoint p = getNearestGPSFromSegdata(m); xp[ip] = (float) p.getUTMX(); yp[ip] = (float) p.getUTMY(); } if(_blueView == null){ _blueView = _plotPanel.addPoints(xp, yp); _blueView.setMarkStyle(PointsView.Mark.HOLLOW_CIRCLE); _blueView.setLineStyle(PointsView.Line.NONE); _blueView.setMarkColor(Color.BLUE); } else{ _blueView.set(xp, yp); } } } /** * Gets the nearest gps from segdata. * * @param s the s * @return the nearest gps from segdata */ private MPoint getNearestGPSFromSegdata(Segdata s){ if(_gps != null && _gps.size() > 0){ MPoint p = _gps.get(0); for(int i=1; i<_gps.size(); ++i){ if(abs(p.getStation()-s.getSP())>abs(_gps.get(i).getStation()-s.getSP())){ p = _gps.get(i); } } return p; } return null; } /** * Plot active receivers. * * @param s the s */ private void plotActiveReceivers(Segdata s){ if(_gps != null && _gps.size()>0){ ArrayList<Integer> recs = new ArrayList<Integer>(0); ArrayList<MPoint> g = new ArrayList<MPoint>(0); float[][] f = s.getF(); int n2 = f.length; int start = s.getRPF(); for(int i=0; i<n2; ++i){ if(isActive(f[i])){ recs.add(start+i); } } for(int i=0; i<_gps.size(); ++i){ MPoint p = _gps.get(i); if(recs.contains(p.getStation())){ g.add(p); } } int np = g.size(); float[] xp = new float[np]; float[] yp = new float[np]; for (int ip = 0; ip < np; ++ip) { MPoint m = g.get(ip); xp[ip] = (float) m.getUTMX(); yp[ip] = (float) m.getUTMY(); } if(_greenView == null){ _greenView = _plotPanel.addPoints(xp, yp); _greenView.setMarkStyle(PointsView.Mark.CROSS); _greenView.setLineStyle(PointsView.Line.NONE); _greenView.setMarkColor(Color.GREEN); } else{ _greenView.set(xp, yp); } } } /** * Plot active receivers. * * @param seg the seg */ private void plotActiveReceivers(ArrayList<Segdata> seg){ for(Segdata s:seg){ plotActiveReceivers(s); } } /** * Checks if is active. * * @param f the f * @return true, if is active */ private boolean isActive(float[] f){ int n1 = f.length; for(int i=0; i<n1; ++i){ if(f[i] != 0){ return true; } } return false; } /** * Gps within range. * * @param g the g * @param d the d * @return the array list */ public ArrayList<MPoint> gpsWithinRange(MPoint g, double d){ if(_gps!=null && _gps.size()>0){ ArrayList<MPoint> p = new ArrayList<MPoint>(0); for(MPoint m:_gps){ if(g.xyDist(m) <= d){ p.add(m); } } return p; } return null; } /** * Seg within range. * * @param g the g * @return the array list */ public ArrayList<Segdata> segWithinRange(ArrayList<MPoint> g){ ArrayList<Segdata> p = new ArrayList<Segdata>(0); int max = maxStation(g); int min = minStation(g); for(Segdata s:_segd){ if(s.getSP() <= max && s.getSP()>=min){ p.add(s); } } return p; } /** * Draw circle. * * @param mid the mid * @param r the r */ public void drawCircle(MPoint mid, double r){ float[][] circlePoints = makeCirclePoints(mid, r); if(_circleView == null){ _circleView = _plotPanel.addPoints(circlePoints[0],circlePoints[1]); _circleView.setMarkStyle(PointsView.Mark.NONE); _circleView.setLineStyle(PointsView.Line.SOLID); _circleView.setLineColor(Color.RED); } else{ _circleView.set(circlePoints[0],circlePoints[1]); } } /** * Make circle points. * * @param mid the mid * @param r the r * @return the float[][] */ public float[][] makeCirclePoints(MPoint mid, double r){ int nt = 1000; double dt = 2.0*DBL_PI/(nt-1); float[] x = new float[nt]; float[] y = new float[nt]; for (int it=0; it<nt; ++it) { float t = (float)(it*dt); x[it] = (float)(mid.getUTMX()+r*cos(t)); y[it] = (float)(mid.getUTMY()-r*sin(t)); } return new float[][]{x,y}; } } /** * The Class ResponsePlot. * * Creates and controls the Response plot (shot record, brute stack, etc.) * * @author Colton Kohnke, Colorado School of Mines * @version 1.0 * @since April 13, 2014 */ private class ResponsePlot { // private PlotPanel _plotPanel; /** The sp. */ public SimplePlot sp; /** The pv. */ private PixelsView pv; /** The gain num. */ private double gainNum = 40.0; private JLabel gainLabel; /** The tpow num. */ private float tpowNum = 0.0f; private JLabel tpowLabel; /** The lowpass num. */ private double lowpassNum = 25.0; private JLabel lowpassLabel; /** The slider frame. */ private JFrame sliderFrame; /** The slider panel. */ private JPanel sliderPanel; /** The s1. */ private Sampling s1; /** The s2. */ private Sampling s2; /** The plot array. */ private float[][] plotArray; // The Shot response /** * Instantiates a new response plot. */ private ResponsePlot() { // Makes Sliders for gain, tpow and lowpass sliderFrame = new JFrame(); sliderFrame.setTitle("Plot Sliders"); sliderFrame.setSize(250,300); sliderFrame.setLocation(100,500); sliderPanel = new JPanel(); sliderFrame.add(sliderPanel); gainSlider = new JSlider(0,100,40); gainSlider.setOrientation(JSlider.HORIZONTAL); gainSlider.setMajorTickSpacing(20); gainSlider.setMinorTickSpacing(5); gainSlider.setPaintTicks(true); gainSlider.setPaintLabels(true); gainSlider.setSize(200,100); sliderPanel.add(gainSlider); gainSlider.addChangeListener(cl); gainLabel = new JLabel("Gain Control", JLabel.CENTER); gainLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sliderPanel.add(gainLabel); lowpassSlider = new JSlider(0,100,25); lowpassSlider.setOrientation(JSlider.HORIZONTAL); lowpassSlider.setMajorTickSpacing(20); lowpassSlider.setMinorTickSpacing(5); lowpassSlider.setPaintTicks(true); lowpassSlider.setPaintLabels(true); lowpassSlider.setSize(200,100); sliderPanel.add(lowpassSlider); lowpassSlider.addChangeListener(cl); lowpassLabel = new JLabel("Lowpass Freq. (cycles/s)", JLabel.CENTER); lowpassLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sliderPanel.add(lowpassLabel); tpowSlider = new JSlider(0,50,0); tpowSlider.setOrientation(JSlider.HORIZONTAL); tpowSlider.setMajorTickSpacing(10); tpowSlider.setMinorTickSpacing(1); tpowSlider.setPaintTicks(true); tpowSlider.setPaintLabels(true); Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>(); labelTable.put(new Integer(0), new JLabel("0.0")); labelTable.put(new Integer(10), new JLabel("1.0")); labelTable.put(new Integer(20), new JLabel("2.0")); labelTable.put(new Integer(30), new JLabel("3.0")); labelTable.put(new Integer(40), new JLabel("4.0")); labelTable.put(new Integer(50), new JLabel("5.0")); tpowSlider.setLabelTable(labelTable); tpowSlider.setSize(200,100); sliderPanel.add(tpowSlider); tpowSlider.addChangeListener(cl); tpowLabel = new JLabel("tpow Power", JLabel.CENTER); tpowLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sliderPanel.add(tpowLabel); sliderFrame.setVisible(false); sp = new SimplePlot(SimplePlot.Origin.UPPER_LEFT); sp.setSize(600, 600); sp.setVLabel("Time (s)"); sp.setLocation(500,0); pv = null; // Menu for Response Plot JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); fileMenu.add(new SaveAsPngAction(sp)).setMnemonic('a'); fileMenu.add(new ExitAction()).setMnemonic('x'); JMenu plotMenu = new JMenu("Plot Tools"); plotMenu.add(new ShowPlotSettings()).setMnemonic('p'); // Menu bar for Response Plot JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(plotMenu); sp.setJMenuBar(menuBar); } /** The cl. */ private ChangeListener cl = new ChangeListener(){ public void stateChanged(ChangeEvent e) { gainNum = gainSlider.getValue(); lowpassNum = lowpassSlider.getValue(); if(lowpassNum==0) lowpassNum=0.01; //butterworth filter must be > 0 tpowNum = tpowSlider.getValue()/10.0f; updateRP(); gainLabel.setText("Gain Number: "+gainNum); lowpassLabel.setText("Lowpass Freq. (cycles/s): "+lowpassNum); tpowLabel.setText("tpow Power: "+tpowNum); } }; /** * Update rp. */ public void updateRP(){ if(plotArray != null){ pv = sp.addPixels(s1, s2, gain2(lowpass2(tpow2(plotArray, tpowNum), lowpassNum), gainNum)); pv.setPercentiles(1, 99); } } /** * Update rp. * * @param seg the seg */ public void updateRP(Segdata seg) { int n1 = seg.getF()[0].length; int n2 = seg.getF().length; s1 = new Sampling(n1, 0.001, 0.0); s2 = new Sampling(n2, 1.0, seg.getRPF()); if (s2.getDelta() == 1.0) sp.setHLabel("Station"); else sp.setHLabel("Offset (km)"); sp.setHLimits(seg.getRPF(), seg.getRPL()); sp.setTitle("Shot " + seg.getSP()); plotArray = seg.getF(); updateRP(); } /** * Update rp. * * @param s the s */ public void updateRP(ArrayList<Segdata> s) { if(s != null && s.size()>0){ int n1 = getN1(s); int n2 = getN2(s); int rpf = getRPF(s); int rpl = rpf+n2; int minSP = minShot(s); int maxSP = maxShot(s); float[] count = new float[n2]; float[][] stot = new float[n2][n1]; for (int i = 0; i < s.size(); ++i) { Segdata seg = s.get(i); int rpftmp = seg.getRPF(); int rpltmp = seg.getRPL(); float[][] f = seg.getF(); for(int j=0; j<f.length; ++j){ int index = j+(rpftmp-rpf); if(isActive(f[j])){ for(int k=0; k<f[0].length; ++k){ stot[index][k] += f[j][k]; } ++count[index]; } } } for(int i=0;i<n2; ++i){ for(int j=0;j<n1;++j){ stot[i][j] = stot[i][j]/count[i]; } } s1 = new Sampling(n1, 0.001, 0.0); s2 = new Sampling(n2, 1.0, rpf); plotArray = stot; updateRP(); sp.setHLimits(rpf, rpl); if((maxSP-minSP)==0){ sp.setTitle("Shot: "+minSP); } else{ sp.setTitle("Stack: "+minSP+"-"+maxSP); } sp.setHLabel("Station"); } } /** * Update rp. * * @param s the s * @param channel the channel */ public void updateRP(ArrayList<Segdata> s, int channel) { if(s!=null && s.size()>0){ ArrayList<Segdata> seg = new ArrayList<Segdata>(0); int min = firstShot(s).getRPF(); int station = min+channel; for(int i=0; i<s.size(); ++i){ Segdata t = s.get(i); if(t.getF().length>=channel){ seg.add(t); } } int rpf = getRPF(seg); int fsp = getFirstSP(seg); int lsp = getLastSP(seg); int n1 = getN1(seg); int n2 = lsp-fsp+1; int rpl = rpf+n2; float[][] chan = new float[n2][n1]; for (int i = 0; i < seg.size(); ++i) { Segdata tmp = seg.get(i); int stmp = tmp.getSP(); int rpftmp = tmp.getRPF(); // float[] c = tmp.getF()[(rpf-rpftmp)+channel-1]; float[] c = tmp.getF()[channel]; if(isActive(c)){ for(int j=0;j<c.length; ++j){ chan[stmp-fsp][j] += c[j]; } } } s1 = new Sampling(n1, 0.001, 0.0); s2 = new Sampling(n2, 1.0, fsp); plotArray = chan; updateRP(); sp.setHLimits(fsp, maxShot(seg)); sp.setTitle("Channel: "+channel); sp.setHLabel("Station Number"); if(_gps != null && _gps.size()>0){ for(Segdata r:seg){ _bp.plotActiveReceivers(r); } _bp.drawCurrentSeg(seg); } } } /** * Gets the n1. * * @param s the s * @return the n1 */ private int getN1(ArrayList<Segdata> s){ int n1 = s.get(0).getF()[0].length; for(int i=1; i<s.size(); ++i){ Segdata tmp = s.get(i); int t = tmp.getF()[0].length; if(t>n1) n1=t; } return n1; } /** * Gets the n2. * * @param s the s * @return the n2 */ private int getN2(ArrayList<Segdata> s){ int s1 = s.get(0).getRPF(); int s2 = s.get(0).getRPL(); for(int i=1; i<s.size(); ++i){ Segdata tmp = s.get(i); int t1 = tmp.getRPF(); int t2 = tmp.getRPL(); if(t1<s1) s1=t1; if(t2>s2) s2=t2; } return s2-s1+1; } /** * Gets the first sp. * * @param s the s * @return the first sp */ private int getFirstSP(ArrayList<Segdata> s){ int s1 = s.get(0).getSP(); for(int i=1; i<s.size(); ++i){ Segdata tmp = s.get(i); int t1 = tmp.getSP(); if(t1<s1) s1=t1; } return s1; } /** * Gets the last sp. * * @param s the s * @return the last sp */ private int getLastSP(ArrayList<Segdata> s){ int s1 = s.get(0).getSP(); for(int i=1; i<s.size(); ++i){ Segdata tmp = s.get(i); int t1 = tmp.getSP(); if(t1>s1) s1=t1; } return s1; } /** * Gets the rpf. * * @param s the s * @return the rpf */ private int getRPF(ArrayList<Segdata> s){ int s1 = s.get(0).getRPF(); for(int i=1; i<s.size(); ++i){ Segdata tmp = s.get(i); int t1 = tmp.getRPF(); if(t1<s1) s1=t1; } return s1; } /** * Checks if a receiver is active. * * @param f the f * @return true, if is active */ private boolean isActive(float[] f){ int n1 = f.length; for(int i=0; i<n1; ++i){ if(f[i] != 0){ return true; } } return false; } /** * Show plot slider. */ public void showPlotSlider(){ sliderFrame.setVisible(true); } } /** * The Class ElevPlot. * * <p> Controls the Elevation plot * * @author Colton Kohnke, Colorado School of Mines * @version 1.0 * @since April 13, 2014 */ private class ElevPlot { /** The elev. */ private SimplePlot elev; /** The pv. */ private PointsView pv; /** * Instantiates a new elev plot. */ private ElevPlot() { elev = new SimplePlot(SimplePlot.Origin.LOWER_LEFT); elev.setSize(500, 250); elev.setVLabel("meters (m)"); elev.setHLabel("Station ID"); elev.setLocation(0,500); // Menu for Elev Plot JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); fileMenu.add(new SaveAsPngAction(elev)).setMnemonic('a'); fileMenu.add(new ExitAction()).setMnemonic('x'); // Menu bar for Elev Plot JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); elev.setJMenuBar(menuBar); } /** * Update elev. * * @param e the e */ public void updateElev(ArrayList<MPoint> e) { // TODO: Update to make xaxis distance between points instead of stationID if(e != null && e.size() >0){ int n = e.size(); float[] x = new float[n]; float[] y = new float[n]; for (int i = 0; i < n; ++i) { MPoint p = e.get(i); x[i] = p.getStation(); y[i] = (float) p.getElev(); } elev.setHLimits(min(x) - 10, max(x) + 10); elev.setVLimits(min(y) - 50, max(y) + 50); if(pv == null){ pv = elev.addPoints(x,y); } else{ pv.set(x, y); } } } } /** * The Class RoamMode. * * <p> Mode that allows for click and drag exploration of imported seismic data. * * @author Colton Kohnke, Colorado School of Mines * @version 1.0 * @since April 13, 2014 */ private class RoamMode extends Mode { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new roam mode. * * @param modeManager the mode manager */ public RoamMode(ModeManager modeManager) { super(modeManager); setName("Roaming Mode"); setIcon(loadIcon(SeisPlot.class,"Roam16.png")); setMnemonicKey(KeyEvent.VK_R); setAcceleratorKey(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0)); setShortDescription("Roaming Mode"); } /** The slider frame. */ private JFrame sliderFrame; /** The slider panel. */ private JPanel sliderPanel; /** The slider near. */ private JSlider sliderNear; private JLabel nearLabel; /** The sum dist. */ private int sumDist = 0; /** The nearest. */ private MPoint nearest; // When this mode is activated (or deactivated) for a tile, it simply // adds (or removes) its mouse listener to (or from) that tile. /* (non-Javadoc) * @see edu.mines.jtk.awt.Mode#setActive(java.awt.Component, boolean) */ protected void setActive(Component component, boolean active) { if (component instanceof Tile) { if (active) { component.addMouseListener(_ml); if(sliderFrame == null){ sliderFrame = new JFrame(); sliderFrame.setTitle("Sum Slider (m)"); sliderFrame.setSize(250,100); sliderFrame.setLocation(100,500); sliderPanel = new JPanel(); sliderFrame.add(sliderPanel); sliderNear = new JSlider(JSlider.HORIZONTAL,0,1000,0); sliderNear.setMajorTickSpacing(200); sliderNear.setMinorTickSpacing(50); sliderNear.setPaintTicks(true); sliderNear.setPaintLabels(true); sliderNear.setSize(250,100); sliderPanel.add(sliderNear); nearLabel = new JLabel("Sum Distance", JLabel.CENTER); nearLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sliderPanel.add(nearLabel); } sliderNear.addChangeListener(cl); sliderFrame.setVisible(true); } else { component.removeMouseListener(_ml); sliderFrame.setVisible(false); sliderNear.removeChangeListener(cl); } } } /** The _moving. */ private boolean _moving; // if true, currently moving /** The _tile. */ private Tile _tile; // tile in which editing began /** The _ml. */ private MouseListener _ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (beginMove(e)) { _moving = true; _tile.addMouseMotionListener(_mml); } } public void mouseReleased(MouseEvent e) { _tile.removeMouseMotionListener(_mml); endMove(e); _moving = false; } }; /** The cl. */ private ChangeListener cl = new ChangeListener(){ public void stateChanged(ChangeEvent e) { sumDist = sliderNear.getValue(); _bp.drawCircle(nearest, sumDist); updatePlot(); nearLabel.setText("Sum Distance: "+sumDist+"m"); } }; // Handles mouse dragged events. /** The _mml. */ private MouseMotionListener _mml = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (_moving) duringMove(e); } }; /** * Begin move. * * @param e the e * @return true, if successful */ private boolean beginMove(MouseEvent e) { _tile = (Tile) e.getSource(); return true; } /** * During move. * * @param e the e */ private void duringMove(MouseEvent e) { int x = e.getX(); int y = e.getY(); ArrayList<MPoint> gpsPlot = new ArrayList<MPoint>(0); ArrayList<Segdata> segPlot = new ArrayList<Segdata>(0); nearest = getNearestGPS(x, y); Segdata segNear = getNearestSegdata(nearest.getStation()); gpsPlot.add(nearest); segPlot.add(segNear); if(sumDist > 0){ gpsPlot = _bp.gpsWithinRange(nearest, sumDist); segPlot = _bp.segWithinRange(gpsPlot); } _bp.drawCurrentSeg(segPlot); _bp.plotActiveReceivers(segPlot); _bp.drawCircle(nearest, sumDist); //_bp.drawCurrentGPS(gpsPlot); _rp.updateRP(segPlot); } /** * Update plot. */ private void updatePlot() { ArrayList<MPoint> gpsPlot = new ArrayList<MPoint>(0); ArrayList<Segdata> segPlot = new ArrayList<Segdata>(0); Segdata segNear = getNearestSegdata(nearest.getStation()); gpsPlot.add(nearest); segPlot.add(segNear); if(sumDist > 0){ gpsPlot = _bp.gpsWithinRange(nearest, sumDist); segPlot = _bp.segWithinRange(gpsPlot); } _bp.drawCurrentSeg(segPlot); _bp.plotActiveReceivers(segPlot); //_bp.drawCurrentGPS(gpsPlot); _rp.updateRP(segPlot); } /** * End move. * * @param e the e */ private void endMove(MouseEvent e) { duringMove(e); } /** * Gets the nearest gps. * * @param x the x * @param y the y * @return the nearest gps */ private MPoint getNearestGPS(int x, int y) { if(_gps!=null && _gps.size()>0){ Transcaler ts = _tile.getTranscaler(); Projector hp = _tile.getHorizontalProjector(); Projector vp = _tile.getVerticalProjector(); double xu = ts.x(x); double yu = ts.y(y); double xv = hp.v(xu); double yv = vp.v(yu); MPoint test = new MPoint(xv, yv, true); MPoint near = _gps.get(0); MPoint fin = _gps.get(0); double d = near.xyDist(test); for (int i = 1; i < _gps.size(); ++i) { near = _gps.get(i); if (near.xyDist(test) < d) { fin = _gps.get(i); d = fin.xyDist(test); } } return fin; } return null; } /** * Gets the nearest segdata. * * @param stationID the station id * @return the nearest segdata */ private Segdata getNearestSegdata(int stationID) { if(_segd!=null && _segd.size()>0){ Segdata seg1 = _segd.get(0); Segdata seg2 = _segd.get(0); int d1 = abs(seg1.getSP() - stationID); for (int i = 1; i < _segd.size(); ++i) { seg2 = _segd.get(i); int d2 = abs(seg2.getSP() - stationID); if (d2 < d1) { seg1 = seg2; d1 = abs(seg1.getSP() - stationID); } } return seg1; } return null; } } /** * The Class ChannelMode. * * <p> Mode that allows for dynamic view of channels using a slider * @author Colton Kohnke, Colorado School of Mines * @version 1.0 * @since April 13, 2014 */ private class ChannelMode extends Mode { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new channel mode. * * @param modeManager the mode manager */ public ChannelMode(ModeManager modeManager) { super(modeManager); setName("Channel Mode"); setIcon(loadIcon(SeisPlot.class,"Chan16.png")); setShortDescription("Display a Channel Mode"); } /** The slider frame. */ private JFrame sliderFrame; /** The slider panel. */ private JPanel sliderPanel; /** The slider chan. */ private JSlider sliderChan; private JLabel chanLabel; /* (non-Javadoc) * @see edu.mines.jtk.awt.Mode#setActive(java.awt.Component, boolean) */ protected void setActive(Component component, boolean active) { if (active) { if(sliderFrame == null){ sliderFrame = new JFrame(); sliderFrame.setTitle("Channel Slider"); sliderFrame.setSize(250,100); sliderFrame.setLocation(100,500); sliderPanel = new JPanel(); sliderFrame.add(sliderPanel); sliderChan = new JSlider(JSlider.HORIZONTAL,0,getMaxNumChan(_segd),0); sliderChan.setMajorTickSpacing(50); sliderChan.setPaintTicks(true); sliderChan.setPaintLabels(true); sliderChan.setSize(200,100); sliderPanel.add(sliderChan); chanLabel = new JLabel("Channel Number", JLabel.CENTER); chanLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sliderPanel.add(chanLabel); } sliderChan.setMaximum(getMaxNumChan(_segd)); sliderChan.addChangeListener(cl); sliderFrame.setVisible(true); } else { sliderFrame.setVisible(false); sliderChan.removeChangeListener(cl); } } /** The cl. */ private ChangeListener cl = new ChangeListener(){ public void stateChanged(ChangeEvent e) { adjust(sliderChan.getValue()); chanLabel.setText("Channel Number: "+sliderChan.getValue()); } }; /** * Adjust. * * @param chan the chan */ private void adjust(int chan){ if(_segd != null && _segd.size()>0){ _rp.updateRP(_segd,chan); } } } /** * The Class NoGPSMode. * * <p> Mode that allows for dynamic view of shots without GPS data imported. * * @author Colton Kohnke, Colorado School of Mines * @version 1.0 * @since April 26, 2014 */ private class NoGPSMode extends Mode { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new no GPS mode. * * @param modeManager the mode manager */ public NoGPSMode(ModeManager modeManager) { super(modeManager); setName("No GPS Mode"); setIcon(loadIcon(SeisPlot.class,"NoGPS16.png")); setShortDescription("Explore Without GPS"); } /** The slider frame. */ private JFrame sliderFrame; /** The slider panel. */ private JPanel sliderPanel; /** The slider chan. */ private JSlider sliderShot; private JSlider sliderNum; private JLabel sumLabel; private JLabel shotLabel; /* (non-Javadoc) * @see edu.mines.jtk.awt.Mode#setActive(java.awt.Component, boolean) */ protected void setActive(Component component, boolean active) { if (active) { if(sliderFrame == null){ sliderFrame = new JFrame(); sliderFrame.setTitle("Shot Slider"); sliderFrame.setSize(250,180); sliderFrame.setLocation(100,500); sliderPanel = new JPanel(); sliderFrame.add(sliderPanel); sliderShot = new JSlider(JSlider.HORIZONTAL,0,1,0); sliderShot.setMajorTickSpacing(50); sliderShot.setPaintTicks(true); sliderShot.setPaintLabels(true); sliderShot.setSize(200,100); sliderPanel.add(sliderShot); shotLabel = new JLabel("Shot Number", JLabel.CENTER); shotLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sliderPanel.add(shotLabel); sliderNum = new JSlider(JSlider.HORIZONTAL,0,100,1); sliderNum.setMajorTickSpacing(_segd.size()/4); sliderNum.setPaintTicks(true); sliderNum.setPaintLabels(true); sliderNum.setSize(200,100); sliderPanel.add(sliderNum); sumLabel = new JLabel("Sum Nearest", JLabel.CENTER); sumLabel.setAlignmentX(Component.CENTER_ALIGNMENT); sliderPanel.add(sumLabel); } sliderShot.setMinimum(minShot(_segd)); sliderShot.setMaximum(maxShot(_segd)); sliderShot.addChangeListener(cl); sliderNum.setMinimum(1); sliderNum.setMaximum(_segd.size()); sliderNum.addChangeListener(cl); sliderFrame.setVisible(true); } else { sliderFrame.setVisible(false); sliderShot.removeChangeListener(cl); } } /** The cl. */ private ChangeListener cl = new ChangeListener(){ public void stateChanged(ChangeEvent e) { adjust(sliderShot.getValue(), sliderNum.getValue()); shotLabel.setText("Shot Number: "+sliderShot.getValue()); sumLabel.setText("Sum Nearest: "+sliderNum.getValue()); } }; /** * Adjust. * * @param chan the chan */ private void adjust(int shot, int sum){ if(_segd != null && _segd.size()>0){ ArrayList<Segdata> tmp = new ArrayList<Segdata>(0); for(Segdata s:_segd){ if(abs(s.getSP()-shot)<=(sum-1)){ tmp.add(s); } } _rp.updateRP(tmp); } } } private class CircleMode extends Mode { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new circle mode. * * @param modeManager the mode manager */ public CircleMode(ModeManager modeManager) { super(modeManager); setName("Circle Mode"); setIcon(loadIcon(SeisPlot.class,"Circle16.png")); setShortDescription("Display within a Circle"); } /* (non-Javadoc) * @see edu.mines.jtk.awt.Mode#setActive(java.awt.Component, boolean) */ protected void setActive(Component component, boolean active) { if (active) { component.addMouseListener(_ml); } else { component.removeMouseListener(_ml); } } /** The _ml. */ private MouseListener _ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if(beginMove(e)){ _tile.addMouseMotionListener(_mml); } } public void mouseReleased(MouseEvent e) { endMove(e); _tile.removeMouseMotionListener(_mml); } }; /** The _mml. */ private MouseMotionListener _mml = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); Transcaler ts = _tile.getTranscaler(); Projector hp = _tile.getHorizontalProjector(); Projector vp = _tile.getVerticalProjector(); double xu = ts.x(x); double yu = ts.y(y); double xv = hp.v(xu); double yv = vp.v(yu); MPoint tmp = new MPoint(xv,yv,true); plotCircle(p1, tmp); } }; /** * Begin move. * * @param e the e * @return true, if successful */ private boolean beginMove(MouseEvent e){ _tile = (Tile) e.getSource(); int x = e.getX(); int y = e.getY(); Transcaler ts = _tile.getTranscaler(); Projector hp = _tile.getHorizontalProjector(); Projector vp = _tile.getVerticalProjector(); double xu = ts.x(x); double yu = ts.y(y); double xv = hp.v(xu); double yv = vp.v(yu); p1 = new MPoint(xv,yv,true); return true; } /** * End move. * * @param e the e */ private void endMove(MouseEvent e){ int x = e.getX(); int y = e.getY(); Transcaler ts = _tile.getTranscaler(); Projector hp = _tile.getHorizontalProjector(); Projector vp = _tile.getVerticalProjector(); double xu = ts.x(x); double yu = ts.y(y); double xv = hp.v(xu); double yv = vp.v(yu); p2 = new MPoint(xv,yv,true); plotCircle(p1,p2); } /** * Plot circle. * * @param m1 the m1 * @param m2 the m2 */ private void plotCircle(MPoint m1, MPoint m2){ _bp.drawCircle(m1,m1.xyDist(m2)); ArrayList<Segdata> segPlot = _bp.segWithinRange(_bp.gpsWithinRange(m1, m1.xyDist(m2))); if(segPlot.size()>0){ _bp.drawCurrentSeg(segPlot); _bp.plotActiveReceivers(segPlot); _rp.updateRP(segPlot); } } /** The p2. */ private MPoint p1, p2; /** The _tile. */ private Tile _tile; } // Actions common to both plot frames. /** * The Class ExitAction. */ private class ExitAction extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new exit action. */ private ExitAction() { super("Exit"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { System.exit(0); } } /** * The Class SaveAsPngAction. */ private class SaveAsPngAction extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The _plot frame. */ private PlotFrame _plotFrame; /** * Instantiates a new save as png action. * * @param plotFrame the plot frame */ private SaveAsPngAction(PlotFrame plotFrame) { super("Save as PNG"); _plotFrame = plotFrame; } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.showSaveDialog(_plotFrame); File file = fc.getSelectedFile(); if (file != null) { String filename = file.getAbsolutePath(); _plotFrame.paintToPng(300, 6, filename); } } } /** * The Class GetDEM. */ private class GetDEM extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new gets the dem. * * @param plotPanel the plot panel */ private GetDEM(PlotPanel plotPanel) { super("Import NED Files"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { try{ JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.setFileFilter(new FileNameExtensionFilter("GridFloat File", "flt")); fc.showOpenDialog(null); File f = fc.getSelectedFile(); if(f!=null){ if(_nedFiles==null) _nedFiles = new ArrayList<NedFile>(0); _nedFiles.add(importNed(f)); } } catch(Exception e){ System.out.println(e); } } } /** * The Class ReadNedElevation. */ private class ReadNedElevation extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new read ned elevation. * * @param plotPanel the plot panel */ private ReadNedElevation(PlotPanel plotPanel) { super("Read Elevation from NED"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event){ try{ if(_nedFiles.size() > 0){ for(NedFile f:_nedFiles){ readNed(f,_gps); } _elev.updateElev(_gps); } } catch (Exception e){ System.out.println(e); } } } /** * The Class GetFlagsFromHH. */ private class GetFlagsFromHH extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new gets the flags from hh. */ private GetFlagsFromHH() { super("Get HandHeld GPS"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.showOpenDialog(null); fc.setFileFilter(new FileNameExtensionFilter("TSV,CSV, or GPX File", "txt", "csv", "asc", "gpx")); File f = fc.getSelectedFile(); if(f != null){ String ext = ""; int i = f.getName().lastIndexOf('.'); if (i > 0) { ext = f.getName().substring(i + 1); } if (ext.equals("gpx")){ _gps = readLatLonFromXML(f); } else if (ext.equals("csv")){ _gps = readLatLonFromCSV(f); } else { _gps = readLatLonFromTSV(f); } Waypoints.latLonToUTM(_gps); // Waypoints.extrapolateGPS(_gps); _bp.updateBPView(); _elev.updateElev(_gps); } } } /** * The Class ExportFlagsToCSV. */ private class ExportFlagsToCSV extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new export flags to csv. */ private ExportFlagsToCSV() { super("Export GPS to CSV"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.showSaveDialog(null); File f = fc.getSelectedFile(); if(f!=null){ Waypoints.exportToCSV(_gps, f); } } } /** * The Class ImportSegdDir. */ private class ImportSegdDir extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new import segd dir. */ private ImportSegdDir() { super("Import SEGD Directory"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.showSaveDialog(null); File f = fc.getSelectedFile(); if(f!=null){ ArrayList<Segdata> tmp = Segd.readLineSegd(f.getAbsolutePath()); if(_segd == null){ _segd = new ArrayList<Segdata>(0); } for(Segdata s:tmp){ _segd.add(s); } System.out.println("SEGD IMPORTED"); System.out.println("_segd size: "+_segd.size()); } } } /** * The Class ImportSegdFile. */ private class ImportSegdFile extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new import segd file. */ private ImportSegdFile() { super("Import SEGD File(s)"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { try{ JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.setMultiSelectionEnabled(true); fc.setFileFilter(new FileNameExtensionFilter("SEGD Files", "segd")); fc.showSaveDialog(null); File[] f = fc.getSelectedFiles(); if(f!=null){ ArrayList<Segdata> tmp = new ArrayList<Segdata>(0); for(int i=0; i<f.length; ++i){ Segdata ts = readSegd(f[i]); tmp.add(ts); } if(_segd == null){ _segd = new ArrayList<Segdata>(0); } for(Segdata s:tmp){ _segd.add(s); } System.out.println("SEGD IMPORTED"); System.out.println("_segd size: "+_segd.size()); } } catch(Exception e){ System.out.println(e); } } } /** * The Class ClearData. */ private class ClearData extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new clear data. */ private ClearData() { super("Clear Data"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { if(_segd != null && _segd.size()>0){ _segd.removeAll(_segd); } if(_gps != null && _gps.size()>0){ _gps.removeAll(_gps); } if(_nedFiles != null && _nedFiles.size()>0){ _nedFiles.removeAll(_nedFiles); } System.out.println("Cleared Data from GPS, NED and SEGD files"); } } /** * The Class ShowPlotSettings. */ private class ShowPlotSettings extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new show plot settings. */ private ShowPlotSettings() { super("Plot Controls"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { _rp.showPlotSlider(); } } /** * The Class ShowPlotSettings. */ private class DownloadNedFile extends AbstractAction { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new show plot settings. */ private DownloadNedFile() { super("Download NED Zip Archive"); } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { Object[] opt = {"Continue","Cancel"}; int k = JOptionPane.showOptionDialog(null, "Warning, this may take a long time.", "Warning: Time Conflict", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, opt, opt[1]); if(k==0){ String ns = JOptionPane.showInputDialog( "Enter North Latitude (Integer)" ); int n = Integer.parseInt(ns); String ws = JOptionPane.showInputDialog( "Enter West Longitude (Integer)" ); int w = Integer.parseInt(ws); try{ JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.showSaveDialog(null); File f = fc.getSelectedFile(); if(f!=null){ NedFileDownloader.get(n,w,f.getAbsolutePath()); } }catch(IOException e){ e.printStackTrace(); } } } } }
package cgeo.geocaching; import butterknife.ButterKnife; import butterknife.InjectView; import cgeo.geocaching.activity.Keyboard; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.LogResult; import cgeo.geocaching.connector.trackable.AbstractTrackableLoggingManager; import cgeo.geocaching.connector.trackable.TrackableConnector; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.Loaders; import cgeo.geocaching.enumerations.LogTypeTrackable; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.sensors.Sensors; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.twitter.Twitter; import cgeo.geocaching.ui.dialog.CoordinatesInputDialog; import cgeo.geocaching.ui.dialog.CoordinatesInputDialog.CoordinateUpdate; import cgeo.geocaching.ui.dialog.DateDialog; import cgeo.geocaching.ui.dialog.DateDialog.DateDialogParent; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.ui.dialog.TimeDialog; import cgeo.geocaching.ui.dialog.TimeDialog.TimeDialogParent; import cgeo.geocaching.utils.AsyncTaskWithProgress; import cgeo.geocaching.utils.Formatter; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.LogTemplateProvider; import cgeo.geocaching.utils.LogTemplateProvider.LogContext; import cgeo.geocaching.utils.LogTemplateProvider.LogTemplate; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class LogTrackableActivity extends AbstractLoggingActivity implements DateDialogParent, TimeDialogParent, CoordinateUpdate, LoaderManager.LoaderCallbacks<List<LogTypeTrackable>> { @InjectView(R.id.type) protected Button typeButton; @InjectView(R.id.date) protected Button dateButton; @InjectView(R.id.time) protected Button timeButton; @InjectView(R.id.geocode) protected EditText geocacheEditText; @InjectView(R.id.coordinates) protected Button coordinatesButton; @InjectView(R.id.tracking) protected EditText trackingEditText; @InjectView(R.id.log) protected EditText logEditText; @InjectView(R.id.tweet) protected CheckBox tweetCheck; @InjectView(R.id.tweet_box) protected LinearLayout tweetBox; private List<LogTypeTrackable> possibleLogTypesTrackable = new ArrayList<>(); private String geocode = null; private Geopoint geopoint; private Geocache geocache = new Geocache(); /** * As long as we still fetch the current state of the trackable from the Internet, the user cannot yet send a log. */ private boolean postReady = true; private Calendar date = Calendar.getInstance(); private LogTypeTrackable typeSelected = LogTypeTrackable.getById(Settings.getTrackableAction()); private Trackable trackable; TrackableConnector connector; private AbstractTrackableLoggingManager loggingManager; final public static int LOG_TRACKABLE = 1; @Override public Loader<List<LogTypeTrackable>> onCreateLoader(final int id, final Bundle bundle) { showProgress(true); loggingManager = connector.getTrackableLoggingManager(this); if (loggingManager == null) { showToast(res.getString(R.string.err_tb_not_loggable)); finish(); return null; } if (id == Loaders.LOGGING_TRAVELBUG.getLoaderId()) { loggingManager.setGuid(trackable.getGuid()); } return loggingManager; } @Override public void onLoadFinished(final Loader<List<LogTypeTrackable>> listLoader, final List<LogTypeTrackable> logTypesTrackable) { if (CollectionUtils.isNotEmpty(logTypesTrackable)) { possibleLogTypesTrackable.clear(); possibleLogTypesTrackable.addAll(logTypesTrackable); } if (logTypesTrackable != null && !logTypesTrackable.contains(typeSelected) && !logTypesTrackable.isEmpty()) { setType(logTypesTrackable.get(0)); showToast(res.getString(R.string.info_log_type_changed)); } postReady = loggingManager.postReady(); // we're done, user can post log showProgress(false); } @Override public void onLoaderReset(final Loader<List<LogTypeTrackable>> listLoader) { // nothing } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.logtrackable_activity); ButterKnife.inject(this); // get parameters final Bundle extras = getIntent().getExtras(); if (extras != null) { geocode = extras.getString(Intents.EXTRA_GEOCODE); // Load geocache if we can if (StringUtils.isNotBlank(extras.getString(Intents.EXTRA_GEOCACHE))) { final Geocache tmpGeocache = DataStore.loadCache(extras.getString(Intents.EXTRA_GEOCACHE), LoadFlags.LOAD_CACHE_OR_DB); if (tmpGeocache != null) { geocache = tmpGeocache; } } // Display tracking code if we have, and move cursor next if (StringUtils.isNotBlank(extras.getString(Intents.EXTRA_TRACKING_CODE))) { trackingEditText.setText(extras.getString(Intents.EXTRA_TRACKING_CODE)); Dialogs.moveCursorToEnd(trackingEditText); } } // Load Trackable from internal trackable = DataStore.loadTrackable(geocode); if (trackable == null) { Log.e("LogTrackableActivity.onCreate: cannot load trackable " + geocode); setResult(RESULT_CANCELED); finish(); return; } if (StringUtils.isNotBlank(trackable.getName())) { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getName()); } else { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getGeocode()); } // We're in LogTrackableActivity, so trackable must be loggable ;) if (!trackable.isLoggable()) { showToast(res.getString(R.string.err_tb_not_loggable)); finish(); return; } // create trackable connector connector = ConnectorFactory.getTrackableConnector(geocode); // Start loading in background getSupportLoaderManager().initLoader(connector.getTrackableLoggingManagerLoaderId(), null, this).forceLoad(); // Show retrieved infos displayTrackable(); init(); requestKeyboardForLogging(); } private void displayTrackable() { if (StringUtils.isNotBlank(trackable.getName())) { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getName()); } else { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getGeocode()); } } @Override protected void requestKeyboardForLogging() { if (StringUtils.isBlank(trackingEditText.getText())) { new Keyboard(this).show(trackingEditText); } else { super.requestKeyboardForLogging(); } } @Override public void onConfigurationChanged(final Configuration newConfig) { super.onConfigurationChanged(newConfig); init(); } @Override public void onCreateContextMenu(final ContextMenu menu, final View view, final ContextMenu.ContextMenuInfo info) { super.onCreateContextMenu(menu, view, info); final int viewId = view.getId(); if (viewId == R.id.type) { for (final LogTypeTrackable typeOne : possibleLogTypesTrackable) { menu.add(viewId, typeOne.id, 0, typeOne.getLabel()); } } } @Override public boolean onContextItemSelected(final MenuItem item) { final int group = item.getGroupId(); final int id = item.getItemId(); if (group == R.id.type) { setType(LogTypeTrackable.getById(id)); return true; } return false; } public void init() { registerForContextMenu(typeButton); typeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { openContextMenu(view); } }); setType(typeSelected); dateButton.setOnClickListener(new DateListener()); setDate(date); if (loggingManager.canLogTime()) { timeButton.setOnClickListener(new TimeListener()); setTime(date); timeButton.setVisibility(View.VISIBLE); } else { timeButton.setVisibility(View.GONE); } // Register Coordinates Listener if (loggingManager.canLogCoordinates()) { geocacheEditText.setOnFocusChangeListener(new LoadGeocacheListener()); geocacheEditText.setText(geocache.getGeocode()); updateCoordinates(geocache.getCoords()); coordinatesButton.setOnClickListener(new CoordinatesListener()); } initTwitter(); if (CollectionUtils.isEmpty(possibleLogTypesTrackable)) { possibleLogTypesTrackable = Trackable.getPossibleLogTypes(); } disableSuggestions(trackingEditText); } @Override public void setDate(final Calendar dateIn) { date = dateIn; dateButton.setText(Formatter.formatShortDateVerbally(date.getTime().getTime())); } @Override public void setTime(final Calendar dateIn) { date = dateIn; timeButton.setText(Formatter.formatTime(date.getTime().getTime())); } public void setType(final LogTypeTrackable type) { typeSelected = type; typeButton.setText(typeSelected.getLabel()); if (LogTypeTrackable.isCoordinatesNeeded(typeSelected) && loggingManager.canLogCoordinates()) { geocacheEditText.setVisibility(View.VISIBLE); coordinatesButton.setVisibility(View.VISIBLE); } else { geocacheEditText.setVisibility(View.GONE); coordinatesButton.setVisibility(View.GONE); } } private void initTwitter() { tweetCheck.setChecked(true); if (Settings.isUseTwitter() && Settings.isTwitterLoginValid()) { tweetBox.setVisibility(View.VISIBLE); } else { tweetBox.setVisibility(View.GONE); } } @Override public void updateCoordinates(final Geopoint geopointIn) { if (geopointIn == null) { return; } geopoint = geopointIn; coordinatesButton.setText(geopoint.toString()); geocache.setCoords(geopoint); } private class DateListener implements View.OnClickListener { @Override public void onClick(final View arg0) { final DateDialog dateDialog = DateDialog.getInstance(date); dateDialog.setCancelable(true); dateDialog.show(getSupportFragmentManager(), "date_dialog"); } } private class TimeListener implements View.OnClickListener { @Override public void onClick(final View arg0) { final TimeDialog timeDialog = TimeDialog.getInstance(date); timeDialog.setCancelable(true); timeDialog.show(getSupportFragmentManager(),"time_dialog"); } } private class CoordinatesListener implements View.OnClickListener { @Override public void onClick(final View arg0) { final CoordinatesInputDialog coordinatesDialog = CoordinatesInputDialog.getInstance(geocache, geopoint, Sensors.getInstance().currentGeo()); coordinatesDialog.setCancelable(true); coordinatesDialog.show(getSupportFragmentManager(),"coordinates_dialog"); } } // React when changing geocode private class LoadGeocacheListener implements OnFocusChangeListener { @Override public void onFocusChange(final View view, final boolean hasFocus) { if (!hasFocus && !geocacheEditText.getText().toString().isEmpty()) { final Geocache tmpGeocache = DataStore.loadCache(geocacheEditText.getText().toString(), LoadFlags.LOAD_CACHE_OR_DB); if (tmpGeocache == null) { geocache.setGeocode(geocacheEditText.getText().toString()); } else { geocache = tmpGeocache; updateCoordinates(geocache.getCoords()); } } } } private class Poster extends AsyncTaskWithProgress<String, StatusCode> { public Poster(final Activity activity, final String progressMessage) { super(activity, null, progressMessage, true); } @Override protected StatusCode doInBackgroundInternal(final String[] params) { final String logMsg = params[0]; try { // Set selected action final TrackableLog trackableLog = new TrackableLog(trackable.getGeocode(), trackable.getTrackingcode(), trackable.getName(), 0, 0, trackable.getBrand()); trackableLog.setAction(typeSelected); // Real call to post log final LogResult logResult = loggingManager.postLog(geocache, trackableLog, date, logMsg); // Now posting tweet if log is OK if (logResult.getPostLogResult() == StatusCode.NO_ERROR) { addLocalTrackableLog(logMsg); if (tweetCheck.isChecked() && tweetBox.getVisibility() == View.VISIBLE) { // TODO oldLogType as a temp workaround... final LogEntry logNow = new LogEntry(date.getTimeInMillis(), typeSelected.oldLogtype, logMsg); Twitter.postTweetTrackable(trackable.getGeocode(), logNow); } } // Display errors to the user if (StringUtils.isNoneEmpty(logResult.getLogId())) { showToast(logResult.getLogId()); } // Return request status return logResult.getPostLogResult(); } catch (final RuntimeException e) { Log.e("LogTrackableActivity.Poster.doInBackgroundInternal", e); } return StatusCode.LOG_POST_ERROR; } @Override protected void onPostExecuteInternal(final StatusCode status) { if (status == StatusCode.NO_ERROR) { showToast(res.getString(R.string.info_log_posted)); finish(); } else if (status == StatusCode.LOG_SAVED) { // is this part of code really reachable ? Dind't see StatusCode.LOG_SAVED in postLog() showToast(res.getString(R.string.info_log_saved)); finish(); } else { showToast(status.getErrorString(res)); } } } /** * Adds the new log to the list of log entries for this trackable to be able to show it in the trackable activity. * * */ private void addLocalTrackableLog(final String logText) { // TODO create a LogTrackableEntry. For now use "oldLogtype" as a temporary migration path final LogEntry logEntry = new LogEntry(date.getTimeInMillis(), typeSelected.oldLogtype, logText); final ArrayList<LogEntry> modifiedLogs = new ArrayList<>(trackable.getLogs()); modifiedLogs.add(0, logEntry); trackable.setLogs(modifiedLogs); DataStore.saveTrackable(trackable); } public static Intent getIntent(final Context context, final Trackable trackable) { final Intent logTouchIntent = new Intent(context, LogTrackableActivity.class); logTouchIntent.putExtra(Intents.EXTRA_GEOCODE, trackable.getGeocode()); logTouchIntent.putExtra(Intents.EXTRA_TRACKING_CODE, trackable.getTrackingcode()); return logTouchIntent; } public static Intent getIntent(final Context context, final Trackable trackable, final String geocache) { final Intent logTouchIntent = getIntent(context, trackable); logTouchIntent.putExtra(Intents.EXTRA_GEOCACHE, geocache); return logTouchIntent; } @Override protected LogContext getLogContext() { return new LogContext(trackable, null); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_send: sendLog(); return true; default: break; } return super.onOptionsItemSelected(item); } private void sendLog() { // Can logging? if (!postReady) { showToast(res.getString(R.string.log_post_not_possible)); return; } if (!loggingManager.isRegistered()) { final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle(R.string.init_summary_geokrety_account); alertDialog.setMessage(R.string.init_summary_geokrety_not_anonymous); alertDialog.setPositiveButton(R.string.ok, null); alertDialog.show(); // TODO redirect user to geokrety settings page // this throw "android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?" //SettingsActivity.openForScreen(R.string.preference_screen_geokrety, getApplicationContext()); return; } // Check Tracking Code existance if (trackingEditText.getText().toString().isEmpty()) { showToast(res.getString(R.string.err_log_post_missing_tracking_code)); return; } trackable.setTrackingcode(trackingEditText.getText().toString()); // Check params for trackables needing coordinates if (loggingManager.canLogCoordinates() && LogTypeTrackable.isCoordinatesNeeded(typeSelected)) { // Check geocode if (geocacheEditText.getText().toString().isEmpty()) { showToast(res.getString(R.string.log_post_geocode_missing)); return; } // Check Coordinates if (null == geopoint) { showToast(res.getString(R.string.err_log_post_missing_coordinates)); return; } } // Post Log in Background new Poster(this, res.getString(R.string.log_saving)).execute(logEditText.getText().toString()); Settings.setLastTrackableLog(logEditText.getText().toString()); } @Override public boolean onCreateOptionsMenu(final Menu menu) { final boolean result = super.onCreateOptionsMenu(menu); for (final LogTemplate template : LogTemplateProvider.getTemplatesWithoutSignature()) { if (template.getTemplateString().equals("NUMBER")) { menu.findItem(R.id.menu_templates).getSubMenu().removeItem(template.getItemId()); } } return result; } @Override protected String getLastLog() { return Settings.getLastTrackableLog(); } }
package outbackcdx; import outbackcdx.auth.Authorizer; import outbackcdx.auth.JwtAuthorizer; import outbackcdx.auth.KeycloakConfig; import outbackcdx.auth.NullAuthorizer; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.URL; import java.nio.channels.Channel; import java.nio.channels.ServerSocketChannel; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void usage() { System.err.println("Usage: java " + Main.class.getName() + " [options...]"); System.err.println(""); System.err.println(" -b bindaddr Bind to a particular IP address"); System.err.println(" -d datadir Directory to store index data under"); System.err.println(" -i Inherit the server socket via STDIN (for use with systemd, inetd etc)"); System.err.println(" -j jwks-url perm-path Use JSON Web Tokens for authorization"); System.err.println(" -k url realm clientid Use a Keycloak server for authorization"); System.err.println(" -p port Local port to listen on"); System.err.println(" -t count Number of web server threads"); System.err.println(" -v Verbose logging"); System.err.println(); System.err.println("Primary mode (runs as a replication target for downstream Secondaries)"); System.err.println(" --replication-window interval interval, in seconds, to delete replication history from disk."); System.err.println(" 0 disables automatic deletion. History files can be deleted manually by"); System.err.println(" POSTing a replication sequenceNumber to /<collection>/truncate_replication"); System.err.println(); System.err.println("Secondary mode (runs read-only; polls upstream server on 'collection-url' for changes)"); System.err.println(" --primary collection-url URL of collection on upstream primary to poll for changes"); System.err.println(" --update-interval poll-interval Polling frequency for upstream changes, in seconds. Default: 10"); System.exit(1); } public static void main(String args[]) { boolean undertow = false; String host = null; int port = 8080; int webThreads = Runtime.getRuntime().availableProcessors(); boolean inheritSocket = false; File dataPath = new File("data"); boolean verbose = false; Authorizer authorizer = new NullAuthorizer(); int pollingInterval = 10; String collectionUrl = null; long replicationWindow = 60 * 60 * 24 * 2; // two days Map<String,Object> dashboardConfig = new HashMap<>(); dashboardConfig.put("featureFlags", FeatureFlags.asMap()); for (int i = 0; i < args.length; i++) { switch (args[i]) { case "-u": undertow = true; break; case "-p": port = Integer.parseInt(args[++i]); break; case "-b": host = args[++i]; break; case "-d": dataPath = new File(args[++i]); break; case "-i": inheritSocket = true; break; case "-j": try { authorizer = new JwtAuthorizer(new URL(args[++i]), args[++i]); } catch (MalformedURLException e) { System.err.println("Malformed JWKS URL in -j option"); System.exit(1); } break; case "-k": KeycloakConfig keycloakConfig = new KeycloakConfig(args[++i], args[++i], args[++i]); authorizer = keycloakConfig.toAuthorizer(); dashboardConfig.put("keycloak", keycloakConfig); break; case "-v": verbose = true; break; case "-t": webThreads = Integer.parseInt(args[++i]); break; case "--primary": collectionUrl = args[++i]; break; case "--update-interval": pollingInterval = Integer.parseInt(args[++i]); break; case "--replication-window": replicationWindow = Long.parseLong(args[++i]); break; default: usage(); break; } } try (DataStore dataStore = new DataStore(dataPath, replicationWindow)) { Webapp controller = new Webapp(dataStore, verbose, dashboardConfig); if (undertow) { UWeb.UServer server = new UWeb.UServer(host, port, controller, authorizer); server.start(); System.out.println("OutbackCDX http://" + (host == null ? "localhost" : host) + ":" + port); Thread.sleep(Long.MAX_VALUE); } else { ServerSocket socket = openSocket(host, port, inheritSocket); Web.Server server = new Web.Server(socket, controller, authorizer); ExecutorService threadPool = Executors.newFixedThreadPool(webThreads); if (collectionUrl != null){ ChangePollingThread cpt = new ChangePollingThread(collectionUrl, pollingInterval, dataStore); cpt.setDaemon(true); cpt.start(); } try { server.setAsyncRunner(threadPool::execute); server.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { server.stop(); dataStore.close(); })); System.out.println("OutbackCDX http://" + (host == null ? "localhost" : host) + ":" + port); Thread.sleep(Long.MAX_VALUE); } finally { threadPool.shutdown(); } } } catch (InterruptedException | IOException e) { e.printStackTrace(); } } private static ServerSocket openSocket(String host, int port, boolean inheritSocket) throws IOException { ServerSocket socket;Channel channel = System.inheritedChannel(); if (inheritSocket && channel instanceof ServerSocketChannel) { socket = ((ServerSocketChannel) channel).socket(); } else { socket = new ServerSocket(port, -1, InetAddress.getByName(host)); } return socket; } }
package abc.player; /** * Header is a mutable type that represents the header of a music piece. * It has the basic informations about the piece, which are: * title, composer, key, meter, tempo (defines the speed of a default note), and index. * */ public class Header { private String composer; private KeySignature key; private Fraction noteLength; private Fraction meter; private int tempo; private String title; private int index; // default values private Fraction DEFAULT_METER = new Fraction(4,4); private Fraction DEFAULT_NOTE_LENGTH = new Fraction(1,8); private int DEFAULT_TEMPO = 100; private String DEFAULT_COMPOSER = "Unknown"; /** * Makes a header with the given index, title, and key. * The meter will be set to 4/4, note length to 1/8, tempo = 100, and composer = "Unknown" * @param index the index of the piece * @param title the title of the piece * @param key the key of the piece */ public Header(int index, String title, KeySignature key){ this.index = index; this.title = title; this.key = key; this.composer = DEFAULT_COMPOSER; this.meter = DEFAULT_METER; this.tempo = DEFAULT_TEMPO; this.noteLength = DEFAULT_NOTE_LENGTH; } /** * * @return the composer of the piece */ public String composer(){ return composer; } /** * * @return the key signature of the piece */ public KeySignature keySignature(){ return key; } /** * * @return the note length of the default note */ public Fraction noteLength(){ return noteLength; } /** * * @return the meter of the piece. */ public Fraction meter(){ return meter; } /** * * @return the tempo of the piece */ public int tempo(){ return tempo; } /** * * @return the title of the piece */ public String title(){ return title; } /** * * @return the index of the piece */ public int index(){ return index; } /** * Sets the composer of the piece to composer * @param composer the name of the composer */ public void setComposer(String composer){ this.composer = composer; } /** * Sets the meter of the piece to the meter * @param meter the meter of the piece */ public void setMeter(Fraction meter){ this.meter = meter; } /** * Sets the tempo of the piece to the tempo * @param tempo the tempo of the piece */ public void setTempo(int tempo){ this.tempo = tempo; } /** * Sets the default note length of the piece to noteLength * @param noteLength the length of the default note */ public void setNoteLength(Fraction noteLength){ this.noteLength = noteLength; } }
package com.nodehope.cordova.plugins.smartlink; import com.hiflying.smartlink.ISmartLinker; import com.hiflying.smartlink.OnSmartLinkListener; import com.hiflying.smartlink.SmartLinkedModule; import com.hiflying.smartlink.v7.MulticastSmartLinker; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.content.Context; public class SmartLink extends CordovaPlugin implements OnSmartLinkListener{ protected ISmartLinker mSnifferSmartLinker; protected CallbackContext mCallbackContext; @Override public void onLinked(final SmartLinkedModule module) { mCallbackContext.success(module.getMac()); } @Override public void onCompleted() { } @Override public void onTimeOut() { mCallbackContext.error(","); } // @Override // protected void onDestroy() { // super.onDestroy(); // mSnifferSmartLinker.setOnSmartLinkListener(null); // mSnifferSmartLinker.stop(); public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { mCallbackContext = callbackContext; if (action.equals("startLink")) { String ssid = args.getString(0); String password = args.getString(1); mSnifferSmartLinker = MulticastSmartLinker.getInstance(); //ssid pswd try { mSnifferSmartLinker.setOnSmartLinkListener(SmartLink.this); // smartLink mSnifferSmartLinker.start(getApplicationContext(), password.trim(), ssid.trim()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); mCallbackContext.error("wifi"); } return true; } else if (action.equals("getWifiInfo")) { WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE); if (wm !=null) { WifiInfo wi = wm.getConnectionInfo(); String ssid = wi.getSSID(); mCallbackContext.success(ssid); } else { mCallbackContext.error("wifi,"); } return true; } return false; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.util.stream.Stream; import javax.swing.*; import javax.swing.plaf.basic.BasicToolBarUI; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JPopupMenu popup = new JPopupMenu(); initMenu(popup); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); initMenu(menu); menuBar.add(menu); EventQueue.invokeLater(() -> getRootPane().setJMenuBar(menuBar)); JToolBar toolBar = new JToolBar(); toolBar.add(new JLabel("Floatable JToolBar:")); toolBar.add(Box.createGlue()); toolBar.add(new ExitAction()); JTree tree = new JTree(); tree.setComponentPopupMenu(popup); add(toolBar, BorderLayout.SOUTH); add(new JScrollPane(tree)); setPreferredSize(new Dimension(320, 240)); } private static void initMenu(JComponent p) { Stream.of( new JMenuItem("Open(dummy)"), new JMenuItem("Save(dummy)"), new JSeparator(), new JMenuItem(new ExitAction())).forEach(p::add); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class ExitAction extends AbstractAction { protected ExitAction() { super("Exit"); } @Override public void actionPerformed(ActionEvent e) { Component root; Container parent = SwingUtilities.getUnwrappedParent((Component) e.getSource()); if (parent instanceof JPopupMenu) { JPopupMenu popup = (JPopupMenu) parent; root = SwingUtilities.getRoot(popup.getInvoker()); } else if (parent instanceof JToolBar) { JToolBar toolbar = (JToolBar) parent; if (((BasicToolBarUI) toolbar.getUI()).isFloating()) { root = SwingUtilities.getWindowAncestor(toolbar).getOwner(); } else { root = SwingUtilities.getRoot(toolbar); } } else { root = SwingUtilities.getRoot(parent); } if (root instanceof Window) { Window window = (Window) root; window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); } } }
package net.jonp.sorm; import java.lang.ref.WeakReference; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; /** * Wraps a database connection and useful metadata used by Sorm. */ public class SormSession { private final Connection _connection; private final String _dialect; // Used for Immediate CacheMode; map of object class onto a map of // identifier onto object private final Map<Class<? extends SormObject>, Map<Object, WeakReference<Object>>> _weakCache = new HashMap<Class<? extends SormObject>, Map<Object, WeakReference<Object>>>(); // TODO: Two strong caches with definite ordering will be needed for Delayed // CacheMode (one for in-use objects, and one for deleted objects) private final CacheMode _cacheMode; private boolean _closed = false; protected SormSession(final Connection connection, final String dialect, final CacheMode cacheMode) { _connection = connection; _dialect = dialect; _cacheMode = cacheMode; // TODO: CacheMode.Delayed is not yet supported if (CacheMode.Delayed == _cacheMode) { throw new UnsupportedOperationException("Delayed CacheMode is not yet implemented."); } } public Connection getConnection() { return _connection; } public String getDialect() { return _dialect; } public CacheMode getCacheMode() { return _cacheMode; } public boolean isClosed() { return _closed; } public void close() throws SQLException { if (!isClosed()) { getConnection().close(); _weakCache.clear(); _closed = true; } } public void cacheAdd(final Class<? extends SormObject> type, final Object key, final Object value) { if (isClosed()) { throw new IllegalStateException(getClass().getSimpleName() + " is closed."); } if (CacheMode.None == getCacheMode()) { // No caching in this mode return; } if (null == value) { // Nothing to do, don't bother evicting since it probably wasn't // here in the first place return; } Map<Object, WeakReference<Object>> typemap; synchronized (_weakCache) { typemap = _weakCache.get(type); if (null == typemap) { typemap = new WeakHashMap<Object, WeakReference<Object>>(); _weakCache.put(type, typemap); } } synchronized (typemap) { typemap.put(key, new WeakReference<Object>(value)); } } public <T> T cacheGet(final Class<T> type, final Object key) { if (isClosed()) { throw new IllegalStateException(getClass().getSimpleName() + " is closed."); } if (CacheMode.None == getCacheMode()) { // No caching in this mode return null; } final Map<Object, WeakReference<Object>> typemap; synchronized (_weakCache) { typemap = _weakCache.get(type); } if (null == typemap) { return null; } final WeakReference<Object> ref = typemap.get(key); if (null == ref) { return null; } return cast(type, ref.get()); } public void cacheDel(final Class<? extends SormObject> type, final Object key) { if (isClosed()) { throw new IllegalStateException(getClass().getSimpleName() + " is closed."); } if (CacheMode.None == getCacheMode()) { // No caching in this mode return; } final Map<Object, WeakReference<Object>> typemap; synchronized (_weakCache) { typemap = _weakCache.get(type); } if (null != typemap) { typemap.remove(key); } } @SuppressWarnings("unchecked") private static <T> T cast(final Class<T> type, final Object o) { return (T)o; } }
package gui; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.Font; public class PanelCabecera extends JPanel { private static final long serialVersionUID = 1L; private Image imagen; public PanelCabecera() { this.setBackground(new Color(0, 100, 172)); String texto = "<html><body><h1><strong>Proyecto DSI</strong></h1>Sistema de informacin dedicado a la asignacin de horarios y salas de clases para la universidad del Bo-Bo.</body></html>"; JLabel lblNewLabel = new JLabel(texto); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblNewLabel.setToolTipText(""); add(lblNewLabel); imagen = new ImageIcon(this.getClass().getResource("/texturaOP.png")).getImage(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int i = imagen.getWidth(this); int j = imagen.getHeight(this); if (i > 0 && j > 0) { for (int x = 0; x < getWidth(); x += i) { for (int y = 0; y < getHeight(); y += j) { g.drawImage(imagen, x, y, i, j, this); } } } } }
package cgeo.geocaching.network; import cgeo.geocaching.R; import cgeo.geocaching.Settings; import cgeo.geocaching.cgBase; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.files.LocalStorage; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.entity.BufferedHttpEntity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.Html; import android.util.Log; import android.view.Display; import android.view.WindowManager; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; public class HtmlImage implements Html.ImageGetter { private static final String[] BLOCKED = new String[] { "gccounter.de", "gccounter.com", "cachercounter/?", "gccounter/imgcount.php", "flagcounter.com", "compteur-blog.net", "counter.digits.com" }; final private Context context; final private String geocode; /** * on error: return large error image, if <code>true</code>, otherwise empty 1x1 image */ final private boolean returnErrorImage; final private int reason; final private boolean onlySave; final private boolean save; final private BitmapFactory.Options bfOptions; final private int maxWidth; final private int maxHeight; public HtmlImage(final Context context, final String geocode, final boolean returnErrorImage, final int reason, final boolean onlySave) { this(context, geocode, returnErrorImage, reason, onlySave, true); } public HtmlImage(final Context contextIn, final String geocode, final boolean returnErrorImage, final int reason, final boolean onlySave, final boolean save) { this.context = contextIn; this.geocode = geocode; this.returnErrorImage = returnErrorImage; this.reason = reason; this.onlySave = onlySave; this.save = save; bfOptions = new BitmapFactory.Options(); bfOptions.inTempStorage = new byte[16 * 1024]; final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); this.maxWidth = display.getWidth() - 25; this.maxHeight = display.getHeight() - 25; } @Override public BitmapDrawable getDrawable(final String url) { // Reject empty and counter images URL if (StringUtils.isBlank(url) || isCounter(url)) { return null; } Bitmap imagePre = null; // Load image from cache if (!onlySave) { imagePre = loadImageFromStorage(url); } // Download image and save it to the cache if (imagePre == null || onlySave) { final String absoluteURL = makeAbsoluteURL(url); BufferedHttpEntity bufferedEntity = null; if (absoluteURL != null) { try { final HttpResponse httpResponse = cgBase.request(absoluteURL, null, false); if (httpResponse != null) { bufferedEntity = new BufferedHttpEntity(httpResponse.getEntity()); } } catch (Exception e) { Log.e(Settings.tag, "HtmlImage.getDrawable (downloading from web)", e); } } if (save) { final File file = LocalStorage.getStorageFile(geocode, url, true); LocalStorage.saveEntityToFile(bufferedEntity, file); } else { setSampleSize(bufferedEntity.getContentLength()); InputStream is; try { is = bufferedEntity.getContent(); imagePre = BitmapFactory.decodeStream(is, null, bfOptions); } catch (IOException e) { Log.e(Settings.tag, "HtmlImage.getDrawable (decoding image)", e); } } } if (onlySave) { return null; } // now load the newly downloaded image if (imagePre == null) { imagePre = loadImageFromStorage(url); } // get image and return if (imagePre == null) { Log.d(Settings.tag, "HtmlImage.getDrawable: Failed to obtain image"); if (returnErrorImage) { imagePre = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_not_loaded); } else { imagePre = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_no_placement); } } final int imgWidth = imagePre.getWidth(); final int imgHeight = imagePre.getHeight(); int width; int height; if (imgWidth > maxWidth || imgHeight > maxHeight) { final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth); width = (int) Math.ceil(imgWidth * ratio); height = (int) Math.ceil(imgHeight * ratio); try { imagePre = Bitmap.createScaledBitmap(imagePre, width, height, true); } catch (Exception e) { Log.d(Settings.tag, "HtmlImage.getDrawable: Failed to scale image"); return null; } } else { width = imgWidth; height = imgHeight; } final BitmapDrawable image = new BitmapDrawable(imagePre); image.setBounds(new Rect(0, 0, width, height)); return image; } private Bitmap loadImageFromStorage(final String url) { try { final File file = LocalStorage.getStorageFile(geocode, url, true); final Bitmap image = loadCachedImage(file); if (image != null) { return image; } final File fileSec = LocalStorage.getStorageSecFile(geocode, url, true); return loadCachedImage(fileSec); } catch (Exception e) { Log.w(Settings.tag, "HtmlImage.getDrawable (reading cache): " + e.toString()); } return null; } private final String makeAbsoluteURL(final String url) { try { // Check if uri is absolute or not, if not attach the connector hostname // FIXME: that should also include the scheme if (Uri.parse(url).isAbsolute()) { return url; } else { final String host = ConnectorFactory.getConnector(geocode).getHost(); if (StringUtils.isNotEmpty(host)) { return "http://" + host + url; } } } catch (Exception e) { Log.e(Settings.tag, "HtmlImage.makeAbsoluteURL (parse URL)", e); } return null; } private Bitmap loadCachedImage(final File file) { if (file.exists()) { if (reason > 0 || file.lastModified() > (new Date().getTime() - (24 * 60 * 60 * 1000))) { setSampleSize(file.length()); return BitmapFactory.decodeFile(file.getPath(), bfOptions); } } return null; } private void setSampleSize(final long imageSize) { // large images will be downscaled on input to save memory if (imageSize > (6 * 1024 * 1024)) { bfOptions.inSampleSize = 48; } else if (imageSize > (4 * 1024 * 1024)) { bfOptions.inSampleSize = 16; } else if (imageSize > (2 * 1024 * 1024)) { bfOptions.inSampleSize = 10; } else if (imageSize > (1 * 1024 * 1024)) { bfOptions.inSampleSize = 6; } else if (imageSize > (0.5 * 1024 * 1024)) { bfOptions.inSampleSize = 2; } } private static boolean isCounter(final String url) { for (String entry : BLOCKED) { if (StringUtils.containsIgnoreCase(url, entry)) { return true; } } return false; } }
//FILE: XYPositionListDlg.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // Nico Stuurman, nico@cmp.ucsf.edu June 23, 2009 //This file is distributed in the hope that it will be useful, //of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. //CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //CVS: $Id$ package org.micromanager; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.Vector; import java.util.prefs.Preferences; import javax.swing.AbstractCellEditor; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SpringLayout; import javax.swing.filechooser.FileFilter; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.StrVector; import org.micromanager.api.DeviceControlGUI; import org.micromanager.navigation.MultiStagePosition; import org.micromanager.navigation.PositionList; import org.micromanager.navigation.StagePosition; import org.micromanager.utils.GUIColors; import org.micromanager.utils.MMDialog; import com.swtdesigner.SwingResourceManager; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.FileDialogs.FileType; import org.micromanager.utils.ReportingUtils; public class PositionListDlg extends MMDialog implements MouseListener { private static final long serialVersionUID = 1L; private static String POSITION_LIST_FILE_NAME = "MMPositionList.pos"; private String posListDir_; private File curFile_; @SuppressWarnings("unused") private static final String MAC_BUTTON_SHAPE = "mini"; private static FileType POSITION_LIST_FILE = new FileType("POSITION_LIST_FILE","Position list file", System.getProperty("user.home") + "/PositionList.pos", true,"pos"); private JTable posTable_; private JTable axisTable_; private SpringLayout springLayout; private CMMCore core_; private DeviceControlGUI dGUI_; private MMOptions opts_; private Preferences prefs_; private TileCreatorDlg tileCreatorDlg_; private GUIColors guiColors_; private AxisList axisList_; private MultiStagePosition curMsp_; public JButton markButtonRef; private class PosTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; public final String[] COLUMN_NAMES = new String[] { "Label", "Position [um]" }; private PositionList posList_; public void setData(PositionList pl) { posList_ = pl; } public PositionList getPositionList() { return posList_; } public int getRowCount() { return posList_.getNumberOfPositions() + 1; } public int getColumnCount() { return COLUMN_NAMES.length; } public String getColumnName(int columnIndex) { return COLUMN_NAMES[columnIndex]; } public Object getValueAt(int rowIndex, int columnIndex) { MultiStagePosition msp; if (rowIndex == 0) msp = curMsp_; else msp = posList_.getPosition(rowIndex -1); if (columnIndex == 0) { if (rowIndex == 0) return ("Current"); return msp.getLabel(); } else if (columnIndex == 1) { StringBuffer sb = new StringBuffer(); for (int i=0; i<msp.size(); i++) { StagePosition sp = msp.get(i); if (i!=0) sb.append(";"); sb.append(sp.getVerbose()); } return sb.toString(); } else return null; } public boolean isCellEditable(int rowIndex, int columnIndex) { if (rowIndex == 0) return false; if (columnIndex == 0) return true; return false; } public void setValueAt(Object value, int rowIndex, int columnIndex) { if (columnIndex == 0) { MultiStagePosition msp = posList_.getPosition(rowIndex - 1); if (msp != null) msp.setLabel(((String) value).replaceAll("[^0-9a-zA-Z_]", "-")); } } } private class AxisData { public AxisData(boolean use, String axisName) { use_ = use; axisName_ = axisName; } public boolean getUse() {return use_;} public String getAxisName() {return axisName_;} public void setUse(boolean use) {use_ = use;} private boolean use_; private String axisName_; } /** * List with Axis data. Currently, we use only a singel global instance of this class */ private class AxisList { private Vector<AxisData> axisList_ = new Vector<AxisData>(); public AxisList() { // Initialize the axisList. try { // add 1D stages StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice); for (int i=0; i<stages.size(); i++) { axisList_.add(new AxisData(prefs_.getBoolean(stages.get(i),true), stages.get(i))); } // read 2-axis stages StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice); for (int i=0; i<stages2D.size(); i++) { axisList_.add(new AxisData(prefs_.getBoolean(stages2D.get(i),true), stages2D.get(i))); } } catch (Exception e) { handleError(e); } } public AxisData get(int i) { if (i >=0 && i < axisList_.size()) return ((AxisData) axisList_.get(i)); return null; } public int getNumberOfPositions() { return axisList_.size(); } public boolean use(String axisName) { for (int i=0; i< axisList_.size(); i++) { if (axisName.equals(get(i).getAxisName())) return get(i).getUse(); } // not in the list?? It might be time to refresh the list. return true; } } /** * Model holding axis data, used to determine which axis will be recorded */ private class AxisTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; public final String[] COLUMN_NAMES = new String[] { "Use", "Axis" }; /* public AxisData getAxisData(int i) { if (i>=0 && i < getRowCount()) return axisList_.get(i); return null; } */ public int getRowCount() { return axisList_.getNumberOfPositions(); } public int getColumnCount() { return COLUMN_NAMES.length; } public String getColumnName(int columnIndex) { return COLUMN_NAMES[columnIndex]; } public Object getValueAt(int rowIndex, int columnIndex) { AxisData aD = axisList_.get(rowIndex); if (aD != null) { if (columnIndex == 0) { return aD.getUse(); } else if (columnIndex == 1) { return aD.getAxisName(); } } return null; } public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int rowIndex, int columnIndex) { if (columnIndex == 0) return true; return false; } public void setValueAt(Object value, int rowIndex, int columnIndex) { if (columnIndex == 0) { axisList_.get(rowIndex).setUse( (Boolean) value); prefs_.putBoolean(axisList_.get(rowIndex).getAxisName(), (Boolean) value); } fireTableCellUpdated(rowIndex, columnIndex); axisTable_.clearSelection(); } } /** * Renders the first row of the position list table */ public class FirstRowRenderer extends JLabel implements TableCellRenderer { private static final long serialVersionUID = 1L; public FirstRowRenderer() { setFont(new Font("Arial", Font.PLAIN, 10)); setOpaque(true); } public Component getTableCellRendererComponent( JTable table, Object text, boolean isSelected, boolean hasFocus, int row, int column) { setText((String) text); setBackground(Color.lightGray); return this; } } /** * Create the dialog */ public PositionListDlg(CMMCore core, DeviceControlGUI dGUI, PositionList posList, MMOptions opts) { super(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent arg0) { savePosition(); } }); core_ = core; dGUI_ = dGUI; opts_ = opts; guiColors_ = new GUIColors(); setTitle("Stage-position List"); springLayout = new SpringLayout(); getContentPane().setLayout(springLayout); setBounds(100, 100, 362, 595); Preferences root = Preferences.userNodeForPackage(this.getClass()); prefs_ = root.node(root.absolutePath() + "/XYPositionListDlg"); setPrefsNode(prefs_); Rectangle r = getBounds(); loadPosition(r.x, r.y, r.width, r.height); setBackground(dGUI_.getBackgroundColor()); dGUI_.addMMBackgroundListener(this); final JScrollPane scrollPane = new JScrollPane(); getContentPane().add(scrollPane); final JScrollPane axisPane = new JScrollPane(); getContentPane().add(axisPane); final TableCellRenderer firstRowRenderer = new FirstRowRenderer(); posTable_ = new JTable() { private static final long serialVersionUID = -3873504142761785021L; public TableCellRenderer getCellRenderer(int row, int column) { if (row == 0) return firstRowRenderer; return super.getCellRenderer(row, column); } }; posTable_.setFont(new Font("Arial", Font.PLAIN, 10)); PosTableModel model = new PosTableModel(); model.setData(posList); posTable_.setModel(model); CellEditor cellEditor_ = new CellEditor(); posTable_.setDefaultEditor(Object.class, cellEditor_); posTable_.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scrollPane.setViewportView(posTable_); posTable_.addMouseListener(this); axisTable_ = new JTable(); axisTable_.setFont(new Font("Arial", Font.PLAIN, 10)); axisList_ = new AxisList(); AxisTableModel axisModel = new AxisTableModel(); axisTable_.setModel(axisModel); axisPane.setViewportView(axisTable_); axisTable_.addMouseListener(this); springLayout.putConstraint(SpringLayout.SOUTH, axisPane, -10, SpringLayout.SOUTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, scrollPane, -10, SpringLayout.NORTH, axisPane); springLayout.putConstraint(SpringLayout.NORTH, scrollPane, 10, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.NORTH, axisPane, -(23 + 23*axisModel.getRowCount()), SpringLayout.SOUTH, getContentPane()); // mark / replace button: JButton markButton = new JButton(); this.markButtonRef = markButton; markButton.setFont(new Font("Arial", Font.PLAIN, 10)); markButton.setMaximumSize(new Dimension(0,0)); markButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { markPosition(); posTable_.clearSelection(); } }); markButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/flag_green.png")); markButton.setText("Mark"); markButton.setToolTipText("Adds point with coordinates of current stage position"); getContentPane().add(markButton); int northConstraint = 17; final int buttonHeight = 27; springLayout.putConstraint(SpringLayout.NORTH, markButton, northConstraint, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, markButton, northConstraint+=buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, markButton, -9, SpringLayout.EAST, getContentPane()); springLayout.putConstraint(SpringLayout.WEST, markButton, -105, SpringLayout.EAST, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, scrollPane, -9, SpringLayout.WEST, markButton); springLayout.putConstraint(SpringLayout.WEST, scrollPane, 10, SpringLayout.WEST, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, axisPane, -9, SpringLayout.WEST, markButton); springLayout.putConstraint(SpringLayout.WEST, axisPane, 10, SpringLayout.WEST, getContentPane()); posTable_.addFocusListener( new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { updateMarkButtonText(); } public void focusGained(java.awt.event.FocusEvent evt) { updateMarkButtonText(); } } ); // the re-ordering buttons: // move selected row up one row final JButton upButton = new JButton(); upButton.setFont(new Font("Arial", Font.PLAIN, 10)); upButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { incrementOrderOfSelectedPosition(-1); } }); upButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/arrow_up.png")); upButton.setText(""); upButton.setToolTipText("Move currently selected position up list (positions higher on list are acquired earlier)"); getContentPane().add(upButton); springLayout.putConstraint(SpringLayout.NORTH, upButton, northConstraint, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, upButton, northConstraint+buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, upButton, -48, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, upButton, 0, SpringLayout.WEST, markButton); // move selected row down one row final JButton downButton = new JButton(); downButton.setFont(new Font("Arial", Font.PLAIN, 10)); downButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { incrementOrderOfSelectedPosition(1); } }); downButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/arrow_down.png")); downButton.setText(""); // "Down" downButton.setToolTipText("Move currently selected position down list (lower positions on list are acquired later)"); getContentPane().add(downButton); springLayout.putConstraint(SpringLayout.NORTH, downButton, northConstraint, SpringLayout.NORTH, getContentPane()); // increment northConstraint for next button.... springLayout.putConstraint(SpringLayout.SOUTH, downButton, northConstraint+=buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, downButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, downButton, 48, SpringLayout.WEST, markButton); // from this point on, the top right button's positions are computed // the Go To button: final JButton gotoButton = new JButton(); gotoButton.setFont(new Font("Arial", Font.PLAIN, 10)); gotoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { goToCurrentPosition(); } }); gotoButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/resultset_next.png")); gotoButton.setText("Go to"); gotoButton.setToolTipText("Moves stage to currently selected position"); getContentPane().add(gotoButton); springLayout.putConstraint(SpringLayout.NORTH, gotoButton, northConstraint, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, gotoButton, northConstraint+=buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, gotoButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, gotoButton, 0, SpringLayout.WEST, markButton); final JButton refreshButton = new JButton(); refreshButton.setFont(new Font("Arial", Font.PLAIN, 10)); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { refreshCurrentPosition(); } }); refreshButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/arrow_refresh.png")); refreshButton.setText("Refresh"); getContentPane().add(refreshButton); springLayout.putConstraint(SpringLayout.NORTH, refreshButton, northConstraint, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, refreshButton, northConstraint+=buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, refreshButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, refreshButton, 0, SpringLayout.WEST, markButton); refreshCurrentPosition(); final JButton removeButton = new JButton(); removeButton.setFont(new Font("Arial", Font.PLAIN, 10)); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { removeCurrentPosition(); } }); removeButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/cross.png")); removeButton.setText("Remove"); removeButton.setToolTipText("Removes currently selected position from list"); getContentPane().add(removeButton); springLayout.putConstraint(SpringLayout.NORTH, removeButton, northConstraint, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, removeButton, northConstraint+=buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, removeButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, removeButton, 0, SpringLayout.WEST, markButton); final JButton setOriginButton = new JButton(); setOriginButton.setFont(new Font("Arial", Font.PLAIN, 10)); setOriginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { calibrate(); //setOrigin(); } }); setOriginButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/empty.png")); setOriginButton.setText("Set Origin"); setOriginButton.setToolTipText("Drives X and Y stages back to their original positions and zeros their position values"); getContentPane().add(setOriginButton); springLayout.putConstraint(SpringLayout.NORTH, setOriginButton, northConstraint, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, setOriginButton, northConstraint+=buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, setOriginButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, setOriginButton, 0, SpringLayout.WEST, markButton); final JButton removeAllButton = new JButton(); removeAllButton.setFont(new Font("Arial", Font.PLAIN, 10)); removeAllButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int ret = JOptionPane.showConfirmDialog(null, "Are you sure you want to erase\nall positions from the position list?", "Clear all positions?", JOptionPane.YES_NO_OPTION); if (ret == JOptionPane.YES_OPTION) clearAllPositions(); } }); removeAllButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/delete.png")); removeAllButton.setText("Clear All"); removeAllButton.setToolTipText("Removes all positions from list"); getContentPane().add(removeAllButton); springLayout.putConstraint(SpringLayout.NORTH, removeAllButton, northConstraint, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, removeAllButton, northConstraint+=buttonHeight, SpringLayout.NORTH, getContentPane()); springLayout.putConstraint(SpringLayout.EAST, removeAllButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, removeAllButton, 0, SpringLayout.WEST, markButton); final JButton closeButton = new JButton(); closeButton.setFont(new Font("Arial", Font.PLAIN, 10)); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { savePosition(); dispose(); } }); closeButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/empty.png")); closeButton.setText("Close"); getContentPane().add(closeButton); springLayout.putConstraint(SpringLayout.SOUTH, closeButton, 0, SpringLayout.SOUTH, axisPane); springLayout.putConstraint(SpringLayout.NORTH, closeButton, -27, SpringLayout.SOUTH, axisPane); springLayout.putConstraint(SpringLayout.EAST, closeButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, closeButton, 0, SpringLayout.WEST, markButton); final JButton tileButton = new JButton(); tileButton.setFont(new Font("Arial", Font.PLAIN, 10)); tileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showCreateTileDlg(); } }); tileButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/empty.png")); tileButton.setText("Create Grid"); tileButton.setToolTipText("Open new window to create grid of equally spaced positions"); getContentPane().add(tileButton); springLayout.putConstraint(SpringLayout.SOUTH, tileButton, -1, SpringLayout.NORTH, closeButton); springLayout.putConstraint(SpringLayout.NORTH, tileButton, -27, SpringLayout.NORTH, closeButton); springLayout.putConstraint(SpringLayout.EAST, tileButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, tileButton, 0, SpringLayout.WEST, markButton); final JButton saveAsButton = new JButton(); saveAsButton.setFont(new Font("Arial", Font.PLAIN, 10)); saveAsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { savePositionListAs(); } }); saveAsButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/empty.png")); saveAsButton.setText("Save As..."); saveAsButton.setToolTipText("Save position list as"); getContentPane().add(saveAsButton); springLayout.putConstraint(SpringLayout.SOUTH, saveAsButton, -28, SpringLayout.NORTH, closeButton); springLayout.putConstraint(SpringLayout.NORTH, saveAsButton, -55, SpringLayout.NORTH, closeButton); springLayout.putConstraint(SpringLayout.EAST, saveAsButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, saveAsButton, 0, SpringLayout.WEST, markButton); final JButton loadButton = new JButton(); loadButton.setFont(new Font("Arial", Font.PLAIN, 10)); loadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { loadPositionList(); } }); loadButton.setIcon(SwingResourceManager.getIcon(PositionListDlg.class, "icons/empty.png")); loadButton.setText("Load..."); loadButton.setToolTipText("Load position list"); getContentPane().add(loadButton); springLayout.putConstraint(SpringLayout.SOUTH, loadButton, -56, SpringLayout.NORTH, closeButton); springLayout.putConstraint(SpringLayout.NORTH, loadButton, -83, SpringLayout.NORTH, closeButton); springLayout.putConstraint(SpringLayout.EAST, loadButton, 0, SpringLayout.EAST, markButton); springLayout.putConstraint(SpringLayout.WEST, loadButton, 0, SpringLayout.WEST, markButton); } protected void updateMarkButtonText() { //String newText; PosTableModel tm = (PosTableModel)posTable_.getModel(); MultiStagePosition msp = tm.getPositionList().getPosition(posTable_.getSelectedRow() - 1); if( null== msp) { markButtonRef.setText("Mark"); } else { markButtonRef.setText("Replace"); } } public void addPosition(MultiStagePosition msp, String label) { PosTableModel ptm = (PosTableModel)posTable_.getModel(); msp.setLabel(label); ptm.getPositionList().addPosition(msp); ptm.fireTableDataChanged(); } public void addPosition(MultiStagePosition msp) { PosTableModel ptm = (PosTableModel)posTable_.getModel(); msp.setLabel(ptm.getPositionList().generateLabel()); ptm.getPositionList().addPosition(msp); ptm.fireTableDataChanged(); } protected boolean savePositionListAs() { File f = FileDialogs.save(this, "Save the position list", POSITION_LIST_FILE); if (f != null) { curFile_ = f; try { getPositionList().save(curFile_.getAbsolutePath()); posListDir_ = curFile_.getParent(); } catch (Exception e) { handleError(e); return false; } return true; } return false; } protected void loadPositionList() { File f = FileDialogs.openFile(this, "Load a position list", POSITION_LIST_FILE); if (f != null) { curFile_ = f; try { getPositionList().load(curFile_.getAbsolutePath()); posListDir_ = curFile_.getParent(); } catch (Exception e) { handleError(e); } finally { updatePositionData(); } } } public void updatePositionData() { PosTableModel ptm = (PosTableModel)posTable_.getModel(); ptm.fireTableDataChanged(); } public void rebuildAxisList() { axisList_ = new AxisList(); AxisTableModel axm = (AxisTableModel)axisTable_.getModel(); axm.fireTableDataChanged(); } public void setPositionList(PositionList pl) { PosTableModel ptm = (PosTableModel)posTable_.getModel(); ptm.setData(pl); ptm.fireTableDataChanged(); } protected void goToCurrentPosition() { PosTableModel ptm = (PosTableModel)posTable_.getModel(); MultiStagePosition msp = ptm.getPositionList().getPosition(posTable_.getSelectedRow() - 1); if (msp == null) return; try { MultiStagePosition.goToPosition(msp, core_); } catch (Exception e) { handleError(e); } refreshCurrentPosition(); } protected void clearAllPositions() { PosTableModel ptm = (PosTableModel)posTable_.getModel(); ptm.getPositionList().clearAllPositions(); ptm.fireTableDataChanged(); } protected void incrementOrderOfSelectedPosition(int direction) { PosTableModel ptm = (PosTableModel)posTable_.getModel(); int currentRow = posTable_.getSelectedRow()-1; int newEdittingRow = -1; if( 0 <= currentRow) { int destinationRow = currentRow + direction; { if (0 <= destinationRow) { if ( destinationRow < posTable_.getRowCount() ) { PositionList pl = ptm.getPositionList(); MultiStagePosition[] mspos =pl.getPositions(); MultiStagePosition tmp = mspos[currentRow]; pl.replacePosition( currentRow, mspos[destinationRow]); pl.replacePosition(destinationRow, tmp); ptm.setData(pl); if( destinationRow+1 < ptm.getRowCount() ) newEdittingRow = destinationRow+1; } else { newEdittingRow = posTable_.getRowCount()-1; } } else { newEdittingRow = 1; } } } ptm.fireTableDataChanged(); if(-1 < newEdittingRow) { posTable_.changeSelection(newEdittingRow, newEdittingRow, false, false); posTable_.requestFocusInWindow(); } updateMarkButtonText(); } protected void removeCurrentPosition() { PosTableModel ptm = (PosTableModel)posTable_.getModel(); ptm.getPositionList().removePosition(posTable_.getSelectedRow() - 1); ptm.fireTableDataChanged(); } /** * Store current xyPosition. * Use data collected in refreshCurrentPosition() */ public void markPosition() { refreshCurrentPosition(); MultiStagePosition msp = new MultiStagePosition(); msp = curMsp_; PosTableModel ptm = (PosTableModel)posTable_.getModel(); MultiStagePosition selMsp = ptm.getPositionList().getPosition(posTable_.getSelectedRow() -1); int selectedRow = 0; if (selMsp == null) { msp.setLabel(ptm.getPositionList().generateLabel()); ptm.getPositionList().addPosition(msp); ptm.fireTableDataChanged(); } else { // replace instead of add msp.setLabel(ptm.getPositionList().getPosition(posTable_.getSelectedRow() - 1).getLabel() ); selectedRow = posTable_.getSelectedRow(); ptm.getPositionList().replacePosition(posTable_.getSelectedRow() -1, msp); ptm.fireTableCellUpdated(selectedRow, 1); // Not sure why this is here as we undo the selecion after this functions exits... posTable_.setRowSelectionInterval(selectedRow, selectedRow); } } /** * Editor component for the position list table */ public class CellEditor extends AbstractCellEditor implements TableCellEditor, FocusListener { private static final long serialVersionUID = 3L; // This is the component that will handle editing of the cell's value JTextField text_ = new JTextField(); int editingCol_; public CellEditor() { super(); text_.addFocusListener(this); } public void focusLost(FocusEvent e) { fireEditingStopped(); } public void focusGained(FocusEvent e) { } // This method is called when a cell value is edited by the user. public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int colIndex) { editingCol_ = colIndex; // Configure the component with the specified value if (colIndex == 0) { text_.setText((String)value); return text_; } return null; } // This method is called when editing is completed. // It must return the new value to be stored in the cell. public Object getCellEditorValue() { if (editingCol_ == 0) { return text_.getText(); } return null; } } /** * Update display of the current xy position. */ private void refreshCurrentPosition() { StringBuffer sb = new StringBuffer(); MultiStagePosition msp = new MultiStagePosition(); msp.setDefaultXYStage(core_.getXYStageDevice()); msp.setDefaultZStage(core_.getFocusDevice()); // read 1-axis stages try { StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice); for (int i=0; i<stages.size(); i++) { if (axisList_.use(stages.get(i))) { StagePosition sp = new StagePosition(); sp.stageName = stages.get(i); sp.numAxes = 1; sp.x = core_.getPosition(stages.get(i)); msp.add(sp); sb.append(sp.getVerbose() + "\n"); } } // read 2-axis stages StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice); for (int i=0; i<stages2D.size(); i++) { if (axisList_.use(stages2D.get(i))) { StagePosition sp = new StagePosition(); sp.stageName = stages2D.get(i); sp.numAxes = 2; sp.x = core_.getXPosition(stages2D.get(i)); sp.y = core_.getYPosition(stages2D.get(i)); msp.add(sp); sb.append(sp.getVerbose() + "\n"); } } } catch (Exception e) { handleError(e); } curMsp_ = msp; PosTableModel ptm = (PosTableModel)posTable_.getModel(); int selectedRow = posTable_.getSelectedRow(); ptm.fireTableCellUpdated(0, 1); if (selectedRow > 0) posTable_.setRowSelectionInterval(selectedRow, selectedRow); } public boolean useDrive(String drive) { return axisList_.use(drive); } protected void showCreateTileDlg() { if (tileCreatorDlg_ == null) { tileCreatorDlg_ = new TileCreatorDlg(core_, opts_, this); dGUI_.addMMBackgroundListener(tileCreatorDlg_); } tileCreatorDlg_.setBackground(guiColors_.background.get(opts_.displayBackground_)); tileCreatorDlg_.setVisible(true); } private PositionList getPositionList() { PosTableModel ptm = (PosTableModel)posTable_.getModel(); return ptm.getPositionList(); } private void handleError(Exception e) { ReportingUtils.showError(e); } /** * Calibrate the XY stage. */ private void calibrate() { JOptionPane.showMessageDialog(this, "ALERT! Please REMOVE objectives! It may damage lens!", "Calibrate the XY stage", JOptionPane.WARNING_MESSAGE); Object[] options = { "Yes", "No"}; if (JOptionPane.YES_OPTION != JOptionPane.showOptionDialog(this, "Really calibrate your XY stage?", "Are you sure?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1])) return ; // calibrate xy-axis stages try { // read 2-axis stages StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice); for (int i=0; i<stages2D.size(); i++) { String deviceName = stages2D.get(i); double [] x1 = new double[1]; double [] y1 = new double[1]; core_.getXYPosition(deviceName,x1,y1); StopCalThread stopThread = new StopCalThread(); CalThread calThread = new CalThread(); stopThread.setPara(calThread, this, deviceName, x1, y1); calThread.setPara(stopThread, this, deviceName, x1, y1); stopThread.start(); Thread.sleep(100); calThread.start(); } } catch (Exception e) { handleError(e); } } class StopCalThread extends Thread{ double [] x1; double [] y1; String deviceName; MMDialog d; Thread otherThread; public void setPara(Thread calThread, MMDialog d, String deviceName, double [] x1, double [] y1) { // if ( calThread==null || d ==null || deviceName==null || x1==null || y1==null){ // JOptionPane.showMessageDialog(d, "parent dialog or x1 or y1 is null!"); this.otherThread = calThread; this.d = d; this.deviceName = deviceName; this.x1 = x1; this.y1 = y1; } public void run() { try { // popup a dialog that says stop the calibration Object[] options = { "Stop" }; int option = JOptionPane.showOptionDialog(d, "Stop calibration?", "Calibration", JOptionPane.CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (option==0) {//stop the calibration otherThread.interrupt(); otherThread = null; if (isInterrupted())return; Thread.sleep(50); core_.stop(deviceName); if (isInterrupted())return; boolean busy = core_.deviceBusy(deviceName); while (busy){ if (isInterrupted())return; core_.stop(deviceName); if (isInterrupted())return; busy = core_.deviceBusy(deviceName); } Object[] options2 = { "Yes", "No" }; option = JOptionPane.showOptionDialog(d, "RESUME calibration?", "Calibration", JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE, null, options2, options2[0]); if (option==1) return; // not to resume, just stop core_.home(deviceName); StopCalThread sct = new StopCalThread(); sct.setPara(this, d, deviceName, x1, y1); busy = core_.deviceBusy(deviceName); if ( busy ) sct.start(); if (isInterrupted())return; busy = core_.deviceBusy(deviceName); while (busy){ if (isInterrupted())return; Thread.sleep(100); if (isInterrupted())return; busy = core_.deviceBusy(deviceName); } sct.interrupt(); sct=null; //calibrate_(deviceName, x1, y1); double [] x2 = new double[1]; double [] y2 = new double[1]; // check if the device busy? busy = core_.deviceBusy(deviceName); int delay=500; //500 ms int period=600000;//600 sec int elapse = 0; while (busy && elapse<period){ Thread.sleep(delay); busy = core_.deviceBusy(deviceName); elapse+=delay; } // now the device is not busy core_.getXYPosition(deviceName,x2,y2); // zero the coordinates core_.setOriginXY(deviceName); BackThread bt = new BackThread(); bt.setPara(d); bt.start(); core_.setXYPosition(deviceName, x1[0]-x2[0], y1[0]-y2[0]); busy = core_.deviceBusy(deviceName); if (isInterrupted())return; busy = core_.deviceBusy(deviceName); while (busy){ if (isInterrupted())return; Thread.sleep(100); if (isInterrupted())return; busy = core_.deviceBusy(deviceName); } bt.interrupt(); bt=null; } } catch (InterruptedException e) { ReportingUtils.logError(e);} catch (Exception e) { handleError(e); } } } class CalThread extends Thread{ double [] x1; double [] y1; String deviceName; MMDialog d; Thread stopThread; public void setPara(Thread stopThread, MMDialog d, String deviceName, double [] x1, double [] y1) { // if ( stopThread==null || d ==null || deviceName==null || x1==null || y1==null){ // JOptionPane.showMessageDialog(d, "parent dialog or x1 or y1 is null!"); this.stopThread = stopThread; this.d = d; this.deviceName = deviceName; this.x1 = x1; this.y1 = y1; } public void run() { try { core_.home(deviceName); // check if the device busy? boolean busy = core_.deviceBusy(deviceName); int delay=500; //500 ms int period=600000;//600 sec int elapse = 0; while (busy && elapse<period){ Thread.sleep(delay); busy = core_.deviceBusy(deviceName); elapse+=delay; } stopThread.interrupt(); stopThread = null; double [] x2 = new double[1]; double [] y2 = new double[1]; core_.getXYPosition(deviceName,x2,y2); // zero the coordinates core_.setOriginXY(deviceName); BackThread bt = new BackThread(); bt.setPara(d); bt.start(); core_.setXYPosition(deviceName, x1[0]-x2[0], y1[0]-y2[0]); busy = core_.deviceBusy(deviceName); if (isInterrupted())return; busy = core_.deviceBusy(deviceName); while (busy){ if (isInterrupted())return; Thread.sleep(100); if (isInterrupted())return; busy = core_.deviceBusy(deviceName); } bt.interrupt(); bt=null; } catch (InterruptedException e) { ReportingUtils.logError(e); } catch (Exception e) { handleError(e); } } } class BackThread extends Thread{ MMDialog d; public void setPara(MMDialog d) { // if ( d ==null ){ // JOptionPane.showMessageDialog(d, "parent dialog is null!"); this.d = d; } public void run() { JOptionPane.showMessageDialog(d, "Going back to the original position!"); } } /* * Implementation of MouseListener * Sole purpose is to be able to unselect rows in the positionlist table */ public void mousePressed (MouseEvent e) {} public void mouseReleased (MouseEvent e) {} public void mouseEntered (MouseEvent e) {} public void mouseExited (MouseEvent e) {} /* * This event is fired after the table sets its selection * Remember where was clicked previously so as to allow for toggling the selected row */ private static int lastRowClicked_; public void mouseClicked (MouseEvent e) { java.awt.Point p = e.getPoint(); int rowIndex = posTable_.rowAtPoint(p); if (rowIndex >= 0) { if (rowIndex == posTable_.getSelectedRow() && rowIndex == lastRowClicked_) { posTable_.clearSelection(); lastRowClicked_ = -1; } else lastRowClicked_ = rowIndex; } updateMarkButtonText(); } }
package org.eddy.ognl; import org.apache.ibatis.ognl.Ognl; import org.apache.ibatis.ognl.OgnlException; import org.eddy.xml.context.XmlDataContext; import org.eddy.xml.data.RuleNode; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; public class OgnlTest { @Test public void test() throws OgnlException { List<RuleNode> dataNodes = XmlDataContext.getContext().getNodes(); Object value = Ognl.getValue("[0].keyColumn.table", dataNodes); System.out.println(value); } @Test public void test2() throws OgnlException { List<RuleNode> dataNodes = XmlDataContext.getContext().getNodes(); Map<String, RuleNode> map = new HashMap<>(); map.put("key1", dataNodes.get(0)); map.put("key2", dataNodes.get(1)); Object value = Ognl.getValue("key1.keyColumn.table", map); System.out.println(value); Object value2 = Ognl.getValue("key2.keyColumn.table", map); System.out.println(value2); } @Test public void test3() throws OgnlException { List<RuleNode> dataNodes = XmlDataContext.getContext().getNodes(); Map<String, List<RuleNode>> map = new HashMap<>(); map.put("key", dataNodes); Object value = Ognl.getValue("key[1].keyColumn.table", map); System.out.println(value); } }
package net.acomputerdog.core.logger; import net.acomputerdog.core.java.Patterns; import net.acomputerdog.core.time.StandardClock; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Writer; /** * Customized logger. Tagged with a name specified by the creator of the logger. * Sample output: * [Test Mod][INFO] This is CLogger.logInfo(). * [UNKNOWN][FATAL] The chat monitor thread has died unexpectedly! * [TPSMonitor][WARNING] The game tick rate has dropped below 50%! * [Awesome Logger of Awesomeness!] I'm Awesome! */ public class CLogger { /** * Clock used by all CLogger instances to print date and time. */ private static final StandardClock loggerClock = new StandardClock(); /** * Default stream for new CLoggers */ private static PrintStream defaultOut = System.out; /** * The PrintWriter used to write Exception output */ private final PrintWriter exceptionLogger; /** * Name used to tag this logger's output. */ private final String name; /** * Include dates in debug messages? */ private boolean includeDate; /** * Include time in debug messages? */ private boolean includeTime; /** * The minimum logging level. */ private LogLevel minimumLogLevel; /** * The PrintStream that this CLogger outputs to. */ private PrintStream loggerOutput; /** * Creates a new CLogger. * @param name The name of this CLogger */ public CLogger(String name) { this(name, false, false); } /** * Creates a new CLogger * * @param name The name of this CLogger * @param includeDate If true, date will be printed with log output * @param includeTime If true, time will be printed with log output */ public CLogger(String name, boolean includeDate, boolean includeTime) { this(name, includeDate, includeTime, LogLevel.DEBUG); } /** * Crates a new CLogger. * * @param name The Name of this CLogger * @param includeDate Set to true to include the date in log messages. * @param includeTime Set to true to include the time in log messages. */ public CLogger(String name, boolean includeDate, boolean includeTime, LogLevel minimumLevel) { this.name = (name == null ? "NULL" : name); this.includeDate = includeDate; this.includeTime = includeTime; this.minimumLogLevel = minimumLevel; this.loggerOutput = defaultOut; this.exceptionLogger = new PrintWriter(new CLoggerWriter()); } /** * Gets the date formatted for display, if enabled. * * @return Returns the date formatted for display, or "" if disabled. */ private String getFormattedDate() { if (includeDate) { return "[" + loggerClock.getDateAsString() + "]"; } else { return ""; } } /** * Gets the time formatted for display, if enabled. * * @return Returns the time formatted for display, or "" if disabled. */ private String getFormattedTime() { if (includeTime) { return "[" + loggerClock.getSimpleTimeAsString() + "]"; } else { return ""; } } /** * Prints out a message in the format [{name}]{message}/n. * * @param message The message to print. */ private void log(String message) { loggerOutput.println(formatMessage(message)); } /** * Formats a message by adding logger name, date, time, etc. * * @param message The message to log * @return Return the formatted string */ protected String formatMessage(String message) { return getFormattedDate() + getFormattedTime() + "[" + name + "]" + message; } /** * Prints out a message in the format [{name}] {message}/n. This will always log, irregardless of the minium log level. * * @param message The message to print. */ public void logRaw(String message) { log(message); } /** * Logs a message with the specified LogLevel, if that level is >= this logger's minimum level * * @param level The level to log at. * @param message The message to log. * @return Return true if the logging as allowed, false otherwise */ public boolean log(LogLevel level, String message) { if (level.isAllowedBy(minimumLogLevel)) { log("[" + level.getLevelName() + "] " + message); return true; } return false; } /** * Prints out a message in the format [{name}][DEBUG] {message}/n, if Debug logging is allowed. * * @param message The message to print. * @return Return true if the logging as allowed, false otherwise */ public boolean logDebug(String message) { return log(LogLevel.DEBUG, message); } /** * Prints out a message in the format [{name}][DETAIL] {message}/n, if Detail logging is enabled. * * @param message The message to print. * @return Return true if the logging as allowed, false otherwise */ public boolean logDetail(String message) { return log(LogLevel.DETAIL, message); } /** * Prints out a message in the format [{name}][INFO] {message}/n, if Info logging is enabled. * * @param message The message to print. * @return Return true if the logging as allowed, false otherwise */ public boolean logInfo(String message) { return log(LogLevel.INFO, message); } /** * Prints out a message in the format [{name}][WARNING] {message}/n, if Warning logging is enabled. * * @param message The message to print. * @return Return true if the logging as allowed, false otherwise */ public boolean logWarning(String message, Throwable... throwables) { if (log(LogLevel.WARNING, message)) { logThrowables(throwables); return true; } return false; } /** * Prints out a message in the format [{name}][ERROR] {message}/n, if Error logging is enabled. * * @param message The message to print. * @param throwables Optional parameter. Exception that has occurred * @return Return true if the logging as allowed, false otherwise */ public boolean logError(String message, Throwable... throwables) { if (log(LogLevel.ERROR, message)) { logThrowables(throwables); return true; } return false; } /** * Prints out a message in the format [{name}][FATAL] {message}/n, if Fatal logging is enabled. * * @param message The message to print. * @param throwables Optional parameter. Exception that has occurred * @return Return true if the logging as allowed, false otherwise */ public boolean logFatal(String message, Throwable... throwables) { if (log(LogLevel.FATAL, message)) { logThrowables(throwables); return true; } return false; } /** * Logs a message with the [STACK] log level. This level will always print, if the level calling it is allowed. * @param message The message to print. */ private void logStack(String message) { log(LogLevel.STACK, message); } /** * Logs one or more Throwables with the [STACK] log level * @param throwables The throwables to log */ private void logThrowables(Throwable... throwables) { for (Throwable t : throwables) { t.printStackTrace(exceptionLogger); } } /** * Checks if this logger will include the date * @return Return true if this logger will include the date. */ public boolean doesIncludeDate() { return includeDate; } /** * Sets if this logger will include the date. * @param includeDate If true, this logger will include the date. If false, it will not. */ public void setIncludeDate(boolean includeDate) { this.includeDate = includeDate; } /** * Checks if this logger will include the time * @return Return true if this logger will include the time. */ public boolean doesIncludeTime() { return includeTime; } /** * Sets if this logger will include the time. * @param includeTime If true, this logger will include the time. If false, it will not. */ public void setIncludeTime(boolean includeTime) { this.includeTime = includeTime; } /** * Gets the minimum logging level of this CLogger. LogLevels below this amount will be hidden. * @return Return the LogLevel of this CLogger. */ public LogLevel getMinimumLogLevel() { return minimumLogLevel; } /** * Sets the minimum logging level of this CLogger. LogLevels below this amount will be hidden. * @param minimumLogLevel The minimum LogLevel to set */ public void setMinimumLogLevel(LogLevel minimumLogLevel) { this.minimumLogLevel = minimumLogLevel; } /** * Gets the name of this CLogger * @return Return the name of this CLogger */ public String getName() { return name; } /** * Gets the PrintStream that this CLogger prints to. * * @return Return the PrintStream that this CLogger prints to. */ public PrintStream getLoggerOutput() { return loggerOutput; } /** * Sets the PrintStream that this CLogger will print to. * @param loggerOutput The PrintStream that this CLogger will output to. Cannot be null. */ public void setLoggerOutput(PrintStream loggerOutput) { if (loggerOutput == null) { throw new IllegalArgumentException("Logger output cannot be null!"); } this.loggerOutput = loggerOutput; } /** * Gets the stream that will be used by new loggers * * @return return the default printStream */ public static PrintStream getDefaultOut() { return defaultOut; } /** * Sets the stream that will be used by new loggers * * @param defaultOut the new stream. cannot be null. */ public static void setDefaultOut(PrintStream defaultOut) { if (defaultOut == null) { throw new IllegalArgumentException("Default stream cannot be null!"); } CLogger.defaultOut = defaultOut; } /** * Writer that outputs to the [STACK] LogLevel of this CLogger. Will print out one item per line, skipping empty lines. Used for printing Exceptions */ private class CLoggerWriter extends Writer { /** * Creates a new CLoggerWriter */ private CLoggerWriter() { super(); } @Override /** * Writes the passed data to the [STACK] LogLevel of this CLogger, skipping empty lines. */ public void write(char[] cbuf, int off, int len) throws IOException { StringBuilder builder = new StringBuilder(); for (int index = off; index < off + len; index++) { char chr = cbuf[index]; builder.append(chr); } if (builder.length() > 0) { String output = builder.toString(); String[] outputs = output.split(Patterns.quote("\n")); for (String out : outputs) { if (!(out.isEmpty() || out.trim().isEmpty())) { logStack(out); } } } } @Override public void flush() throws IOException { //Does nothing } @Override public void close() throws IOException { //Does nothing } } }
package org.jfree.chart.block; import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.ui.Size2D; /** * A description of a constraint for resizing a rectangle. Constraints are * immutable. */ public class RectangleConstraint { /** * An instance representing no constraint. */ public static final RectangleConstraint NONE = new RectangleConstraint( 0.0, null, LengthConstraintType.NONE, 0.0, null, LengthConstraintType.NONE); /** The width. */ private double width; /** The width range. */ private Range widthRange; /** The width constraint type. */ private LengthConstraintType widthConstraintType; /** The fixed or maximum height. */ private double height; private Range heightRange; /** The constraint type. */ private LengthConstraintType heightConstraintType; /** * Creates a new "fixed width and height" instance. * * @param w the fixed width. * @param h the fixed height. */ public RectangleConstraint(double w, double h) { this(w, null, LengthConstraintType.FIXED, h, null, LengthConstraintType.FIXED); } /** * Creates a new "range width and height" instance. * * @param w the width range. * @param h the height range. */ public RectangleConstraint(Range w, Range h) { this(0.0, w, LengthConstraintType.RANGE, 0.0, h, LengthConstraintType.RANGE); } /** * Creates a new constraint with a range for the width and a * fixed height. * * @param w the width range. * @param h the fixed height. */ public RectangleConstraint(Range w, double h) { this(0.0, w, LengthConstraintType.RANGE, h, null, LengthConstraintType.FIXED); } /** * Creates a new constraint with a fixed width and a range for * the height. * * @param w the fixed width. * @param h the height range. */ public RectangleConstraint(double w, Range h) { this(w, null, LengthConstraintType.FIXED, 0.0, h, LengthConstraintType.RANGE); } /** * Creates a new constraint. * * @param w the fixed or maximum width. * @param widthRange the width range. * @param widthConstraintType the width type. * @param h the fixed or maximum height. * @param heightRange the height range. * @param heightConstraintType the height type. */ public RectangleConstraint(double w, Range widthRange, LengthConstraintType widthConstraintType, double h, Range heightRange, LengthConstraintType heightConstraintType) { ParamChecks.nullNotPermitted(widthConstraintType, "widthConstraintType"); ParamChecks.nullNotPermitted(heightConstraintType, "heightConstraintType"); this.width = w; this.widthRange = widthRange; this.widthConstraintType = widthConstraintType; this.height = h; this.heightRange = heightRange; this.heightConstraintType = heightConstraintType; } /** * Returns the fixed width. * * @return The width. */ public double getWidth() { return this.width; } /** * Returns the width range. * * @return The range (possibly <code>null</code>). */ public Range getWidthRange() { return this.widthRange; } /** * Returns the constraint type. * * @return The constraint type (never <code>null</code>). */ public LengthConstraintType getWidthConstraintType() { return this.widthConstraintType; } /** * Returns the fixed height. * * @return The height. */ public double getHeight() { return this.height; } /** * Returns the width range. * * @return The range (possibly <code>null</code>). */ public Range getHeightRange() { return this.heightRange; } /** * Returns the constraint type. * * @return The constraint type (never <code>null</code>). */ public LengthConstraintType getHeightConstraintType() { return this.heightConstraintType; } /** * Returns a constraint that matches this one on the height attributes, * but has no width constraint. * * @return A new constraint. */ public RectangleConstraint toUnconstrainedWidth() { if (this.widthConstraintType == LengthConstraintType.NONE) { return this; } else { return new RectangleConstraint(this.width, this.widthRange, LengthConstraintType.NONE, this.height, this.heightRange, this.heightConstraintType); } } /** * Returns a constraint that matches this one on the width attributes, * but has no height constraint. * * @return A new constraint. */ public RectangleConstraint toUnconstrainedHeight() { if (this.heightConstraintType == LengthConstraintType.NONE) { return this; } else { return new RectangleConstraint(this.width, this.widthRange, this.widthConstraintType, 0.0, this.heightRange, LengthConstraintType.NONE); } } /** * Returns a constraint that matches this one on the height attributes, * but has a fixed width constraint. * * @param width the fixed width. * * @return A new constraint. */ public RectangleConstraint toFixedWidth(double width) { return new RectangleConstraint(width, this.widthRange, LengthConstraintType.FIXED, this.height, this.heightRange, this.heightConstraintType); } /** * Returns a constraint that matches this one on the width attributes, * but has a fixed height constraint. * * @param height the fixed height. * * @return A new constraint. */ public RectangleConstraint toFixedHeight(double height) { return new RectangleConstraint(this.width, this.widthRange, this.widthConstraintType, height, this.heightRange, LengthConstraintType.FIXED); } /** * Returns a constraint that matches this one on the height attributes, * but has a range width constraint. * * @param range the width range (<code>null</code> not permitted). * * @return A new constraint. */ public RectangleConstraint toRangeWidth(Range range) { ParamChecks.nullNotPermitted(range, "range"); return new RectangleConstraint(range.getUpperBound(), range, LengthConstraintType.RANGE, this.height, this.heightRange, this.heightConstraintType); } /** * Returns a constraint that matches this one on the width attributes, * but has a range height constraint. * * @param range the height range (<code>null</code> not permitted). * * @return A new constraint. */ public RectangleConstraint toRangeHeight(Range range) { ParamChecks.nullNotPermitted(range, "range"); return new RectangleConstraint(this.width, this.widthRange, this.widthConstraintType, range.getUpperBound(), range, LengthConstraintType.RANGE); } /** * Returns a string representation of this instance, mostly used for * debugging purposes. * * @return A string. */ public String toString() { return "RectangleConstraint[" + this.widthConstraintType.toString() + ": width=" + this.width + ", height=" + this.height + "]"; } /** * Returns the new size that reflects the constraints defined by this * instance. * * @param base the base size. * * @return The constrained size. */ public Size2D calculateConstrainedSize(Size2D base) { Size2D result = new Size2D(); if (this.widthConstraintType == LengthConstraintType.NONE) { result.width = base.width; if (this.heightConstraintType == LengthConstraintType.NONE) { result.height = base.height; } else if (this.heightConstraintType == LengthConstraintType.RANGE) { result.height = this.heightRange.constrain(base.height); } else if (this.heightConstraintType == LengthConstraintType.FIXED) { result.height = this.height; } } else if (this.widthConstraintType == LengthConstraintType.RANGE) { result.width = this.widthRange.constrain(base.width); if (this.heightConstraintType == LengthConstraintType.NONE) { result.height = base.height; } else if (this.heightConstraintType == LengthConstraintType.RANGE) { result.height = this.heightRange.constrain(base.height); } else if (this.heightConstraintType == LengthConstraintType.FIXED) { result.height = this.height; } } else if (this.widthConstraintType == LengthConstraintType.FIXED) { result.width = this.width; if (this.heightConstraintType == LengthConstraintType.NONE) { result.height = base.height; } else if (this.heightConstraintType == LengthConstraintType.RANGE) { result.height = this.heightRange.constrain(base.height); } else if (this.heightConstraintType == LengthConstraintType.FIXED) { result.height = this.height; } } return result; } }
package graph; import gcm.parser.GCMFile; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.metal.MetalButtonUI; import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import lpn.parser.LhpnFile; import main.Gui; import main.Log; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.StandardTickUnitSource; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.GradientBarPainter; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.title.LegendTitle; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jibble.epsgraphics.EpsGraphics2D; import org.sbml.libsbml.ListOf; import org.sbml.libsbml.Model; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.w3c.dom.DOMImplementation; import parser.TSDParser; import reb2sac.Reb2Sac; import util.Utility; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.DefaultFontMapper; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private XYSeriesCollection curData; // Data in the current graph private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private Gui biomodelsim; // tstubd gui private JButton save, run, saveAs; private JButton export, refresh; // buttons // private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg, // exportCsv; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private LinkedList<GraphProbs> probGraphed; private JCheckBox resize; private JComboBox XVariable; private JCheckBox LogX, LogY; private JCheckBox visibleLegend; private LegendTitle legend; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JButton> colorsButtons; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; private String separator; private boolean change; private boolean timeSeries; private boolean topLevel; private ArrayList<String> graphProbs; private JTree tree; private IconNode node, simDir; private Reb2Sac reb2sac; // reb2sac options private ArrayList<String> learnSpecs; private boolean warn; private ArrayList<String> averageOrder; private JPopupMenu popup; // popup menu private ArrayList<String> directories; private JPanel specPanel; private JScrollPane scrollpane; private JPanel all; private JPanel titlePanel; private JScrollPane scroll; private boolean updateXNumber; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(Reb2Sac reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim, String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) { this.reb2sac = reb2sac; averageOrder = null; popup = new JPopupMenu(); warn = false; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // initializes member variables this.log = log; this.timeSeries = timeSeries; if (graphName != null) { this.graphName = graphName; topLevel = true; } else { if (timeSeries) { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf"; } else { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb"; } topLevel = false; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data = new XYSeriesCollection(); if (learnGraph) { updateSpecies(); } else { learnSpecs = null; } // graph the output data if (timeSeries) { setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, data, time); if (open != null) { open(open); } } else { setUpShapesAndColors(); probGraphed = new LinkedList<GraphProbs>(); selected = ""; lastSelected = ""; probGraph(label); if (open != null) { open(open); } } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.addProgressListener(this); legend = chart.getLegend(); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XVariable = new JComboBox(); updateXNumber = false; XVariable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (updateXNumber && node != null) { String curDir = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName(); } else if (directories.contains(((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent()).getName(); } else { curDir = ""; } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(curDir)) { graphed.get(i).setXNumber(XVariable.getSelectedIndex()); } } } } }); LogX = new JCheckBox("LogX"); LogX.setSelected(false); LogY = new JCheckBox("LogY"); LogY.setSelected(false); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); graphSpecies = new TSDParser(file, true).getSpecies(); Gui.frame.setCursor(null); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); i } } } } /** * This public helper method parses the output file of ODE, monte carlo, and * markov abstractions. */ public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) { warn = warning; String[] s = file.split(separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance")) || (label.contains("deviation") && file.contains("standard_deviation"))) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } if (label.contains("average") || label.contains("variance") || label.contains("deviation")) { int counter = 1; while (!(new File(file).exists())) { file = file.substring(0, file.length() - getLast.length()); file += stem; file += counter + ""; file += "." + printer_id.substring(0, printer_id.length() - 8); counter++; } } if (label.contains("average")) { return calculateAverageVarianceDeviation(file, stem, 0, directory, warn); } else if (label.contains("variance")) { return calculateAverageVarianceDeviation(file, stem, 1, directory, warn); } else if (label.contains("deviation")) { return calculateAverageVarianceDeviation(file, stem, 2, directory, warn); } else { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == run) { reb2sac.getRunButton().doClick(); } if (e.getSource() == save) { save(); } // if the save as button is clicked if (e.getSource() == saveAs) { saveAs(); } // if the export button is clicked else if (e.getSource() == export) { export(); } else if (e.getSource() == refresh) { refresh(); } else if (e.getActionCommand().equals("rename")) { String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { boolean write = true; if (rename.equals(node.getName())) { write = false; } else if (new File(outDir + separator + rename).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(outDir + separator + rename); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) { simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals( "" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(rename)) { graphed.remove(i); i } } } else { write = false; } } if (write) { String getFile = node.getName(); IconNode s = node; while (s.getParent().getParent() != null) { getFile = s.getName() + separator + getFile; s = (IconNode) s.getParent(); } getFile = outDir + separator + getFile; new File(getFile).renameTo(new File(outDir + separator + rename)); for (GraphSpecies spec : graphed) { if (spec.getDirectory().equals(node.getName())) { spec.setDirectory(rename); } } directories.remove(node.getName()); directories.add(rename); node.setUserObject(rename); node.setName(rename); simDir.remove(node); int i; for (i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase( rename) > 0) { simDir.insert(node, i); break; } } else { break; } } simDir.insert(node, i); ArrayList<String> rows = new ArrayList<String>(); for (i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); int select = 0; for (i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } if (rename.equals(node.getName())) { select = i; } } tree.removeTreeSelectionListener(t); addTreeListener(); tree.setSelectionRow(select); } } } else if (e.getActionCommand().equals("delete")) { TreePath[] selected = tree.getSelectionPaths(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) { tree.removeTreeSelectionListener(listen); } tree.addTreeSelectionListener(t); for (TreePath select : selected) { tree.setSelectionPath(select); if (!((IconNode) select.getLastPathComponent()).getName().equals("Average") && !((IconNode) select.getLastPathComponent()).getName().equals("Variance") && !((IconNode) select.getLastPathComponent()).getName().equals( "Standard Deviation") && ((IconNode) select.getLastPathComponent()).getParent() != null) { for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select .getLastPathComponent())) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } directories.remove(((IconNode) select.getLastPathComponent()) .getName()); for (int j = 0; j < graphed.size(); j++) { if (graphed.get(j).getDirectory().equals( ((IconNode) select.getLastPathComponent()).getName())) { graphed.remove(j); j } } } else { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } int count = 0; for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { count++; } } if (count == 3) { for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { simDir.remove(j); j } } } } } else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) { if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select .getLastPathComponent())) { ((IconNode) simDir.getChildAt(i)).remove(j); File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + ((IconNode) select.getLastPathComponent()).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } boolean checked = false; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)) .getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { ((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory .getTreeFolderIcon()); ((IconNode) simDir.getChildAt(i)).setIconName(""); } int count = 0; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)) .getChildCount() == 0) { count++; } } if (count == 3) { File dir2 = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir2.isDirectory()) { biomodelsim.deleteDir(dir2); } else { dir2.delete(); } directories.remove(((IconNode) simDir.getChildAt(i)) .getName()); for (int k = 0; k < graphed.size(); k++) { if (graphed.get(k).getDirectory().equals( ((IconNode) simDir.getChildAt(i)).getName())) { graphed.remove(k); k } } simDir.remove(i); } } } } } } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete runs")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average") && !((IconNode) simDir.getChildAt(i)).getName().equals("Variance") && !((IconNode) simDir.getChildAt(i)).getName().equals( "Standard Deviation")) { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete all")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average") && !((IconNode) simDir.getChildAt(i)).getName().equals("Variance") && !((IconNode) simDir.getChildAt(i)).getName().equals( "Standard Deviation")) { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } } simDir.remove(i); } else { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } // // if the export as jpeg button is clicked // else if (e.getSource() == exportJPeg) { // export(0); // // if the export as png button is clicked // else if (e.getSource() == exportPng) { // export(1); // // if the export as pdf button is clicked // else if (e.getSource() == exportPdf) { // export(2); // // if the export as eps button is clicked // else if (e.getSource() == exportEps) { // export(3); // // if the export as svg button is clicked // else if (e.getSource() == exportSvg) { // export(4); // } else if (e.getSource() == exportCsv) { // export(5); } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); double[][] seriesArray = series.toArray(); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(seriesArray[1][k], maxY); minY = Math.min(seriesArray[1][k], minY); maxX = Math.max(seriesArray[0][k], maxX); minX = Math.min(seriesArray[0][k], minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxY - minY) < .001) { // axis.setRange(minY - 1, maxY + 1); else { /* * axis.setRange(Double.parseDouble(num.format(minY - * (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY + * (Math.abs(maxY) .1)))); */ if ((maxY - minY) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1)); } axis.setAutoTickUnitSelection(true); if (LogY.isSelected()) { try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis() .getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxX - minX) < .001) { // axis.setRange(minX - 1, maxX + 1); else { if ((maxX - minX) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minX, maxX); } axis.setAutoTickUnitSelection(true); if (LogX.isSelected()) { try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis() .getLabel()); domainAxis.setStrictValuesFlag(false); plot.setDomainAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getXYPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { if (e.getSource() != tree) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (timeSeries) { editGraph(); } else { editProbGraph(); } } } } public void mousePressed(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); // colors.put("Red ", draw.getNextPaint()); // colors.put("Blue ", draw.getNextPaint()); // colors.put("Green ", draw.getNextPaint()); // colors.put("Yellow ", draw.getNextPaint()); // colors.put("Magenta ", draw.getNextPaint()); // colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); colors.put("Gray (Light)", new java.awt.Color(238, 238, 238)); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } public void editGraph() { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); LogX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot() .getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setRangeAxis(domainAxis); } catch (Exception e1) { JOptionPane .showMessageDialog( Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis() .getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } }); LogY.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot() .getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane .showMessageDialog( Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis() .getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } } }); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } Properties p = null; if (learnSpecs != null) { try { String[] split = outDir.split(separator); p = new Properties(); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); } catch (Exception e) { } } String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean add = false; boolean addTerm = false; boolean addPercent = false; boolean addConst = false; directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { if (file.contains("run-") || file.contains("mean") || file.contains("variance") || file.contains("standard_deviation")) { add = true; } else if (file.startsWith("term-time")) { addTerm = true; } else if (file.contains("percent-term-time")) { addPercent = true; } else if (file.contains("sim-rep")) { addConst = true; } else { IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring( 0, file.length() - 4)); boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; String[] files3 = new File(outDir + separator + file).list(); // for (int i = 1; i < files3.length; i++) { // String index = files3[i]; // int j = i; // while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) > // files3[j] = files3[j - 1]; // j = j - 1; // files3[j] = index; for (String getFile : files3) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile) .isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); boolean add2 = false; boolean addTerm2 = false; boolean addPercent2 = false; boolean addConst2 = false; for (String f : files3) { if (f.contains(printer_id.substring(0, printer_id.length() - 8))) { if (f.contains("run-") || f.contains("mean") || f.contains("variance") || f.contains("standard_deviation")) { add2 = true; } else if (f.startsWith("term-time")) { addTerm2 = true; } else if (f.contains("percent-term-time")) { addPercent2 = true; } else if (f.contains("sim-rep")) { addConst2 = true; } else { IconNode n = new IconNode(f.substring(0, f.length() - 4), f .substring(0, f.length() - 4)); boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if (d.getChildAt(j).toString() .compareToIgnoreCase(n.toString()) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; String[] files2 = new File(outDir + separator + file + separator + f) .list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; for (String getFile2 : files2) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals( "." + printer_id.substring(0, printer_id .length() - 8))) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); boolean add3 = false; boolean addTerm3 = false; boolean addPercent3 = false; boolean addConst3 = false; for (String f2 : files2) { if (f2.contains(printer_id .substring(0, printer_id.length() - 8))) { if (f2.contains("run-") || f2.contains("mean") || f2.contains("variance") || f2.contains("standard_deviation")) { add3 = true; } else if (f2.startsWith("term-time")) { addTerm3 = true; } else if (f2.contains("percent-term-time")) { addPercent3 = true; } else if (f2.contains("sim-rep")) { addConst3 = true; } else { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); boolean added = false; for (int j = 0; j < d2.getChildCount(); j++) { if (d2.getChildAt(j).toString() .compareToIgnoreCase(n.toString()) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals( f2.substring(0, f2.length() - 4)) && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (add3) { IconNode n = new IconNode("Average", "Average"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm3) { IconNode n = new IconNode("Termination Time", "Termination Time"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent3) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst3) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r2 = null; for (String s : files2) { if (s.contains("run-")) { r2 = s; } } if (r2 != null) { for (String s : files2) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer .parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8)), "run-" + (i + 1)); if (d2.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d2.getChildCount(); j++) { if (d2 .getChildAt(j) .toString() .compareToIgnoreCase( (String) p .get("run-" + (i + 1) + "." + printer_id .substring( 0, printer_id .length() - 8))) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } } else { d2.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase( d2.toString()) > 0) || new File( outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + "." + printer_id .substring(0, printer_id .length() - 8))) .isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (add2) { IconNode n = new IconNode("Average", "Average"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm2) { IconNode n = new IconNode("Termination Time", "Termination Time"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent2) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst2) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r = null; for (String s : files3) { if (s.contains("run-")) { r = s; } } if (r != null) { for (String s : files3) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s .length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d.getChildCount(); j++) { if (d.getChildAt(j).toString().compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8))) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } } else { d.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + "." + printer_id .substring(0, printer_id.length() - 8))).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (add) { IconNode n = new IconNode("Average", "Average"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm) { IconNode n = new IconNode("Termination Time", "Termination Time"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String runs = null; for (String s : new File(outDir).list()) { if (s.contains("run-")) { runs = s; } } if (runs != null) { for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (simDir.getChildCount() > 3) { boolean added = false; for (int j = 3; j < simDir.getChildCount(); j++) { if (simDir.getChildAt(j).toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8))) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } } else { simDir.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { all = new JPanel(new BorderLayout()); specPanel = new JPanel(); scrollpane = new JScrollPane(); refreshTree(); addTreeListener(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); // JButton ok = new JButton("Ok"); /* * ok.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { double minY; double maxY; double * scaleY; double minX; double maxX; double scaleX; change = true; * try { minY = Double.parseDouble(YMin.getText().trim()); maxY = * Double.parseDouble(YMax.getText().trim()); scaleY = * Double.parseDouble(YScale.getText().trim()); minX = * Double.parseDouble(XMin.getText().trim()); maxX = * Double.parseDouble(XMax.getText().trim()); scaleX = * Double.parseDouble(XScale.getText().trim()); NumberFormat num = * NumberFormat.getInstance(); num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { * JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles * into the inputs " + "to change the graph's dimensions!", "Error", * JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; * selected = ""; ArrayList<XYSeries> graphData = new * ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = * (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int * thisOne = -1; for (int i = 1; i < graphed.size(); i++) { * GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && * (graphed.get(j - * 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { * graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, * index); } ArrayList<GraphSpecies> unableToGraph = new * ArrayList<GraphSpecies>(); HashMap<String, * ArrayList<ArrayList<Double>>> allData = new HashMap<String, * ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { * if (g.getDirectory().equals("")) { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8)).exists()) { * readGraphSpecies(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getRunNumber() + * "." + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir).list()) { if * (s.length() > 3 && s.substring(0, 4).equals("run-")) { * ableToGraph = true; } } } catch (Exception e1) { ableToGraph = * false; } if (ableToGraph) { int next = 1; while (!new File(outDir * + separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + "run-" + next + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + "run-1." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame, * y.getText().trim(), g.getRunNumber().toLowerCase(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } else { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getDirectory() + separator + * g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { readGraphSpecies( outDir + * separator + g.getDirectory() + separator + g.getRunNumber() + "." * + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber(), g.getDirectory()); for (int i = 2; i < * graphSpecies.size(); i++) { String index = graphSpecies.get(i); * ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) * && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { * graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, * data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); * data.set(j, index2); } allData.put(g.getRunNumber() + " " + * g.getDirectory(), data); } graphData.add(new * XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = * 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir + separator + * g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, * 4).equals("run-")) { ableToGraph = true; } } } catch (Exception * e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; * while (!new File(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + "run-1." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = * 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : * unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset * = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); * i++) { dataset.addSeries(graphData.get(i)); } * fixGraph(title.getText().trim(), x.getText().trim(), * y.getText().trim(), dataset); * chart.getXYPlot().setRenderer(rend); XYPlot plot = * chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } * else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); * axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); * axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) * plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); * axis.setRange(minX, maxX); axis.setTickUnit(new * NumberTickUnit(scaleX)); } //f.dispose(); } }); */ // final JButton cancel = new JButton("Cancel"); // cancel.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // selected = ""; // int size = graphed.size(); // for (int i = 0; i < size; i++) { // graphed.remove(); // for (GraphSpecies g : old) { // graphed.add(g); // f.dispose(); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n .getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(3, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xMin); titlePanel1.add(XMin); titlePanel1.add(yMin); titlePanel1.add(YMin); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(xMax); titlePanel1.add(XMax); titlePanel1.add(yMax); titlePanel1.add(YMax); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel1.add(xScale); titlePanel1.add(XScale); titlePanel1.add(yScale); titlePanel1.add(YScale); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(resize); titlePanel2.add(XVariable); titlePanel2.add(LogX); titlePanel2.add(LogY); titlePanel2.add(visibleLegend); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); // JPanel buttonPanel = new JPanel(); // buttonPanel.add(ok); // buttonPanel.add(deselect); // buttonPanel.add(cancel); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); // all.add(buttonPanel, "South"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane .showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; change = true; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot() .getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData .put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()) .list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData .put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } } // WindowListener w = new WindowListener() { // public void windowClosing(WindowEvent arg0) { // cancel.doClick(); // public void windowOpened(WindowEvent arg0) { // public void windowClosed(WindowEvent arg0) { // public void windowIconified(WindowEvent arg0) { // public void windowDeiconified(WindowEvent arg0) { // public void windowActivated(WindowEvent arg0) { // public void windowDeactivated(WindowEvent arg0) { // f.addWindowListener(w); // f.setContentPane(all); // f.pack(); // Dimension screenSize; // try { // Toolkit tk = Toolkit.getDefaultToolkit(); // screenSize = tk.getScreenSize(); // catch (AWTError awe) { // screenSize = new Dimension(640, 480); // Dimension frameSize = f.getSize(); // if (frameSize.height > screenSize.height) { // frameSize.height = screenSize.height; // if (frameSize.width > screenSize.width) { // frameSize.width = screenSize.width; // int xx = screenSize.width / 2 - frameSize.width / 2; // int yy = screenSize.height / 2 - frameSize.height / 2; // f.setLocation(xx, yy); // f.setVisible(true); } } private void refreshTree() { tree = new JTree(simDir); if (!topLevel && learnSpecs == null) { tree.addMouseListener(this); } tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); } private void addTreeListener() { boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName()) && node.getParent() != null && !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) { selected = node.getName(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else if (selected.equals("Termination Time")) { select = 0; } else if (selected.equals("Percent Termination")) { select = 0; } else if (selected.equals("Constraint Termination")) { select = 0; } else { try { if (selected.contains("run-")) { select = Integer.parseInt(selected.substring(4)) + 2; } else { select = -1; } } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixGraphChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground( (Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground( (Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground( (Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground( (Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground( (Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground( (Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()) .getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = graphSpecies.get(i + 1); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } else { String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()) .getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } } private JPanel fixGraphChoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) { if (selected.equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) { if (selected.equals("Average") && new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs; if (biomodelsim.lema || biomodelsim.atacs) { specs = new JLabel("Variables"); } else { specs = new JLabel("Species"); } JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connect"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Fill"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k) .setBackground((Color) colory.get("Yellow")); colorsButtons.get(k) .setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground( (Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground( (Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground( (Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground( (Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground( (Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground( (Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground( (Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground( (Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground( (Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground( (Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground( (Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground( (Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground( (Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground( (Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground( (Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground( (Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground( (Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Gray (Light)")); } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } /* * else if * (graph.getShapeAndPaint().getPaintName().equals * ("Red ")) { cols[15]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Blue ")) { cols[16]++; * } else if * (graph.getShapeAndPaint().getPaintName() * .equals("Green ")) { cols[17]++; } else if * (graph. * getShapeAndPaint().getPaintName().equals("Yellow " * )) { cols[18]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getShapeAndPaint().getPaintName * ().equals("Cyan ")) { cols[20]++; } */ else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) { cols[34]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName() .equals("Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i) .getSelectedItem()), color, filled.get(i).isSelected(), visible .get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(), series.get(i).getText().trim(), XVariable .getSelectedIndex(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals( "" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i) .setBackground( (Color) colors.get(((JComboBox) (e.getSource())) .getSelectedItem())); colorsButtons.get(i) .setForeground( (Color) colors.get(((JComboBox) (e.getSource())) .getSelectedItem())); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB()); } } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { curData = dataset; // chart = ChartFactory.createXYLineChart(title, x, y, dataset, // PlotOrientation.VERTICAL, // true, true, false); chart.getXYPlot().setDataset(dataset); chart.setTitle(title); chart.getXYPlot().getDomainAxis().setLabel(x); chart.getXYPlot().getRangeAxis().setLabel(y); // chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); // chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); // chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export() { try { int output = 2; /* Default is currently pdf */ int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".jpg"))) { output = 0; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".png"))) { output = 1; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".pdf"))) { output = 2; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".eps"))) { output = 3; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".svg"))) { output = 4; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".csv"))) { output = 5; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".dat"))) { output = 6; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".tsd"))) { output = 7; } if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void export(int output) { // jpg = 0 // png = 1 // pdf = 2 // eps = 3 // svg = 4 // csv = 5 (data) // dat = 6 (data) // tsd = 7 (data) try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void exportDataFile(File file, int output) { try { int count = curData.getSeries(0).getItemCount(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (curData.getSeries(i).getItemCount() != count) { JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } for (int j = 0; j < count; j++) { Number Xval = curData.getSeries(0).getDataItem(j).getX(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) { JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } } FileOutputStream csvFile = new FileOutputStream(file); PrintWriter csvWriter = new PrintWriter(csvFile); if (output == 7) { csvWriter.print("(("); } else if (output == 6) { csvWriter.print(" } csvWriter.print("\"Time\""); count = curData.getSeries(0).getItemCount(); int pos = 0; for (int i = 0; i < curData.getSeriesCount(); i++) { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print("\"" + curData.getSeriesKey(i) + "\""); if (curData.getSeries(i).getItemCount() > count) { count = curData.getSeries(i).getItemCount(); pos = i; } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } for (int j = 0; j < count; j++) { if (output == 7) { csvWriter.print(","); } for (int i = 0; i < curData.getSeriesCount(); i++) { if (i == 0) { if (output == 7) { csvWriter.print("("); } csvWriter.print(curData.getSeries(pos).getDataItem(j).getX()); } XYSeries data = curData.getSeries(i); if (j < data.getItemCount()) { XYDataItem item = data.getDataItem(j); if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print(item.getY()); } else { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } } if (output == 7) { csvWriter.println(")"); } csvWriter.close(); csvFile.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile, String fileStem, int choice, String directory, boolean warning) { warn = warning; ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); // TSDParser p = new TSDParser(startFile, biomodelsim, false); ArrayList<ArrayList<Double>> data = readData(startFile, "", directory, warn); averageOrder = graphSpecies; boolean first = true; int runsToMake = 1; String[] findNum = startFile.split(separator); String search = findNum[findNum.length - 1]; int firstOne = Integer.parseInt(search.substring(4, search.length() - 4)); if (directory == null) { for (String f : new File(outDir).list()) { if (f.contains(fileStem)) { try { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } catch (Exception e) { } } } } else { for (String f : new File(outDir + separator + directory).list()) { if (f.contains(fileStem)) { try { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } catch (Exception e) { } } } } for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>(); // int count = 0; int skip = firstOne; for (int j = 0; j < runsToMake; j++) { if (!first) { if (firstOne != 1) { j firstOne = 1; } boolean loop = true; while (loop && j < runsToMake && (j + 1) != skip) { if (directory == null) { if (new File(outDir + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8), "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } loop = false; // count++; } else { j++; } } else { if (new File(outDir + separator + directory + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8), "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } loop = false; // count++; } else { j++; } } } } // ArrayList<ArrayList<Double>> data = p.getData(); for (int k = 0; k < data.get(0).size(); k++) { if (first) { double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); dataCounts.put(put, 1); } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } for (int i = 0; i < data.size(); i++) { if (i == 0) { variance.get(i).add((data.get(i)).get(k)); average.get(i).add(put); } else { variance.get(i).add(0.0); average.get(i).add((data.get(i)).get(k)); } } } else { int index = -1; double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); } else { put = (data.get(0)).get(k); } } else if (k == data.get(0).size() - 1 && k == 1) { if (average.get(0).size() > 1) { put = (average.get(0)).get(k); } else { put = (data.get(0)).get(k); } } else { put = (data.get(0)).get(k); } if (average.get(0).contains(put)) { index = average.get(0).indexOf(put); int count = dataCounts.get(put); dataCounts.put(put, count + 1); for (int i = 1; i < data.size(); i++) { double old = (average.get(i)).get(index); (average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1))); double newMean = (average.get(i)).get(index); double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data .get(i)).get(k) - newMean) * ((data.get(i)).get(k) - old)) / count; (variance.get(i)).set(index, vary); } } else { dataCounts.put(put, 1); for (int a = 0; a < average.get(0).size(); a++) { if (average.get(0).get(a) > put) { index = a; break; } } if (index == -1) { index = average.get(0).size() - 1; } average.get(0).add(put); variance.get(0).add(put); for (int a = 1; a < average.size(); a++) { average.get(a).add(data.get(a).get(k)); variance.get(a).add(0.0); } if (index != average.get(0).size() - 1) { for (int a = average.get(0).size() - 2; a >= 0; a if (average.get(0).get(a) > average.get(0).get(a + 1)) { for (int b = 0; b < average.size(); b++) { double temp = average.get(b).get(a); average.get(b).set(a, average.get(b).get(a + 1)); average.get(b).set(a + 1, temp); temp = variance.get(b).get(a); variance.get(b).set(a, variance.get(b).get(a + 1)); variance.get(b).set(a + 1, temp); } } else { break; } } } } } } first = false; } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } averageOrder = null; if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } public void run() { reb2sac.getRunButton().doClick(); } public void save() { if (timeSeries) { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Probability Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public void saveAs() { if (timeSeries) { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1] .length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); if (topLevel) { graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } else { if (graphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + graphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } else { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1] .length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof GradientBarPainter)); graph .setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()) .getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); if (topLevel) { graph.setProperty("species.directory." + i, probGraphed.get(i) .getDirectory()); } else { if (probGraphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + probGraphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Probability Graph Data"); store.close(); log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void open(String filename) { if (timeSeries) { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph .getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot() .setBackgroundPaint( new Color(Integer.parseInt(graph .getProperty("plot.background.paint")))); } if (graph.containsKey("plot.domain.grid.line.paint")) { chart.getXYPlot().setDomainGridlinePaint( new Color(Integer.parseInt(graph .getProperty("plot.domain.grid.line.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getXYPlot().setRangeGridlinePaint( new Color(Integer.parseInt(graph .getProperty("plot.range.grid.line.paint")))); } chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) { LogX.setSelected(true); } else { LogX.setSelected(false); } if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) { LogY.setSelected(true); } else { LogY.setSelected(false); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } int xnumber = 0; if (graph.containsKey("species.xnumber." + next)) { xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next)); } graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next).trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id." + next), graph .getProperty("species.name." + next), xnumber, Integer .parseInt(graph.getProperty("species.number." + next)), graph .getProperty("species.directory." + next))); next++; } updateXNumber = false; XVariable.addItem("time"); refresh(); } catch (IOException except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph .getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot() .setBackgroundPaint( new Color(Integer.parseInt(graph .getProperty("plot.background.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getCategoryPlot().setRangeGridlinePaint( new Color(Integer.parseInt(graph .getProperty("plot.range.grid.line.paint")))); } chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new GradientBarPainter()); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new StandardBarPainter()); } if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { String color = graph.getProperty("species.paint." + next).trim(); Paint paint; if (color.startsWith("Custom_")) { paint = new Color(Integer.parseInt(color.replace("Custom_", ""))); } else { paint = colors.get(color); } probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next), Integer .parseInt(graph.getProperty("species.number." + next)), graph .getProperty("species.directory." + next))); next++; } refreshProb(); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public boolean isTSDGraph() { return timeSeries; } public void refresh() { if (timeSeries) { if (learnSpecs != null) { updateSpecies(); } double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); num.setGroupingUsed(false); * minY = Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + "run-" + // nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + // g.getDirectory() + separator // + "run-" + nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), g.getDirectory(), false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { if (graphProbs.contains(g.getID())) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt") .exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { String compare = g.getID().replace(" (", "~"); if (graphProbs.contains(compare.split("~")[0].trim())) { for (int i = 0; i < graphProbs.size(); i++) { if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis() .getLabel(), chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset, rend); } } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, String p) { shape = s; if (p.startsWith("Custom_")) { paint = new Color(Integer.parseInt(p.replace("Custom_", ""))); } else { paint = colors.get(p); } } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Custom_" + ((Color) paint).getRGB(); } public void setPaint(String paint) { if (paint.startsWith("Custom_")) { this.paint = new Color(Integer.parseInt(paint.replace("Custom_", ""))); } else { this.paint = colors.get(paint); } } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory, id; private int xnumber, number; private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species, int xnumber, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.xnumber = xnumber; this.number = number; this.directory = directory; this.id = id; } private void setDirectory(String directory) { this.directory = directory; } private void setXNumber(int xnumber) { this.xnumber = xnumber; } private void setNumber(int number) { this.number = number; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getXNumber() { return xnumber; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } private String getID() { return id; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } public boolean hasChanged() { return change; } private void probGraph(String label) { chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false); ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new StandardBarPainter()); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); legend = chart.getLegend(); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); } private void editProbGraph() { final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { old.add(g); } final JPanel titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JCheckBox gradient = new JCheckBox("Paint In Gradient Style"); gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof StandardBarPainter)); final JCheckBox shadow = new JCheckBox("Paint Bar Shadows"); shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()) .getShadowsVisible()); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5); String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) { if (file.contains("sim-rep")) { add = true; } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile) .isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); String[] files2 = new File(outDir + separator + file).list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; boolean add2 = false; for (String f : files2) { if (f.equals("sim-rep.txt")) { add2 = true; } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; for (String getFile : new File(outDir + separator + file + separator + f).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); for (String f2 : new File(outDir + separator + file + separator + f) .list()) { if (f2.equals("sim-rep.txt")) { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase( d2.toString()) > 0) || new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt")) .isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (add2) { IconNode n = new IconNode("sim-rep", "sim-rep"); d.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (add) { IconNode n = new IconNode("sim-rep", "sim-rep"); simDir.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { tree = new JTree(simDir); tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); final JPanel all = new JPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } public void treeExpanded(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } }); // for (int i = 0; i < tree.getRowCount(); i++) { // tree.expandRow(i); JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); final JPanel specPanel = new JPanel(); boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName())) { selected = node.getName(); int select; if (selected.equals("sim-rep")) { select = 0; } else { select = -1; } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent()) .getName())); } else { specPanel.add(fixProbChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphProbs.get(i)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground( (Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground( (Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName().split("_")[0]); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground( (Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground( (Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName().split("_")[0]); } } } else { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground( (Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground( (Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName().split("_")[0]); } } } boolean allChecked = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()) .getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = series.get(i).getText(); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); } else { String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()) .getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = graphProbs.get(i); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n .getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(1, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(yLabel); titlePanel1.add(y); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(gradient); titlePanel2.add(shadow); titlePanel2.add(visibleLegend); titlePanel2.add(new JPanel()); titlePanel2.add(new JPanel()); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane .showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { change = true; lastSelected = selected; selected = ""; BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); if (gradient.isSelected()) { rend.setBarPainter(new GradientBarPainter()); } else { rend.setBarPainter(new StandardBarPainter()); } if (shadow.isSelected()) { rend.setShadowVisible(true); } else { rend.setShadowVisible(false); } int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend); } else { selected = ""; int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } for (GraphProbs g : old) { probGraphed.add(g); } } } } private JPanel fixProbChoices(final String directory) { if (directory.equals("")) { readProbSpecies(outDir + separator + "sim-rep.txt"); } else { readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt"); } for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); j = j - 1; } graphProbs.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Constraint"); JLabel color = new JLabel("Color"); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphProbs.size(); i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k) .setBackground((Color) colory.get("Yellow")); colorsButtons.get(k) .setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground( (Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground( (Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground( (Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground( (Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground( (Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground( (Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground( (Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground( (Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground( (Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground( (Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground( (Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground( (Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground( (Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground( (Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground( (Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground( (Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground( (Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground( (Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem() .equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground( (Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground( (Color) colory.get("Gray (Light)")); } } } for (GraphProbs graph : probGraphed) { if (graph.getPaintName().equals("Red")) { cols[0]++; } else if (graph.getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getPaintName().equals("Green")) { cols[2]++; } else if (graph.getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getPaintName().equals("Black")) { cols[14]++; } /* * else if (graph.getPaintName().equals("Red ")) { * cols[15]++; } else if * (graph.getPaintName().equals("Blue ")) { * cols[16]++; } else if * (graph.getPaintName().equals("Green ")) { * cols[17]++; } else if * (graph.getPaintName().equals("Yellow ")) { * cols[18]++; } else if * (graph.getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getPaintName().equals("Cyan ")) { * cols[20]++; } */ else if (graph.getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getPaintName().equals("Gray (Light)")) { cols[34]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText().trim(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals( "" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphProbs g : remove) { probGraphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); } } }); boxes.add(temp); JTextField seriesName = new JTextField(graphProbs.get(i)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i) .setBackground( (Color) colors.get(((JComboBox) (e.getSource())) .getSelectedItem())); colorsButtons.get(i) .setForeground( (Color) colors.get(((JComboBox) (e.getSource())) .getSelectedItem())); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName((String) ((JComboBox) e.getSource()) .getSelectedItem()); g.setPaint(colory .get(((JComboBox) e.getSource()).getSelectedItem())); } } } else { for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB()); g.setPaint(colorsButtons.get(i).getBackground()); } } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); return speciesPanel; } private void readProbSpecies(String file) { graphProbs = new ArrayList<String>(); ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } for (String s : data) { if (!s.split(" ")[0].equals("#total")) { graphProbs.add(s.split(" ")[0]); } } } private double[] readProbs(String file) { ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return new double[0]; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } double[] dataSet = new double[data.size()]; double total = 0; int i = 0; if (data.get(0).split(" ")[0].equals("#total")) { total = Double.parseDouble(data.get(0).split(" ")[1]); i = 1; } for (; i < data.size(); i++) { if (total == 0) { dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]); } else { dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total); } } return dataSet; } private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) { Paint chartBackground = chart.getBackgroundPaint(); Paint plotBackground = chart.getPlot().getBackgroundPaint(); Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint(); chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false); chart.getCategoryPlot().setRenderer(rend); chart.setBackgroundPaint(chartBackground); chart.getPlot().setBackgroundPaint(plotBackground); chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine); ChartPanel graph = new ChartPanel(chart); legend = chart.getLegend(); if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } if (probGraphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } public void refreshProb() { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt") .exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot() .getRangeAxis().getLabel(), histDataset, rend); } private void updateSpecies() { String background; try { Properties p = new Properties(); String[] split = outDir.split(separator); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); background = outDir .substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); background = outDir .substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else { background = null; } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); background = null; } learnSpecs = new ArrayList<String>(); if (background != null) { if (background.contains(".gcm")) { GCMFile gcm = new GCMFile(biomodelsim.getRoot()); gcm.load(background); HashMap<String, Properties> speciesMap = gcm.getSpecies(); for (String s : speciesMap.keySet()) { learnSpecs.add(s); } } else if (background.contains(".lpn")) { LhpnFile lhpn = new LhpnFile(biomodelsim.log); lhpn.load(background); HashMap<String, Properties> speciesMap = lhpn.getContinuous(); /* * for (String s : speciesMap.keySet()) { learnSpecs.add(s); } */ // ADDED BY SB. TSDParser extractVars; ArrayList<String> datFileVars = new ArrayList<String>(); // ArrayList<String> allVars = new ArrayList<String>(); Boolean varPresent = false; // Finding the intersection of all the variables present in all // data files. for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) { extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false); datFileVars = extractVars.getSpecies(); if (i == 1) { learnSpecs.addAll(datFileVars); } for (String s : learnSpecs) { varPresent = false; for (String t : datFileVars) { if (s.equalsIgnoreCase(t)) { varPresent = true; break; } } if (!varPresent) { learnSpecs.remove(s); } } } // END ADDED BY SB. } else { SBMLDocument document = Gui.readSBML(background); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { learnSpecs.add(((Species) ids.get(i)).getId()); } } } for (int i = 0; i < learnSpecs.size(); i++) { String index = learnSpecs.get(i); int j = i; while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) { learnSpecs.set(j, learnSpecs.get(j - 1)); j = j - 1; } learnSpecs.set(j, index); } } public boolean getWarning() { return warn; } private class GraphProbs { private Paint paint; private String species, directory, id, paintName; private int number; private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) { this.paint = paint; this.paintName = paintName; this.species = species; this.number = number; this.directory = directory; this.id = id; } private Paint getPaint() { return paint; } private void setPaint(Paint p) { paint = p; } private String getPaintName() { return paintName; } private void setPaintName(String p) { paintName = p; } private String getSpecies() { return species; } private void setSpecies(String s) { species = s; } private String getDirectory() { return directory; } private String getID() { return id; } private int getNumber() { return number; } private void setNumber(int n) { number = n; } } private Hashtable makeIcons() { Hashtable<String, Icon> icons = new Hashtable<String, Icon>(); icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon()); icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon()); icons.put("computer", MetalIconFactory.getTreeComputerIcon()); icons.put("c", TextIcons.getIcon("c")); icons.put("java", TextIcons.getIcon("java")); icons.put("html", TextIcons.getIcon("html")); return icons; } } class IconNodeRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -940588131120912851L; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); Icon icon = ((IconNode) value).getIcon(); if (icon == null) { Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons"); String name = ((IconNode) value).getIconName(); if ((icons != null) && (name != null)) { icon = (Icon) icons.get(name); if (icon != null) { setIcon(icon); } } } else { setIcon(icon); } return this; } } class IconNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 2887169888272379817L; protected Icon icon; protected String iconName; private String hiddenName; public IconNode() { this(null, ""); } public IconNode(Object userObject, String name) { this(userObject, true, null, name); } public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) { super(userObject, allowsChildren); this.icon = icon; hiddenName = name; } public String getName() { return hiddenName; } public void setName(String name) { hiddenName = name; } public void setIcon(Icon icon) { this.icon = icon; } public Icon getIcon() { return icon; } public String getIconName() { if (iconName != null) { return iconName; } else { String str = userObject.toString(); int index = str.lastIndexOf("."); if (index != -1) { return str.substring(++index); } else { return null; } } } public void setIconName(String name) { iconName = name; } } class TextIcons extends MetalIconFactory.TreeLeafIcon { private static final long serialVersionUID = 1623303213056273064L; protected String label; private static Hashtable<String, String> labels; protected TextIcons() { } public void paintIcon(Component c, Graphics g, int x, int y) { super.paintIcon(c, g, x, y); if (label != null) { FontMetrics fm = g.getFontMetrics(); int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2; int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2; g.drawString(label, x + offsetX, y + offsetY + fm.getHeight()); } } public static Icon getIcon(String str) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } TextIcons icon = new TextIcons(); icon.label = (String) labels.get(str); return icon; } public static void setLabelSet(String ext, String label) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } labels.put(ext, label); } private static void setDefaultSet() { labels.put("c", "C"); labels.put("java", "J"); labels.put("html", "H"); labels.put("htm", "H"); labels.put("g", "" + (char) 10003); // and so on /* * labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc" * ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++"); * labels.put("exe" ,"BIN"); labels.put("class" ,"BIN"); * labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF"); * * labels.put("", ""); */ } }
package graph; import gcm2sbml.parser.GCMFile; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import lhpn2sbml.parser.LhpnFile; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.StandardTickUnitSource; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.GradientBarPainter; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jibble.epsgraphics.EpsGraphics2D; import org.sbml.libsbml.ListOf; import org.sbml.libsbml.Model; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.w3c.dom.DOMImplementation; import parser.TSDParser; import reb2sac.Reb2Sac; import biomodelsim.BioSim; import biomodelsim.Log; import buttons.Buttons; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.DefaultFontMapper; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private XYSeriesCollection curData; // Data in the current graph private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private BioSim biomodelsim; // tstubd gui private JButton save, run, saveAs; private JButton export, refresh; // buttons // private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg, // exportCsv; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private LinkedList<GraphProbs> probGraphed; private JCheckBox resize; private JComboBox XVariable; private JCheckBox LogX, LogY; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; private String separator; private boolean change; private boolean timeSeries; private boolean topLevel; private ArrayList<String> graphProbs; private JTree tree; private IconNode node, simDir; private Reb2Sac reb2sac; // reb2sac options private ArrayList<String> learnSpecs; private boolean warn; private ArrayList<String> averageOrder; private JPopupMenu popup; // popup menu private ArrayList<String> directories; private JPanel specPanel; private JScrollPane scrollpane; private JPanel all; private JPanel titlePanel; private JScrollPane scroll; private boolean updateXNumber; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(Reb2Sac reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, BioSim biomodelsim, String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) { this.reb2sac = reb2sac; averageOrder = null; popup = new JPopupMenu(); warn = false; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // initializes member variables this.log = log; this.timeSeries = timeSeries; if (graphName != null) { this.graphName = graphName; topLevel = true; } else { if (timeSeries) { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf"; } else { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb"; } topLevel = false; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data = new XYSeriesCollection(); if (learnGraph) { updateSpecies(); } else { learnSpecs = null; } // graph the output data if (timeSeries) { setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, data, time); if (open != null) { open(open); } } else { setUpShapesAndColors(); probGraphed = new LinkedList<GraphProbs>(); selected = ""; lastSelected = ""; probGraph(label); if (open != null) { open(open); } } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XVariable = new JComboBox(); updateXNumber = false; XVariable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (updateXNumber && node != null) { String curDir = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName(); } else if (directories.contains(((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent()).getName(); } else { curDir = ""; } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(curDir)) { graphed.get(i).setXNumber(XVariable.getSelectedIndex()); } } } } }); LogX = new JCheckBox("LogX"); LogX.setSelected(false); LogY = new JCheckBox("LogY"); LogY.setSelected(false); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file) { biomodelsim.frame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); graphSpecies = new TSDParser(file, biomodelsim, true).getSpecies(); biomodelsim.frame().setCursor(null); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); i } } } } /** * This public helper method parses the output file of ODE, monte carlo, and * markov abstractions. */ public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) { warn = warning; String[] s = file.split(separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance")) || (label.contains("deviation") && file.contains("standard_deviation"))) { biomodelsim.frame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, biomodelsim, warn); biomodelsim.frame().setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } if (label.contains("average") || label.contains("variance") || label.contains("deviation")) { int counter = 1; while (!(new File(file).exists())) { file = file.substring(0, file.length() - getLast.length()); file += stem; file += counter + ""; file += "." + printer_id.substring(0, printer_id.length() - 8); counter++; } } if (label.contains("average")) { return calculateAverageVarianceDeviation(file, stem, 0, directory, warn); } else if (label.contains("variance")) { return calculateAverageVarianceDeviation(file, stem, 1, directory, warn); } else if (label.contains("deviation")) { return calculateAverageVarianceDeviation(file, stem, 2, directory, warn); } else { biomodelsim.frame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, biomodelsim, warn); biomodelsim.frame().setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == run) { reb2sac.getRunButton().doClick(); } if (e.getSource() == save) { save(); } // if the save as button is clicked if (e.getSource() == saveAs) { saveAs(); } // if the export button is clicked else if (e.getSource() == export) { export(); } else if (e.getSource() == refresh) { refresh(); } else if (e.getActionCommand().equals("rename")) { String rename = JOptionPane.showInputDialog(biomodelsim.frame(), "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { boolean write = true; if (rename.equals(node.getName())) { write = false; } else if (new File(outDir + separator + rename).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(outDir + separator + rename); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) { simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals( "" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(rename)) { graphed.remove(i); i } } } else { write = false; } } if (write) { String getFile = node.getName(); IconNode s = node; while (s.getParent().getParent() != null) { getFile = s.getName() + separator + getFile; s = (IconNode) s.getParent(); } getFile = outDir + separator + getFile; new File(getFile).renameTo(new File(outDir + separator + rename)); for (GraphSpecies spec : graphed) { if (spec.getDirectory().equals(node.getName())) { spec.setDirectory(rename); } } directories.remove(node.getName()); directories.add(rename); node.setUserObject(rename); node.setName(rename); simDir.remove(node); int i; for (i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase( rename) > 0) { simDir.insert(node, i); break; } } else { break; } } simDir.insert(node, i); ArrayList<String> rows = new ArrayList<String>(); for (i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); int select = 0; for (i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } if (rename.equals(node.getName())) { select = i; } } tree.removeTreeSelectionListener(t); addTreeListener(); tree.setSelectionRow(select); } } } else if (e.getActionCommand().equals("delete")) { TreePath[] selected = tree.getSelectionPaths(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) { tree.removeTreeSelectionListener(listen); } tree.addTreeSelectionListener(t); for (TreePath select : selected) { tree.setSelectionPath(select); if (!((IconNode) select.getLastPathComponent()).getName().equals("Average") && !((IconNode) select.getLastPathComponent()).getName().equals("Variance") && !((IconNode) select.getLastPathComponent()).getName().equals( "Standard Deviation") && ((IconNode) select.getLastPathComponent()).getParent() != null) { for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select .getLastPathComponent())) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } directories.remove(((IconNode) select.getLastPathComponent()) .getName()); for (int j = 0; j < graphed.size(); j++) { if (graphed.get(j).getDirectory().equals( ((IconNode) select.getLastPathComponent()).getName())) { graphed.remove(j); j } } } else { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } int count = 0; for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { count++; } } if (count == 3) { for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { simDir.remove(j); j } } } } } else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) { if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select .getLastPathComponent())) { ((IconNode) simDir.getChildAt(i)).remove(j); File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + ((IconNode) select.getLastPathComponent()).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } boolean checked = false; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)) .getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { ((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory .getTreeFolderIcon()); ((IconNode) simDir.getChildAt(i)).setIconName(""); } int count = 0; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)) .getChildCount() == 0) { count++; } } if (count == 3) { File dir2 = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir2.isDirectory()) { biomodelsim.deleteDir(dir2); } else { dir2.delete(); } directories.remove(((IconNode) simDir.getChildAt(i)) .getName()); for (int k = 0; k < graphed.size(); k++) { if (graphed.get(k).getDirectory().equals( ((IconNode) simDir.getChildAt(i)).getName())) { graphed.remove(k); k } } simDir.remove(i); } } } } } } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete runs")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average") && !((IconNode) simDir.getChildAt(i)).getName().equals("Variance") && !((IconNode) simDir.getChildAt(i)).getName().equals( "Standard Deviation")) { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete all")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average") && !((IconNode) simDir.getChildAt(i)).getName().equals("Variance") && !((IconNode) simDir.getChildAt(i)).getName().equals( "Standard Deviation")) { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } } simDir.remove(i); } else { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } // // if the export as jpeg button is clicked // else if (e.getSource() == exportJPeg) { // export(0); // // if the export as png button is clicked // else if (e.getSource() == exportPng) { // export(1); // // if the export as pdf button is clicked // else if (e.getSource() == exportPdf) { // export(2); // // if the export as eps button is clicked // else if (e.getSource() == exportEps) { // export(3); // // if the export as svg button is clicked // else if (e.getSource() == exportSvg) { // export(4); // } else if (e.getSource() == exportCsv) { // export(5); } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); double[][] seriesArray = series.toArray(); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(seriesArray[1][k], maxY); minY = Math.min(seriesArray[1][k], minY); maxX = Math.max(seriesArray[0][k], maxX); minX = Math.min(seriesArray[0][k], minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxY - minY) < .001) { // axis.setRange(minY - 1, maxY + 1); else { /* * axis.setRange(Double.parseDouble(num.format(minY - * (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY + * (Math.abs(maxY) .1)))); */ if ((maxY - minY) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1)); } axis.setAutoTickUnitSelection(true); if (LogY.isSelected()) { try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis() .getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxX - minX) < .001) { // axis.setRange(minX - 1, maxX + 1); else { if ((maxX - minX) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } axis.setRange(minX, maxX); } axis.setAutoTickUnitSelection(true); if (LogX.isSelected()) { try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis() .getLabel()); domainAxis.setStrictValuesFlag(false); plot.setDomainAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getXYPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { if (e.getSource() != tree) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (timeSeries) { editGraph(); } else { editProbGraph(); } } } } public void mousePressed(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); // colors.put("Red ", draw.getNextPaint()); // colors.put("Blue ", draw.getNextPaint()); // colors.put("Green ", draw.getNextPaint()); // colors.put("Yellow ", draw.getNextPaint()); // colors.put("Magenta ", draw.getNextPaint()); // colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); colors.put("Gray (Light)", new java.awt.Color(238, 238, 238)); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } private void editGraph() { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); LogX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot() .getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setRangeAxis(domainAxis); } catch (Exception e1) { JOptionPane .showMessageDialog( biomodelsim.frame(), "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis() .getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } }); LogY.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot() .getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane .showMessageDialog( biomodelsim.frame(), "Semilog plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis() .getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } } }); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } Properties p = null; if (learnSpecs != null) { try { String[] split = outDir.split(separator); p = new Properties(); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); } catch (Exception e) { } } String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); for (int i = 1; i < files.length; i++) { String index = files[i]; int j = i; while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { files[j] = files[j - 1]; j = j - 1; } files[j] = index; } boolean add = false; directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { if (file.contains("run-") || file.contains("mean") || file.contains("variance") || file.contains("standard_deviation")) { add = true; } else { IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring( 0, file.length() - 4)); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; String[] files3 = new File(outDir + separator + file).list(); for (int i = 1; i < files3.length; i++) { String index = files3[i]; int j = i; while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) > 0) { files3[j] = files3[j - 1]; j = j - 1; } files3[j] = index; } for (String getFile : files3) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile) .isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); boolean add2 = false; for (String f : files3) { if (f.contains(printer_id.substring(0, printer_id.length() - 8))) { if (f.contains("run-") || f.contains("mean") || f.contains("variance") || f.contains("standard_deviation")) { add2 = true; } else { IconNode n = new IconNode(f.substring(0, f.length() - 4), f .substring(0, f.length() - 4)); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; String[] files2 = new File(outDir + separator + file + separator + f) .list(); for (int i = 1; i < files2.length; i++) { String index = files2[i]; int j = i; while ((j > 0) && files2[j - 1].compareToIgnoreCase(index) > 0) { files2[j] = files2[j - 1]; j = j - 1; } files2[j] = index; } for (String getFile2 : files2) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals( "." + printer_id.substring(0, printer_id .length() - 8))) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); boolean add3 = false; for (String f2 : files2) { if (f2.contains(printer_id .substring(0, printer_id.length() - 8))) { if (f2.contains("run-") || f2.contains("mean") || f2.contains("variance") || f2.contains("standard_deviation")) { add3 = true; } else { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals( f2.substring(0, f2.length() - 4)) && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (add3) { IconNode n = new IconNode("Average", "Average"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r2 = null; for (String s : files2) { if (s.contains("run-")) { r2 = s; } } if (r2 != null) { for (String s : files2) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer .parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8)), "run-" + (i + 1)); if (d2.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d2.getChildCount(); j++) { if (d2 .getChildAt(j) .toString() .compareToIgnoreCase( (String) p .get("run-" + (i + 1) + "." + printer_id .substring( 0, printer_id .length() - 8))) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } } else { d2.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } d.add(d2); } } } if (add2) { IconNode n = new IconNode("Average", "Average"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r = null; for (String s : files3) { if (s.contains("run-")) { r = s; } } if (r != null) { for (String s : files3) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s .length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d.getChildCount(); j++) { if (d.getChildAt(j).toString().compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8))) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } } else { d.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } simDir.add(d); } } } if (add) { IconNode n = new IconNode("Average", "Average"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String runs = null; for (String s : new File(outDir).list()) { if (s.contains("run-")) { runs = s; } } if (runs != null) { for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (simDir.getChildCount() > 3) { boolean added = false; for (int j = 3; j < simDir.getChildCount(); j++) { if (simDir.getChildAt(j).toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8))) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } } else { simDir.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { all = new JPanel(new BorderLayout()); specPanel = new JPanel(); scrollpane = new JScrollPane(); refreshTree(); addTreeListener(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); // JButton ok = new JButton("Ok"); /* * ok.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { double minY; double maxY; double * scaleY; double minX; double maxX; double scaleX; change = true; * try { minY = Double.parseDouble(YMin.getText().trim()); maxY = * Double.parseDouble(YMax.getText().trim()); scaleY = * Double.parseDouble(YScale.getText().trim()); minX = * Double.parseDouble(XMin.getText().trim()); maxX = * Double.parseDouble(XMax.getText().trim()); scaleX = * Double.parseDouble(XScale.getText().trim()); NumberFormat num = * NumberFormat.getInstance(); num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { * JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter * doubles into the inputs " + "to change the graph's * dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } * lastSelected = selected; selected = ""; ArrayList<XYSeries> * graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer * rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); * int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { * GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && * (graphed.get(j - * 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { * graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, * index); } ArrayList<GraphSpecies> unableToGraph = new * ArrayList<GraphSpecies>(); HashMap<String, * ArrayList<ArrayList<Double>>> allData = new HashMap<String, * ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { * if (g.getDirectory().equals("")) { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8)).exists()) { * readGraphSpecies(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8), * biomodelsim.frame()); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getRunNumber() + * "." + printer_id.substring(0, printer_id.length() - 8), * biomodelsim.frame(), y.getText().trim(), g.getRunNumber(), null); * for (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir).list()) { if * (s.length() > 3 && s.substring(0, 4).equals("run-")) { * ableToGraph = true; } } } catch (Exception e1) { ableToGraph = * false; } if (ableToGraph) { int next = 1; while (!new File(outDir * + separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + "run-" + next + "." + * printer_id.substring(0, printer_id.length() - 8), * biomodelsim.frame()); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + "run-1." + * printer_id.substring(0, printer_id.length() - 8), * biomodelsim.frame(), y.getText().trim(), * g.getRunNumber().toLowerCase(), null); for (int i = 2; i < * graphSpecies.size(); i++) { String index = graphSpecies.get(i); * ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) * && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { * graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, * data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); * data.set(j, index2); } allData.put(g.getRunNumber() + " " + * g.getDirectory(), data); } graphData.add(new * XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = * 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } else { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getDirectory() + separator + * g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { readGraphSpecies( outDir + * separator + g.getDirectory() + separator + g.getRunNumber() + "." * + printer_id.substring(0, printer_id.length() - 8), * biomodelsim.frame()); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8), biomodelsim.frame(), * y.getText().trim(), g.getRunNumber(), g.getDirectory()); for (int * i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir + separator + * g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, * 4).equals("run-")) { ableToGraph = true; } } } catch (Exception * e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; * while (!new File(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8), biomodelsim.frame()); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + "run-1." + printer_id.substring(0, * printer_id.length() - 8), biomodelsim.frame(), * y.getText().trim(), g.getRunNumber().toLowerCase(), * g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) * { String index = graphSpecies.get(i); ArrayList<Double> index2 = * data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : * unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset * = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); * i++) { dataset.addSeries(graphData.get(i)); } * fixGraph(title.getText().trim(), x.getText().trim(), * y.getText().trim(), dataset); * chart.getXYPlot().setRenderer(rend); XYPlot plot = * chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } * else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); * axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); * axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) * plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); * axis.setRange(minX, maxX); axis.setTickUnit(new * NumberTickUnit(scaleX)); } //f.dispose(); } }); */ // final JButton cancel = new JButton("Cancel"); // cancel.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // selected = ""; // int size = graphed.size(); // for (int i = 0; i < size; i++) { // graphed.remove(); // for (GraphSpecies g : old) { // graphed.add(g); // f.dispose(); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n .getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(3, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xMin); titlePanel1.add(XMin); titlePanel1.add(yMin); titlePanel1.add(YMin); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(xMax); titlePanel1.add(XMax); titlePanel1.add(yMax); titlePanel1.add(YMax); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel1.add(xScale); titlePanel1.add(XScale); titlePanel1.add(yScale); titlePanel1.add(YScale); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(resize); titlePanel2.add(XVariable); titlePanel2.add(LogX); titlePanel2.add(new JPanel()); titlePanel2.add(LogY); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); // JPanel buttonPanel = new JPanel(); // buttonPanel.add(ok); // buttonPanel.add(deselect); // buttonPanel.add(cancel); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); // all.add(buttonPanel, "South"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane .showOptionDialog(biomodelsim.frame(), all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; change = true; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot() .getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData .put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()) .list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData .put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } } // WindowListener w = new WindowListener() { // public void windowClosing(WindowEvent arg0) { // cancel.doClick(); // public void windowOpened(WindowEvent arg0) { // public void windowClosed(WindowEvent arg0) { // public void windowIconified(WindowEvent arg0) { // public void windowDeiconified(WindowEvent arg0) { // public void windowActivated(WindowEvent arg0) { // public void windowDeactivated(WindowEvent arg0) { // f.addWindowListener(w); // f.setContentPane(all); // f.pack(); // Dimension screenSize; // try { // Toolkit tk = Toolkit.getDefaultToolkit(); // screenSize = tk.getScreenSize(); // catch (AWTError awe) { // screenSize = new Dimension(640, 480); // Dimension frameSize = f.getSize(); // if (frameSize.height > screenSize.height) { // frameSize.height = screenSize.height; // if (frameSize.width > screenSize.width) { // frameSize.width = screenSize.width; // int xx = screenSize.width / 2 - frameSize.width / 2; // int yy = screenSize.height / 2 - frameSize.height / 2; // f.setLocation(xx, yy); // f.setVisible(true); } } private void refreshTree() { tree = new JTree(simDir); if (!topLevel && learnSpecs == null) { tree.addMouseListener(this); } tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); } private void addTreeListener() { boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName()) && node.getParent() != null && !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) { selected = node.getName(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else { try { if (selected.contains("run-")) { select = Integer.parseInt(selected.substring(4)) + 2; } else { select = -1; } } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixGraphChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()) .getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = graphSpecies.get(i + 1); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); } else { String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()) .getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } } private JPanel fixGraphChoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { if (selected.equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { if (selected.equals("Average") && new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs; if (biomodelsim.lema || biomodelsim.atacs) { specs = new JLabel("Variables"); } else { specs = new JLabel("Species"); } JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connect"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Fill"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Green (Dark)")) { cols[10]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Blue (Light)")) { cols[29]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Cyan (Light)")) { cols[33]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Gray (Light)")) { cols[34]++; } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } /* * else if * (graph.getShapeAndPaint().getPaintName().equals * ("Red ")) { cols[15]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Blue ")) { cols[16]++; * } else if * (graph.getShapeAndPaint().getPaintName() * .equals("Green ")) { cols[17]++; } else if * (graph. * getShapeAndPaint().getPaintName().equals("Yellow " * )) { cols[18]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getShapeAndPaint().getPaintName * ().equals("Cyan ")) { cols[20]++; } */ else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) { cols[34]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName() .equals("Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i) .getSelectedItem()), colory.get(colorsCombo.get(i) .getSelectedItem()), filled.get(i).isSelected(), visible.get(i) .isSelected(), connected.get(i).isSelected(), selected, boxes .get(i).getName(), series.get(i).getText().trim(), XVariable .getSelectedIndex(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals( "" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); Object[] col = this.colors.keySet().toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorsCombo.get(i)); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { curData = dataset; chart = ChartFactory.createXYLineChart(title, x, y, dataset, PlotOrientation.VERTICAL, true, true, false); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export() { try { int output = 2; /* Default is currently pdf */ int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Buttons.browse(biomodelsim.frame(), file, null, JFileChooser.FILES_ONLY, export, output); if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".jpg"))) { output = 0; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".png"))) { output = 1; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".pdf"))) { output = 2; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".eps"))) { output = 3; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".svg"))) { output = 4; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".csv"))) { output = 5; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".dat"))) { output = 6; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".tsd"))) { output = 7; } if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void export(int output) { // jpg = 0 // png = 1 // pdf = 2 // eps = 3 // svg = 4 // csv = 5 (data) // dat = 6 (data) // tsd = 7 (data) try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Buttons.browse(biomodelsim.frame(), file, null, JFileChooser.FILES_ONLY, export, output); if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void exportDataFile(File file, int output) { try { int count = curData.getSeries(0).getItemCount(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (curData.getSeries(i).getItemCount() != count) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Data series do not have the same number of points!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } for (int j = 0; j < count; j++) { Number Xval = curData.getSeries(0).getDataItem(j).getX(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Data series time points are not the same!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } } FileOutputStream csvFile = new FileOutputStream(file); PrintWriter csvWriter = new PrintWriter(csvFile); if (output == 7) { csvWriter.print("(("); } else if (output == 6) { csvWriter.print(" } csvWriter.print("\"Time\""); count = curData.getSeries(0).getItemCount(); int pos = 0; for (int i = 0; i < curData.getSeriesCount(); i++) { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print("\"" + curData.getSeriesKey(i) + "\""); if (curData.getSeries(i).getItemCount() > count) { count = curData.getSeries(i).getItemCount(); pos = i; } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } for (int j = 0; j < count; j++) { if (output == 7) { csvWriter.print(","); } for (int i = 0; i < curData.getSeriesCount(); i++) { if (i == 0) { if (output == 7) { csvWriter.print("("); } csvWriter.print(curData.getSeries(pos).getDataItem(j).getX()); } XYSeries data = curData.getSeries(i); if (j < data.getItemCount()) { XYDataItem item = data.getDataItem(j); if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print(item.getY()); } else { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } } if (output == 7) { csvWriter.println(")"); } csvWriter.close(); csvFile.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile, String fileStem, int choice, String directory, boolean warning) { warn = warning; ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); // TSDParser p = new TSDParser(startFile, biomodelsim, false); ArrayList<ArrayList<Double>> data = readData(startFile, "", directory, warn); averageOrder = graphSpecies; boolean first = true; int runsToMake = 1; String[] findNum = startFile.split(separator); String search = findNum[findNum.length - 1]; int firstOne = Integer.parseInt(search.substring(4, search.length() - 4)); if (directory == null) { for (String f : new File(outDir).list()) { if (f.contains(fileStem)) { try { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } catch (Exception e) { } } } } else { for (String f : new File(outDir + separator + directory).list()) { if (f.contains(fileStem)) { try { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } catch (Exception e) { } } } } for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>(); // int count = 0; int skip = firstOne; for (int j = 0; j < runsToMake; j++) { if (!first) { if (firstOne != 1) { j firstOne = 1; } boolean loop = true; while (loop && j < runsToMake && (j + 1) != skip) { if (directory == null) { if (new File(outDir + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8), "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } loop = false; // count++; } else { j++; } } else { if (new File(outDir + separator + directory + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8), "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } loop = false; // count++; } else { j++; } } } } // ArrayList<ArrayList<Double>> data = p.getData(); for (int k = 0; k < data.get(0).size(); k++) { if (first) { double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); dataCounts.put(put, 1); } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } for (int i = 0; i < data.size(); i++) { if (i == 0) { variance.get(i).add((data.get(i)).get(k)); average.get(i).add(put); } else { variance.get(i).add(0.0); average.get(i).add((data.get(i)).get(k)); } } } else { int index = -1; double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); } else { put = (data.get(0)).get(k); } } else if (k == data.get(0).size() - 1 && k == 1) { if (average.get(0).size() > 1) { put = (average.get(0)).get(k); } else { put = (data.get(0)).get(k); } } else { put = (data.get(0)).get(k); } if (average.get(0).contains(put)) { index = average.get(0).indexOf(put); int count = dataCounts.get(put); dataCounts.put(put, count + 1); for (int i = 1; i < data.size(); i++) { double old = (average.get(i)).get(index); (average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1))); double newMean = (average.get(i)).get(index); double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data .get(i)).get(k) - newMean) * ((data.get(i)).get(k) - old)) / count; (variance.get(i)).set(index, vary); } } else { dataCounts.put(put, 1); for (int a = 0; a < average.get(0).size(); a++) { if (average.get(0).get(a) > put) { index = a; break; } } if (index == -1) { index = average.get(0).size() - 1; } average.get(0).add(put); variance.get(0).add(put); for (int a = 1; a < average.size(); a++) { average.get(a).add(data.get(a).get(k)); variance.get(a).add(0.0); } if (index != average.get(0).size() - 1) { for (int a = average.get(0).size() - 2; a >= 0; a if (average.get(0).get(a) > average.get(0).get(a + 1)) { for (int b = 0; b < average.size(); b++) { double temp = average.get(b).get(a); average.get(b).set(a, average.get(b).get(a + 1)); average.get(b).set(a + 1, temp); temp = variance.get(b).get(a); variance.get(b).set(a, variance.get(b).get(a + 1)); variance.get(b).set(a + 1, temp); } } else { break; } } } } } } first = false; } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } averageOrder = null; if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } public void run() { reb2sac.getRunButton().doClick(); } public void save() { if (timeSeries) { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Probability Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public void saveAs() { if (timeSeries) { String graphName = JOptionPane.showInputDialog(biomodelsim.frame(), "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1] .length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); if (topLevel) { graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } else { if (graphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + graphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.refreshTree(); } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } else { String graphName = JOptionPane.showInputDialog(biomodelsim.frame(), "Enter Probability Graph Name:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1] .length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof GradientBarPainter)); graph .setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()) .getShadowsVisible()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); if (topLevel) { graph.setProperty("species.directory." + i, probGraphed.get(i) .getDirectory()); } else { if (probGraphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + probGraphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Probability Graph Data"); store.close(); log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.refreshTree(); } catch (Exception except) { JOptionPane .showMessageDialog(biomodelsim.frame(), "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void open(String filename) { if (timeSeries) { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) { LogX.setSelected(true); } else { LogX.setSelected(false); } if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) { LogY.setSelected(true); } else { LogY.setSelected(false); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } int xnumber = 0; if (graph.containsKey("species.xnumber." + next)) { xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next)); } graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), colors.get(graph.getProperty("species.paint." + next)), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id." + next), graph .getProperty("species.name." + next), xnumber, Integer .parseInt(graph.getProperty("species.number." + next)), graph .getProperty("species.directory." + next))); next++; } updateXNumber = false; XVariable.addItem("time"); refresh(); } catch (IOException except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); chart.setTitle(graph.getProperty("title")); chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new GradientBarPainter()); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new StandardBarPainter()); } if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true); } int next = 0; while (graph.containsKey("species.name." + next)) { probGraphed.add(new GraphProbs(colors.get(graph.getProperty("species.paint." + next)), graph.getProperty("species.paint." + next), graph .getProperty("species.id." + next), graph.getProperty("species.name." + next), Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } refreshProb(); } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public boolean isTSDGraph() { return timeSeries; } public void refresh() { if (timeSeries) { if (learnSpecs != null) { updateSpecies(); } double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); num.setGroupingUsed(false); * minY = Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + "run-" + // nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + // g.getDirectory() + separator // + "run-" + nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), g.getDirectory(), false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { if (graphProbs.contains(g.getID())) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt") .exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { String compare = g.getID().replace(" (", "~"); if (graphProbs.contains(compare.split("~")[0].trim())) { for (int i = 0; i < graphProbs.size(); i++) { if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis() .getLabel(), chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset, rend); } } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, Paint p) { shape = s; paint = p; } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Unknown Color"; } public void setPaint(String paint) { this.paint = colors.get(paint); } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory, id; private int xnumber, number; private GraphSpecies(Shape s, Paint p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species, int xnumber, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.xnumber = xnumber; this.number = number; this.directory = directory; this.id = id; } private void setDirectory(String directory) { this.directory = directory; } private void setXNumber(int xnumber) { this.xnumber = xnumber; } private void setNumber(int number) { this.number = number; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getXNumber() { return xnumber; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } private String getID() { return id; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } public boolean hasChanged() { return change; } private void probGraph(String label) { chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false); ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new StandardBarPainter()); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); } private void editProbGraph() { final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { old.add(g); } final JPanel titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JCheckBox gradient = new JCheckBox("Paint In Gradient Style"); gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof StandardBarPainter)); final JCheckBox shadow = new JCheckBox("Paint Bar Shadows"); shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()) .getShadowsVisible()); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5); String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); for (int i = 1; i < files.length; i++) { String index = files[i]; int j = i; while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { files[j] = files[j - 1]; j = j - 1; } files[j] = index; } boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) { if (file.contains("sim-rep")) { add = true; } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile) .isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); String[] files2 = new File(outDir + separator + file).list(); for (int i = 1; i < files2.length; i++) { String index = files2[i]; int j = i; while ((j > 0) && files2[j - 1].compareToIgnoreCase(index) > 0) { files2[j] = files2[j - 1]; j = j - 1; } files2[j] = index; } boolean add2 = false; for (String f : files2) { if (f.equals("sim-rep.txt")) { add2 = true; } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; for (String getFile : new File(outDir + separator + file + separator + f).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); for (String f2 : new File(outDir + separator + file + separator + f) .list()) { if (f2.equals("sim-rep.txt")) { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } d.add(d2); } } } if (add2) { IconNode n = new IconNode("sim-rep", "sim-rep"); d.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } simDir.add(d); } } } if (add) { IconNode n = new IconNode("sim-rep", "sim-rep"); simDir.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { tree = new JTree(simDir); tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); final JPanel all = new JPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } public void treeExpanded(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } }); // for (int i = 0; i < tree.getRowCount(); i++) { // tree.expandRow(i); JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); final JPanel specPanel = new JPanel(); boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName())) { selected = node.getName(); int select; if (selected.equals("sim-rep")) { select = 0; } else { select = -1; } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent()) .getName())); } else { specPanel.add(fixProbChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphProbs.get(i)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName()); } } } else { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName()); } } } boolean allChecked = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()) .getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = series.get(i).getText(); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); } else { String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()) .getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = graphProbs.get(i); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n .getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(1, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel2.add(new JPanel()); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(gradient); titlePanel2.add(shadow); titlePanel2.add(new JPanel()); titlePanel2.add(new JPanel()); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { change = true; lastSelected = selected; selected = ""; BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); if (gradient.isSelected()) { rend.setBarPainter(new GradientBarPainter()); } else { rend.setBarPainter(new StandardBarPainter()); } if (shadow.isSelected()) { rend.setShadowVisible(true); } else { rend.setShadowVisible(false); } int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend); } else { selected = ""; int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } for (GraphProbs g : old) { probGraphed.add(g); } } } } private JPanel fixProbChoices(final String directory) { if (directory.equals("")) { readProbSpecies(outDir + separator + "sim-rep.txt"); } else { readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt"); } for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); j = j - 1; } graphProbs.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Constraint"); JLabel color = new JLabel("Color"); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphProbs.size(); i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Green (Dark)")) { cols[10]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Blue (Light)")) { cols[29]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Cyan (Light)")) { cols[33]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Gray (Light)")) { cols[34]++; } } } for (GraphProbs graph : probGraphed) { if (graph.getPaintName().equals("Red")) { cols[0]++; } else if (graph.getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getPaintName().equals("Green")) { cols[2]++; } else if (graph.getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getPaintName().equals("Black")) { cols[14]++; } /* * else if (graph.getPaintName().equals("Red ")) { * cols[15]++; } else if * (graph.getPaintName().equals("Blue ")) { * cols[16]++; } else if * (graph.getPaintName().equals("Green ")) { * cols[17]++; } else if * (graph.getPaintName().equals("Yellow ")) { * cols[18]++; } else if * (graph.getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getPaintName().equals("Cyan ")) { * cols[20]++; } */ else if (graph.getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getPaintName().equals("Gray (Light)")) { cols[34]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } probGraphed.add(new GraphProbs(colory.get(colorsCombo.get(i) .getSelectedItem()), (String) colorsCombo.get(i).getSelectedItem(), boxes.get(i).getName(), series.get(i).getText().trim(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals( "" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphProbs g : remove) { probGraphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); JTextField seriesName = new JTextField(graphProbs.get(i)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); Object[] col = this.colors.keySet().toArray(); Arrays.sort(col); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem()); g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem())); } } } }); colorsCombo.add(colBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorsCombo.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); return speciesPanel; } private void readProbSpecies(String file) { graphProbs = new ArrayList<String>(); ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } for (String s : data) { if (!s.split(" ")[0].equals("#total")) { graphProbs.add(s.split(" ")[0]); } } } private double[] readProbs(String file) { ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return new double[0]; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } double[] dataSet = new double[data.size()]; double total = 0; int i = 0; if (data.get(0).split(" ")[0].equals("#total")) { total = Double.parseDouble(data.get(0).split(" ")[1]); i = 1; } for (; i < data.size(); i++) { if (total == 0) { dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]); } else { dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total); } } return dataSet; } private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) { chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false); chart.getCategoryPlot().setRenderer(rend); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); ChartPanel graph = new ChartPanel(chart); if (probGraphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } public void refreshProb() { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt") .exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot() .getRangeAxis().getLabel(), histDataset, rend); } private void updateSpecies() { String background; try { Properties p = new Properties(); String[] split = outDir.split(separator); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); background = outDir .substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); background = outDir .substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else { background = null; } } catch (Exception e) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); background = null; } learnSpecs = new ArrayList<String>(); if (background != null) { if (background.contains(".gcm")) { GCMFile gcm = new GCMFile(biomodelsim.getRoot()); gcm.load(background); HashMap<String, Properties> speciesMap = gcm.getSpecies(); for (String s : speciesMap.keySet()) { learnSpecs.add(s); } } else if (background.contains(".lpn")) { LhpnFile lhpn = new LhpnFile(biomodelsim.log); lhpn.load(background); HashMap<String, Properties> speciesMap = lhpn.getContinuous(); /* * for (String s : speciesMap.keySet()) { learnSpecs.add(s); } */ // ADDED BY SB. TSDParser extractVars; ArrayList<String> datFileVars = new ArrayList<String>(); // ArrayList<String> allVars = new ArrayList<String>(); Boolean varPresent = false; // Finding the intersection of all the variables present in all // data files. for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) { extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", biomodelsim, false); datFileVars = extractVars.getSpecies(); if (i == 1) { learnSpecs.addAll(datFileVars); } for (String s : learnSpecs) { varPresent = false; for (String t : datFileVars) { if (s.equalsIgnoreCase(t)) { varPresent = true; break; } } if (!varPresent) { learnSpecs.remove(s); } } } // END ADDED BY SB. } else { SBMLDocument document = BioSim.readSBML(background); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { learnSpecs.add(((Species) ids.get(i)).getId()); } } } for (int i = 0; i < learnSpecs.size(); i++) { String index = learnSpecs.get(i); int j = i; while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) { learnSpecs.set(j, learnSpecs.get(j - 1)); j = j - 1; } learnSpecs.set(j, index); } } public boolean getWarning() { return warn; } private class GraphProbs { private Paint paint; private String species, directory, id, paintName; private int number; private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) { this.paint = paint; this.paintName = paintName; this.species = species; this.number = number; this.directory = directory; this.id = id; } private Paint getPaint() { return paint; } private void setPaint(Paint p) { paint = p; } private String getPaintName() { return paintName; } private void setPaintName(String p) { paintName = p; } private String getSpecies() { return species; } private void setSpecies(String s) { species = s; } private String getDirectory() { return directory; } private String getID() { return id; } private int getNumber() { return number; } private void setNumber(int n) { number = n; } } private Hashtable makeIcons() { Hashtable<String, Icon> icons = new Hashtable<String, Icon>(); icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon()); icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon()); icons.put("computer", MetalIconFactory.getTreeComputerIcon()); icons.put("c", TextIcons.getIcon("c")); icons.put("java", TextIcons.getIcon("java")); icons.put("html", TextIcons.getIcon("html")); return icons; } } class IconNodeRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -940588131120912851L; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); Icon icon = ((IconNode) value).getIcon(); if (icon == null) { Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons"); String name = ((IconNode) value).getIconName(); if ((icons != null) && (name != null)) { icon = (Icon) icons.get(name); if (icon != null) { setIcon(icon); } } } else { setIcon(icon); } return this; } } class IconNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 2887169888272379817L; protected Icon icon; protected String iconName; private String hiddenName; public IconNode() { this(null, ""); } public IconNode(Object userObject, String name) { this(userObject, true, null, name); } public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) { super(userObject, allowsChildren); this.icon = icon; hiddenName = name; } public String getName() { return hiddenName; } public void setName(String name) { hiddenName = name; } public void setIcon(Icon icon) { this.icon = icon; } public Icon getIcon() { return icon; } public String getIconName() { if (iconName != null) { return iconName; } else { String str = userObject.toString(); int index = str.lastIndexOf("."); if (index != -1) { return str.substring(++index); } else { return null; } } } public void setIconName(String name) { iconName = name; } } class TextIcons extends MetalIconFactory.TreeLeafIcon { private static final long serialVersionUID = 1623303213056273064L; protected String label; private static Hashtable<String, String> labels; protected TextIcons() { } public void paintIcon(Component c, Graphics g, int x, int y) { super.paintIcon(c, g, x, y); if (label != null) { FontMetrics fm = g.getFontMetrics(); int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2; int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2; g.drawString(label, x + offsetX, y + offsetY + fm.getHeight()); } } public static Icon getIcon(String str) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } TextIcons icon = new TextIcons(); icon.label = (String) labels.get(str); return icon; } public static void setLabelSet(String ext, String label) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } labels.put(ext, label); } private static void setDefaultSet() { labels.put("c", "C"); labels.put("java", "J"); labels.put("html", "H"); labels.put("htm", "H"); labels.put("g", "" + (char) 10003); // and so on /* * labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc" * ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++"); * labels.put("exe" ,"BIN"); labels.put("class" ,"BIN"); * labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF"); * * labels.put("", ""); */ } }
package reb2sac; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; import parser.*; import lpn.gui.LHPNEditor; import lpn.parser.Abstraction; import lpn.parser.LhpnFile; import lpn.parser.Translator; import main.*; import gillespieSSAjava.GillespieSSAJavaSingleStep; import gcm.gui.GCM2SBMLEditor; import gcm.parser.GCMFile; import gcm.util.GlobalConstants; import graph.*; import sbmleditor.*; import stategraph.BuildStateGraphThread; import stategraph.PerfromSteadyStateMarkovAnalysisThread; import stategraph.PerfromTransientMarkovAnalysisThread; import stategraph.StateGraph; import util.*; import verification.AbstPane; /** * This class creates the properties file that is given to the reb2sac program. * It also executes the reb2sac program. * * @author Curtis Madsen */ public class Run implements ActionListener { private Process reb2sac; private String separator; private Reb2Sac r2s; StateGraph sg; public Run(Reb2Sac reb2sac) { r2s = reb2sac; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } } /** * This method is given which buttons are selected and creates the * properties file from all the other information given. * * @param useInterval * * @param stem */ public void createProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, double absError, String outDir, long rndSeed, int run, String[] termCond, String[] intSpecies, String printer_id, String printer_track_quantity, String[] getFilename, String selectedButtons, Component component, String filename, double rap1, double rap2, double qss, int con, JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs, JList loopAbs, JList postAbs, AbstPane abstPane) { Properties abs = new Properties(); if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) { int gcmIndex = 1; for (int i = 0; i < preAbs.getModel().getSize(); i++) { String abstractionOption = (String) preAbs.getModel().getElementAt(i); if (abstractionOption.equals("complex-formation-and-sequestering-abstraction") || abstractionOption.equals("operator-site-reduction-abstraction")) { // abstractionOption.equals("species-sequestering-abstraction")) abs.setProperty("gcm.abstraction.method." + gcmIndex, abstractionOption); gcmIndex++; } else abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), abstractionOption); } for (int i = 0; i < loopAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs.getModel().getElementAt(i)); } // abs.setProperty("reb2sac.abstraction.method.0.1", // "enzyme-kinetic-qssa-1"); // abs.setProperty("reb2sac.abstraction.method.0.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.0.3", // "multiple-products-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.4", // "multiple-reactants-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.5", // "single-reactant-product-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.6", // "dimer-to-monomer-substitutor"); // abs.setProperty("reb2sac.abstraction.method.0.7", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.1", // "modifier-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.2", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.1", // "operator-site-forward-binding-remover"); // abs.setProperty("reb2sac.abstraction.method.2.3", // "enzyme-kinetic-rapid-equilibrium-1"); // abs.setProperty("reb2sac.abstraction.method.2.4", // "irrelevant-species-remover"); // abs.setProperty("reb2sac.abstraction.method.2.5", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.2.6", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.7", // "similar-reaction-combiner"); // abs.setProperty("reb2sac.abstraction.method.2.8", // "modifier-constant-propagation"); } // if (selectedButtons.contains("abs")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction"); // else if (selectedButtons.contains("nary")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction-level-assignment"); for (int i = 0; i < postAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel().getElementAt(i)); } abs.setProperty("simulation.printer", printer_id); abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); // if (selectedButtons.contains("monteCarlo")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "distribute-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.3", // "kinetic-law-constants-simplifier"); // else if (selectedButtons.contains("none")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "kinetic-law-constants-simplifier"); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]); if (split.length > 1) { String[] levels = split[1].split(","); for (int j = 0; j < levels.length; j++) { abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1), levels[j]); } } } } abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); abs.setProperty("reb2sac.qssa.condition.1", "" + qss); abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); if (selectedButtons.contains("none")) { abs.setProperty("reb2sac.abstraction.method", "none"); } if (selectedButtons.contains("abs")) { abs.setProperty("reb2sac.abstraction.method", "abs"); } else if (selectedButtons.contains("nary")) { abs.setProperty("reb2sac.abstraction.method", "nary"); } if (abstPane != null) { for (Integer i = 0; i < abstPane.preAbsModel.size(); i++) { abs.setProperty("abstraction.transform." + abstPane.preAbsModel.getElementAt(i).toString(), "preloop" + i.toString()); } for (Integer i = 0; i < abstPane.loopAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) { String value = abs.getProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString()); value = value + "mainloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop" + i.toString()); } } for (Integer i = 0; i < abstPane.postAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i)) || abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) { String value = abs.getProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString()); value = value + "postloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), "postloop" + i.toString()); } } for (String s : abstPane.transforms) { if (!abstPane.preAbsModel.contains(s) && !abstPane.loopAbsModel.contains(s) && !abstPane.postAbsModel.contains(s)) { abs.remove(s); } } } if (selectedButtons.contains("ODE")) { abs.setProperty("reb2sac.simulation.method", "ODE"); } else if (selectedButtons.contains("monteCarlo")) { abs.setProperty("reb2sac.simulation.method", "monteCarlo"); } else if (selectedButtons.contains("markov")) { abs.setProperty("reb2sac.simulation.method", "markov"); } else if (selectedButtons.contains("sbml")) { abs.setProperty("reb2sac.simulation.method", "SBML"); } else if (selectedButtons.contains("dot")) { abs.setProperty("reb2sac.simulation.method", "Network"); } else if (selectedButtons.contains("xhtml")) { abs.setProperty("reb2sac.simulation.method", "Browser"); } else if (selectedButtons.contains("lhpn")) { abs.setProperty("reb2sac.simulation.method", "LPN"); } if (!selectedButtons.contains("monteCarlo")) { // if (selectedButtons.equals("none_ODE") || // selectedButtons.equals("abs_ODE")) { abs.setProperty("ode.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("ode.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("ode.simulation.time.step", "inf"); } else { abs.setProperty("ode.simulation.time.step", "" + timeStep); } abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep); abs.setProperty("ode.simulation.absolute.error", "" + absError); abs.setProperty("ode.simulation.out.dir", outDir); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); } if (!selectedButtons.contains("ODE")) { // if (selectedButtons.equals("none_monteCarlo") || // selectedButtons.equals("abs_monteCarlo")) { abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs.setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("monte.carlo.simulation.time.step", "inf"); } else { abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); abs.setProperty("monte.carlo.simulation.out.dir", outDir); if (usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "sad"); abs.setProperty("computation.analysis.sad.path", sadFile.getName()); } } if (!usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "constraint"); } if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) { abs.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { abs.setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { if (!getFilename[getFilename.length - 1].contains(".")) { getFilename[getFilename.length - 1] += "."; filename += "."; } int cut = 0; for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename.length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties")); abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for abstraction.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * This method is given what data is entered into the nary frame and creates * the nary properties file from that information. */ public void createNaryProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, String outDir, long rndSeed, int run, String printer_id, String printer_track_quantity, String[] getFilename, Component component, String filename, JRadioButton monteCarlo, String stopE, double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel, ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond, String[] intSpecies, double rap1, double rap2, double qss, int con, ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) { Properties nary = new Properties(); try { FileInputStream load = new FileInputStream(new File(outDir + separator + "species.properties")); nary.load(load); load.close(); } catch (Exception e) { JOptionPane.showMessageDialog(component, "Species Properties File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE); } nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1"); nary.setProperty("reb2sac.abstraction.method.0.2", "reversible-to-irreversible-transformer"); nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.4", "multiple-reactants-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.5", "single-reactant-product-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor"); nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover"); nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1"); nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover"); nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner"); nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction"); nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer"); nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator"); nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator"); nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator"); nary.setProperty("reb2sac.nary.order.decider", "distinct"); nary.setProperty("simulation.printer", printer_id); nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); nary.setProperty("reb2sac.analysis.stop.enabled", stopE); nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR); for (int i = 0; i < getSpeciesProps.size(); i++) { if (!(inhib.get(i).getText().trim() != "<<none>>")) { nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i), inhib.get(i).getText().trim()); } String[] consLevels = Utility.getList(conLevel.get(i), consLevel.get(i)); for (int j = 0; j < counts.get(i); j++) { nary.remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1)); } for (int j = 0; j < consLevels.length; j++) { nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1), consLevels[j]); } } if (monteCarlo.isSelected()) { nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { nary.setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { nary.setProperty("monte.carlo.simulation.time.step", "inf"); } else { nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); nary.setProperty("monte.carlo.simulation.runs", "" + run); nary.setProperty("monte.carlo.simulation.out.dir", "."); } for (int i = 0; i < finalS.length; i++) { if (finalS[i].trim() != "<<unknown>>") { nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]); } } if (usingSSA.isSelected() && monteCarlo.isSelected()) { nary.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < intSpecies.length; i++) { if (intSpecies[i] != "") { nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]); } } nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); nary.setProperty("reb2sac.qssa.condition.1", "" + qss); nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { nary.setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { FileOutputStream store = new FileOutputStream(new File(filename.replace(".sbml", "").replace(".xml", "") + ".properties")); nary.store(store, getFilename[getFilename.length - 1].replace(".sbml", "").replace(".xml", "") + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for simulation.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * Executes the reb2sac program. If ODE, monte carlo, or markov is selected, * this method creates a Graph object. * * @param runTime * @param refresh */ public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml, JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo, String sim, String printer_id, String printer_track_quantity, String outDir, JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA, String ssaFile, Gui biomodelsim, JTabbedPane simTab, String root, JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct, double timeLimit, double runTime, String modelFile, AbstPane abstPane, JRadioButton abstraction, String lpnProperty, double absError, double timeStep, double printInterval, int runs, long rndSeed, boolean refresh) { Runtime exec = Runtime.getRuntime(); int exitValue = 255; while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) { outDir = outDir.substring(0, outDir.length() - 1 - outDir.split(separator)[outDir.split(separator).length - 1].length()); } try { long time1; String directory = ""; String theFile = ""; String sbmlName = ""; String lhpnName = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } if (nary.isSelected() && gcmEditor != null && (monteCarlo.isSelected() || xhtml.isSelected())) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (direct != null && !direct.equals("") && direct.contains("=")) { String[] d = direct.split("_"); ArrayList<String> dd = new ArrayList<String>(); for (int i = 0; i < d.length; i++) { if (!d[i].contains("=")) { String di = d[i]; while (!d[i].contains("=")) { i++; di += "_" + d[i]; } dd.add(di); } else { dd.add(d[i]); } } for (String di : dd) { if (di.contains("-")) { if (gcm.getPromoters().containsKey(di.split("=")[0].split("-")[0])) { Properties promoterProps = gcm.getPromoters().get(di.split("=")[0].split("-")[0]); promoterProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } if (gcm.getSpecies().containsKey(di.split("=")[0].split("-")[0])) { Properties speciesProps = gcm.getSpecies().get(di.split("=")[0].split("-")[0]); speciesProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } String influence = ""; for (String infl : gcm.getInfluences().keySet()) { boolean matchInfl = true; for (String part : di.split("=")[0].split("-")[0].split("_")) { if (!infl.contains(part)) { matchInfl = false; } } if (matchInfl) { influence = infl; } } if (!influence.equals("")) { Properties influenceProps = gcm.getInfluences().get(influence); influenceProps.put(di.split("=")[0].split("-")[1].replace("\"", ""), di.split("=")[1]); } } else { if (gcm.getGlobalParameters().containsKey(di.split("=")[0])) { gcm.getGlobalParameters().put(di.split("=")[0], di.split("=")[1]); } if (gcm.getParameters().containsKey(di.split("=")[0])) { gcm.getParameters().put(di.split("=")[0], di.split("=")[1]); } } } } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); if (lpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lpnFile.addProperty(lpnProperty); } lpnFile.save(root + separator + simName + separator + lpnName); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate(root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + simName + separator + lpnName.replace(".lpn", ".xml")); t1.outputSBML(); } else { return 0; } } if (nary.isSelected() && gcmEditor == null && !sim.contains("markov-chain-analysis") && !lhpn.isSelected() && naryRun == 1) { log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work); } else if (sbml.isSelected()) { sbmlName = JOptionPane.showInputDialog(component, "Enter Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (sbmlName != null && !sbmlName.trim().equals("")) { sbmlName = sbmlName.trim(); if (sbmlName.length() > 4) { if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml") || !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) { sbmlName += ".xml"; } } else { sbmlName += ".xml"; } File f = new File(root + separator + sbmlName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + sbmlName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { progress.setIndeterminate(true); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + modelFile); t1.BuildTemplate(root + separator + simName + separator + modelFile, lpnProperty); } else { t1.BuildTemplate(root + separator + modelFile, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); exitValue = 0; } else if (gcmEditor != null && nary.isSelected()) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); if (lpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lpnFile.addProperty(lpnProperty); } lpnFile.save(root + separator + simName + separator + lpnName); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate(root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); } else { time1 = System.nanoTime(); return 0; } exitValue = 0; } else { if (r2s.reb2sacAbstraction() && (abstraction.isSelected() || nary.isSelected())) { log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + theFile, null, work); } else { log.addText("Outputting SBML file:\n" + root + separator + sbmlName + "\n"); time1 = System.nanoTime(); FileOutputStream fileOutput = new FileOutputStream(new File(root + separator + sbmlName)); FileInputStream fileInput = new FileInputStream(new File(filename)); int read = fileInput.read(); while (read != -1) { fileOutput.write(read); read = fileInput.read(); } fileInput.close(); fileOutput.close(); exitValue = 0; } } } else { time1 = System.nanoTime(); } } else if (lhpn.isSelected()) { lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 4) { if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) { lhpnName += ".lpn"; } } else { lhpnName += ".lpn"; } File f = new File(root + separator + lhpnName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + lhpnName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); if (abstraction.isSelected()) { Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + lhpnName); } else { lhpnFile.save(root + separator + lhpnName); } time1 = System.nanoTime(); exitValue = 0; } else { ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel); if (lhpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lhpnFile.addProperty(lpnProperty); } lhpnFile.save(root + separator + lhpnName); log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName + "\n"); } else { return 0; } exitValue = 0; } } else { time1 = System.nanoTime(); exitValue = 0; } } else if (dot.isSelected()) { if (nary.isSelected() && gcmEditor != null) { LhpnFile lhpnFile = new LhpnFile(log); lhpnFile.load(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn"); lhpnFile.printDot(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".dot"); time1 = System.nanoTime(); exitValue = 0; } else if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); if (abstraction.isSelected()) { Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.printDot(root + separator + simName + separator + modelFile.replace(".lpn", ".dot")); } else { lhpnFile.printDot(root + separator + simName + separator + modelFile.replace(".lpn", ".dot")); } time1 = System.nanoTime(); exitValue = 0; } else { log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); } } else if (xhtml.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); } else if (usingSSA.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile, null, work); } else { if (sim.equals("atacs")) { log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work); } else if (sim.contains("markov-chain-analysis") || sim.equals("reachability-analysis")) { time1 = System.nanoTime(); progress.setIndeterminate(true); LhpnFile lhpnFile = null; if (modelFile.contains(".lpn")) { lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); } else { new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn").delete(); ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (direct != null && !direct.equals("") && direct.contains("=")) { String[] d = direct.split("_"); ArrayList<String> dd = new ArrayList<String>(); for (int i = 0; i < d.length; i++) { if (!d[i].contains("=")) { String di = d[i]; while (!d[i].contains("=")) { i++; di += "_" + d[i]; } dd.add(di); } else { dd.add(d[i]); } } for (String di : dd) { if (di.contains("-")) { if (gcm.getPromoters().containsKey(di.split("=")[0].split("-")[0])) { Properties promoterProps = gcm.getPromoters().get(di.split("=")[0].split("-")[0]); promoterProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } if (gcm.getSpecies().containsKey(di.split("=")[0].split("-")[0])) { Properties speciesProps = gcm.getSpecies().get(di.split("=")[0].split("-")[0]); speciesProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } String influence = ""; for (String infl : gcm.getInfluences().keySet()) { boolean matchInfl = true; for (String part : di.split("=")[0].split("-")[0].split("_")) { if (!infl.contains(part)) { matchInfl = false; } } if (matchInfl) { influence = infl; } } if (!influence.equals("")) { Properties influenceProps = gcm.getInfluences().get(influence); influenceProps.put(di.split("=")[0].split("-")[1].replace("\"", ""), di.split("=")[1]); } } else { if (gcm.getGlobalParameters().containsKey(di.split("=")[0])) { gcm.getGlobalParameters().put(di.split("=")[0], di.split("=")[1]); } if (gcm.getParameters().containsKey(di.split("=")[0])) { gcm.getParameters().put(di.split("=")[0], di.split("=")[1]); } } } } if (gcm.flattenGCM(true) != null) { time1 = System.nanoTime(); lhpnFile = gcm.convertToLHPN(specs, conLevel); if (lhpnFile == null) { return 0; } if (!lpnProperty.equals("")) { lhpnFile.addProperty(lpnProperty); } lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn"); log.addText("Saving GCM file as LHPN:\n" + filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn" + "\n"); } else { return 0; } } if (lhpnFile != null) { sg = new StateGraph(lhpnFile); BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg, progress); buildStateGraph.start(); buildStateGraph.join(); log.addText("Number of states found: " + sg.getNumberOfStates() + "\n"); if (sim.equals("reachability-analysis") && !sg.getStop()) { int value = JOptionPane.YES_OPTION; if (sg.getNumberOfStates() > 100) { Object[] options = { "Yes", "No" }; value = JOptionPane.showOptionDialog(Gui.frame, "The state graph contains " + sg.getNumberOfStates() + " states.\n" + "Do you want to output it to a dot file?", "State Graph Contains Over 100 States", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } if (value == JOptionPane.YES_OPTION) { sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", true); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } else if (sim.equals("steady-state-markov-chain-analysis")) { if (!sg.getStop()) { log.addText("Performing steady state Markov chain analysis.\n"); PerfromSteadyStateMarkovAnalysisThread performMarkovAnalysis = new PerfromSteadyStateMarkovAnalysisThread(sg); if (modelFile.contains(".lpn")) { performMarkovAnalysis.start(absError, null); } else { ArrayList<String> conditions = new ArrayList<String>(); for (int i = 0; i < gcmEditor.getGCM().getConditions().size(); i++) { if (gcmEditor.getGCM().getConditions().get(i).startsWith("St")) { conditions.add(Translator.getProbpropExpression(gcmEditor.getGCM().getConditions().get(i))); } } performMarkovAnalysis.start(absError, conditions); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream(new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } int value = JOptionPane.YES_OPTION; if (sg.getNumberOfStates() > 100) { Object[] options = { "Yes", "No" }; value = JOptionPane.showOptionDialog(Gui.frame, "The state graph contains " + sg.getNumberOfStates() + " states.\n" + "Do you want to output it to a dot file?", "State Graph Contains Over 100 States", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } if (value == JOptionPane.YES_OPTION) { sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", true); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } } else if (sim.equals("transient-markov-chain-analysis")) { if (!sg.getStop()) { log.addText("Performing transient Markov chain analysis with uniformization.\n"); PerfromTransientMarkovAnalysisThread performMarkovAnalysis = new PerfromTransientMarkovAnalysisThread(sg, progress); time1 = System.nanoTime(); if (lpnProperty != null && !lpnProperty.equals("")) { String[] condition = Translator.getProbpropParts(Translator.getProbpropExpression(lpnProperty)); boolean globallyTrue = false; if (lpnProperty.contains("PF")) { condition[0] = "true"; } else if (lpnProperty.contains("PG")) { condition[0] = "true"; globallyTrue = true; } performMarkovAnalysis.start(timeLimit, timeStep, printInterval, absError, condition, globallyTrue); } else { performMarkovAnalysis.start(timeLimit, timeStep, printInterval, absError, null, false); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream(new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } int value = JOptionPane.YES_OPTION; if (sg.getNumberOfStates() > 100) { Object[] options = { "Yes", "No" }; value = JOptionPane.showOptionDialog(Gui.frame, "The state graph contains more than 100 states.\n" + "Do you want to output it to a dot file anyway?", "State Graph Contains Over 100 States", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } if (value == JOptionPane.YES_OPTION) { sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", true); } if (sg.outputTSD(directory + separator + "percent-term-time.tsd")) { if (refresh) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } } } } } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } } if (refresh) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } exitValue = 0; } else { Preferences biosimrc = Preferences.userRoot(); if (sim.equals("gillespieJava")) { time1 = System.nanoTime(); int index = -1; for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { simTab.setSelectedIndex(i); index = i; } } GillespieSSAJavaSingleStep javaSim = new GillespieSSAJavaSingleStep(); String SBMLFileName = directory + separator + theFile; javaSim.PerformSim(SBMLFileName, outDir, timeLimit, timeStep, rndSeed, ((Graph) simTab.getComponentAt(index))); exitValue = 0; return exitValue; } else if (biosimrc.get("biosim.sim.command", "").equals("")) { time1 = System.nanoTime(); log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename + "\n"); reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile, null, work); } else { String command = biosimrc.get("biosim.sim.command", ""); String fileStem = theFile.replaceAll(".xml", ""); fileStem = fileStem.replaceAll(".sbml", ""); command = command.replaceAll("filename", fileStem); command = command.replaceAll("sim", sim); log.addText(command + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec(command, null, work); } } } String error = ""; try { InputStream reb = reb2sac.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); // int count = 0; String line; double time = 0; double oldTime = 0; int runNum = 0; int prog = 0; while ((line = br.readLine()) != null) { try { if (line.contains("Time")) { time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line.length())); if (oldTime > time) { runNum++; } oldTime = time; time += (runNum * timeLimit); double d = ((time * 100) / runTime); String s = d + ""; double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s.length())); if (decimal >= 0.5) { prog = (int) (Math.ceil(d)); } else { prog = (int) (d); } } // else { // log.addText(line); } catch (Exception e) { } progress.setValue(prog); // if (steps > 0) { // count++; // progress.setValue(count); // log.addText(output); } InputStream reb2 = reb2sac.getErrorStream(); int read = reb2.read(); while (read != -1) { error += (char) read; read = reb2.read(); } br.close(); isr.close(); reb.close(); reb2.close(); } catch (Exception e) { } if (reb2sac != null) { exitValue = reb2sac.waitFor(); } long time2 = System.nanoTime(); long minutes; long hours; long days; double secs = ((time2 - time1) / 1000000000.0); long seconds = ((time2 - time1) / 1000000000); secs = secs - seconds; minutes = seconds / 60; secs = seconds % 60 + secs; hours = minutes / 60; minutes = minutes % 60; days = hours / 24; hours = hours % 60; String time; String dayLabel; String hourLabel; String minuteLabel; String secondLabel; if (days == 1) { dayLabel = " day "; } else { dayLabel = " days "; } if (hours == 1) { hourLabel = " hour "; } else { hourLabel = " hours "; } if (minutes == 1) { minuteLabel = " minute "; } else { minuteLabel = " minutes "; } if (seconds == 1) { secondLabel = " second"; } else { secondLabel = " seconds"; } if (days != 0) { time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (hours != 0) { time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (minutes != 0) { time = minutes + minuteLabel + secs + secondLabel; } else { time = secs + secondLabel; } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n"); if (exitValue != 0) { if (exitValue == 143) { JOptionPane.showMessageDialog(Gui.frame, "The simulation was" + " canceled by the user.", "Canceled Simulation", JOptionPane.ERROR_MESSAGE); } else if (exitValue == 139) { JOptionPane.showMessageDialog(Gui.frame, "The selected model is not a valid sbml file." + "\nYou must select an sbml file.", "Not An SBML File", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!\n" + "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE); } } else { if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) { } else if (sbml.isSelected()) { if (sbmlName != null && !sbmlName.trim().equals("")) { String gcmName = sbmlName.replace(".xml", ".gcm"); Gui.createGCMFromSBML(root, root + separator + sbmlName, sbmlName, gcmName, true); if (!biomodelsim.updateOpenGCM(gcmName)) { try { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmName, biomodelsim, log, false, null, null, null, false); biomodelsim.addTab(gcmName, gcm, "GCM Editor"); biomodelsim.addToTree(gcmName); } catch (Exception e) { e.printStackTrace(); } } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(gcmName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (lhpn.isSelected()) { if (lhpnName != null && !lhpnName.trim().equals("")) { if (!biomodelsim.updateOpenLHPN(lhpnName)) { biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null, biomodelsim, log), "LHPN Editor"); biomodelsim.addToTree(lhpnName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (dot.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } } else if (xhtml.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n"); exec.exec("gnome-open " + out + ".xhtml", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n"); exec.exec("open " + out + ".xhtml", null, work); } else { log.addText("Executing:\ncmd /c start " + directory + out + ".xhtml" + "\n"); exec.exec("cmd /c start " + out + ".xhtml", null, work); } } else if (usingSSA.isSelected()) { // if (!printer_id.equals("null.printer")) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } if (refresh) { ((Graph) simTab.getComponentAt(i)).refresh(); } } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (refresh) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } else if (sim.equals("atacs")) { log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA " + filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "out.hse\n"); exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work); if (refresh) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } // simTab.add("Probability Graph", new // Graph(printer_track_quantity, // outDir.split(separator)[outDir.split(separator).length - // simulation results", // printer_id, outDir, "time", biomodelsim, null, log, null, // false)); // simTab.getComponentAt(simTab.getComponentCount() - // 1).setName("ProbGraph"); } else { // if (!printer_id.equals("null.printer")) { if (ode.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } if (refresh) { ((Graph) simTab.getComponentAt(i)).refresh(); } } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (refresh) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } else if (monteCarlo.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } if (refresh) { ((Graph) simTab.getComponentAt(i)).refresh(); } } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; ArrayList<String> run = new ArrayList<String>(); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-") && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { run.add(f); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM || outputV || outputS) { warning = ((Graph) simTab.getComponentAt(i)).getWarning(); ((Graph) simTab.getComponentAt(i)).calculateAverageVarianceDeviation(run, 0, direct, warning, true); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); if (new File(directory + separator + "sim-rep.txt").exists()) { try { Scanner s = new Scanner(new File(directory + separator + "sim-rep.txt")); if (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { } else { for (String add : ss) { if (!add.equals("#total") && !add.equals("time-limit")) { dataLabels.add(add); ArrayList<Double> times = new ArrayList<Double>(); terms.add(times); } } } } } catch (Exception e) { } } Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add(Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add(data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add(percentData.get(k).get(percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data.get(k).set(data.get(k).size() - 1, data.get(k).get(data.get(k).size() - 1) + 1); percentData.get(k).set(percentData.get(k).size() - 1, ((data.get(k).get(data.get(k).size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (refresh) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } } } } catch (InterruptedException e1) { JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!", "Error In Execution", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } catch (IOException e1) { JOptionPane.showMessageDialog(Gui.frame, "File I/O Error!", "File I/O Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } return exitValue; } /** * This method is called if a button that cancels the simulation is pressed. */ public void actionPerformed(ActionEvent e) { if (reb2sac != null) { reb2sac.destroy(); } if (sg != null) { sg.stop(); } } }
package peergos.server.storage; import peergos.server.*; import peergos.server.corenode.*; import peergos.server.sql.*; import peergos.server.util.*; import peergos.shared.*; import peergos.shared.cbor.*; import peergos.shared.crypto.asymmetric.*; import peergos.shared.crypto.hash.*; import peergos.shared.io.ipfs.cid.*; import peergos.shared.mutable.*; import peergos.shared.storage.*; import peergos.shared.io.ipfs.multihash.*; import io.prometheus.client.Histogram; import peergos.shared.util.*; import java.io.*; import java.nio.file.*; import java.sql.*; import java.time.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.*; public class S3BlockStorage implements ContentAddressedStorage { private static final Logger LOG = Logger.getGlobal(); private static final Histogram readTimerLog = Histogram.build() .labelNames("filesize") .name("block_read_seconds") .help("Time to read a block from immutable storage") .exponentialBuckets(0.01, 2, 16) .register(); private static final Histogram writeTimerLog = Histogram.build() .labelNames("filesize") .name("s3_block_write_seconds") .help("Time to write a block to immutable storage") .exponentialBuckets(0.01, 2, 16) .register(); private final Multihash id; private final String region, bucket, folder, regionEndpoint, host; private final String accessKeyId, secretKey; private final BlockStoreProperties props; private final TransactionStore transactions; private final ContentAddressedStorage p2pFallback; public S3BlockStorage(S3Config config, Multihash id, BlockStoreProperties props, TransactionStore transactions, ContentAddressedStorage p2pFallback) { this.id = id; this.region = config.region; this.bucket = config.bucket; this.folder = config.path.isEmpty() || config.path.endsWith("/") ? config.path : config.path + "/"; this.regionEndpoint = config.regionEndpoint; this.host = bucket + "." + regionEndpoint; this.accessKeyId = config.accessKey; this.secretKey = config.secretKey; LOG.info("Using S3 Block Storage at " + config.regionEndpoint + ", bucket " + config.bucket + ", path: " + config.path); this.props = props; this.transactions = transactions; this.p2pFallback = p2pFallback; } private static String hashToKey(Multihash hash) { return DirectS3BlockStore.hashToKey(hash); } private Multihash keyToHash(String key) { return DirectS3BlockStore.keyToHash(key.substring(folder.length())); } @Override public CompletableFuture<BlockStoreProperties> blockStoreProperties() { return Futures.of(props); } @Override public CompletableFuture<List<PresignedUrl>> authReads(List<Multihash> blocks) { if (blocks.size() > 50) throw new IllegalStateException("Too many reads to auth!"); List<PresignedUrl> res = new ArrayList<>(); String host = bucket + "." + regionEndpoint; for (Multihash block : blocks) { String s3Key = hashToKey(block); res.add(S3Request.preSignGet(s3Key, Optional.of(600), ZonedDateTime.now(), host, region, accessKeyId, secretKey)); } return Futures.of(res); } @Override public CompletableFuture<List<PresignedUrl>> authWrites(PublicKeyHash owner, PublicKeyHash writerHash, List<byte[]> signedHashes, List<Integer> blockSizes, boolean isRaw, TransactionId tid) { try { if (signedHashes.size() > 50) throw new IllegalStateException("Too many writes to auth!"); if (blockSizes.size() != signedHashes.size()) throw new IllegalStateException("Number of sizes doesn't match number of signed hashes!"); PublicSigningKey writer = getSigningKey(writerHash).get().get(); List<Pair<Multihash, Integer>> blockProps = new ArrayList<>(); for (int i=0; i < signedHashes.size(); i++) { Cid.Codec codec = isRaw ? Cid.Codec.Raw : Cid.Codec.DagCbor; Cid cid = new Cid(1, codec, Multihash.Type.sha2_256, writer.unsignMessage(signedHashes.get(i))); blockProps.add(new Pair<>(cid, blockSizes.get(i))); } List<PresignedUrl> res = new ArrayList<>(); for (Pair<Multihash, Integer> props : blockProps) { if (props.left.type != Multihash.Type.sha2_256) throw new IllegalStateException("Can only pre-auth writes of sha256 hashed blocks!"); transactions.addBlock(props.left, tid, owner); String s3Key = hashToKey(props.left); String contentSha256 = ArrayOps.bytesToHex(props.left.getHash()); String host = bucket + "." + regionEndpoint; Map<String, String> extraHeaders = new LinkedHashMap<>(); extraHeaders.put("Content-Type", "application/octet-stream"); res.add(S3Request.preSignPut(s3Key, props.right, contentSha256, false, ZonedDateTime.now(), host, extraHeaders, region, accessKeyId, secretKey)); } return Futures.of(res); } catch (Exception e) { throw new RuntimeException(e); } } @Override public CompletableFuture<Optional<CborObject>> get(Multihash hash) { if (hash instanceof Cid && ((Cid) hash).codec == Cid.Codec.Raw) throw new IllegalStateException("Need to call getRaw if cid is not cbor!"); return getRaw(hash).thenApply(opt -> opt.map(CborObject::fromByteArray)); } @Override public CompletableFuture<Optional<byte[]>> getRaw(Multihash hash) { PresignedUrl getUrl = S3Request.preSignGet(folder + hashToKey(hash), Optional.of(600), ZonedDateTime.now(), host, region, accessKeyId, secretKey); Histogram.Timer readTimer = readTimerLog.labels("read").startTimer(); try { return Futures.of(Optional.of(HttpUtil.get(getUrl))); } catch (IOException e) { return p2pFallback.getRaw(hash); } finally { readTimer.observeDuration(); } } @Override public CompletableFuture<List<Multihash>> pinUpdate(PublicKeyHash owner, Multihash existing, Multihash updated) { return Futures.of(Collections.singletonList(updated)); } @Override public CompletableFuture<List<Multihash>> recursivePin(PublicKeyHash owner, Multihash hash) { return Futures.of(Collections.singletonList(hash)); } @Override public CompletableFuture<List<Multihash>> recursiveUnpin(PublicKeyHash owner, Multihash hash) { return Futures.of(Collections.singletonList(hash)); } @Override public CompletableFuture<Boolean> gc() { return Futures.errored(new IllegalStateException("S3 doesn't implement GC!")); } /** The result of this method is a snapshot of the mutable pointers that is consistent with the blocks store * after GC has completed (saved to a file which can be independently backed up). * * @param pointers * @return */ private void collectGarbage(JdbcIpnsAndSocial pointers) throws IOException { // TODO: do this more efficiently with a bloom filter, and streaming long t0 = System.nanoTime(); List<Multihash> present = getFiles(Integer.MAX_VALUE); long t1 = System.nanoTime(); System.out.println("Listing block store took " + (t1-t0)/1_000_000_000 + "s"); List<Multihash> pending = transactions.getOpenTransactionBlocks(); long t2 = System.nanoTime(); System.out.println("Listing pending blocks took " + (t2-t1)/1_000_000_000 + "s"); // This pointers call must happen AFTER the previous two for correctness Map<PublicKeyHash, byte[]> allPointers = pointers.getAllEntries(); long t3 = System.nanoTime(); System.out.println("Listing pointers took " + (t3-t2)/1_000_000_000 + "s"); BitSet reachable = new BitSet(present.size()); for (PublicKeyHash writerHash : allPointers.keySet()) { byte[] signedRawCas = allPointers.get(writerHash); PublicSigningKey writer = getSigningKey(writerHash).join().get(); byte[] bothHashes = writer.unsignMessage(signedRawCas); HashCasPair cas = HashCasPair.fromCbor(CborObject.fromByteArray(bothHashes)); MaybeMultihash updated = cas.updated; if (updated.isPresent()) markReachable(updated.get(), present, reachable); } for (Multihash additional : pending) { int index = present.indexOf(additional); if (index >= 0) reachable.set(index); } long t4 = System.nanoTime(); System.out.println("Marking reachable took " + (t4-t3)/1_000_000_000 + "s"); // Save pointers snapshot to file Path pointerSnapshotFile = Paths.get("pointers-snapshot-" + LocalDateTime.now() + ".txt"); for (Map.Entry<PublicKeyHash, byte[]> entry : allPointers.entrySet()) { Files.write(pointerSnapshotFile, (entry.getKey() + ":" + ArrayOps.bytesToHex(entry.getValue()) + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } long deletedBlocks = 0; long deletedSize = 0; for (int i = reachable.nextClearBit(0); i >= 0 && i < present.size(); i = reachable.nextClearBit(i + 1)) { Multihash hash = present.get(i); try { int size = getSize(hash).join().get(); deletedBlocks++; deletedSize += size; delete(hash); } catch (Exception e) { System.out.println("Unable to read " + hash); } } long t5 = System.nanoTime(); System.out.println("Deleting blocks took " + (t5-t4)/1_000_000_000 + "s"); System.out.println("GC complete. Freed " + deletedBlocks + " blocks totalling " + deletedSize + " bytes"); } private void markReachable(Multihash root, List<Multihash> present, BitSet reachable) { int index = present.indexOf(root); if (index >= 0) reachable.set(index); List<Multihash> links = getLinks(root).join(); for (Multihash link : links) { markReachable(link, present, reachable); } } @Override public CompletableFuture<Optional<Integer>> getSize(Multihash hash) { if (hash.isIdentity()) // Identity hashes are not actually stored explicitly return Futures.of(Optional.of(0)); Histogram.Timer readTimer = readTimerLog.labels("size").startTimer(); try { PresignedUrl headUrl = S3Request.preSignHead(folder + hashToKey(hash), Optional.of(60), ZonedDateTime.now(), host, region, accessKeyId, secretKey); Map<String, List<String>> headRes = HttpUtil.head(headUrl); long size = Long.parseLong(headRes.get("Content-Length").get(0)); return Futures.of(Optional.of((int)size)); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Futures.of(Optional.empty()); } finally { readTimer.observeDuration(); } } public boolean contains(Multihash hash) { try { PresignedUrl headUrl = S3Request.preSignHead(folder + hashToKey(hash), Optional.of(60), ZonedDateTime.now(), host, region, accessKeyId, secretKey); Map<String, List<String>> headRes = HttpUtil.head(headUrl); return true; } catch (Exception e) { return false; } } @Override public CompletableFuture<Multihash> id() { return Futures.of(id); } @Override public CompletableFuture<TransactionId> startTransaction(PublicKeyHash owner) { return CompletableFuture.completedFuture(transactions.startTransaction(owner)); } @Override public CompletableFuture<Boolean> closeTransaction(PublicKeyHash owner, TransactionId tid) { transactions.closeTransaction(owner, tid); return CompletableFuture.completedFuture(true); } @Override public CompletableFuture<List<Multihash>> put(PublicKeyHash owner, PublicKeyHash writer, List<byte[]> signedHashes, List<byte[]> blocks, TransactionId tid) { return put(owner, writer, signedHashes, blocks, false, tid); } @Override public CompletableFuture<List<Multihash>> putRaw(PublicKeyHash owner, PublicKeyHash writer, List<byte[]> signatures, List<byte[]> blocks, TransactionId tid, ProgressConsumer<Long> progressConsumer) { return put(owner, writer, signatures, blocks, true, tid); } private CompletableFuture<List<Multihash>> put(PublicKeyHash owner, PublicKeyHash writer, List<byte[]> signatures, List<byte[]> blocks, boolean isRaw, TransactionId tid) { return CompletableFuture.completedFuture(blocks.stream() .map(b -> put(b, isRaw, tid, owner)) .collect(Collectors.toList())); } /** Must be atomic relative to reads of the same key * * @param data */ public Multihash put(byte[] data, boolean isRaw, TransactionId tid, PublicKeyHash owner) { Histogram.Timer writeTimer = writeTimerLog.labels("write").startTimer(); Multihash hash = new Multihash(Multihash.Type.sha2_256, Hash.sha256(data)); Cid cid = new Cid(1, isRaw ? Cid.Codec.Raw : Cid.Codec.DagCbor, hash.type, hash.getHash()); String key = hashToKey(cid); try { transactions.addBlock(cid, tid, owner); String s3Key = folder + key; Map<String, String> extraHeaders = new TreeMap<>(); extraHeaders.put("Content-Type", "application/octet-stream"); boolean hashContent = true; String contentHash = hashContent ? ArrayOps.bytesToHex(hash.getHash()) : "UNSIGNED-PAYLOAD"; PresignedUrl putUrl = S3Request.preSignPut(s3Key, data.length, contentHash, false, ZonedDateTime.now(), host, extraHeaders, region, accessKeyId, secretKey); HttpUtil.put(putUrl, data); return cid; } catch (IOException e) { LOG.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { writeTimer.observeDuration(); } } private List<Multihash> getFiles(long maxReturned) { List<Multihash> results = new ArrayList<>(); applyToAll(obj -> { try { results.add(keyToHash(obj.key)); } catch (Exception e) { LOG.warning("Couldn't parse S3 key to Cid: " + obj.key); } }, maxReturned); return results; } private List<String> getFilenames(long maxReturned) { List<String> results = new ArrayList<>(); applyToAll(obj -> results.add(obj.key), maxReturned); return results; } private void applyToAll(Consumer<S3Request.ObjectMetadata> processor, long maxObjects) { try { Optional<String> continuationToken = Optional.empty(); S3Request.ListObjectsReply result; long processedObjects = 0; do { result = S3Request.listObjects(folder, 1_000, continuationToken, ZonedDateTime.now(), host, region, accessKeyId, secretKey, url -> { try { return HttpUtil.get(url); } catch (IOException e) { throw new RuntimeException(e); } }); for (S3Request.ObjectMetadata objectSummary : result.objects) { if (objectSummary.key.endsWith("/")) { LOG.fine(" - " + objectSummary.key + " " + "(directory)"); continue; } processor.accept(objectSummary); processedObjects++; if (processedObjects >= maxObjects) return; } LOG.log(Level.FINE, "Next Continuation Token : " + result.continuationToken); continuationToken = result.continuationToken; } while (result.isTruncated); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage(), e); } } public void delete(Multihash hash) { try { PresignedUrl delUrl = S3Request.preSignDelete(folder + hashToKey(hash), ZonedDateTime.now(), host, region, accessKeyId, secretKey); HttpUtil.delete(delUrl); } catch (Exception e) { throw new RuntimeException(e); } } public void bulkDelete(List<Multihash> hash) { try { List<String> keys = hash.stream() .map(h -> folder + hashToKey(h)) .collect(Collectors.toList()); S3Request.bulkDelete(keys, ZonedDateTime.now(), host, region, accessKeyId, secretKey, b -> ArrayOps.bytesToHex(Hash.sha256(b)), (url, body) -> { try { return HttpUtil.post(url, body); } catch (IOException e) { throw new RuntimeException(e); } }); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { System.out.println("Performing GC on block store..."); Args a = Args.parse(args); S3Config config = S3Config.build(a); boolean usePostgres = a.getBoolean("use-postgres", false); SqlSupplier sqlCommands = usePostgres ? new PostgresCommands() : new SqliteCommands(); Supplier<Connection> database = Main.getDBConnector(a, "mutable-pointers-file"); Supplier<Connection> transactionsDb = Main.getDBConnector(a, "transactions-sql-file"); TransactionStore transactions = JdbcTransactionStore.build(transactionsDb, sqlCommands); S3BlockStorage s3 = new S3BlockStorage(config, Cid.decode(a.getArg("ipfs.id")), BlockStoreProperties.empty(), transactions, new RAMStorage()); JdbcIpnsAndSocial rawPointers = new JdbcIpnsAndSocial(database, sqlCommands); s3.collectGarbage(rawPointers); } public static void test(String[] args) throws Exception { // Use this method to test access to a bucket S3Config config = S3Config.build(Args.parse(args)); System.out.println("Testing S3 bucket: " + config.bucket + " in region " + config.region + " with base dir: " + config.path); Multihash id = new Multihash(Multihash.Type.sha2_256, RAMStorage.hash("S3Storage".getBytes())); TransactionStore transactions = JdbcTransactionStore.build(Main.buildEphemeralSqlite(), new SqliteCommands()); S3BlockStorage s3 = new S3BlockStorage(config, id, BlockStoreProperties.empty(), transactions, new RAMStorage()); System.out.println("***** Testing ls and read"); System.out.println("Testing ls..."); List<Multihash> files = s3.getFiles(1000); System.out.println("Success! found " + files.size()); System.out.println("Testing read..."); byte[] data = s3.getRaw(files.get(0)).join().get(); System.out.println("Success: read blob of size " + data.length); System.out.println("Testing write..."); byte[] uploadData = new byte[10 * 1024]; new Random().nextBytes(uploadData); PublicKeyHash owner = PublicKeyHash.NULL; TransactionId tid = s3.startTransaction(owner).join(); Multihash put = s3.put(uploadData, true, tid, owner); System.out.println("Success!"); System.out.println("Testing delete..."); s3.delete(put); System.out.println("Success!"); } @Override public String toString() { return "S3BlockStore[" + bucket + ":" + folder + "]"; } }
package org.jasig.portal.channels; import java.io.StringWriter; import java.util.ResourceBundle; import java.text.MessageFormat; import java.lang.String; import org.jasig.portal.ChannelRuntimeData; import org.jasig.portal.ChannelRuntimeProperties; import org.jasig.portal.ChannelStaticData; import org.jasig.portal.IChannel; import org.jasig.portal.PortalEvent; import org.jasig.portal.PortalException; import org.jasig.portal.services.LogService; import org.jasig.portal.utils.XSLT; import org.xml.sax.ContentHandler; /** <p>A number guessing game which asks the user to enter a number within * a certain range as determined by this channel's parameters.</p> * @author Ken Weiner, kweiner@interactivebusiness.com * @version $Revision$ */ public class CNumberGuess implements IChannel { ChannelStaticData staticData = null; ChannelRuntimeData runtimeData = null; private static final String sslLocation = "CNumberGuess/CNumberGuess.ssl"; private static final String bundleLocation = "/org/jasig/portal/channels/CNumberGuess/CNumberGuess"; private int iMinNum = 0; private int iMaxNum = 0; private int iGuess = 0; private int iGuesses = 0; private int iAnswer = 0; private boolean bFirstTime = true; /** Constructs a CNumberGuess. */ public CNumberGuess () { this.staticData = new ChannelStaticData (); this.runtimeData = new ChannelRuntimeData (); } /** Returns channel runtime properties * @return handle to runtime properties */ public ChannelRuntimeProperties getRuntimeProperties () { // Channel will always render, so the default values are ok return new ChannelRuntimeProperties (); } /** Processes layout-level events coming from the portal * @param ev a portal layout event */ public void receiveEvent (PortalEvent ev) { // no events for this channel } /** Receive static channel data from the portal * @param sd static channel data */ public void setStaticData (ChannelStaticData sd) { this.staticData = sd; String sMinNum = null; String sMaxNum = null; try { if ((sMinNum = sd.getParameter ("minNum")) != null ) iMinNum = Integer.parseInt (sMinNum); if ((sMaxNum = sd.getParameter ("maxNum")) != null) iMaxNum = Integer.parseInt (sMaxNum); iAnswer = getRandomNumber (iMinNum, iMaxNum); } catch (NumberFormatException nfe) { iMinNum = 0; iMaxNum = 100; LogService.log(LogService.WARN, "CNumberGuess::setStaticData() : either " + sMinNum + " or " + sMaxNum + " (minNum, maxNum) is not a valid integer. Defaults " + iMinNum + " and " + iMaxNum + " will be used instead."); } } /** Receives channel runtime data from the portal and processes actions * passed to it. The names of these parameters are entirely up to the channel. * @param rd handle to channel runtime data */ public void setRuntimeData (ChannelRuntimeData rd) { this.runtimeData = rd; String sGuess = runtimeData.getParameter ("guess"); if (sGuess != null) { try { iGuess = Integer.parseInt (sGuess); } catch (NumberFormatException nfe) { // Assume that the guess was the same as last time } bFirstTime = false; iGuesses++; } } /** Output channel content to the portal * @param out a sax document handler */ public void renderXML (ContentHandler out) throws PortalException { String sSuggest = null; ResourceBundle l10n = ResourceBundle.getBundle(bundleLocation,runtimeData.getLocales()[0]); if (iGuess < iAnswer) sSuggest = l10n.getString("HIGHER"); else if (iGuess > iAnswer) sSuggest = l10n.getString("LOWER"); String GUESS_SUGGEST = MessageFormat.format(l10n.getString("GUESS_SUGGEST"), new String[] {sSuggest}); String THE_ANSWER_WAS_X = MessageFormat.format(l10n.getString("THE_ANSWER_WAS_X"), new String[] {String.valueOf(iAnswer)}); String YOU_GOT_IT_AFTER_X_TRIES = MessageFormat.format(l10n.getString("YOU_GOT_IT_AFTER_X_TRIES"), new String[] {String.valueOf(iGuesses)}); String YOU_HAVE_MADE_X_GUESSES = MessageFormat.format(l10n.getString("YOU_HAVE_MADE_X_GUESSES"), new String[] {String.valueOf(iGuesses)}); String YOUR_GUESS_OF_GUESS_WAS_INCORRECT = MessageFormat.format(l10n.getString("YOUR_GUESS_OF_GUESS_WAS_INCORRECT"), new String[] {String.valueOf(iGuess)}); String I_AM_THINKING_OF_A_NUMBER_BETWEEN_X_AND_Y = MessageFormat.format(l10n.getString("I_AM_THINKING_OF_A_NUMBER_BETWEEN_X_AND_Y"), new String[] {String.valueOf(iMinNum), String.valueOf(iMaxNum)}); StringWriter w = new StringWriter (); w.write ("<?xml version='1.0'?>\n"); w.write ("<content>\n"); w.write (" <minNum>" + iMinNum + "</minNum>\n"); w.write (" <maxNum>" + iMaxNum + "</maxNum>\n"); w.write (" <guesses>" + iGuesses + "</guesses>\n"); w.write (" <guess>" + iGuess + "</guess>\n"); if (bFirstTime) ; // Do nothing else if (iGuess == iAnswer) { w.write (" <answer>" + iAnswer + "</answer>\n"); bFirstTime = true; iGuesses = 0; iAnswer = getRandomNumber (iMinNum, iMaxNum); } else w.write (" <suggest>" + sSuggest + "</suggest>\n"); w.write ("</content>\n"); XSLT xslt = XSLT.getTransformer(this); xslt.setResourceBundle(l10n); xslt.setXML(w.toString()); xslt.setXSL(sslLocation, "main", runtimeData.getBrowserInfo()); xslt.setTarget(out); xslt.setStylesheetParameter("baseActionURL", runtimeData.getBaseActionURL()); xslt.setStylesheetParameter("guessSuggest", GUESS_SUGGEST); xslt.setStylesheetParameter("theAnswerWasX", THE_ANSWER_WAS_X); xslt.setStylesheetParameter("youHaveMadeXGuesses", YOU_HAVE_MADE_X_GUESSES); xslt.setStylesheetParameter("youGotItAfterXTries", YOU_GOT_IT_AFTER_X_TRIES); xslt.setStylesheetParameter("YourGuessOfGuessWasIncorrect", YOUR_GUESS_OF_GUESS_WAS_INCORRECT); xslt.setStylesheetParameter("IAmThinkingOfANumberBetweenXAndY", I_AM_THINKING_OF_A_NUMBER_BETWEEN_X_AND_Y); xslt.transform(); } private int getRandomNumber (int min, int max) { return new Double ((max - min) * Math.random () + min).intValue (); } }
package org.apache.batik.bridge; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.batik.dom.DocumentWrapper; import org.apache.batik.dom.DOMImplementationWrapper; import org.apache.batik.gvt.GraphicsNode; import org.apache.batik.gvt.RootGraphicsNode; import org.apache.batik.gvt.UpdateTracker; import org.apache.batik.gvt.renderer.ImageRenderer; import org.apache.batik.util.RunnableQueue; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.svg.SVGSVGElement; import org.w3c.dom.events.DocumentEvent; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import org.w3c.dom.events.MutationEvent; /** * This class provides features to manage the update of an SVG document. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id$ */ public class UpdateManager implements RunnableQueue.RunHandler { /** * The bridge context. */ protected BridgeContext bridgeContext; /** * The document to manage. */ protected Document document; /** * The renderer used to paint. */ protected ImageRenderer renderer; /** * The update RunnableQueue. */ protected RunnableQueue updateRunnableQueue; /** * The initial time. */ protected long initialTime; /** * The time elapsed in suspended state. */ protected long suspendedTime; /** * The starting time of the current pause. */ protected long suspendStartTime; /** * Whether the update manager is running. */ protected volatile boolean running; /** * The listeners. */ protected List listeners = Collections.synchronizedList(new LinkedList()); /** * The starting time. */ protected long startingTime; /** * The scripting environment. */ protected ScriptingEnvironment scriptingEnvironment; /** * The repaint manager. */ protected RepaintManager repaintManager; /** * The repaint-rate manager. */ protected RepaintRateManager repaintRateManager; /** * The update tracker. */ protected UpdateTracker updateTracker; /** * The GraphicsNode whose updates are to be tracked. */ protected GraphicsNode graphicsNode; /** * Creates a new update manager. * @param ctx The bridge context. * @param gn GraphicsNode whose updates are to be tracked. * @param doc The document to manage. * @param r The renderer. */ public UpdateManager(BridgeContext ctx, GraphicsNode gn, Document doc, ImageRenderer r) { bridgeContext = ctx; bridgeContext.setUpdateManager(this); document = doc; renderer = r; updateRunnableQueue = RunnableQueue.createRunnableQueue(); updateRunnableQueue.setRunHandler(this); updateTracker = new UpdateTracker(); graphicsNode = gn; RootGraphicsNode root = gn.getRoot(); if (root != null){ root.addTreeGraphicsNodeChangeListener(getUpdateTracker()); } repaintManager = new RepaintManager(this); repaintRateManager = new RepaintRateManager(this); repaintRateManager.start(); scriptingEnvironment = new ScriptingEnvironment(this); } /** * Returns the bridge context. */ public BridgeContext getBridgeContext() { return bridgeContext; } /** * Returns the update RunnableQueue. */ public RunnableQueue getUpdateRunnableQueue() { return updateRunnableQueue; } /** * Returns the repaint manager. */ public RepaintManager getRepaintManager() { return repaintManager; } /** * Returns the GVT update tracker. */ public UpdateTracker getUpdateTracker() { return updateTracker; } /** * Returns the current Document. */ public Document getDocument() { return document; } /** * Returns the scripting environment. */ public ScriptingEnvironment getScriptingEnvironment() { return scriptingEnvironment; } /** * Tells whether the update manager is currently running. */ public boolean isRunning() { return running; } /** * Returns the presentation time, in milliseconds. */ public long getPresentationTime() { if (running) { return System.currentTimeMillis() - initialTime - suspendedTime; } else { return suspendStartTime - initialTime - suspendedTime; } } /** * Suspends the update manager. */ public void suspend() { if (running) { running = false; updateRunnableQueue.suspendExecution(false); } } /** * Resumes the update manager. */ public void resume() { if (!running) { running = true; updateRunnableQueue.resumeExecution(); } } /** * Dispatches an 'SVGLoad' event to the document. * NOTE: This method starts the update manager threads so one can't use * the update runnable queue to invoke this method. */ public void dispatchSVGLoad() { updateRunnableQueue.resumeExecution(); updateRunnableQueue.invokeLater(new Runnable() { public void run() { running = true; startingTime = System.currentTimeMillis(); fireManagerStartedEvent(); SVGSVGElement svgElement = (SVGSVGElement)document.getDocumentElement(); String language = svgElement.getContentScriptType(); BridgeEventSupport.loadScripts(bridgeContext, svgElement); BridgeEventSupport.dispatchOnLoad(bridgeContext, svgElement, language); } }); } /** * Dispatches an 'SVGUnLoad' event to the document. * This method interrupts the update manager threads. * NOTE: this method must be called outside the update thread. */ public void dispatchSVGUnLoad() { resume(); updateRunnableQueue.invokeLater(new Runnable() { public void run() { Event evt = ((DocumentEvent)document).createEvent("SVGEvents"); evt.initEvent("SVGUnload", false, false); ((EventTarget)(document.getDocumentElement())). dispatchEvent(evt); running = false; repaintRateManager.interrupt(); updateRunnableQueue.getThread().interrupt(); fireManagerStoppedEvent(); } }); } /** * Call this to let the Update Manager know that certain areas * in the image have been modified and need to be rerendered.. */ public void modifiedAreas(List areas) { AffineTransform at = renderer.getTransform(); Iterator i = areas.iterator(); while (i.hasNext()) { Shape s = (Shape)i.next(); Rectangle r = at.createTransformedShape(s).getBounds(); renderer.flush(r); } } /** * Updates the rendering buffer. * @param u2d The user to device transform. * @param dbr Whether the double buffering should be used. * @param aoi The area of interest in the renderer space units. * @param width&nbsp;height The offscreen buffer size. */ public void updateRendering(AffineTransform u2d, boolean dbr, Shape aoi, int width, int height) { renderer.setTransform(u2d); renderer.setDoubleBuffered(dbr); renderer.updateOffScreen(width, height); renderer.clearOffScreen(); List l = new ArrayList(1); l.add(aoi); updateRendering(l); } /** * Updates the rendering buffer. * @param aoi The area of interest in the renderer space units. */ public void updateRendering(List areas) { try { fireStartedEvent(renderer.getOffScreen()); List rects = new ArrayList(areas.size()); AffineTransform at = renderer.getTransform(); Iterator i = areas.iterator(); while (i.hasNext()) { Shape s = (Shape)i.next(); Rectangle r = at.createTransformedShape(s).getBounds(); rects.add(r); } renderer.repaint(areas); fireCompletedEvent(renderer.getOffScreen(), rects); } catch (Exception e) { fireFailedEvent(); } } /** * Adds a UpdateManagerListener to this UpdateManager. */ public void addUpdateManagerListener(UpdateManagerListener l) { listeners.add(l); } /** * Removes a UpdateManagerListener from this UpdateManager. */ public void removeUpdateManagerListener(UpdateManagerListener l) { listeners.remove(l); } /** * Fires a UpdateManagerEvent to notify that the manager was started. */ protected void fireManagerStartedEvent() { Object[] dll = listeners.toArray(); if (dll.length > 0) { UpdateManagerEvent ev = new UpdateManagerEvent(this, null, null); for (int i = 0; i < dll.length; i++) { ((UpdateManagerListener)dll[i]).managerStarted(ev); } } } /** * Fires a UpdateManagerEvent to notify that the manager was stopped. */ protected void fireManagerStoppedEvent() { Object[] dll = listeners.toArray(); if (dll.length > 0) { UpdateManagerEvent ev = new UpdateManagerEvent(this, null, null); for (int i = 0; i < dll.length; i++) { ((UpdateManagerListener)dll[i]).managerStopped(ev); } } } /** * Fires a UpdateManagerEvent to notify that the manager was suspended. */ protected void fireManagerSuspendedEvent() { Object[] dll = listeners.toArray(); if (dll.length > 0) { UpdateManagerEvent ev = new UpdateManagerEvent(this, null, null); for (int i = 0; i < dll.length; i++) { ((UpdateManagerListener)dll[i]).managerSuspended(ev); } } } /** * Fires a UpdateManagerEvent to notify that the manager was resumed. */ protected void fireManagerResumedEvent() { suspendedTime = System.currentTimeMillis() - suspendStartTime; Object[] dll = listeners.toArray(); if (dll.length > 0) { UpdateManagerEvent ev = new UpdateManagerEvent(this, null, null); for (int i = 0; i < dll.length; i++) { ((UpdateManagerListener)dll[i]).managerResumed(ev); } } } /** * Fires a UpdateManagerEvent in the starting phase of an update. */ protected void fireStartedEvent(BufferedImage bi) { Object[] dll = listeners.toArray(); if (dll.length > 0) { UpdateManagerEvent ev = new UpdateManagerEvent(this, bi, null); for (int i = 0; i < dll.length; i++) { ((UpdateManagerListener)dll[i]).updateStarted(ev); } } } /** * Fires a UpdateManagerEvent when an update completed. */ protected void fireCompletedEvent(BufferedImage bi, List rects) { Object[] dll = listeners.toArray(); if (dll.length > 0) { UpdateManagerEvent ev = new UpdateManagerEvent(this, bi, rects); for (int i = 0; i < dll.length; i++) { ((UpdateManagerListener)dll[i]).updateCompleted(ev); } } } /** * Fires a UpdateManagerEvent when an update failed. */ protected void fireFailedEvent() { Object[] dll = listeners.toArray(); if (dll.length > 0) { UpdateManagerEvent ev = new UpdateManagerEvent(this, null, null); for (int i = 0; i < dll.length; i++) { ((UpdateManagerListener)dll[i]).updateFailed(ev); } } } // RunnableQueue.RunHandler ///////////////////////////////////////// /** * Called when the given Runnable has just been invoked and * has returned. */ public void runnableInvoked(RunnableQueue rq, Runnable r) { } /** * Called when the execution of the queue has been suspended. */ public void executionSuspended(RunnableQueue rq) { if (!running) { suspendStartTime = System.currentTimeMillis(); if (scriptingEnvironment != null) { scriptingEnvironment.suspendScripts(); } fireManagerSuspendedEvent(); } } /** * Called when the execution of the queue has been resumed. */ public void executionResumed(RunnableQueue rq) { if (running) { suspendedTime = System.currentTimeMillis() - suspendStartTime; fireManagerResumedEvent(); if (scriptingEnvironment != null) { scriptingEnvironment.resumeScripts(); } } } }
package org.broad.igv; import org.apache.log4j.Logger; import java.awt.*; import java.io.IOException; import java.util.*; import java.util.List; import java.util.regex.Pattern; public class Globals { private static Logger log = Logger.getLogger(Globals.class); /** * CONSTANTS */ public static final String CHR_ALL = "All"; public static final String TRACK_NAME_ATTRIBUTE = "NAME"; public static final String TRACK_DATA_FILE_ATTRIBUTE = "DATA FILE"; public static final String TRACK_DATA_TYPE_ATTRIBUTE = "DATA TYPE"; private static boolean headless = false; private static boolean suppressMessages = false; private static boolean batch = false; private static boolean testing = false; public static int CONNECT_TIMEOUT = 20000; // 20 seconds public static int READ_TIMEOUT = 1000 * 3 * 60; // 3 minutes /** * Field description */ final public static String SESSION_FILE_EXTENSION = ".xml"; /** * GENOME ARCHIVE CONSTANTS */ final public static String GENOME_FILE_EXTENSION = ".genome"; final public static String ZIP_EXTENSION = ".zip"; final public static String GZIP_FILE_EXTENSION = ".gz"; final public static String GENOME_ARCHIVE_PROPERTY_FILE_NAME = "property.txt"; final public static String GENOME_ARCHIVE_ID_KEY = "id"; final public static String GENOME_ARCHIVE_NAME_KEY = "name"; final public static String GENOME_ARCHIVE_VERSION_KEY = "version"; final public static String GENOME_ORDERED_KEY = "ordered"; final public static String GENOME_GENETRACK_NAME = "geneTrackName"; final public static String GENOME_URL_KEY = "url"; final public static String GENOME_ARCHIVE_CYTOBAND_FILE_KEY = "cytobandFile"; final public static String GENOME_ARCHIVE_GENE_FILE_KEY = "geneFile"; final public static String GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY = "sequenceLocation"; public static final String GENOME_CHR_ALIAS_FILE_KEY = "chrAliasFile"; public static final String DEFAULT_GENOME = "hg18"; // Default user folder final static public Pattern commaPattern = Pattern.compile(","); final static public Pattern tabPattern = Pattern.compile("\t"); final static public Pattern colonPattern = Pattern.compile(":"); final static public Pattern dashPattern = Pattern.compile("-"); final static public Pattern equalPattern = Pattern.compile("="); final static public Pattern semicolonPattern = Pattern.compile(";"); final static public Pattern singleTabMultiSpacePattern = Pattern.compile("\t|( +)"); final static public Pattern forwardSlashPattern = Pattern.compile("/"); final static public Pattern whitespacePattern = Pattern.compile("\\s+"); public static List emptyList = new ArrayList(); public static String VERSION; public static String BUILD; public static String TIMESTAMP; public static double log2 = Math.log(2); final public static boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows"); final public static boolean IS_MAC = System.getProperty("os.name").toLowerCase().startsWith("mac"); final public static boolean IS_LINUX = System.getProperty("os.name").toLowerCase().startsWith("linux"); final public static boolean IS_JWS = System.getProperty("webstart.version", null) != null || System.getProperty("javawebstart.version", null) != null; public static final String JAVA_VERSION_STRING = "java.version"; public static Map<Character, Color> nucleotideColors; //Location of bedtools executable //Note: It is recommended you use an absolute path here. //System paths can be finnicky and vary depending on how IGV is launched //However, the path environment variable will be checked if the executable //is named rather than the full path given public static String BEDtoolsPath = "/usr/local/bin/bedtools"; //"bedtools" public static boolean toolsMenuEnabled = false; public static boolean production; static { Properties properties = new Properties(); try { properties.load(Globals.class.getResourceAsStream("/resources/about.properties")); } catch (IOException e) { log.error("*** Error retrieving version and build information! ***", e); } VERSION = properties.getProperty("version", "???"); BUILD = properties.getProperty("build", "???"); TIMESTAMP = properties.getProperty("timestamp", "???"); nucleotideColors = new HashMap(); nucleotideColors.put('A', Color.GREEN); nucleotideColors.put('a', Color.GREEN); nucleotideColors.put('C', Color.BLUE); nucleotideColors.put('c', Color.BLUE); nucleotideColors.put('T', Color.RED); nucleotideColors.put('t', Color.RED); nucleotideColors.put('G', new Color(209, 113, 5)); nucleotideColors.put('g', new Color(209, 113, 5)); nucleotideColors.put('N', Color.gray.brighter()); nucleotideColors.put('n', Color.gray.brighter()); BEDtoolsPath = System.getProperty("BEDtoolsPath", BEDtoolsPath); final String prodProperty = System.getProperty("production", "true"); production = Boolean.parseBoolean(prodProperty); } public static void setHeadless(boolean bool) { headless = bool; } public static boolean isHeadless() { return headless; } public static void setTesting(boolean testing) { Globals.testing = testing; } public static boolean isTesting() { return testing; } public static void setSuppressMessages(boolean bool) { suppressMessages = bool; } public static boolean isSuppressMessages() { return suppressMessages; } public static String applicationString() { return "IGV Version " + VERSION + " (" + BUILD + ")" + TIMESTAMP; } public static String versionString() { return "<html>Version " + VERSION + " (" + BUILD + ")<br>" + TIMESTAMP; } public static boolean isProduction() { return production; } public static boolean isBatch() { return batch; } public static void setBatch(boolean batch) { Globals.batch = batch; } /** * Checks whether the current JVM is the minimum specified version * or higher. Only compares up to as many characters as * in {@code minVersion} * * @param minVersion * @return */ public static boolean isVersionOrHigher(String minVersion) { String curVersion = System.getProperty(JAVA_VERSION_STRING); if (curVersion.length() >= minVersion.length()) { curVersion = curVersion.substring(0, minVersion.length()); } return curVersion.compareTo(minVersion) >= 0; } }
package org.exist.backup; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Properties; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.xml.parsers.ParserConfigurationException; import org.apache.avalon.excalibur.cli.CLArgsParser; import org.apache.avalon.excalibur.cli.CLOption; import org.apache.avalon.excalibur.cli.CLOptionDescriptor; import org.apache.avalon.excalibur.cli.CLUtil; import org.exist.xmldb.DatabaseInstanceManager; import org.xml.sax.SAXException; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.base.XMLDBException; /** * Main.java * * @author Wolfgang Meier */ public class Main { private final static int HELP_OPT = 'h'; private final static int USER_OPT = 'u'; private final static int PASS_OPT = 'p'; private final static int BACKUP_OPT = 'b'; private final static int BACKUP_DIR_OPT = 'd'; private final static int RESTORE_OPT = 'r'; private final static int OPTION_OPT = 'o'; private final static int GUI_OPT = 'U'; private final static CLOptionDescriptor OPTIONS[] = new CLOptionDescriptor[] { new CLOptionDescriptor( "help", CLOptionDescriptor.ARGUMENT_DISALLOWED, HELP_OPT, "print help on command line options and exit."), new CLOptionDescriptor( "gui", CLOptionDescriptor.ARGUMENT_DISALLOWED, GUI_OPT, "start in GUI mode"), new CLOptionDescriptor( "user", CLOptionDescriptor.ARGUMENT_REQUIRED, USER_OPT, "set user."), new CLOptionDescriptor( "password", CLOptionDescriptor.ARGUMENT_REQUIRED, PASS_OPT, "set password."), new CLOptionDescriptor( "backup", CLOptionDescriptor.ARGUMENT_OPTIONAL, BACKUP_OPT, "backup the specified collection."), new CLOptionDescriptor( "dir", CLOptionDescriptor.ARGUMENT_REQUIRED, BACKUP_DIR_OPT, "specify the directory to use for backups."), new CLOptionDescriptor( "restore", CLOptionDescriptor.ARGUMENT_REQUIRED, RESTORE_OPT, "read the specified restore file and restore the " + "resources described there."), new CLOptionDescriptor( "option", CLOptionDescriptor.ARGUMENTS_REQUIRED_2 | CLOptionDescriptor.DUPLICATES_ALLOWED, OPTION_OPT, "specify extra options: property=value. For available properties see " + "client.properties.")}; /** * Constructor for Main. */ public static void process(String args[]) { // read properties Properties properties = new Properties(); try { String home = System.getProperty("exist.home"); File propFile; if (home == null) propFile = new File("backup.properties"); else propFile = new File( home + System.getProperty("file.separator", "/") + "backup.properties"); InputStream pin; if (propFile.canRead()) pin = new FileInputStream(propFile); else pin = Main.class.getResourceAsStream("backup.properties"); if (pin != null) properties.load(pin); } catch (IOException ioe) { } // parse command-line options final CLArgsParser optParser = new CLArgsParser(args, OPTIONS); if (optParser.getErrorString() != null) { System.err.println("ERROR: " + optParser.getErrorString()); return; } final List opt = optParser.getArguments(); final int size = opt.size(); CLOption option; String optionBackup = null; String optionRestore = null; String optionPass = null; boolean doBackup = false; boolean doRestore = false; boolean guiMode = false; for (int i = 0; i < size; i++) { option = (CLOption) opt.get(i); switch (option.getId()) { case HELP_OPT : printUsage(); return; case GUI_OPT : guiMode = true; break; case OPTION_OPT : properties.setProperty(option.getArgument(0), option.getArgument(1)); break; case USER_OPT : properties.setProperty("user", option.getArgument()); break; case PASS_OPT : optionPass = option.getArgument(); break; case BACKUP_OPT : if (option.getArgumentCount() == 1) optionBackup = option.getArgument(); else optionBackup = null; doBackup = true; break; case RESTORE_OPT : if(option.getArgumentCount() == 1) optionRestore = option.getArgument(); doRestore = true; break; case BACKUP_DIR_OPT : properties.setProperty("backup-dir", option.getArgument()); break; } } // initialize driver Database database; try { Class cl = Class.forName(properties.getProperty("driver", "org.exist.xmldb.DatabaseImpl")); database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); if (properties.containsKey("configuration")) database.setProperty("configuration", properties.getProperty("configuration")); DatabaseManager.registerDatabase(database); } catch (ClassNotFoundException e) { reportError(e); return; } catch (InstantiationException e) { reportError(e); return; } catch (IllegalAccessException e) { reportError(e); return; } catch (XMLDBException e) { reportError(e); return; } // process if (doBackup) { if (optionBackup == null) { if (guiMode) { CreateBackupDialog dialog = new CreateBackupDialog( properties.getProperty("uri", "xmldb:exist: properties.getProperty("user", "admin"), optionPass, properties.getProperty("backup-dir", System.getProperty("user.home") + File.separatorChar + "backup")); if (JOptionPane .showOptionDialog( null, dialog, "Create Backup", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null) == JOptionPane.YES_OPTION) { optionBackup = dialog.getCollection(); properties.setProperty("backup-dir", dialog.getBackupDir()); } } else optionBackup = "/db"; } if (optionBackup != null) { Backup backup = new Backup( properties.getProperty("user", "admin"), optionPass, properties.getProperty("backup-dir", "backup"), properties.getProperty("uri", "xmldb:exist://") + optionBackup); try { backup.backup(guiMode, null); } catch (XMLDBException e) { reportError(e); } catch (IOException e) { reportError(e); } catch (SAXException e) { System.err.println("ERROR: " + e.getMessage()); System.err.println("caused by "); e.getException().printStackTrace(); } } } if (doRestore) { if (optionRestore == null && guiMode) { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if (chooser.showDialog(null, "Select backup file for restore") == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); optionRestore = f.getAbsolutePath(); } } if (optionRestore != null) { try { Restore restore = new Restore( properties.getProperty("user", "admin"), optionPass, new File(optionRestore), properties.getProperty("uri", "xmldb:exist: restore.restore(guiMode, null); } catch (FileNotFoundException e) { reportError(e); } catch (ParserConfigurationException e) { reportError(e); } catch (SAXException e) { reportError(e); } catch (XMLDBException e) { reportError(e); } catch (IOException e) { reportError(e); } } } try { Collection root = DatabaseManager.getCollection( properties.getProperty("uri", "xmldb:exist: properties.getProperty("user", "admin"), optionPass); shutdown(root); } catch (XMLDBException e1) { e1.printStackTrace(); } System.exit(0); } private final static void reportError(Throwable e) { System.err.println("ERROR: " + e.getMessage()); e.printStackTrace(); if (e.getCause() != null) { System.err.println("caused by "); e.getCause().printStackTrace(); } } private final static void printUsage() { System.out.println("Usage: java " + Main.class.getName() + " [options]"); System.out.println(CLUtil.describeOptions(OPTIONS).toString()); } private final static void shutdown(Collection root) { try { DatabaseInstanceManager mgr = (DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0"); if (mgr == null) { System.err.println("service is not available"); } else if (mgr.isLocalInstance()) { System.out.println("shutting down database..."); mgr.shutdown(); } } catch (XMLDBException e) { System.err.println("database shutdown failed: "); e.printStackTrace(); } } public static void main(String[] args) { process(args); } }
package org.jgroups.util; import org.jgroups.*; import org.jgroups.auth.AuthToken; import org.jgroups.blocks.Connection; import org.jgroups.conf.ClassConfigurator; import org.jgroups.jmx.JmxConfigurator; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.protocols.*; import org.jgroups.protocols.pbcast.FLUSH; import org.jgroups.protocols.pbcast.GMS; import org.jgroups.stack.IpAddress; import org.jgroups.stack.ProtocolStack; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.io.*; import java.lang.annotation.Annotation; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.security.MessageDigest; import java.text.NumberFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * Collection of various utility routines that can not be assigned to other classes. * @author Bela Ban * @version $Id: Util.java,v 1.275 2010/09/28 15:10:31 belaban Exp $ */ public class Util { private static NumberFormat f; private static Map<Class,Byte> PRIMITIVE_TYPES=new HashMap<Class,Byte>(15); private static final byte TYPE_NULL = 0; private static final byte TYPE_STREAMABLE = 1; private static final byte TYPE_SERIALIZABLE = 2; private static final byte TYPE_BOOLEAN = 10; private static final byte TYPE_BYTE = 11; private static final byte TYPE_CHAR = 12; private static final byte TYPE_DOUBLE = 13; private static final byte TYPE_FLOAT = 14; private static final byte TYPE_INT = 15; private static final byte TYPE_LONG = 16; private static final byte TYPE_SHORT = 17; private static final byte TYPE_STRING = 18; private static final byte TYPE_BYTEARRAY = 19; // constants public static final int MAX_PORT=65535; // highest port allocatable static boolean resolve_dns=false; private static short COUNTER=1; private static Pattern METHOD_NAME_TO_ATTR_NAME_PATTERN=Pattern.compile("[A-Z]+"); private static Pattern ATTR_NAME_TO_METHOD_NAME_PATTERN=Pattern.compile("_."); protected static int CCHM_INITIAL_CAPACITY=16; protected static float CCHM_LOAD_FACTOR=0.75f; protected static int CCHM_CONCURRENCY_LEVEL=16; /** * Global thread group to which all (most!) JGroups threads belong */ private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") { public void uncaughtException(Thread t, Throwable e) { LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e); final ThreadGroup tgParent = getParent(); if(tgParent != null) { tgParent.uncaughtException(t,e); } } }; public static ThreadGroup getGlobalThreadGroup() { return GLOBAL_GROUP; } public static enum AddressScope {GLOBAL, SITE_LOCAL, LINK_LOCAL, LOOPBACK, NON_LOOPBACK}; private static StackType ip_stack_type=_getIpStackType(); static { try { resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue(); } catch (SecurityException ex){ resolve_dns=false; } f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); // f.setMinimumFractionDigits(2); f.setMaximumFractionDigits(2); PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN)); PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE)); PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR)); PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE)); PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT)); PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT)); PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG)); PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT)); PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING)); PRIMITIVE_TYPES.put(byte[].class, new Byte(TYPE_BYTEARRAY)); if(ip_stack_type == StackType.Unknown) ip_stack_type=StackType.IPv6; try { String cchm_initial_capacity=System.getProperty(Global.CCHM_INITIAL_CAPACITY); if(cchm_initial_capacity != null) CCHM_INITIAL_CAPACITY=Integer.valueOf(cchm_initial_capacity); } catch(SecurityException ex) {} try { String cchm_load_factor=System.getProperty(Global.CCHM_LOAD_FACTOR); if(cchm_load_factor != null) CCHM_LOAD_FACTOR=Float.valueOf(cchm_load_factor); } catch(SecurityException ex) {} try { String cchm_concurrency_level=System.getProperty(Global.CCHM_CONCURRENCY_LEVEL); if(cchm_concurrency_level != null) CCHM_CONCURRENCY_LEVEL=Integer.valueOf(cchm_concurrency_level); } catch(SecurityException ex) {} } public static void assertTrue(boolean condition) { assert condition; } public static void assertTrue(String message, boolean condition) { if(message != null) assert condition : message; else assert condition; } public static void assertFalse(boolean condition) { assertFalse(null, condition); } public static void assertFalse(String message, boolean condition) { if(message != null) assert !condition : message; else assert !condition; } public static void assertEquals(String message, Object val1, Object val2) { if(message != null) { assert val1.equals(val2) : message; } else { assert val1.equals(val2); } } public static void assertEquals(Object val1, Object val2) { assertEquals(null, val1, val2); } public static void assertNotNull(String message, Object val) { if(message != null) assert val != null : message; else assert val != null; } public static void assertNotNull(Object val) { assertNotNull(null, val); } public static void assertNull(String message, Object val) { if(message != null) assert val == null : message; else assert val == null; } /** * Blocks until all channels have the same view * @param timeout How long to wait (max in ms) * @param interval Check every interval ms * @param channels The channels which should form the view. The expected view size is channels.length. * Must be non-null */ public static void blockUntilViewsReceived(long timeout, long interval, Channel ... channels) throws TimeoutException { final int expected_size=channels.length; if(interval > timeout) throw new IllegalArgumentException("interval needs to be smaller than timeout"); final long end_time=System.currentTimeMillis() + timeout; while(System.currentTimeMillis() < end_time) { boolean all_ok=true; for(Channel ch: channels) { View view=ch.getView(); if(view == null || view.size() != expected_size) { all_ok=false; break; } } if(all_ok) return; Util.sleep(interval); } throw new TimeoutException(); } public static void addFlush(Channel ch, FLUSH flush) { if(ch == null || flush == null) throw new IllegalArgumentException("ch and flush have to be non-null"); ProtocolStack stack=ch.getProtocolStack(); stack.insertProtocolAtTop(flush); } public static void setScope(Message msg, short scope) { SCOPE.ScopeHeader hdr=SCOPE.ScopeHeader.createMessageHeader(scope); msg.putHeader(Global.SCOPE_ID, hdr); msg.setFlag(Message.SCOPED); } public static short getScope(Message msg) { SCOPE.ScopeHeader hdr=(SCOPE.ScopeHeader)msg.getHeader(Global.SCOPE_ID); return hdr != null? hdr.getScope() : 0; } public static SCOPE.ScopeHeader getScopeHeader(Message msg) { return (SCOPE.ScopeHeader)msg.getHeader(Global.SCOPE_ID); } /** * Utility method. If the dest address is IPv6, convert scoped link-local addrs into unscoped ones * @param sock * @param dest * @param sock_conn_timeout * @throws IOException */ public static void connect(Socket sock, SocketAddress dest, int sock_conn_timeout) throws IOException { if(dest instanceof InetSocketAddress) { InetAddress addr=((InetSocketAddress)dest).getAddress(); if(addr instanceof Inet6Address) { Inet6Address tmp=(Inet6Address)addr; if(tmp.getScopeId() != 0) { dest=new InetSocketAddress(InetAddress.getByAddress(tmp.getAddress()), ((InetSocketAddress)dest).getPort()); } } } sock.connect(dest, sock_conn_timeout); } public static void close(InputStream inp) { if(inp != null) try {inp.close();} catch(IOException e) {} } public static void close(OutputStream out) { if(out != null) { try {out.close();} catch(IOException e) {} } } public static void close(Socket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(ServerSocket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(DatagramSocket my_sock) { if(my_sock != null) { try {my_sock.close();} catch(Throwable t) {} } } public static void close(Channel ch) { if(ch != null) { try {ch.close();} catch(Throwable t) {} } } public static void close(Channel ... channels) { if(channels != null) { for(Channel ch: channels) Util.close(ch); } } public static void close(Connection conn) { if(conn != null) { try {conn.close();} catch(Throwable t) {} } } /** Drops messages to/from other members and then closes the channel. Note that this member won't get excluded from * the view until failure detection has kicked in and the new coord installed the new view */ public static void shutdown(Channel ch) throws Exception { DISCARD discard=new DISCARD(); discard.setLocalAddress(ch.getAddress()); discard.setDiscardAll(true); ProtocolStack stack=ch.getProtocolStack(); TP transport=stack.getTransport(); stack.insertProtocol(discard, ProtocolStack.ABOVE, transport.getClass()); //abruptly shutdown FD_SOCK just as in real life when member gets killed non gracefully FD_SOCK fd = (FD_SOCK) ch.getProtocolStack().findProtocol("FD_SOCK"); if(fd != null) fd.stopServerSocket(false); View view=ch.getView(); if (view != null) { ViewId vid = view.getViewId(); List<Address> members = Arrays.asList(ch.getAddress()); ViewId new_vid = new ViewId(ch.getAddress(), vid.getId() + 1); View new_view = new View(new_vid, members); // inject view in which the shut down member is the only element GMS gms = (GMS) stack.findProtocol(GMS.class); gms.installView(new_view); } Util.close(ch); } public static byte setFlag(byte bits, byte flag) { return bits |= flag; } public static boolean isFlagSet(byte bits, byte flag) { return (bits & flag) == flag; } public static byte clearFlags(byte bits, byte flag) { return bits &= ~flag; } /** * Creates an object from a byte buffer */ public static Object objectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; return objectFromByteBuffer(buffer, 0, buffer.length); } public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Object retval=null; byte type=buffer[offset]; switch(type) { case TYPE_NULL: return null; case TYPE_STREAMABLE: ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset+1, length-1); InputStream in=new DataInputStream(in_stream); retval=readGenericStreamable((DataInputStream)in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable in_stream=new ExposedByteArrayInputStream(buffer, offset+1, length-1); in=new ObjectInputStream(in_stream); // changed Nov 29 2004 (bela) try { retval=((ObjectInputStream)in).readObject(); } finally { Util.close(in); } break; case TYPE_BOOLEAN: return ByteBuffer.wrap(buffer, offset + 1, length - 1).get() == 1; case TYPE_BYTE: return ByteBuffer.wrap(buffer, offset + 1, length - 1).get(); case TYPE_CHAR: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getChar(); case TYPE_DOUBLE: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getDouble(); case TYPE_FLOAT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getFloat(); case TYPE_INT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getInt(); case TYPE_LONG: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getLong(); case TYPE_SHORT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getShort(); case TYPE_STRING: byte[] tmp=new byte[length -1]; System.arraycopy(buffer, offset +1, tmp, 0, length -1); return new String(tmp); case TYPE_BYTEARRAY: tmp=new byte[length -1]; System.arraycopy(buffer, offset +1, tmp, 0, length -1); return tmp; default: throw new IllegalArgumentException("type " + type + " is invalid"); } return retval; } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable or Streamable. */ public static byte[] objectToByteBuffer(Object obj) throws Exception { if(obj == null) return ByteBuffer.allocate(Global.BYTE_SIZE).put(TYPE_NULL).array(); if(obj instanceof Streamable) { final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(128); final ExposedDataOutputStream out=new ExposedDataOutputStream(out_stream); out_stream.write(TYPE_STREAMABLE); writeGenericStreamable((Streamable)obj, out); return out_stream.toByteArray(); } Byte type=PRIMITIVE_TYPES.get(obj.getClass()); if(type == null) { // will throw an exception if object is not serializable final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(128); out_stream.write(TYPE_SERIALIZABLE); ObjectOutputStream out=new ObjectOutputStream(out_stream); out.writeObject(obj); out.close(); return out_stream.toByteArray(); } switch(type.byteValue()) { case TYPE_BOOLEAN: return ByteBuffer.allocate(Global.BYTE_SIZE * 2).put(TYPE_BOOLEAN) .put(((Boolean)obj).booleanValue()? (byte)1 : (byte)0).array(); case TYPE_BYTE: return ByteBuffer.allocate(Global.BYTE_SIZE *2).put(TYPE_BYTE).put(((Byte)obj).byteValue()).array(); case TYPE_CHAR: return ByteBuffer.allocate(Global.BYTE_SIZE *3).put(TYPE_CHAR).putChar(((Character)obj).charValue()).array(); case TYPE_DOUBLE: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.DOUBLE_SIZE).put(TYPE_DOUBLE) .putDouble(((Double)obj).doubleValue()).array(); case TYPE_FLOAT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.FLOAT_SIZE).put(TYPE_FLOAT) .putFloat(((Float)obj).floatValue()).array(); case TYPE_INT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.INT_SIZE).put(TYPE_INT) .putInt(((Integer)obj).intValue()).array(); case TYPE_LONG: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.LONG_SIZE).put(TYPE_LONG) .putLong(((Long)obj).longValue()).array(); case TYPE_SHORT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.SHORT_SIZE).put(TYPE_SHORT) .putShort(((Short)obj).shortValue()).array(); case TYPE_STRING: String str=(String)obj; byte[] buf=new byte[str.length()]; for(int i=0; i < buf.length; i++) buf[i]=(byte)str.charAt(i); return ByteBuffer.allocate(Global.BYTE_SIZE + buf.length).put(TYPE_STRING).put(buf, 0, buf.length).array(); case TYPE_BYTEARRAY: buf=(byte[])obj; return ByteBuffer.allocate(Global.BYTE_SIZE + buf.length).put(TYPE_BYTEARRAY) .put(buf, 0, buf.length).array(); default: throw new IllegalArgumentException("type " + type + " is invalid"); } } public static void objectToStream(Object obj, DataOutputStream out) throws Exception { if(obj == null) { out.write(TYPE_NULL); return; } Byte type; try { if(obj instanceof Streamable) { // use Streamable if we can out.write(TYPE_STREAMABLE); writeGenericStreamable((Streamable)obj, out); } else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) { out.write(type.byteValue()); switch(type.byteValue()) { case TYPE_BOOLEAN: out.writeBoolean(((Boolean)obj).booleanValue()); break; case TYPE_BYTE: out.writeByte(((Byte)obj).byteValue()); break; case TYPE_CHAR: out.writeChar(((Character)obj).charValue()); break; case TYPE_DOUBLE: out.writeDouble(((Double)obj).doubleValue()); break; case TYPE_FLOAT: out.writeFloat(((Float)obj).floatValue()); break; case TYPE_INT: out.writeInt(((Integer)obj).intValue()); break; case TYPE_LONG: out.writeLong(((Long)obj).longValue()); break; case TYPE_SHORT: out.writeShort(((Short)obj).shortValue()); break; case TYPE_STRING: String str=(String)obj; if(str.length() > Short.MAX_VALUE) { out.writeBoolean(true); ObjectOutputStream oos=new ObjectOutputStream(out); try { oos.writeObject(str); } finally { oos.close(); } } else { out.writeBoolean(false); out.writeUTF(str); } break; case TYPE_BYTEARRAY: byte[] buf=(byte[])obj; out.writeInt(buf.length); out.write(buf, 0, buf.length); break; default: throw new IllegalArgumentException("type " + type + " is invalid"); } } else { // will throw an exception if object is not serializable out.write(TYPE_SERIALIZABLE); ObjectOutputStream tmp=new ObjectOutputStream(out); tmp.writeObject(obj); } } finally { Util.close(out); } } public static Object objectFromStream(DataInputStream in) throws Exception { if(in == null) return null; Object retval=null; byte b=(byte)in.read(); switch(b) { case TYPE_NULL: return null; case TYPE_STREAMABLE: retval=readGenericStreamable(in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable ObjectInputStream tmp=new ObjectInputStream(in); retval=tmp.readObject(); break; case TYPE_BOOLEAN: retval=Boolean.valueOf(in.readBoolean()); break; case TYPE_BYTE: retval=Byte.valueOf(in.readByte()); break; case TYPE_CHAR: retval=Character.valueOf(in.readChar()); break; case TYPE_DOUBLE: retval=Double.valueOf(in.readDouble()); break; case TYPE_FLOAT: retval=Float.valueOf(in.readFloat()); break; case TYPE_INT: retval=Integer.valueOf(in.readInt()); break; case TYPE_LONG: retval=Long.valueOf(in.readLong()); break; case TYPE_SHORT: retval=Short.valueOf(in.readShort()); break; case TYPE_STRING: if(in.readBoolean()) { // large string ObjectInputStream ois=new ObjectInputStream(in); try { retval=ois.readObject(); } finally { ois.close(); } } else { retval=in.readUTF(); } break; case TYPE_BYTEARRAY: int len=in.readInt(); byte[] tmpbuf=new byte[len]; in.readFully(tmpbuf, 0, tmpbuf.length); retval=tmpbuf; break; default: throw new IllegalArgumentException("type " + b + " is invalid"); } return retval; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static byte[] streamableToByteBuffer(Streamable obj) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(out_stream); obj.writeTo(out); result=out_stream.toByteArray(); out.close(); return result; } public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(out_stream); Util.writeAddresses(c, out); result=out_stream.toByteArray(); out.close(); return result; } public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{ Util.writeString(token.getName(), out); token.writeTo(out); } public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { try{ String type = Util.readString(in); Object obj = Class.forName(type).newInstance(); AuthToken token = (AuthToken) obj; token.readFrom(in); return token; } catch(ClassNotFoundException cnfe){ return null; } } public static void writeView(View view, DataOutputStream out) throws IOException { if(view == null) { out.writeBoolean(false); return; } out.writeBoolean(true); out.writeBoolean(view instanceof MergeView); view.writeTo(out); } public static View readView(DataInputStream in) throws IOException, InstantiationException, IllegalAccessException { if(in.readBoolean() == false) return null; boolean isMergeView=in.readBoolean(); View view; if(isMergeView) view=new MergeView(); else view=new View(); view.readFrom(in); return view; } public static void writeAddress(Address addr, DataOutputStream out) throws IOException { byte flags=0; boolean streamable_addr=true; if(addr == null) { flags=Util.setFlag(flags, Address.NULL); out.writeByte(flags); return; } if(addr instanceof UUID) { flags=Util.setFlag(flags, Address.UUID_ADDR); } else if(addr instanceof IpAddress) { flags=Util.setFlag(flags, Address.IP_ADDR); } else { streamable_addr=false; } out.writeByte(flags); if(streamable_addr) addr.writeTo(out); else writeOtherAddress(addr, out); } public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { byte flags=in.readByte(); if(Util.isFlagSet(flags, Address.NULL)) return null; Address addr; if(Util.isFlagSet(flags, Address.UUID_ADDR)) { addr=new UUID(); addr.readFrom(in); } else if(Util.isFlagSet(flags, Address.IP_ADDR)) { addr=new IpAddress(); addr.readFrom(in); } else { addr=readOtherAddress(in); } return addr; } public static int size(Address addr) { int retval=Global.BYTE_SIZE; // flags if(addr != null) { if(addr instanceof UUID || addr instanceof IpAddress) retval+=addr.size(); else { retval+=Global.SHORT_SIZE; // magic number retval+=addr.size(); } } return retval; } public static int size(View view) { int retval=Global.BYTE_SIZE; // presence if(view != null) retval+=view.serializedSize() + Global.BYTE_SIZE; // merge view or regular view return retval; } private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { short magic_number=in.readShort(); Class cl=ClassConfigurator.get(magic_number); if(cl == null) throw new RuntimeException("class for magic number " + magic_number + " not found"); Address addr=(Address)cl.newInstance(); addr.readFrom(in); return addr; } private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException { short magic_number=ClassConfigurator.getMagicNumber(addr.getClass()); // write the class info if(magic_number == -1) throw new RuntimeException("magic number " + magic_number + " not found"); out.writeShort(magic_number); addr.writeTo(out); } /** * Writes a Vector of Addresses. Can contain 65K addresses at most * @param v A Collection<Address> * @param out * @throws IOException */ public static void writeAddresses(Collection<? extends Address> v, DataOutputStream out) throws IOException { if(v == null) { out.writeShort(-1); return; } out.writeShort(v.size()); for(Address addr: v) { Util.writeAddress(addr, out); } } public static Collection<? extends Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException { short length=in.readShort(); if(length < 0) return null; Collection<Address> retval=(Collection<Address>)cl.newInstance(); Address addr; for(int i=0; i < length; i++) { addr=Util.readAddress(in); retval.add(addr); } return retval; } /** * Returns the marshalled size of a Collection of Addresses. * <em>Assumes elements are of the same type !</em> * @param addrs Collection<Address> * @return long size */ public static long size(Collection<? extends Address> addrs) { int retval=Global.SHORT_SIZE; // number of elements if(addrs != null && !addrs.isEmpty()) { Address addr=addrs.iterator().next(); retval+=size(addr) * addrs.size(); } return retval; } public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException { if(obj == null) { out.writeBoolean(false); return; } out.writeBoolean(true); obj.writeTo(out); } public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { Streamable retval=null; if(in.readBoolean() == false) return null; retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException { short magic_number; String classname; if(obj == null) { out.write(0); return; } out.write(1); magic_number=ClassConfigurator.getMagicNumber(obj.getClass()); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); classname=obj.getClass().getName(); out.writeUTF(classname); } else { out.writeBoolean(true); out.writeShort(magic_number); } // write the contents obj.writeTo(out); } public static Streamable readGenericStreamable(DataInputStream in) throws IOException { Streamable retval=null; int b=in.read(); if(b == 0) return null; boolean use_magic_number=in.readBoolean(); String classname; Class clazz; try { if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.get(magic_number); if (clazz==null) { throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } } else { classname=in.readUTF(); clazz=ClassConfigurator.get(classname); if (clazz==null) { throw new ClassNotFoundException(classname); } } retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } catch(Exception ex) { throw new IOException("failed reading object: " + ex.toString()); } } public static void writeObject(Object obj, DataOutputStream out) throws Exception { if(obj == null || !(obj instanceof Streamable)) { byte[] buf=objectToByteBuffer(obj); out.writeShort(buf.length); out.write(buf, 0, buf.length); } else { out.writeShort(-1); writeGenericStreamable((Streamable)obj, out); } } public static Object readObject(DataInputStream in) throws Exception { short len=in.readShort(); Object retval=null; if(len == -1) { retval=readGenericStreamable(in); } else { byte[] buf=new byte[len]; in.readFully(buf, 0, len); retval=objectFromByteBuffer(buf); } return retval; } public static void writeString(String s, DataOutputStream out) throws IOException { if(s != null) { out.write(1); out.writeUTF(s); } else { out.write(0); } } public static String readString(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) return in.readUTF(); return null; } public static void writeAsciiString(String str, DataOutputStream out) throws IOException { if(str == null) { out.write(-1); return; } int length=str.length(); if(length > Byte.MAX_VALUE) throw new IllegalArgumentException("string is > " + Byte.MAX_VALUE); out.write(length); out.writeBytes(str); } public static String readAsciiString(DataInputStream in) throws IOException { byte length=(byte)in.read(); if(length == -1) return null; byte[] tmp=new byte[length]; in.readFully(tmp, 0, tmp.length); return new String(tmp, 0, tmp.length); } public static String parseString(DataInputStream in) { return parseString(in, false); } public static String parseString(DataInputStream in, boolean break_on_newline) { StringBuilder sb=new StringBuilder(); int ch; // read white space while(true) { try { ch=in.read(); if(ch == -1) { return null; // eof } if(Character.isWhitespace(ch)) { if(break_on_newline && ch == '\n') return null; } else { sb.append((char)ch); break; } } catch(IOException e) { break; } } while(true) { try { ch=in.read(); if(ch == -1) break; if(Character.isWhitespace(ch)) break; else { sb.append((char)ch); } } catch(IOException e) { break; } } return sb.toString(); } public static String readStringFromStdin(String message) throws Exception { System.out.print(message); System.out.flush(); System.in.skip(System.in.available()); BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); return reader.readLine().trim(); } public static long readLongFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Long.parseLong(tmp); } public static double readDoubleFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Double.parseDouble(tmp); } public static int readIntFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Integer.parseInt(tmp); } public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException { writeByteBuffer(buf, 0, buf.length, out); } public static void writeByteBuffer(byte[] buf, int offset, int length, DataOutputStream out) throws IOException { if(buf != null) { out.write(1); out.writeInt(length); out.write(buf, offset, length); } else { out.write(0); } } public static byte[] readByteBuffer(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) { b=in.readInt(); byte[] buf=new byte[b]; in.readFully(buf, 0, buf.length); return buf; } return null; } public static Buffer messageToByteBuffer(Message msg) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(output); out.writeBoolean(msg != null); if(msg != null) msg.writeTo(out); out.flush(); Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception { ByteArrayInputStream input=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); if(!in.readBoolean()) return null; Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); return msg; } /** * Marshalls a list of messages. * @param xmit_list LinkedList<Message> * @return Buffer * @throws IOException */ public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(output); Buffer retval=null; out.writeInt(xmit_list.size()); for(Message msg: xmit_list) { msg.writeTo(out); } out.flush(); retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception { List<Message> retval=null; ByteArrayInputStream input=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); int size=in.readInt(); if(size == 0) return null; Message msg; retval=new LinkedList<Message>(); for(int i=0; i < size; i++) { msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); retval.add(msg); } return retval; } public static boolean match(Object obj1, Object obj2) { if(obj1 == null && obj2 == null) return true; if(obj1 != null) return obj1.equals(obj2); else return obj2.equals(obj1); } public static boolean sameViewId(ViewId one, ViewId two) { return one.getId() == two.getId() && one.getCoordAddress().equals(two.getCoordAddress()); } public static boolean match(long[] a1, long[] a2) { if(a1 == null && a2 == null) return true; if(a1 == null || a2 == null) return false; if(a1 == a2) // identity return true; // at this point, a1 != null and a2 != null if(a1.length != a2.length) return false; for(int i=0; i < a1.length; i++) { if(a1[i] != a2[i]) return false; } return true; } /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */ public static void sleep(long timeout) { try { Thread.sleep(timeout); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } public static void sleep(long timeout, int nanos) { try { Thread.sleep(timeout,nanos); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ public static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } public static int keyPress(String msg) { System.out.println(msg); try { int ret=System.in.read(); System.in.skip(System.in.available()); return ret; } catch(IOException e) { return 0; } } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long)((Math.random() * range) % range) + 1; } /** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */ public static void sleepRandom(long timeout) { if(timeout <= 0) { return; } long r=(int)((Math.random() * 100000) % timeout) + 1; sleep(r); } /** Sleeps between floor and ceiling milliseconds, chosen randomly */ public static void sleepRandom(long floor, long ceiling) { if(ceiling - floor<= 0) { return; } long diff = ceiling - floor; long r=(int)((Math.random() * 100000) % diff) + floor; sleep(r); } /** Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. */ public static boolean tossWeightedCoin(double probability) { long r=random(100); long cutoff=(long)(probability * 100); return r < cutoff; } public static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch(Exception ex) { } return "localhost"; } public static void dumpStack(boolean exit) { try { throw new Exception("Dumping stack:"); } catch(Exception e) { e.printStackTrace(); if(exit) System.exit(0); } } public static String dumpThreads() { StringBuilder sb=new StringBuilder(); ThreadMXBean bean=ManagementFactory.getThreadMXBean(); long[] ids=bean.getAllThreadIds(); ThreadInfo[] threads=bean.getThreadInfo(ids, 20); for(int i=0; i < threads.length; i++) { ThreadInfo info=threads[i]; if(info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace=info.getStackTrace(); for(int j=0; j < stack_trace.length; j++) { StackTraceElement el=stack_trace[j]; sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } return sb.toString(); } public static boolean interruptAndWaitToDie(Thread t) { return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME); } public static boolean interruptAndWaitToDie(Thread t, long timeout) { if(t == null) throw new IllegalArgumentException("Thread can not be null"); t.interrupt(); // interrupts the sleep() try { t.join(timeout); } catch(InterruptedException e){ Thread.currentThread().interrupt(); // set interrupt flag again } return t.isAlive(); } /** * Debugging method used to dump the content of a protocol queue in a * condensed form. Useful to follow the evolution of the queue's content in * time. */ public static String dumpQueue(Queue q) { StringBuilder sb=new StringBuilder(); LinkedList values=q.values(); if(values.isEmpty()) { sb.append("empty"); } else { for(Object o: values) { String s=null; if(o instanceof Event) { Event event=(Event)o; int type=event.getType(); s=Event.type2String(type); if(type == Event.VIEW_CHANGE) s+=" " + event.getArg(); if(type == Event.MSG) s+=" " + event.getArg(); if(type == Event.MSG) { s+="["; Message m=(Message)event.getArg(); Map<Short,Header> headers=new HashMap<Short,Header>(m.getHeaders()); for(Map.Entry<Short,Header> entry: headers.entrySet()) { short id=entry.getKey(); Header value=entry.getValue(); String headerToString=null; if(value instanceof FD.FdHeader) { headerToString=value.toString(); } else if(value instanceof PingHeader) { headerToString=ClassConfigurator.getProtocol(id) + "-"; if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { headerToString+="GMREQ"; } else if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { headerToString+="GMRSP"; } else { headerToString+="UNKNOWN"; } } else { headerToString=ClassConfigurator.getProtocol(id) + "-" + (value == null ? "null" : value.toString()); } s+=headerToString; s+=" "; } s+="]"; } } else { s=o.toString(); } sb.append(s).append("\n"); } } return sb.toString(); } /** * Use with caution: lots of overhead */ public static String printStackTrace(Throwable t) { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); return s.toString(); } public static String getStackTrace(Throwable t) { return printStackTrace(t); } public static String print(Throwable t) { return printStackTrace(t); } public static void crash() { System.exit(-1); } public static String printEvent(Event evt) { Message msg; if(evt.getType() == Event.MSG) { msg=(Message)evt.getArg(); if(msg != null) { if(msg.getLength() > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.toString(); } /** Tries to read an object from the message's buffer and prints it */ public static String printMessage(Message msg) { if(msg == null) return ""; if(msg.getLength() == 0) return null; try { return msg.getObject().toString(); } catch(Exception e) { // it is not an object return ""; } } public static String mapToString(Map<? extends Object,? extends Object> map) { if(map == null) return "null"; StringBuilder sb=new StringBuilder(); for(Map.Entry<? extends Object,? extends Object> entry: map.entrySet()) { Object key=entry.getKey(); Object val=entry.getValue(); sb.append(key).append("="); if(val == null) sb.append("null"); else sb.append(val); sb.append("\n"); } return sb.toString(); } /** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it. Returns empty string if object is not a method call */ public static String printMethodCall(Message msg) { Object obj; if(msg == null) return ""; if(msg.getLength() == 0) return ""; try { obj=msg.getObject(); return obj.toString(); } catch(Exception e) { // it is not an object return ""; } } public static void printThreads() { Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); System.out.println(" for(int i=0; i < threads.length; i++) { System.out.println("#" + i + ": " + threads[i]); } System.out.println(" } public static String activeThreads() { StringBuilder sb=new StringBuilder(); Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); sb.append(" for(int i=0; i < threads.length; i++) { sb.append("#").append(i).append(": ").append(threads[i]).append('\n'); } sb.append(" return sb.toString(); } public static String printBytes(long bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static String format(double value) { return f.format(value); } public static long readBytesLong(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return (long)(num * tuple.getVal2()); } public static int readBytesInteger(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return (int)(num * tuple.getVal2()); } public static double readBytesDouble(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return num * tuple.getVal2(); } private static Tuple<String,Long> readBytes(String input) { input=input.trim().toLowerCase(); int index=-1; long factor=1; if((index=input.indexOf("k")) != -1) factor=1000; else if((index=input.indexOf("kb")) != -1) factor=1000; else if((index=input.indexOf("m")) != -1) factor=1000000; else if((index=input.indexOf("mb")) != -1) factor=1000000; else if((index=input.indexOf("g")) != -1) factor=1000000000; else if((index=input.indexOf("gb")) != -1) factor=1000000000; String str=index != -1? input.substring(0, index) : input; return new Tuple<String,Long>(str, factor); } public static String printBytes(double bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static List<String> split(String input, int separator) { List<String> retval=new ArrayList<String>(); if(input == null) return retval; int index=0, end; while(true) { index=input.indexOf(separator, index); if(index == -1) break; index++; end=input.indexOf(separator, index); if(end == -1) retval.add(input.substring(index)); else retval.add(input.substring(index, end)); } return retval; } /* public static String[] components(String path, String separator) { if(path == null || path.length() == 0) return null; String[] tmp=path.split(separator + "+"); // multiple separators could be present if(tmp == null) return null; if(tmp.length == 0) return null; if(tmp[0].length() == 0) { tmp[0]=separator; if(tmp.length > 1) { String[] retval=new String[tmp.length -1]; retval[0]=tmp[0] + tmp[1]; System.arraycopy(tmp, 2, retval, 1, tmp.length-2); return retval; } return tmp; } return tmp; }*/ public static String[] components(String path, String separator) { if(path == null || path.length() == 0) return null; String[] tmp=path.split(separator + "+"); // multiple separators could be present if(tmp == null) return null; if(tmp.length == 0) return null; if(tmp[0].length() == 0) tmp[0]=separator; return tmp; } /** Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes. @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size=0; byte[] fragment; int tmp_size=0; int num_frags; int index=0; num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval=new byte[num_frags][]; while(accumulated_size < length) { if(accumulated_size + frag_size <= length) tmp_size=frag_size; else tmp_size=length - accumulated_size; fragment=new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++]=fragment; accumulated_size+=tmp_size; } return retval; } public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { return fragmentBuffer(buf, frag_size, buf.length); } /** * Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and * return them in a list. Example:<br/> * Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). * This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment * starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length * of 2 bytes. * @param frag_size * @return List. A List<Range> of offset/length pairs */ public static List<Range> computeFragOffsets(int offset, int length, int frag_size) { List<Range> retval=new ArrayList<Range>(); long total_size=length + offset; int index=offset; int tmp_size=0; Range r; while(index < total_size) { if(index + frag_size <= total_size) tmp_size=frag_size; else tmp_size=(int)(total_size - index); r=new Range(index, tmp_size); retval.add(r); index+=tmp_size; } return retval; } public static List<Range> computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.length, frag_size); } /** Concatenates smaller fragments into entire buffers. @param fragments An array of byte buffers (<code>byte[]</code>) @return A byte buffer */ public static byte[] defragmentBuffer(byte[] fragments[]) { int total_length=0; byte[] ret; int index=0; if(fragments == null) return null; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; total_length+=fragments[i].length; } ret=new byte[total_length]; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); index+=fragments[i].length; } return ret; } public static void printFragments(byte[] frags[]) { for(int i=0; i < frags.length; i++) System.out.println('\'' + new String(frags[i]) + '\''); } public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(T el: list) { if(first) { first=false; } else { sb.append(delimiter); } sb.append(el); } return sb.toString(); } public static <T> String printMapWithDelimiter(Map<T,T> map, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(Map.Entry<T,T> entry: map.entrySet()) { if(first) first=false; else sb.append(delimiter); sb.append(entry.getKey()).append("=").append(entry.getValue()); } return sb.toString(); } public static String array2String(long[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(short[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(int[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(boolean[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(Object[] array) { return Arrays.toString(array); } /** Returns true if all elements of c match obj */ public static boolean all(Collection c, Object obj) { for(Iterator iterator=c.iterator(); iterator.hasNext();) { Object o=iterator.next(); if(!o.equals(obj)) return false; } return true; } /** * Returns a list of members which left from view one to two * @param one * @param two * @return */ public static List<Address> leftMembers(View one, View two) { if(one == null || two == null) return null; List<Address> retval=new ArrayList<Address>(one.getMembers()); retval.removeAll(two.getMembers()); return retval; } public static List<Address> leftMembers(Collection<Address> old_list, Collection<Address> new_list) { if(old_list == null || new_list == null) return null; List<Address> retval=new ArrayList<Address>(old_list); retval.removeAll(new_list); return retval; } public static List<Address> newMembers(List<Address> old_list, List<Address> new_list) { if(old_list == null || new_list == null) return null; List<Address> retval=new ArrayList<Address>(new_list); retval.removeAll(old_list); return retval; } /** * Selects a random subset of members according to subset_percentage and returns them. * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. */ public static Vector<Address> pickSubset(Vector<Address> members, double subset_percentage) { Vector<Address> ret=new Vector<Address>(), tmp_mbrs; int num_mbrs=members.size(), subset_size, index; if(num_mbrs == 0) return ret; subset_size=(int)Math.ceil(num_mbrs * subset_percentage); tmp_mbrs=(Vector<Address>)members.clone(); for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); ret.addElement(tmp_mbrs.elementAt(index)); tmp_mbrs.removeElementAt(index); } return ret; } public static boolean containsViewId(Collection<View> views, ViewId vid) { for(View view: views) { ViewId tmp=view.getVid(); if(Util.sameViewId(vid, tmp)) return true; } return false; } /** * Determines the members which take part in a merge. The resulting list consists of all merge coordinators * plus members outside a merge partition, e.g. for views A={B,A,C}, B={B,C} and C={B,C}, the merge coordinator * is B, but the merge participants are B and A. * @param map * @return */ public static Collection<Address> determineMergeParticipants(Map<Address,View> map) { Set<Address> coords=new HashSet<Address>(); Set<Address> all_addrs=new HashSet<Address>(); if(map == null) return Collections.emptyList(); for(View view: map.values()) all_addrs.addAll(view.getMembers()); for(View view: map.values()) { Address coord=view.getCreator(); if(coord != null) coords.add(coord); } for(Address coord: coords) { View view=map.get(coord); Collection<Address> mbrs=view != null? view.getMembers() : null; if(mbrs != null) all_addrs.removeAll(mbrs); } coords.addAll(all_addrs); return coords; } /** * This is the same or a subset of {@link #determineMergeParticipants(java.util.Map)} and contains only members * which are currently sub-partition coordinators. * @param map * @return */ public static Collection<Address> determineMergeCoords(Map<Address,View> map) { Set<Address> retval=new HashSet<Address>(); if(map != null) { for(View view: map.values()) { Address coord=view.getCreator(); if(coord != null) retval.add(coord); } } return retval; } public static int getRank(View view, Address addr) { if(view == null || addr == null) return 0; List<Address> members=view.getMembers(); for(int i=0; i < members.size(); i++) { Address mbr=members.get(i); if(mbr.equals(addr)) return i+1; } return 0; } public static Object pickRandomElement(List list) { if(list == null) return null; int size=list.size(); int index=(int)((Math.random() * size * 10) % size); return list.get(index); } public static Object pickRandomElement(Object[] array) { if(array == null) return null; int size=array.length; int index=(int)((Math.random() * size * 10) % size); return array[index]; } /** * Returns the object next to element in list * @param list * @param obj * @param <T> * @return */ public static <T> T pickNext(List<T> list, T obj) { if(list == null || obj == null) return null; Object[] array=list.toArray(); for(int i=0; i < array.length; i++) { T tmp=(T)array[i]; if(tmp != null && tmp.equals(obj)) return (T)array[(i+1) % array.length]; } return null; } public static View createView(Address coord, long id, Address ... members) { Vector<Address> mbrs=new Vector<Address>(); mbrs.addAll(Arrays.asList(members)); return new View(coord, id, mbrs); } public static Address createRandomAddress() { return createRandomAddress(generateLocalName()); } public static Address createRandomAddress(String name) { UUID retval=UUID.randomUUID(); UUID.add(retval, name); return retval; } public static Object[][] createTimer() { return new Object[][] { {new DefaultTimeScheduler(5)}, {new TimeScheduler2()}, {new HashedTimingWheel(5)} }; } /** * Returns all members that left between 2 views. All members that are element of old_mbrs but not element of * new_mbrs are returned. */ public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) { Vector<Address> retval=new Vector<Address>(); Address mbr; if(old_mbrs == null || new_mbrs == null) return retval; for(int i=0; i < old_mbrs.size(); i++) { mbr=old_mbrs.elementAt(i); if(!new_mbrs.contains(mbr)) retval.addElement(mbr); } return retval; } public static String printViews(Collection<View> views) { StringBuilder sb=new StringBuilder(); boolean first=true; for(View view: views) { if(first) first=false; else sb.append(", "); sb.append(view.getVid()); } return sb.toString(); } public static <T> String print(Collection<T> objs) { StringBuilder sb=new StringBuilder(); boolean first=true; for(T obj: objs) { if(first) first=false; else sb.append(", "); sb.append(obj); } return sb.toString(); } public static <T> String print(Map<T,T> map) { StringBuilder sb=new StringBuilder(); boolean first=true; for(Map.Entry<T,T> entry: map.entrySet()) { if(first) first=false; else sb.append(", "); sb.append(entry.getKey()).append("=").append(entry.getValue()); } return sb.toString(); } public static String printPingData(List<PingData> rsps) { StringBuilder sb=new StringBuilder(); if(rsps != null) { int total=rsps.size(); int servers=0, clients=0, coords=0; for(PingData rsp: rsps) { if(rsp.isCoord()) coords++; if(rsp.isServer()) servers++; else clients++; } sb.append(total + " total (" + servers + " servers (" + coords + " coord), " + clients + " clients)"); } return sb.toString(); } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, OutputStream out) throws Exception { if(buf.length > 1) { out.write(buf, 0, 1); out.write(buf, 1, buf.length - 1); } else { out.write(buf, 0, 0); out.write(buf); } } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception { if(length > 1) { out.write(buf, offset, 1); out.write(buf, offset+1, length - 1); } else { out.write(buf, offset, 0); out.write(buf, offset, length); } } /** * if we were to register for OP_WRITE and send the remaining data on * readyOps for this channel we have to either block the caller thread or * queue the message buffers that may arrive while waiting for OP_WRITE. * Instead of the above approach this method will continuously write to the * channel until the buffer sent fully. */ public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException { int written = 0; int toWrite = buf.limit(); while (written < toWrite) { written += out.write(buf); } } public static long sizeOf(String classname) { Object inst; byte[] data; try { inst=Util.loadClass(classname, null).newInstance(); data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static long sizeOf(Object inst) { byte[] data; try { data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static int sizeOf(Streamable inst) { try { ByteArrayOutputStream output=new ExposedByteArrayOutputStream(); DataOutputStream out=new ExposedDataOutputStream(output); inst.writeTo(out); out.flush(); byte[] data=output.toByteArray(); return data.length; } catch(Exception ex) { return -1; } } /** * Tries to load the class from the current thread's context class loader. If * not successful, tries to load the class from the current instance. * @param classname Desired class. * @param clazz Class object used to obtain a class loader * if no context class loader is available. * @return Class, or null on failure. */ public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException { ClassLoader loader; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } throw new ClassNotFoundException(classname); } public static Field[] getAllDeclaredFields(final Class clazz) { return getAllDeclaredFieldsWithAnnotations(clazz); } public static Field[] getAllDeclaredFieldsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) { List<Field> list=new ArrayList<Field>(30); for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { Field[] fields=curr.getDeclaredFields(); if(fields != null) { for(Field field: fields) { if(annotations != null && annotations.length > 0) { for(Class<? extends Annotation> annotation: annotations) { if(field.isAnnotationPresent(annotation)) list.add(field); } } else list.add(field); } } } Field[] retval=new Field[list.size()]; for(int i=0; i < list.size(); i++) retval[i]=list.get(i); return retval; } public static Method[] getAllDeclaredMethods(final Class clazz) { return getAllDeclaredMethodsWithAnnotations(clazz); } public static Method[] getAllDeclaredMethodsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) { List<Method> list=new ArrayList<Method>(30); for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { Method[] methods=curr.getDeclaredMethods(); if(methods != null) { for(Method method: methods) { if(annotations != null && annotations.length > 0) { for(Class<? extends Annotation> annotation: annotations) { if(method.isAnnotationPresent(annotation)) list.add(method); } } else list.add(method); } } } Method[] retval=new Method[list.size()]; for(int i=0; i < list.size(); i++) retval[i]=list.get(i); return retval; } public static Field getField(final Class clazz, String field_name) { if(clazz == null || field_name == null) return null; Field field=null; for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { try { return curr.getDeclaredField(field_name); } catch(NoSuchFieldException e) { } } return field; } public static InputStream getResourceAsStream(String name, Class clazz) { ClassLoader loader; InputStream retval=null; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.getResourceAsStream(name); } } catch(Throwable t) { } return retval; } /** Checks whether 2 Addresses are on the same host */ public static boolean sameHost(Address one, Address two) { InetAddress a, b; String host_a, host_b; if(one == null || two == null) return false; if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) { return false; } a=((IpAddress)one).getIpAddress(); b=((IpAddress)two).getIpAddress(); if(a == null || b == null) return false; host_a=a.getHostAddress(); host_b=b.getHostAddress(); // System.out.println("host_a=" + host_a + ", host_b=" + host_b); return host_a.equals(host_b); } public static boolean fileExists(String fname) { return (new File(fname)).exists(); } /** * Parses comma-delimited longs; e.g., 2000,4000,8000. * Returns array of long, or null. */ public static long[] parseCommaDelimitedLongs(String s) { StringTokenizer tok; Vector<Long> v=new Vector<Long>(); Long l; long[] retval=null; if(s == null) return null; tok=new StringTokenizer(s, ","); while(tok.hasMoreTokens()) { l=new Long(tok.nextToken()); v.addElement(l); } if(v.isEmpty()) return null; retval=new long[v.size()]; for(int i=0; i < v.size(); i++) retval[i]=v.elementAt(i).longValue(); return retval; } /** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */ public static List<String> parseCommaDelimitedStrings(String l) { return parseStringList(l, ","); } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Returns a list of IpAddresses */ public static List<IpAddress> parseCommaDelimitedHosts(String hosts, int port_range) throws UnknownHostException { StringTokenizer tok=new StringTokenizer(hosts, ","); String t; IpAddress addr; Set<IpAddress> retval=new HashSet<IpAddress>(); while(tok.hasMoreTokens()) { t=tok.nextToken().trim(); String host=t.substring(0, t.indexOf('[')); host=host.trim(); int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); for(int i=port;i <= port + port_range;i++) { addr=new IpAddress(host, i); retval.add(addr); } } return Collections.unmodifiableList(new LinkedList<IpAddress>(retval)); } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of * InetSocketAddress */ public static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range) throws UnknownHostException { StringTokenizer tok=new StringTokenizer(hosts, ","); String t; InetSocketAddress addr; Set<InetSocketAddress> retval=new HashSet<InetSocketAddress>(); while(tok.hasMoreTokens()) { t=tok.nextToken().trim(); String host=t.substring(0, t.indexOf('[')); host=host.trim(); int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); for(int i=port;i < port + port_range;i++) { addr=new InetSocketAddress(host, i); retval.add(addr); } } return Collections.unmodifiableList(new LinkedList<InetSocketAddress>(retval)); } public static List<String> parseStringList(String l, String separator) { List<String> tmp=new LinkedList<String>(); StringTokenizer tok=new StringTokenizer(l, separator); String t; while(tok.hasMoreTokens()) { t=tok.nextToken(); tmp.add(t.trim()); } return tmp; } public static String parseString(ByteBuffer buf) { return parseString(buf, true); } public static String parseString(ByteBuffer buf, boolean discard_whitespace) { StringBuilder sb=new StringBuilder(); char ch; // read white space while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { buf.position(buf.position() -1); break; } } if(buf.remaining() == 0) return null; while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { sb.append(ch); } else break; } // read white space if(discard_whitespace) { while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { buf.position(buf.position() -1); break; } } } return sb.toString(); } public static int readNewLine(ByteBuffer buf) { char ch; int num=0; while(buf.remaining() > 0) { ch=(char)buf.get(); num++; if(ch == '\n') break; } return num; } /** * Reads and discards all characters from the input stream until a \r\n or EOF is encountered * @param in * @return */ public static int discardUntilNewLine(InputStream in) { int ch; int num=0; while(true) { try { ch=in.read(); if(ch == -1) break; num++; if(ch == '\n') break; } catch(IOException e) { break; } } return num; } /** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), or a carriage return * followed immediately by a linefeed. * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached * * @exception IOException If an I/O error occurs */ public static String readLine(InputStream in) throws IOException { StringBuilder sb=new StringBuilder(35); int ch; while(true) { ch=in.read(); if(ch == -1) return null; if(ch == '\r') { ; } else { if(ch == '\n') break; else { sb.append((char)ch); } } } return sb.toString(); } public static void writeString(ByteBuffer buf, String s) { for(int i=0; i < s.length(); i++) buf.put((byte)s.charAt(i)); } /** * * @param s * @return List<NetworkInterface> */ public static List<NetworkInterface> parseInterfaceList(String s) throws Exception { List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10); if(s == null) return null; StringTokenizer tok=new StringTokenizer(s, ","); String interface_name; NetworkInterface intf; while(tok.hasMoreTokens()) { interface_name=tok.nextToken(); // try by name first (e.g. (eth0") intf=NetworkInterface.getByName(interface_name); // next try by IP address or symbolic name if(intf == null) intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name)); if(intf == null) throw new Exception("interface " + interface_name + " not found"); if(!interfaces.contains(intf)) { interfaces.add(intf); } } return interfaces; } public static String print(List<NetworkInterface> interfaces) { StringBuilder sb=new StringBuilder(); boolean first=true; for(NetworkInterface intf: interfaces) { if(first) { first=false; } else { sb.append(", "); } sb.append(intf.getName()); } return sb.toString(); } public static String shortName(String hostname) { if(hostname == null) return null; int index=hostname.indexOf('.'); if(index > 0 && !Character.isDigit(hostname.charAt(0))) return hostname.substring(0, index); else return hostname; } public static boolean startFlush(Channel c, List<Address> flushParticipants, int numberOfAttempts, long randomSleepTimeoutFloor,long randomSleepTimeoutCeiling) { boolean successfulFlush = false; int attemptCount = 0; while(attemptCount < numberOfAttempts){ successfulFlush = c.startFlush(flushParticipants, false); if(successfulFlush) break; Util.sleepRandom(randomSleepTimeoutFloor,randomSleepTimeoutCeiling); attemptCount++; } return successfulFlush; } public static boolean startFlush(Channel c, List<Address> flushParticipants) { return startFlush(c,flushParticipants,4,1000,5000); } public static boolean startFlush(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor,long randomSleepTimeoutCeiling) { boolean successfulFlush = false; int attemptCount = 0; while(attemptCount < numberOfAttempts){ successfulFlush = c.startFlush(false); if(successfulFlush) break; Util.sleepRandom(randomSleepTimeoutFloor,randomSleepTimeoutCeiling); attemptCount++; } return successfulFlush; } public static boolean startFlush(Channel c) { return startFlush(c,4,1000,5000); } public static String shortName(InetAddress hostname) { if(hostname == null) return null; StringBuilder sb=new StringBuilder(); if(resolve_dns) sb.append(hostname.getHostName()); else sb.append(hostname.getHostAddress()); return sb.toString(); } public static String generateLocalName() { String retval=null; try { retval=shortName(InetAddress.getLocalHost().getHostName()); } catch(UnknownHostException e) { retval="localhost"; } long counter=Util.random(Short.MAX_VALUE *2); return retval + "-" + counter; } public synchronized static short incrCounter() { short retval=COUNTER++; if(COUNTER >= Short.MAX_VALUE) COUNTER=1; return retval; } public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level) { return new ConcurrentHashMap<K,V>(initial_capacity, load_factor, concurrency_level); } public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity) { return new ConcurrentHashMap<K,V>(initial_capacity); } public static <K,V> ConcurrentMap<K,V> createConcurrentMap() { return new ConcurrentHashMap<K,V>(CCHM_INITIAL_CAPACITY, CCHM_LOAD_FACTOR, CCHM_CONCURRENCY_LEVEL); } /** Finds first available port starting at start_port and returns server socket */ public static ServerSocket createServerSocket(SocketFactory factory, String service_name, int start_port) { ServerSocket ret=null; while(true) { try { ret=factory.createServerSocket(service_name, start_port); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port) { ServerSocket ret=null; while(true) { try { ret=factory.createServerSocket(service_name, start_port, 50, bind_addr); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } /** * Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, * start_port will be incremented until a socket can be created. * @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound. * @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already * in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. */ public static DatagramSocket createDatagramSocket(SocketFactory factory, String service_name, InetAddress addr, int port) throws Exception { DatagramSocket sock=null; if(addr == null) { if(port == 0) { return factory.createDatagramSocket(service_name); } else { while(port < MAX_PORT) { try { return factory.createDatagramSocket(service_name, port); } catch(BindException bind_ex) { // port already used port++; } } } } else { if(port == 0) port=1024; while(port < MAX_PORT) { try { return factory.createDatagramSocket(service_name, port, addr); } catch(BindException bind_ex) { // port already used port++; } } } return sock; // will never be reached, but the stupid compiler didn't figure it out... } public static MulticastSocket createMulticastSocket(SocketFactory factory, String service_name, InetAddress mcast_addr, int port, Log log) throws IOException { if(mcast_addr != null && !mcast_addr.isMulticastAddress()) throw new IllegalArgumentException("mcast_addr (" + mcast_addr + ") is not a valid multicast address"); SocketAddress saddr=new InetSocketAddress(mcast_addr, port); MulticastSocket retval=null; try { retval=factory.createMulticastSocket(service_name, saddr); } catch(IOException ex) { if(log != null && log.isWarnEnabled()) { StringBuilder sb=new StringBuilder(); String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a"; sb.append("could not bind to " + mcast_addr + " (" + type + " address)"); sb.append("; make sure your mcast_addr is of the same type as the preferred IP stack (IPv4 or IPv6)"); sb.append(" by checking the value of the system properties java.net.preferIPv4Stack and java.net.preferIPv6Addresses."); sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " + "(see http: sb.append("\nException was: " + ex); log.warn(sb.toString()); } } if(retval == null) retval=factory.createMulticastSocket(service_name, port); return retval; } /** * Returns the address of the interface to use defined by bind_addr and bind_interface * @param props * @return * @throws UnknownHostException * @throws SocketException */ public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException { // determine the desired values for bind_addr_str and bind_interface_str boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String bind_addr_str =Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr", ignore_systemprops, null); String bind_interface_str =Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface", ignore_systemprops, null); InetAddress bind_addr=null; NetworkInterface bind_intf=null; StackType ip_version=Util.getIpStackType(); // 1. if bind_addr_str specified, get bind_addr and check version if(bind_addr_str != null) { bind_addr=InetAddress.getByName(bind_addr_str); // check that bind_addr_host has correct IP version boolean hasCorrectVersion = ((bind_addr instanceof Inet4Address && ip_version == StackType.IPv4) || (bind_addr instanceof Inet6Address && ip_version == StackType.IPv6)) ; if (!hasCorrectVersion) throw new IllegalArgumentException("bind_addr " + bind_addr_str + " has incorrect IP version") ; } // 2. if bind_interface_str specified, get interface and check that it has correct version if(bind_interface_str != null) { bind_intf=NetworkInterface.getByName(bind_interface_str); if(bind_intf != null) { // check that the interface supports the IP version boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ; if (!supportsVersion) throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ; } else { // (bind_intf == null) throw new UnknownHostException("network interface " + bind_interface_str + " not found"); } } // 3. intf and bind_addr are both are specified, bind_addr needs to be on intf if (bind_intf != null && bind_addr != null) { boolean hasAddress = false ; // get all the InetAddresses defined on the interface Enumeration addresses = bind_intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if address is on interface if (bind_addr.equals(address)) { hasAddress = true ; break ; } } if (!hasAddress) { throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str); } } // 4. if only interface is specified, get first non-loopback address on that interface, else if (bind_intf != null) { bind_addr = getAddress(bind_intf, AddressScope.NON_LOOPBACK) ; } // 5. if neither bind address nor bind interface is specified, get the first non-loopback // address on any interface else if (bind_addr == null) { bind_addr = getNonLoopbackAddress() ; } // if we reach here, if bind_addr == null, we have tried to obtain a bind_addr but were not successful // in such a case, using a loopback address of the correct version is our only option boolean localhost = false; if (bind_addr == null) { bind_addr = getLocalhost(ip_version); localhost = true; } //check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine //in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip //the check in that case if(!localhost && NetworkInterface.getByInetAddress(bind_addr) == null) { throw new UnknownHostException("Invalid bind address " + bind_addr); } if(props != null) { props.remove("bind_addr"); props.remove("bind_interface"); } return bind_addr; } /** * Method used by PropertyConverters.BindInterface to check that a bind_address is * consistent with a specified interface * * Idea: * 1. We are passed a bind_addr, which may be null * 2. If non-null, check that bind_addr is on bind_interface - if not, throw exception, * otherwise, return the original bind_addr * 3. If null, get first non-loopback address on bind_interface, using stack preference to * get the IP version. If no non-loopback address, then just return null (i.e. the * bind_interface did not influence the decision). * */ public static InetAddress validateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str) throws UnknownHostException, SocketException { NetworkInterface bind_intf=null ; // 1. if bind_interface_str is null, or empty, no constraint on bind_addr if (bind_interface_str == null || bind_interface_str.trim().length() == 0) return bind_addr; // 2. get the preferred IP version for the JVM - it will be IPv4 or IPv6 StackType ip_version = getIpStackType(); // 3. if bind_interface_str specified, get interface and check that it has correct version bind_intf=NetworkInterface.getByName(bind_interface_str); if(bind_intf != null) { // check that the interface supports the IP version boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ; if (!supportsVersion) throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ; } else { // (bind_intf == null) throw new UnknownHostException("network interface " + bind_interface_str + " not found"); } // 3. intf and bind_addr are both are specified, bind_addr needs to be on intf if (bind_addr != null) { boolean hasAddress = false ; // get all the InetAddresses defined on the interface Enumeration addresses = bind_intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if address is on interface if (bind_addr.equals(address)) { hasAddress = true ; break ; } } if (!hasAddress) { String bind_addr_str = bind_addr.getHostAddress(); throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str); } } // 4. if only interface is specified, get first non-loopback address on that interface, else { bind_addr = getAddress(bind_intf, AddressScope.NON_LOOPBACK) ; } //check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine //in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip //the check in that case if(bind_addr != null && NetworkInterface.getByInetAddress(bind_addr) == null) { throw new UnknownHostException("Invalid bind address " + bind_addr); } // if bind_addr == null, we have tried to obtain a bind_addr but were not successful // in such a case, return the original value of null so the default will be applied return bind_addr; } public static boolean checkForLinux() { return checkForPresence("os.name", "linux"); } public static boolean checkForHp() { return checkForPresence("os.name", "hp"); } public static boolean checkForSolaris() { return checkForPresence("os.name", "sun"); } public static boolean checkForWindows() { return checkForPresence("os.name", "win"); } public static boolean checkForMac() { return checkForPresence("os.name", "mac"); } private static boolean checkForPresence(String key, String value) { try { String tmp=System.getProperty(key); return tmp != null && tmp.trim().toLowerCase().startsWith(value); } catch(Throwable t) { return false; } } public static void prompt(String s) { System.out.println(s); System.out.flush(); try { while(System.in.available() > 0) System.in.read(); System.in.read(); } catch(IOException e) { e.printStackTrace(); } } public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) { if(v == null) return null; return new UnmodifiableVector(v); } /** IP related utilities */ public static InetAddress getLocalhost(StackType ip_version) throws UnknownHostException { if (ip_version == StackType.IPv4) return InetAddress.getByName("127.0.0.1") ; else return InetAddress.getByName("::1") ; } /** * Returns the first non-loopback address on any interface on the current host. */ public static InetAddress getNonLoopbackAddress() throws SocketException { return getAddress(AddressScope.NON_LOOPBACK); } /** * Returns the first address on any interface of the current host, which satisfies scope */ public static InetAddress getAddress(AddressScope scope) throws SocketException { InetAddress address=null ; Enumeration intfs=NetworkInterface.getNetworkInterfaces(); while(intfs.hasMoreElements()) { NetworkInterface intf=(NetworkInterface)intfs.nextElement(); if(intf.isUp()) { address=getAddress(intf, scope) ; if(address != null) return address; } } return null ; } /** * Returns the first address on the given interface on the current host, which satisfies scope * * @param intf the interface to be checked */ public static InetAddress getAddress(NetworkInterface intf, AddressScope scope) throws SocketException { StackType ip_version=Util.getIpStackType(); for(Enumeration addresses=intf.getInetAddresses(); addresses.hasMoreElements();) { InetAddress addr=(InetAddress)addresses.nextElement(); boolean match; switch(scope) { case GLOBAL: match=!addr.isLoopbackAddress() && !addr.isLinkLocalAddress() && !addr.isSiteLocalAddress(); break; case SITE_LOCAL: match=addr.isSiteLocalAddress(); break; case LINK_LOCAL: match=addr.isLinkLocalAddress(); break; case LOOPBACK: match=addr.isLoopbackAddress(); break; case NON_LOOPBACK: match=!addr.isLoopbackAddress(); break; default: throw new IllegalArgumentException("scope " + scope + " is unknown"); } if(match) { if((addr instanceof Inet4Address && ip_version == StackType.IPv4) || (addr instanceof Inet6Address && ip_version == StackType.IPv6)) return addr; } } return null ; } /** * A function to check if an interface supports an IP version (i.e has addresses * defined for that IP version). * * @param intf * @return */ public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) throws SocketException, UnknownHostException { boolean supportsVersion = false ; if (intf != null) { // get all the InetAddresses defined on the interface Enumeration addresses = intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if we find an address of correct version if ((address instanceof Inet4Address && (ip_version == StackType.IPv4)) || (address instanceof Inet6Address && (ip_version == StackType.IPv6))) { supportsVersion = true ; break ; } } } else { throw new UnknownHostException("network interface " + intf + " not found") ; } return supportsVersion ; } public static StackType getIpStackType() { return ip_stack_type; } /** * Tries to determine the type of IP stack from the available interfaces and their addresses and from the * system properties (java.net.preferIPv4Stack and java.net.preferIPv6Addresses) * @return StackType.IPv4 for an IPv4 only stack, StackYTypeIPv6 for an IPv6 only stack, and StackType.Unknown * if the type cannot be detected */ private static StackType _getIpStackType() { boolean isIPv4StackAvailable = isStackAvailable(true) ; boolean isIPv6StackAvailable = isStackAvailable(false) ; // if only IPv4 stack available if (isIPv4StackAvailable && !isIPv6StackAvailable) { return StackType.IPv4; } // if only IPv6 stack available else if (isIPv6StackAvailable && !isIPv4StackAvailable) { return StackType.IPv6; } // if dual stack else if (isIPv4StackAvailable && isIPv6StackAvailable) { // get the System property which records user preference for a stack on a dual stack machine if(Boolean.getBoolean(Global.IPv4)) // has preference over java.net.preferIPv6Addresses return StackType.IPv4; if(Boolean.getBoolean(Global.IPv6)) return StackType.IPv6; return StackType.IPv6; } return StackType.Unknown; } public static boolean isStackAvailable(boolean ipv4) { Collection<InetAddress> all_addrs=getAllAvailableAddresses(); for(InetAddress addr: all_addrs) if(ipv4 && addr instanceof Inet4Address || (!ipv4 && addr instanceof Inet6Address)) return true; return false; } public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10); NetworkInterface intf; for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { intf=(NetworkInterface)en.nextElement(); retval.add(intf); } return retval; } public static Collection<InetAddress> getAllAvailableAddresses() { Set<InetAddress> retval=new HashSet<InetAddress>(); Enumeration en; try { en=NetworkInterface.getNetworkInterfaces(); if(en == null) return retval; while(en.hasMoreElements()) { NetworkInterface intf=(NetworkInterface)en.nextElement(); Enumeration<InetAddress> addrs=intf.getInetAddresses(); while(addrs.hasMoreElements()) retval.add(addrs.nextElement()); } } catch(SocketException e) { e.printStackTrace(); } return retval; } /** * Returns a value associated wither with one or more system properties, or found in the props map * @param system_props * @param props List of properties read from the configuration file * @param prop_name The name of the property, will be removed from props if found * @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from * props (not system_props) * @param default_value Used to return a default value if the properties or system properties didn't have the value * @return The value, or null if not found */ public static String getProperty(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) { String retval=null; if(props != null && prop_name != null) { retval=props.getProperty(prop_name); props.remove(prop_name); } if(!ignore_sysprops) { String tmp, prop; if(system_props != null) { for(int i=0; i < system_props.length; i++) { prop=system_props[i]; if(prop != null) { try { tmp=System.getProperty(prop); if(tmp != null) return tmp; // system properties override config file definitions } catch(SecurityException ex) {} } } } } if(retval == null) return default_value; return retval; } public static boolean isBindAddressPropertyIgnored() { try { String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY); if(tmp == null) { tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD); if(tmp == null) return false; } tmp=tmp.trim().toLowerCase(); return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on")); } catch(SecurityException ex) { return false; } } public static boolean isCoordinator(JChannel ch) { return isCoordinator(ch.getView(), ch.getAddress()); } public static boolean isCoordinator(View view, Address local_addr) { if(view == null || local_addr == null) return false; Vector<Address> mbrs=view.getMembers(); return !(mbrs == null || mbrs.isEmpty()) && local_addr.equals(mbrs.firstElement()); } public static MBeanServer getMBeanServer() { ArrayList servers = MBeanServerFactory.findMBeanServer(null); if (servers != null && !servers.isEmpty()) { // return 'jboss' server if available for (int i = 0; i < servers.size(); i++) { MBeanServer srv = (MBeanServer) servers.get(i); if ("jboss".equalsIgnoreCase(srv.getDefaultDomain())) return srv; } // return first available server return (MBeanServer) servers.get(0); } else { //if it all fails, create a default return MBeanServerFactory.createMBeanServer(); } } public static void registerChannel(JChannel channel, String name) { MBeanServer server=Util.getMBeanServer(); if(server != null) { try { JmxConfigurator.registerChannel(channel, server, (name != null? name : "jgroups"), channel.getClusterName(), true); } catch(Exception e) { e.printStackTrace(); } } } public static String generateList(Collection c, String separator) { if(c == null) return null; StringBuilder sb=new StringBuilder(); boolean first=true; for(Iterator it=c.iterator(); it.hasNext();) { if(first) { first=false; } else { sb.append(separator); } sb.append(it.next()); } return sb.toString(); } /** * Go through the input string and replace any occurance of ${p} with the * props.getProperty(p) value. If there is no such property p defined, then * the ${p} reference will remain unchanged. * * If the property reference is of the form ${p:v} and there is no such * property p, then the default value v will be returned. * * If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the * primary and the secondary properties will be tried in turn, before * returning either the unchanged input, or the default value. * * The property ${/} is replaced with System.getProperty("file.separator") * value and the property ${:} is replaced with * System.getProperty("path.separator"). * * @param string - * the string with possible ${} references * @param props - * the source for ${x} property ref values, null means use * System.getProperty() * @return the input string with all property references replaced if any. If * there are no valid references the input string will be returned. * @throws {@link java.security.AccessControlException} * when not authorised to retrieved system properties */ public static String replaceProperties(final String string, final Properties props) { /** File separator value */ final String FILE_SEPARATOR=File.separator; /** Path separator value */ final String PATH_SEPARATOR=File.pathSeparator; /** File separator alias */ final String FILE_SEPARATOR_ALIAS="/"; /** Path separator alias */ final String PATH_SEPARATOR_ALIAS=":"; // States used in property parsing final int NORMAL=0; final int SEEN_DOLLAR=1; final int IN_BRACKET=2; final char[] chars=string.toCharArray(); StringBuilder buffer=new StringBuilder(); boolean properties=false; int state=NORMAL; int start=0; for(int i=0;i < chars.length;++i) { char c=chars[i]; // Dollar sign outside brackets if(c == '$' && state != IN_BRACKET) state=SEEN_DOLLAR; // Open bracket immediatley after dollar else if(c == '{' && state == SEEN_DOLLAR) { buffer.append(string.substring(start, i - 1)); state=IN_BRACKET; start=i - 1; } // No open bracket after dollar else if(state == SEEN_DOLLAR) state=NORMAL; // Closed bracket after open bracket else if(c == '}' && state == IN_BRACKET) { // No content if(start + 2 == i) { buffer.append("${}"); // REVIEW: Correct? } else // Collect the system property { String value=null; String key=string.substring(start + 2, i); // check for alias if(FILE_SEPARATOR_ALIAS.equals(key)) { value=FILE_SEPARATOR; } else if(PATH_SEPARATOR_ALIAS.equals(key)) { value=PATH_SEPARATOR; } else { // check from the properties if(props != null) value=props.getProperty(key); else value=System.getProperty(key); if(value == null) { // Check for a default value ${key:default} int colon=key.indexOf(':'); if(colon > 0) { String realKey=key.substring(0, colon); if(props != null) value=props.getProperty(realKey); else value=System.getProperty(realKey); if(value == null) { // Check for a composite key, "key1,key2" value=resolveCompositeKey(realKey, props); // Not a composite key either, use the specified default if(value == null) value=key.substring(colon + 1); } } else { // No default, check for a composite key, "key1,key2" value=resolveCompositeKey(key, props); } } } if(value != null) { properties=true; buffer.append(value); } } start=i + 1; state=NORMAL; } } // No properties if(properties == false) return string; // Collect the trailing characters if(start != chars.length) buffer.append(string.substring(start, chars.length)); // Done return buffer.toString(); } /** * Try to resolve a "key" from the provided properties by checking if it is * actually a "key1,key2", in which case try first "key1", then "key2". If * all fails, return null. * * It also accepts "key1," and ",key2". * * @param key * the key to resolve * @param props * the properties to use * @return the resolved key or null */ private static String resolveCompositeKey(String key, Properties props) { String value=null; // Look for the comma int comma=key.indexOf(','); if(comma > -1) { // If we have a first part, try resolve it if(comma > 0) { // Check the first part String key1=key.substring(0, comma); if(props != null) value=props.getProperty(key1); else value=System.getProperty(key1); } // Check the second part, if there is one and first lookup failed if(value == null && comma < key.length() - 1) { String key2=key.substring(comma + 1); if(props != null) value=props.getProperty(key2); else value=System.getProperty(key2); } } // Return whatever we've found or null return value; } // /** // * Replaces variables with values from system properties. If a system property is not found, the property is // * removed from the output string // * @param input // * @return // */ // public static String substituteVariables(String input) throws Exception { // Collection<Configurator.ProtocolConfiguration> configs=Configurator.parseConfigurations(input); // for(Configurator.ProtocolConfiguration config: configs) { // for(Iterator<Map.Entry<String,String>> it=config.getProperties().entrySet().iterator(); it.hasNext();) { // Map.Entry<String,String> entry=it.next(); // return null; /** * Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns * the same string, otherwise a copy of the string with variables substituted * @param val * @return A string with vars replaced, or the same string if no vars found */ public static String substituteVariable(String val) { if(val == null) return val; String retval=val, prev; while(retval.contains("${")) { // handle multiple variables in val prev=retval; retval=_substituteVar(retval); if(retval.equals(prev)) break; } return retval; } private static String _substituteVar(String val) { int start_index, end_index; start_index=val.indexOf("${"); if(start_index == -1) return val; end_index=val.indexOf("}", start_index+2); if(end_index == -1) throw new IllegalArgumentException("missing \"}\" in " + val); String tmp=getProperty(val.substring(start_index +2, end_index)); if(tmp == null) return val; StringBuilder sb=new StringBuilder(); sb.append(val.substring(0, start_index)); sb.append(tmp); sb.append(val.substring(end_index+1)); return sb.toString(); } public static String getProperty(String s) { String var, default_val, retval=null; int index=s.indexOf(":"); if(index >= 0) { var=s.substring(0, index); default_val=s.substring(index+1); if(default_val != null && default_val.length() > 0) default_val=default_val.trim(); // retval=System.getProperty(var, default_val); retval=_getProperty(var, default_val); } else { var=s; // retval=System.getProperty(var); retval=_getProperty(var, null); } return retval; } /** * Parses a var which might be comma delimited, e.g. bla,foo:1000: if 'bla' is set, return its value. Else, * if 'foo' is set, return its value, else return "1000" * @param var * @param default_value * @return */ private static String _getProperty(String var, String default_value) { if(var == null) return null; List<String> list=parseCommaDelimitedStrings(var); if(list == null || list.isEmpty()) { list=new ArrayList<String>(1); list.add(var); } String retval=null; for(String prop: list) { try { retval=System.getProperty(prop); if(retval != null) return retval; } catch(Throwable e) { } } return default_value; } /** * Used to convert a byte array in to a java.lang.String object * @param bytes the bytes to be converted * @return the String representation */ private static String getString(byte[] bytes) { StringBuilder sb=new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; sb.append(0x00FF & b); if (i + 1 < bytes.length) { sb.append("-"); } } return sb.toString(); } /** * Converts a java.lang.String in to a MD5 hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String md5(String source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { return null; } } /** * Converts a java.lang.String in to a SHA hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String sha(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { e.printStackTrace(); return null; } } public static String methodNameToAttributeName(String methodName) { methodName=methodName.startsWith("get") || methodName.startsWith("set")? methodName.substring(3): methodName; methodName=methodName.startsWith("is")? methodName.substring(2) : methodName; // Pattern p=Pattern.compile("[A-Z]+"); Matcher m=METHOD_NAME_TO_ATTR_NAME_PATTERN.matcher(methodName); StringBuffer sb=new StringBuffer(); while(m.find()) { int start=m.start(), end=m.end(); String str=methodName.substring(start, end).toLowerCase(); if(str.length() > 1) { String tmp1=str.substring(0, str.length() -1); String tmp2=str.substring(str.length() -1); str=tmp1 + "_" + tmp2; } if(start == 0) { m.appendReplacement(sb, str); } else m.appendReplacement(sb, "_" + str); } m.appendTail(sb); return sb.toString(); } public static String attributeNameToMethodName(String attr_name) { if(attr_name.contains("_")) { // Pattern p=Pattern.compile("_."); Matcher m=ATTR_NAME_TO_METHOD_NAME_PATTERN.matcher(attr_name); StringBuffer sb=new StringBuffer(); while(m.find()) { m.appendReplacement(sb, attr_name.substring(m.end() - 1, m.end()).toUpperCase()); } m.appendTail(sb); char first=sb.charAt(0); if(Character.isLowerCase(first)) { sb.setCharAt(0, Character.toUpperCase(first)); } return sb.toString(); } else { if(Character.isLowerCase(attr_name.charAt(0))) { return attr_name.substring(0, 1).toUpperCase() + attr_name.substring(1); } else { return attr_name; } } } /** * Runs a task on a separate thread * @param task * @param factory * @param group * @param thread_name */ public static void runAsync(Runnable task, ThreadFactory factory, ThreadGroup group, String thread_name) { Thread thread=factory.newThread(group, task, thread_name); thread.start(); } }
package org.jgroups.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.*; import org.jgroups.auth.AuthToken; import org.jgroups.conf.ClassConfigurator; import org.jgroups.protocols.FD; import org.jgroups.protocols.PingHeader; import org.jgroups.stack.IpAddress; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.security.MessageDigest; import java.text.NumberFormat; import java.util.*; /** * Collection of various utility routines that can not be assigned to other classes. * @author Bela Ban * @version $Id: Util.java,v 1.154 2008/06/11 12:50:03 belaban Exp $ */ public class Util { private static NumberFormat f; private static Map<Class,Byte> PRIMITIVE_TYPES=new HashMap<Class,Byte>(10); private static final byte TYPE_NULL = 0; private static final byte TYPE_STREAMABLE = 1; private static final byte TYPE_SERIALIZABLE = 2; private static final byte TYPE_BOOLEAN = 10; private static final byte TYPE_BYTE = 11; private static final byte TYPE_CHAR = 12; private static final byte TYPE_DOUBLE = 13; private static final byte TYPE_FLOAT = 14; private static final byte TYPE_INT = 15; private static final byte TYPE_LONG = 16; private static final byte TYPE_SHORT = 17; private static final byte TYPE_STRING = 18; // constants public static final int MAX_PORT=65535; // highest port allocatable static boolean resolve_dns=false; static boolean JGROUPS_COMPAT=false; /** * Global thread group to which all (most!) JGroups threads belong */ private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") { public void uncaughtException(Thread t, Throwable e) { LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e); } }; public static ThreadGroup getGlobalThreadGroup() { return GLOBAL_GROUP; } static { try { resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue(); } catch (SecurityException ex){ resolve_dns=false; } f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); f.setMaximumFractionDigits(2); try { String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false"); JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue(); } catch (SecurityException ex){ } PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN)); PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE)); PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR)); PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE)); PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT)); PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT)); PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG)); PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT)); PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING)); } public static void assertTrue(boolean condition) { assert condition; } public static void assertTrue(String message, boolean condition) { if(message != null) assert condition : message; else assert condition; } public static void assertFalse(boolean condition) { assertFalse(null, condition); } public static void assertFalse(String message, boolean condition) { if(message != null) assert !condition : message; else assert !condition; } public static void assertEquals(String message, Object val1, Object val2) { if(message != null) { assert val1.equals(val2) : message; } else { assert val1.equals(val2); } } public static void assertEquals(Object val1, Object val2) { assertEquals(null, val1, val2); } public static void assertNotNull(String message, Object val) { if(message != null) assert val != null : message; else assert val != null; } public static void assertNotNull(Object val) { assertNotNull(null, val); } public static void assertNull(String message, Object val) { if(message != null) assert val == null : message; else assert val == null; } public static void assertNull(Object val) { assertNotNull(null, val); } /** * Verifies that val is <= max memory * @param buf_name * @param val */ public static void checkBufferSize(String buf_name, long val) { // sanity check that max_credits doesn't exceed memory allocated to VM by -Xmx long max_mem=Runtime.getRuntime().maxMemory(); if(val > max_mem) { throw new IllegalArgumentException(buf_name + "(" + Util.printBytes(val) + ") exceeds max memory allocated to VM (" + Util.printBytes(max_mem) + ")"); } } public static void close(InputStream inp) { if(inp != null) try {inp.close();} catch(IOException e) {} } public static void close(OutputStream out) { if(out != null) { try {out.close();} catch(IOException e) {} } } public static void close(Socket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(DatagramSocket my_sock) { if(my_sock != null) { try {my_sock.close();} catch(Throwable t) {} } } public static void close(Channel ch) { if(ch != null) { try {ch.close();} catch(Throwable t) {} } } public static void close(Channel ... channels) { if(channels != null) { for(Channel ch: channels) Util.close(ch); } } /** * Creates an object from a byte buffer */ public static Object objectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; if(JGROUPS_COMPAT) return oldObjectFromByteBuffer(buffer); return objectFromByteBuffer(buffer, 0, buffer.length); } public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; if(JGROUPS_COMPAT) return oldObjectFromByteBuffer(buffer, offset, length); Object retval=null; InputStream in=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); byte b=(byte)in_stream.read(); try { switch(b) { case TYPE_NULL: return null; case TYPE_STREAMABLE: in=new DataInputStream(in_stream); retval=readGenericStreamable((DataInputStream)in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela) retval=((ContextObjectInputStream)in).readObject(); break; case TYPE_BOOLEAN: in=new DataInputStream(in_stream); retval=Boolean.valueOf(((DataInputStream)in).readBoolean()); break; case TYPE_BYTE: in=new DataInputStream(in_stream); retval=new Byte(((DataInputStream)in).readByte()); break; case TYPE_CHAR: in=new DataInputStream(in_stream); retval=new Character(((DataInputStream)in).readChar()); break; case TYPE_DOUBLE: in=new DataInputStream(in_stream); retval=new Double(((DataInputStream)in).readDouble()); break; case TYPE_FLOAT: in=new DataInputStream(in_stream); retval=new Float(((DataInputStream)in).readFloat()); break; case TYPE_INT: in=new DataInputStream(in_stream); retval=new Integer(((DataInputStream)in).readInt()); break; case TYPE_LONG: in=new DataInputStream(in_stream); retval=new Long(((DataInputStream)in).readLong()); break; case TYPE_SHORT: in=new DataInputStream(in_stream); retval=new Short(((DataInputStream)in).readShort()); break; case TYPE_STRING: in=new DataInputStream(in_stream); if(((DataInputStream)in).readBoolean()) { // large string ObjectInputStream ois=new ObjectInputStream(in); try { return ois.readObject(); } finally { ois.close(); } } else { retval=((DataInputStream)in).readUTF(); } break; default: throw new IllegalArgumentException("type " + b + " is invalid"); } return retval; } finally { Util.close(in); } } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable * or Streamable. Only Streamable objects are interoperable w/ jgroups-me */ public static byte[] objectToByteBuffer(Object obj) throws Exception { if(JGROUPS_COMPAT) return oldObjectToByteBuffer(obj); byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); if(obj == null) { out_stream.write(TYPE_NULL); out_stream.flush(); return out_stream.toByteArray(); } OutputStream out=null; Byte type; try { if(obj instanceof Streamable) { // use Streamable if we can out_stream.write(TYPE_STREAMABLE); out=new DataOutputStream(out_stream); writeGenericStreamable((Streamable)obj, (DataOutputStream)out); } else if((type=(Byte)PRIMITIVE_TYPES.get(obj.getClass())) != null) { out_stream.write(type.byteValue()); out=new DataOutputStream(out_stream); switch(type.byteValue()) { case TYPE_BOOLEAN: ((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue()); break; case TYPE_BYTE: ((DataOutputStream)out).writeByte(((Byte)obj).byteValue()); break; case TYPE_CHAR: ((DataOutputStream)out).writeChar(((Character)obj).charValue()); break; case TYPE_DOUBLE: ((DataOutputStream)out).writeDouble(((Double)obj).doubleValue()); break; case TYPE_FLOAT: ((DataOutputStream)out).writeFloat(((Float)obj).floatValue()); break; case TYPE_INT: ((DataOutputStream)out).writeInt(((Integer)obj).intValue()); break; case TYPE_LONG: ((DataOutputStream)out).writeLong(((Long)obj).longValue()); break; case TYPE_SHORT: ((DataOutputStream)out).writeShort(((Short)obj).shortValue()); break; case TYPE_STRING: String str=(String)obj; if(str.length() > Short.MAX_VALUE) { ((DataOutputStream)out).writeBoolean(true); ObjectOutputStream oos=new ObjectOutputStream(out); try { oos.writeObject(str); } finally { oos.close(); } } else { ((DataOutputStream)out).writeBoolean(false); ((DataOutputStream)out).writeUTF(str); } break; default: throw new IllegalArgumentException("type " + type + " is invalid"); } } else { // will throw an exception if object is not serializable out_stream.write(TYPE_SERIALIZABLE); out=new ObjectOutputStream(out_stream); ((ObjectOutputStream)out).writeObject(obj); } } finally { Util.close(out); } result=out_stream.toByteArray(); return result; } /** For backward compatibility in JBoss 4.0.2 */ public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; return oldObjectFromByteBuffer(buffer, 0, buffer.length); } public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Object retval=null; try { // to read the object as an Externalizable ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela) retval=in.readObject(); in.close(); } catch(StreamCorruptedException sce) { try { // is it Streamable? ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); retval=readGenericStreamable(in); in.close(); } catch(Exception ee) { IOException tmp=new IOException("unmarshalling failed"); tmp.initCause(ee); throw tmp; } } if(retval == null) return null; return retval; } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable * or Streamable. Only Streamable objects are interoperable w/ jgroups-me */ public static byte[] oldObjectToByteBuffer(Object obj) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); if(obj instanceof Streamable) { // use Streamable if we can DataOutputStream out=new DataOutputStream(out_stream); writeGenericStreamable((Streamable)obj, out); out.close(); } else { ObjectOutputStream out=new ObjectOutputStream(out_stream); out.writeObject(obj); out.close(); } result=out_stream.toByteArray(); return result; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static byte[] streamableToByteBuffer(Streamable obj) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(out_stream); obj.writeTo(out); result=out_stream.toByteArray(); out.close(); return result; } public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(out_stream); Util.writeAddresses(c, out); result=out_stream.toByteArray(); out.close(); return result; } public static int size(Address addr) { int retval=Global.BYTE_SIZE; // presence byte if(addr != null) retval+=addr.size() + Global.BYTE_SIZE; // plus type of address return retval; } public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{ Util.writeString(token.getName(), out); token.writeTo(out); } public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { try{ String type = Util.readString(in); Object obj = Class.forName(type).newInstance(); AuthToken token = (AuthToken) obj; token.readFrom(in); return token; } catch(ClassNotFoundException cnfe){ return null; } } public static void writeAddress(Address addr, DataOutputStream out) throws IOException { if(addr == null) { out.writeBoolean(false); return; } out.writeBoolean(true); if(addr instanceof IpAddress) { // regular case, we don't need to include class information about the type of Address, e.g. JmsAddress out.writeBoolean(true); addr.writeTo(out); } else { out.writeBoolean(false); writeOtherAddress(addr, out); } } public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { Address addr=null; if(in.readBoolean() == false) return null; if(in.readBoolean()) { addr=new IpAddress(); addr.readFrom(in); } else { addr=readOtherAddress(in); } return addr; } private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { int b=in.read(); short magic_number; String classname; Class cl=null; Address addr; if(b == 1) { magic_number=in.readShort(); cl=ClassConfigurator.get(magic_number); } else { classname=in.readUTF(); cl=ClassConfigurator.get(classname); } addr=(Address)cl.newInstance(); addr.readFrom(in); return addr; } private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException { short magic_number=ClassConfigurator.getMagicNumber(addr.getClass()); // write the class info if(magic_number == -1) { out.write(0); out.writeUTF(addr.getClass().getName()); } else { out.write(1); out.writeShort(magic_number); } // write the data itself addr.writeTo(out); } /** * Writes a Vector of Addresses. Can contain 65K addresses at most * @param v A Collection<Address> * @param out * @throws IOException */ public static void writeAddresses(Collection<Address> v, DataOutputStream out) throws IOException { if(v == null) { out.writeShort(-1); return; } out.writeShort(v.size()); for(Address addr: v) { Util.writeAddress(addr, out); } } public static Collection<Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException { short length=in.readShort(); if(length < 0) return null; Collection<Address> retval=(Collection<Address>)cl.newInstance(); Address addr; for(int i=0; i < length; i++) { addr=Util.readAddress(in); retval.add(addr); } return retval; } /** * Returns the marshalled size of a Collection of Addresses. * <em>Assumes elements are of the same type !</em> * @param addrs Collection<Address> * @return long size */ public static long size(Collection<Address> addrs) { int retval=Global.SHORT_SIZE; // number of elements if(addrs != null && !addrs.isEmpty()) { Address addr=addrs.iterator().next(); retval+=size(addr) * addrs.size(); } return retval; } public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException { if(obj == null) { out.writeBoolean(false); return; } out.writeBoolean(true); obj.writeTo(out); } public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { Streamable retval=null; if(in.readBoolean() == false) return null; retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException { short magic_number; String classname; if(obj == null) { out.write(0); return; } out.write(1); magic_number=ClassConfigurator.getMagicNumber(obj.getClass()); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); classname=obj.getClass().getName(); out.writeUTF(classname); } else { out.writeBoolean(true); out.writeShort(magic_number); } // write the contents obj.writeTo(out); } public static Streamable readGenericStreamable(DataInputStream in) throws IOException { Streamable retval=null; int b=in.read(); if(b == 0) return null; boolean use_magic_number=in.readBoolean(); String classname; Class clazz; try { if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.get(magic_number); if (clazz==null) { throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } } else { classname=in.readUTF(); clazz=ClassConfigurator.get(classname); if (clazz==null) { throw new ClassNotFoundException(classname); } } retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } catch(Exception ex) { throw new IOException("failed reading object: " + ex.toString()); } } public static void writeObject(Object obj, DataOutputStream out) throws Exception { if(obj == null || !(obj instanceof Streamable)) { byte[] buf=objectToByteBuffer(obj); out.writeShort(buf.length); out.write(buf, 0, buf.length); } else { out.writeShort(-1); writeGenericStreamable((Streamable)obj, out); } } public static Object readObject(DataInputStream in) throws Exception { short len=in.readShort(); Object retval=null; if(len == -1) { retval=readGenericStreamable(in); } else { byte[] buf=new byte[len]; in.readFully(buf, 0, len); retval=objectFromByteBuffer(buf); } return retval; } public static void writeString(String s, DataOutputStream out) throws IOException { if(s != null) { out.write(1); out.writeUTF(s); } else { out.write(0); } } public static String readString(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) return in.readUTF(); return null; } public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException { if(buf != null) { out.write(1); out.writeInt(buf.length); out.write(buf, 0, buf.length); } else { out.write(0); } } public static byte[] readByteBuffer(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) { b=in.readInt(); byte[] buf=new byte[b]; in.read(buf, 0, buf.length); return buf; } return null; } public static Buffer messageToByteBuffer(Message msg) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(output); out.writeBoolean(msg != null); if(msg != null) msg.writeTo(out); out.flush(); Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception { ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); if(!in.readBoolean()) return null; Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); return msg; } /** * Marshalls a list of messages. * @param xmit_list LinkedList<Message> * @return Buffer * @throws IOException */ public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(output); Buffer retval=null; out.writeInt(xmit_list.size()); for(Message msg: xmit_list) { msg.writeTo(out); } out.flush(); retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception { List<Message> retval=null; ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); int size=in.readInt(); if(size == 0) return null; Message msg; retval=new LinkedList<Message>(); for(int i=0; i < size; i++) { msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); retval.add(msg); } return retval; } public static boolean match(Object obj1, Object obj2) { if(obj1 == null && obj2 == null) return true; if(obj1 != null) return obj1.equals(obj2); else return obj2.equals(obj1); } public static boolean match(long[] a1, long[] a2) { if(a1 == null && a2 == null) return true; if(a1 == null || a2 == null) return false; if(a1 == a2) // identity return true; // at this point, a1 != null and a2 != null if(a1.length != a2.length) return false; for(int i=0; i < a1.length; i++) { if(a1[i] != a2[i]) return false; } return true; } /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */ public static void sleep(long timeout) { try { Thread.sleep(timeout); } catch(Throwable e) { } } public static void sleep(long timeout, int nanos) { try { Thread.sleep(timeout, nanos); } catch(Throwable e) { } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ public static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } public static int keyPress(String msg) { System.out.println(msg); try { return System.in.read(); } catch(IOException e) { return 0; } } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long)((Math.random() * 100000) % range) + 1; } /** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */ public static void sleepRandom(long timeout) { if(timeout <= 0) { return; } long r=(int)((Math.random() * 100000) % timeout) + 1; sleep(r); } /** Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. */ public static boolean tossWeightedCoin(double probability) { long r=random(100); long cutoff=(long)(probability * 100); return r < cutoff; } public static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch(Exception ex) { } return "localhost"; } public static void dumpStack(boolean exit) { try { throw new Exception("Dumping stack:"); } catch(Exception e) { e.printStackTrace(); if(exit) System.exit(0); } } public static String dumpThreads() { StringBuilder sb=new StringBuilder(); ThreadMXBean bean=ManagementFactory.getThreadMXBean(); long[] ids=bean.getAllThreadIds(); ThreadInfo[] threads=bean.getThreadInfo(ids, 20); for(int i=0; i < threads.length; i++) { ThreadInfo info=threads[i]; if(info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace=info.getStackTrace(); for(int j=0; j < stack_trace.length; j++) { StackTraceElement el=stack_trace[j]; sb.append("at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } return sb.toString(); } public static boolean interruptAndWaitToDie(Thread t) { return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME); } public static boolean interruptAndWaitToDie(Thread t, long timeout) { if(t == null) throw new IllegalArgumentException("Thread can not be null"); t.interrupt(); // interrupts the sleep() try { t.join(timeout); } catch(InterruptedException e){ Thread.currentThread().interrupt(); // set interrupt flag again } return t.isAlive(); } /** * Debugging method used to dump the content of a protocol queue in a * condensed form. Useful to follow the evolution of the queue's content in * time. */ public static String dumpQueue(Queue q) { StringBuilder sb=new StringBuilder(); LinkedList values=q.values(); if(values.isEmpty()) { sb.append("empty"); } else { for(Iterator it=values.iterator(); it.hasNext();) { Object o=it.next(); String s=null; if(o instanceof Event) { Event event=(Event)o; int type=event.getType(); s=Event.type2String(type); if(type == Event.VIEW_CHANGE) s+=" " + event.getArg(); if(type == Event.MSG) s+=" " + event.getArg(); if(type == Event.MSG) { s+="["; Message m=(Message)event.getArg(); Map<String,Header> headers=new HashMap<String,Header>(m.getHeaders()); for(Iterator i=headers.keySet().iterator(); i.hasNext();) { Object headerKey=i.next(); Object value=headers.get(headerKey); String headerToString=null; if(value instanceof FD.FdHeader) { headerToString=value.toString(); } else if(value instanceof PingHeader) { headerToString=headerKey + "-"; if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { headerToString+="GMREQ"; } else if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { headerToString+="GMRSP"; } else { headerToString+="UNKNOWN"; } } else { headerToString=headerKey + "-" + (value == null ? "null" : value.toString()); } s+=headerToString; if(i.hasNext()) { s+=","; } } s+="]"; } } else { s=o.toString(); } sb.append(s).append("\n"); } } return sb.toString(); } /** * Use with caution: lots of overhead */ public static String printStackTrace(Throwable t) { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); return s.toString(); } public static String getStackTrace(Throwable t) { return printStackTrace(t); } public static String print(Throwable t) { return printStackTrace(t); } public static void crash() { System.exit(-1); } public static String printEvent(Event evt) { Message msg; if(evt.getType() == Event.MSG) { msg=(Message)evt.getArg(); if(msg != null) { if(msg.getLength() > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.toString(); } /** Tries to read an object from the message's buffer and prints it */ public static String printMessage(Message msg) { if(msg == null) return ""; if(msg.getLength() == 0) return null; try { return msg.getObject().toString(); } catch(Exception e) { // it is not an object return ""; } } /** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it. Returns empty string if object is not a method call */ public static String printMethodCall(Message msg) { Object obj; if(msg == null) return ""; if(msg.getLength() == 0) return ""; try { obj=msg.getObject(); return obj.toString(); } catch(Exception e) { // it is not an object return ""; } } public static void printThreads() { Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); System.out.println(" for(int i=0; i < threads.length; i++) { System.out.println("#" + i + ": " + threads[i]); } System.out.println(" } public static String activeThreads() { StringBuilder sb=new StringBuilder(); Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); sb.append(" for(int i=0; i < threads.length; i++) { sb.append("#").append(i).append(": ").append(threads[i]).append('\n'); } sb.append(" return sb.toString(); } public static String printBytes(long bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static String printBytes(double bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } /** Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes. @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size=0; byte[] fragment; int tmp_size=0; int num_frags; int index=0; num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval=new byte[num_frags][]; while(accumulated_size < length) { if(accumulated_size + frag_size <= length) tmp_size=frag_size; else tmp_size=length - accumulated_size; fragment=new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++]=fragment; accumulated_size+=tmp_size; } return retval; } public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { return fragmentBuffer(buf, frag_size, buf.length); } /** * Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and * return them in a list. Example:<br/> * Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). * This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment * starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length * of 2 bytes. * @param frag_size * @return List. A List<Range> of offset/length pairs */ public static List<Range> computeFragOffsets(int offset, int length, int frag_size) { List<Range> retval=new ArrayList<Range>(); long total_size=length + offset; int index=offset; int tmp_size=0; Range r; while(index < total_size) { if(index + frag_size <= total_size) tmp_size=frag_size; else tmp_size=(int)(total_size - index); r=new Range(index, tmp_size); retval.add(r); index+=tmp_size; } return retval; } public static List<Range> computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.length, frag_size); } /** Concatenates smaller fragments into entire buffers. @param fragments An array of byte buffers (<code>byte[]</code>) @return A byte buffer */ public static byte[] defragmentBuffer(byte[] fragments[]) { int total_length=0; byte[] ret; int index=0; if(fragments == null) return null; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; total_length+=fragments[i].length; } ret=new byte[total_length]; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); index+=fragments[i].length; } return ret; } public static void printFragments(byte[] frags[]) { for(int i=0; i < frags.length; i++) System.out.println('\'' + new String(frags[i]) + '\''); } public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(T el: list) { if(first) { first=false; } else { sb.append(delimiter); } sb.append(el); } return sb.toString(); } // /** // Peeks for view on the channel until n views have been received or timeout has elapsed. // Used to determine the view in which we want to start work. Usually, we start as only // member in our own view (1st view) and the next view (2nd view) will be the full view // of all members, or a timeout if we're the first member. If a non-view (a message or // block) is received, the method returns immediately. // @param channel The channel used to peek for views. Has to be operational. // @param number_of_views The number of views to wait for. 2 is a good number to ensure that, // if there are other members, we start working with them included in our view. // @param timeout Number of milliseconds to wait until view is forced to return. A value // of <= 0 means wait forever. // */ // public static View peekViews(Channel channel, int number_of_views, long timeout) { // View retval=null; // Object obj=null; // int num=0; // long start_time=System.currentTimeMillis(); // if(timeout <= 0) { // while(true) { // try { // obj=channel.peek(0); // if(obj == null || !(obj instanceof View)) // break; // else { // retval=(View)channel.receive(0); // num++; // if(num >= number_of_views) // break; // catch(Exception ex) { // break; // else { // while(timeout > 0) { // try { // obj=channel.peek(timeout); // if(obj == null || !(obj instanceof View)) // break; // else { // retval=(View)channel.receive(timeout); // num++; // if(num >= number_of_views) // break; // catch(Exception ex) { // break; // timeout=timeout - (System.currentTimeMillis() - start_time); // return retval; public static String array2String(long[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(short[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(int[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(boolean[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(Object[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } /** Returns true if all elements of c match obj */ public static boolean all(Collection c, Object obj) { for(Iterator iterator=c.iterator(); iterator.hasNext();) { Object o=iterator.next(); if(!o.equals(obj)) return false; } return true; } /** * Selects a random subset of members according to subset_percentage and returns them. * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. */ public static Vector<Address> pickSubset(Vector<Address> members, double subset_percentage) { Vector<Address> ret=new Vector<Address>(), tmp_mbrs; int num_mbrs=members.size(), subset_size, index; if(num_mbrs == 0) return ret; subset_size=(int)Math.ceil(num_mbrs * subset_percentage); tmp_mbrs=(Vector<Address>)members.clone(); for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); ret.addElement(tmp_mbrs.elementAt(index)); tmp_mbrs.removeElementAt(index); } return ret; } public static Object pickRandomElement(List list) { if(list == null) return null; int size=list.size(); int index=(int)((Math.random() * size * 10) % size); return list.get(index); } public static Object pickRandomElement(Object[] array) { if(array == null) return null; int size=array.length; int index=(int)((Math.random() * size * 10) % size); return array[index]; } /** * Returns all members that left between 2 views. All members that are element of old_mbrs but not element of * new_mbrs are returned. */ public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) { Vector<Address> retval=new Vector<Address>(); Address mbr; if(old_mbrs == null || new_mbrs == null) return retval; for(int i=0; i < old_mbrs.size(); i++) { mbr=old_mbrs.elementAt(i); if(!new_mbrs.contains(mbr)) retval.addElement(mbr); } return retval; } public static String printMembers(Vector v) { StringBuilder sb=new StringBuilder("("); boolean first=true; Object el; if(v != null) { for(int i=0; i < v.size(); i++) { if(!first) sb.append(", "); else first=false; el=v.elementAt(i); sb.append(el); } } sb.append(')'); return sb.toString(); } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, OutputStream out) throws Exception { if(buf.length > 1) { out.write(buf, 0, 1); out.write(buf, 1, buf.length - 1); } else { out.write(buf, 0, 0); out.write(buf); } } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception { if(length > 1) { out.write(buf, offset, 1); out.write(buf, offset+1, length - 1); } else { out.write(buf, offset, 0); out.write(buf, offset, length); } } /** * if we were to register for OP_WRITE and send the remaining data on * readyOps for this channel we have to either block the caller thread or * queue the message buffers that may arrive while waiting for OP_WRITE. * Instead of the above approach this method will continuously write to the * channel until the buffer sent fully. */ public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException { int written = 0; int toWrite = buf.limit(); while (written < toWrite) { written += out.write(buf); } } // /* double writes are not required.*/ // public static void doubleWriteBuffer( // ByteBuffer buf, // WritableByteChannel out) // throws Exception // if (buf.limit() > 1) // int actualLimit = buf.limit(); // buf.limit(1); // writeFully(buf,out); // buf.limit(actualLimit); // writeFully(buf,out); // else // buf.limit(0); // writeFully(buf,out); // buf.limit(1); // writeFully(buf,out); public static long sizeOf(String classname) { Object inst; byte[] data; try { inst=Util.loadClass(classname, null).newInstance(); data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static long sizeOf(Object inst) { byte[] data; try { data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static int sizeOf(Streamable inst) { byte[] data; ByteArrayOutputStream output; DataOutputStream out; try { output=new ByteArrayOutputStream(); out=new DataOutputStream(output); inst.writeTo(out); out.flush(); data=output.toByteArray(); return data.length; } catch(Exception ex) { return -1; } } /** * Tries to load the class from the current thread's context class loader. If * not successful, tries to load the class from the current instance. * @param classname Desired class. * @param clazz Class object used to obtain a class loader * if no context class loader is available. * @return Class, or null on failure. */ public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException { ClassLoader loader; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } throw new ClassNotFoundException(classname); } public static InputStream getResourceAsStream(String name, Class clazz) { ClassLoader loader; InputStream retval=null; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.getResourceAsStream(name); } } catch(Throwable t) { } return retval; } /** Checks whether 2 Addresses are on the same host */ public static boolean sameHost(Address one, Address two) { InetAddress a, b; String host_a, host_b; if(one == null || two == null) return false; if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) { return false; } a=((IpAddress)one).getIpAddress(); b=((IpAddress)two).getIpAddress(); if(a == null || b == null) return false; host_a=a.getHostAddress(); host_b=b.getHostAddress(); // System.out.println("host_a=" + host_a + ", host_b=" + host_b); return host_a.equals(host_b); } public static boolean fileExists(String fname) { return (new File(fname)).exists(); } /** * Parses comma-delimited longs; e.g., 2000,4000,8000. * Returns array of long, or null. */ public static long[] parseCommaDelimitedLongs(String s) { StringTokenizer tok; Vector<Long> v=new Vector<Long>(); Long l; long[] retval=null; if(s == null) return null; tok=new StringTokenizer(s, ","); while(tok.hasMoreTokens()) { l=new Long(tok.nextToken()); v.addElement(l); } if(v.isEmpty()) return null; retval=new long[v.size()]; for(int i=0; i < v.size(); i++) retval[i]=v.elementAt(i).longValue(); return retval; } /** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */ public static List<String> parseCommaDelimitedStrings(String l) { return parseStringList(l, ","); } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of * IpAddresses */ public static List<IpAddress> parseCommaDelimetedHosts(String hosts, int port_range) throws UnknownHostException { StringTokenizer tok=new StringTokenizer(hosts, ","); String t; IpAddress addr; Set<IpAddress> retval=new HashSet<IpAddress>(); while(tok.hasMoreTokens()) { t=tok.nextToken().trim(); String host=t.substring(0, t.indexOf('[')); host=host.trim(); int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); for(int i=port;i < port + port_range;i++) { addr=new IpAddress(host, i); retval.add(addr); } } return Collections.unmodifiableList(new LinkedList<IpAddress>(retval)); } public static List<String> parseStringList(String l, String separator) { List<String> tmp=new LinkedList<String>(); StringTokenizer tok=new StringTokenizer(l, separator); String t; while(tok.hasMoreTokens()) { t=tok.nextToken(); tmp.add(t.trim()); } return tmp; } /** * * @param s * @return List<NetworkInterface> */ public static List<NetworkInterface> parseInterfaceList(String s) throws Exception { List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10); if(s == null) return null; StringTokenizer tok=new StringTokenizer(s, ","); String interface_name; NetworkInterface intf; while(tok.hasMoreTokens()) { interface_name=tok.nextToken(); // try by name first (e.g. (eth0") intf=NetworkInterface.getByName(interface_name); // next try by IP address or symbolic name if(intf == null) intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name)); if(intf == null) throw new Exception("interface " + interface_name + " not found"); if(!interfaces.contains(intf)) { interfaces.add(intf); } } return interfaces; } public static String print(List<NetworkInterface> interfaces) { StringBuilder sb=new StringBuilder(); boolean first=true; for(NetworkInterface intf: interfaces) { if(first) { first=false; } else { sb.append(", "); } sb.append(intf.getName()); } return sb.toString(); } public static String shortName(String hostname) { int index; StringBuilder sb=new StringBuilder(); if(hostname == null) return null; index=hostname.indexOf('.'); if(index > 0 && !Character.isDigit(hostname.charAt(0))) sb.append(hostname.substring(0, index)); else sb.append(hostname); return sb.toString(); } public static String shortName(InetAddress hostname) { if(hostname == null) return null; StringBuilder sb=new StringBuilder(); if(resolve_dns) sb.append(hostname.getHostName()); else sb.append(hostname.getHostAddress()); return sb.toString(); } /** Finds first available port starting at start_port and returns server socket */ public static ServerSocket createServerSocket(int start_port) { ServerSocket ret=null; while(true) { try { ret=new ServerSocket(start_port); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) { ServerSocket ret=null; while(true) { try { ret=new ServerSocket(start_port, 50, bind_addr); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } /** * Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, * start_port will be incremented until a socket can be created. * @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound. * @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already * in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. */ public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception { DatagramSocket sock=null; if(addr == null) { if(port == 0) { return new DatagramSocket(); } else { while(port < MAX_PORT) { try { return new DatagramSocket(port); } catch(BindException bind_ex) { // port already used port++; } } } } else { if(port == 0) port=1024; while(port < MAX_PORT) { try { return new DatagramSocket(port, addr); } catch(BindException bind_ex) { // port already used port++; } } } return sock; // will never be reached, but the stupid compiler didn't figure it out... } public static MulticastSocket createMulticastSocket(int port) throws IOException { return createMulticastSocket(null, port, null); } public static MulticastSocket createMulticastSocket(InetAddress mcast_addr, int port, Log log) throws IOException { if(mcast_addr != null && !mcast_addr.isMulticastAddress()) { if(log != null && log.isWarnEnabled()) log.warn("mcast_addr (" + mcast_addr + ") is not a multicast address, will be ignored"); return new MulticastSocket(port); } SocketAddress saddr=new InetSocketAddress(mcast_addr, port); MulticastSocket retval=null; try { retval=new MulticastSocket(saddr); } catch(IOException ex) { if(log != null && log.isWarnEnabled()) { StringBuilder sb=new StringBuilder(); String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a"; sb.append("could not bind to " + mcast_addr + " (" + type + " address)"); sb.append("; make sure your mcast_addr is of the same type as the IP stack (IPv4 or IPv6)."); sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " + "(see http: sb.append("\nException was: " + ex); log.warn(sb); } } if(retval == null) retval=new MulticastSocket(port); return retval; } /** * Returns the address of the interface to use defined by bind_addr and bind_interface * @param props * @return * @throws UnknownHostException * @throws SocketException */ public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException { boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String bind_addr=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr", ignore_systemprops, null); String bind_interface=Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface", ignore_systemprops, null); InetAddress retval=null, bind_addr_host=null; if(bind_addr != null) { bind_addr_host=InetAddress.getByName(bind_addr); } if(bind_interface != null) { NetworkInterface intf=NetworkInterface.getByName(bind_interface); if(intf != null) { for(Enumeration<InetAddress> addresses=intf.getInetAddresses(); addresses.hasMoreElements();) { InetAddress addr=addresses.nextElement(); if(bind_addr == null) { retval=addr; break; } else { if(bind_addr_host != null) { if(bind_addr_host.equals(addr)) { retval=addr; break; } } else if(addr.getHostAddress().trim().equalsIgnoreCase(bind_addr)) { retval=addr; break; } } } } else { throw new UnknownHostException("network interface " + bind_interface + " not found"); } } if(retval == null) { retval=bind_addr != null? InetAddress.getByName(bind_addr) : InetAddress.getLocalHost(); } props.remove("bind_addr"); props.remove("bind_interface"); return retval; } public static boolean checkForLinux() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("linux"); } public static boolean checkForSolaris() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("sun"); } public static boolean checkForWindows() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("win"); } public static void prompt(String s) { System.out.println(s); System.out.flush(); try { while(System.in.available() > 0) System.in.read(); System.in.read(); } catch(IOException e) { e.printStackTrace(); } } public static int getJavaVersion() { String version=System.getProperty("java.version"); int retval=0; if(version != null) { if(version.startsWith("1.2")) return 12; if(version.startsWith("1.3")) return 13; if(version.startsWith("1.4")) return 14; if(version.startsWith("1.5")) return 15; if(version.startsWith("5")) return 15; if(version.startsWith("1.6")) return 16; if(version.startsWith("6")) return 16; } return retval; } public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) { if(v == null) return null; return new UnmodifiableVector(v); } public static String memStats(boolean gc) { StringBuilder sb=new StringBuilder(); Runtime rt=Runtime.getRuntime(); if(gc) rt.gc(); long free_mem, total_mem, used_mem; free_mem=rt.freeMemory(); total_mem=rt.totalMemory(); used_mem=total_mem - free_mem; sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem); sb.append("\nTotal mem: ").append(total_mem); return sb.toString(); } // public static InetAddress getFirstNonLoopbackAddress() throws SocketException { // Enumeration en=NetworkInterface.getNetworkInterfaces(); // while(en.hasMoreElements()) { // NetworkInterface i=(NetworkInterface)en.nextElement(); // for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { // InetAddress addr=(InetAddress)en2.nextElement(); // if(!addr.isLoopbackAddress()) // return addr; // return null; public static InetAddress getFirstNonLoopbackAddress() throws SocketException { Enumeration en=NetworkInterface.getNetworkInterfaces(); boolean preferIpv4=Boolean.getBoolean(Global.IPv4); boolean preferIPv6=Boolean.getBoolean(Global.IPv6); while(en.hasMoreElements()) { NetworkInterface i=(NetworkInterface)en.nextElement(); for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr=(InetAddress)en2.nextElement(); if(!addr.isLoopbackAddress()) { if(addr instanceof Inet4Address) { if(preferIPv6) continue; return addr; } if(addr instanceof Inet6Address) { if(preferIpv4) continue; return addr; } } } } return null; } public static boolean isIPv4Stack() { return getIpStack()== 4; } public static boolean isIPv6Stack() { return getIpStack() == 6; } public static short getIpStack() { short retval=2; if(Boolean.getBoolean(Global.IPv4)) { retval=4; } if(Boolean.getBoolean(Global.IPv6)) { retval=6; } return retval; } public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException { Enumeration en=NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface i=(NetworkInterface)en.nextElement(); for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr=(InetAddress)en2.nextElement(); if(!addr.isLoopbackAddress()) { if(addr instanceof Inet4Address) { continue; } if(addr instanceof Inet6Address) { return addr; } } } } return null; } public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10); NetworkInterface intf; for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { intf=(NetworkInterface)en.nextElement(); retval.add(intf); } return retval; } /** * Returns a value associated wither with one or more system properties, or found in the props map * @param system_props * @param props List of properties read from the configuration file * @param prop_name The name of the property, will be removed from props if found * @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from * props (not system_props) * @param default_value Used to return a default value if the properties or system properties didn't have the value * @return The value, or null if not found */ public static String getProperty(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) { String retval=null; if(props != null && prop_name != null) { retval=props.getProperty(prop_name); props.remove(prop_name); } if(!ignore_sysprops) { String tmp, prop; if(system_props != null) { for(int i=0; i < system_props.length; i++) { prop=system_props[i]; if(prop != null) { try { tmp=System.getProperty(prop); if(tmp != null) return tmp; // system properties override config file definitions } catch(SecurityException ex) {} } } } } if(retval == null) return default_value; return retval; } public static boolean isBindAddressPropertyIgnored() { try { String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY); if(tmp == null) { tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD); if(tmp == null) return false; } tmp=tmp.trim().toLowerCase(); return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on")); } catch(SecurityException ex) { return false; } } public static MBeanServer getMBeanServer() { ArrayList servers=MBeanServerFactory.findMBeanServer(null); if(servers == null || servers.isEmpty()) return null; // return 'jboss' server if available for(int i=0; i < servers.size(); i++) { MBeanServer srv=(MBeanServer)servers.get(i); if("jboss".equalsIgnoreCase(srv.getDefaultDomain())) return srv; } // return first available server return (MBeanServer)servers.get(0); } public static void main(String args[]) throws Exception { System.out.println("IPv4: " + isIPv4Stack()); System.out.println("IPv6: " + isIPv6Stack()); } public static String generateList(Collection c, String separator) { if(c == null) return null; StringBuilder sb=new StringBuilder(); boolean first=true; for(Iterator it=c.iterator(); it.hasNext();) { if(first) { first=false; } else { sb.append(separator); } sb.append(it.next()); } return sb.toString(); } /** * Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns * the same string, otherwise a copy of the string with variables substituted * @param val * @return A string with vars replaced, or the same string if no vars found */ public static String substituteVariable(String val) { if(val == null) return val; String retval=val, prev; while(retval.contains("${")) { // handle multiple variables in val prev=retval; retval=_substituteVar(retval); if(retval.equals(prev)) break; } return retval; } private static String _substituteVar(String val) { int start_index, end_index; start_index=val.indexOf("${"); if(start_index == -1) return val; end_index=val.indexOf("}", start_index+2); if(end_index == -1) throw new IllegalArgumentException("missing \"}\" in " + val); String tmp=getProperty(val.substring(start_index +2, end_index)); if(tmp == null) return val; StringBuilder sb=new StringBuilder(); sb.append(val.substring(0, start_index)); sb.append(tmp); sb.append(val.substring(end_index+1)); return sb.toString(); } private static String getProperty(String s) { String var, default_val, retval=null; int index=s.indexOf(":"); if(index >= 0) { var=s.substring(0, index); default_val=s.substring(index+1); retval=System.getProperty(var, default_val); } else { var=s; retval=System.getProperty(var); } return retval; } /** * Used to convert a byte array in to a java.lang.String object * @param bytes the bytes to be converted * @return the String representation */ private static String getString(byte[] bytes) { StringBuilder sb=new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; sb.append(0x00FF & b); if (i + 1 < bytes.length) { sb.append("-"); } } return sb.toString(); } /** * Converts a java.lang.String in to a MD5 hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String md5(String source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { return null; } } /** * Converts a java.lang.String in to a SHA hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String sha(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { e.printStackTrace(); return null; } } }
package org.joml; /** * Contains intersection tests for some geometric primitives. * * @author Kai Burjack */ public class Intersection { /** * Test whether the given ray with the origin <tt>(originX, originY, originZ)</tt> and direction <tt>(dirX, dirY, dirZ)</tt> * intersects the given sphere with center <tt>(centerX, centerY, centerZ)</tt> and square radius <code>radiusSquared</code>. * * @param originX * the x coordinate of the ray's origin * @param originY * the y coordinate of the ray's origin * @param originZ * the z coordinate of the ray's origin * @param dirX * the x coordinate of the ray's direction * @param dirY * the y coordinate of the ray's direction * @param dirZ * the z coordinate of the ray's direction * @param centerX * the x coordinate of the sphere's center * @param centerY * the y coordinate of the sphere's center * @param centerZ * the z coordinate of the sphere's center * @param radiusSquared * the sphere radius squared * @return <code>true</code> if the ray intersects the sphere; <code>false</code> otherwise */ public static boolean testRaySphere(float originX, float originY, float originZ, float dirX, float dirY, float dirZ, float centerX, float centerY, float centerZ, float radiusSquared) { float Lx = centerX - originX; float Ly = centerY - originY; float Lz = centerZ - originZ; float tca = Lx * dirX + Ly * dirY + Lz * dirZ; float d2 = Lx * Lx + Ly * Ly + Lz * Lz - tca * tca; if (d2 > radiusSquared) return false; float thc = (float) Math.sqrt(radiusSquared - d2); float t0 = tca - thc; float t1 = tca + thc; return t0 < t1 && t1 >= 0.0f; } /** * Test whether the ray with the given <code>origin</code> and direction <code>dir</code> * intersects the sphere with the given <code>center</code> and square radius. * * @param origin * the ray's origin * @param dir * the ray's direction * @param center * the sphere's center * @param radiusSquared * the sphere radius squared * @return <code>true</code> if the ray intersects the sphere; <code>false</code> otherwise */ public static boolean testRaySphere(Vector3f origin, Vector3f dir, Vector3f center, float radiusSquared) { return testRaySphere(origin.x, origin.y, origin.z, dir.x, dir.y, dir.z, center.x, center.y, center.z, radiusSquared); } public static boolean testRayAab(float originX, float originY, float originZ, float dirX, float dirY, float dirZ, float aX, float aY, float aZ, float bX, float bY, float bZ) { float invDirX = 1.0f / dirX, invDirY = 1.0f / dirY, invDirZ = 1.0f / dirZ; float tMinX = (aX - originX) * invDirX; float tMinY = (aY - originY) * invDirY; float tMinZ = (aZ - originZ) * invDirZ; float tMaxX = (bX - originX) * invDirX; float tMaxY = (bY - originY) * invDirY; float tMaxZ = (bZ - originZ) * invDirZ; float t1X = Math.min(tMinX, tMaxX); float t1Y = Math.min(tMinY, tMaxY); float t1Z = Math.min(tMinZ, tMaxZ); float t2X = Math.max(tMinX, tMaxX); float t2Y = Math.max(tMinY, tMaxY); float t2Z = Math.max(tMinZ, tMaxZ); float tNear = Math.max(Math.max(t1X, t1Y), t1Z); float tFar = Math.min(Math.min(t2X, t2Y), t2Z); return tNear < tFar && tFar >= 0.0f; } public static boolean testRayAab(Vector3f origin, Vector3f dir, Vector3f a, Vector3f b) { return testRayAab(origin.x, origin.y, origin.z, dir.x, dir.y, dir.z, a.x, a.y, a.z, b.x, b.y, b.z); } public static boolean testRayTriangle(float originX, float originY, float originZ, float dirX, float dirY, float dirZ, float v0X, float v0Y, float v0Z, float v1X, float v1Y, float v1Z, float v2X, float v2Y, float v2Z, float epsilon) { float edge1X = v1X - v0X; float edge1Y = v1Y - v0Y; float edge1Z = v1Z - v0Z; float edge2X = v2X - v0X; float edge2Y = v2Y - v0Y; float edge2Z = v2Z - v0Z; float pvecX = dirY * edge2Z - dirZ * edge2Y; float pvecY = dirZ * edge2X - dirX * edge2Z; float pvecZ = dirX * edge2Y - dirY * edge2X; float det = edge1X * pvecX + edge1Y * pvecY + edge1Z * pvecZ; if (det <= epsilon) return false; float tvecX = originX - v0X; float tvecY = originY - v0Y; float tvecZ = originZ - v0Z; float u = tvecX * pvecX + tvecY * pvecY + tvecZ * pvecZ; if (u < 0.0f || u > det) return false; float qvecX = tvecY * edge1Z - tvecZ * edge1Y; float qvecY = tvecZ * edge1X - tvecX * edge1Z; float qvecZ = tvecX * edge1Y - tvecY * edge1X; float v = dirX * qvecX + dirY * qvecY + dirZ * qvecZ; if (v < 0.0f || u + v > det) return false; return true; } public static boolean testRayTriangle(Vector3f origin, Vector3f dir, Vector3f v0, Vector3f v1, Vector3f v2, float epsilon) { return testRayTriangle(origin.x, origin.y, origin.z, dir.x, dir.y, dir.z, v0.x, v0.y, v0.z, v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, epsilon); } public static float intersectRayTriangle(float originX, float originY, float originZ, float dirX, float dirY, float dirZ, float v0X, float v0Y, float v0Z, float v1X, float v1Y, float v1Z, float v2X, float v2Y, float v2Z, float epsilon) { float edge1X = v1X - v0X; float edge1Y = v1Y - v0Y; float edge1Z = v1Z - v0Z; float edge2X = v2X - v0X; float edge2Y = v2Y - v0Y; float edge2Z = v2Z - v0Z; float pvecX = dirY * edge2Z - dirZ * edge2Y; float pvecY = dirZ * edge2X - dirX * edge2Z; float pvecZ = dirX * edge2Y - dirY * edge2X; float det = edge1X * pvecX + edge1Y * pvecY + edge1Z * pvecZ; if (det <= epsilon) return -1.0f; float tvecX = originX - v0X; float tvecY = originY - v0Y; float tvecZ = originZ - v0Z; float u = tvecX * pvecX + tvecY * pvecY + tvecZ * pvecZ; if (u < 0.0f || u > det) return -1.0f; float qvecX = tvecY * edge1Z - tvecZ * edge1Y; float qvecY = tvecZ * edge1X - tvecX * edge1Z; float qvecZ = tvecX * edge1Y - tvecY * edge1X; float v = dirX * qvecX + dirY * qvecY + dirZ * qvecZ; if (v < 0.0f || u + v > det) return -1.0f; float invDet = 1.0f / det; float t = (edge2X * qvecX + edge2Y * qvecY + edge2Z * qvecZ) * invDet; return t; } public static float intersectRayTriangle(Vector3f origin, Vector3f dir, Vector3f v0, Vector3f v1, Vector3f v2, float epsilon) { return intersectRayTriangle(origin.x, origin.y, origin.z, dir.x, dir.y, dir.z, v0.x, v0.y, v0.z, v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, epsilon); } }
package au.id.chenery.mapyrus; import java.util.ArrayList; import java.util.HashMap; /** * A parsed statement. * Can be one of several types. A conditional statement, * a block of statements making a procedure or just a plain command. */ public class Statement { /* * Possible types of statements. */ public static final int CONDITIONAL = 2; public static final int LOOP = 3; public static final int BLOCK = 4; public static final int COLOR = 10; public static final int LINESTYLE = 11; public static final int FONT = 12; public static final int JUSTIFY = 13; public static final int MOVE = 14; public static final int DRAW = 15; public static final int ARC = 16; public static final int ADDPATH = 17; public static final int CLEARPATH = 18; public static final int SAMPLEPATH = 19; public static final int STRIPEPATH = 20; public static final int STROKE = 21; public static final int FILL = 22; public static final int PROTECT = 23; public static final int CLIP = 24; public static final int LABEL = 25; public static final int SCALE = 26; public static final int ROTATE = 27; public static final int WORLDS = 28; public static final int PROJECT = 29; public static final int DATASET = 30; public static final int IMPORT = 31; public static final int FETCH = 32; public static final int NEWPAGE = 33; public static final int PRINT = 34; public static final int LOCAL = 35; public static final int LET = 36; /* * Statement type for call to user defined procedure block. */ public static final int CALL = 1000; private int mType; /* * Statements in an if-then-else statement. */ private ArrayList mThenStatements; private ArrayList mElseStatements; /* * Statements in a while loop statement. */ private ArrayList mLoopStatements; /* * Name of procedure block, * variable names of parameters to this procedure * and block of statements in a procedure in order of execution */ private String mBlockName; private ArrayList mStatementBlock; private ArrayList mParameters; private Expression []mExpressions; /* * Filename and line number within file that this * statement was read from. */ private String mFilename; private int mLineNumber; /* * Static statement type lookup table for fast lookup. */ private static HashMap mStatementTypeLookup; static { mStatementTypeLookup = new HashMap(); mStatementTypeLookup.put("color", new Integer(COLOR)); mStatementTypeLookup.put("colour", new Integer(COLOR)); mStatementTypeLookup.put("linestyle", new Integer(LINESTYLE)); mStatementTypeLookup.put("font", new Integer(FONT)); mStatementTypeLookup.put("justify", new Integer(JUSTIFY)); mStatementTypeLookup.put("move", new Integer(MOVE)); mStatementTypeLookup.put("draw", new Integer(DRAW)); mStatementTypeLookup.put("arc", new Integer(ARC)); mStatementTypeLookup.put("addpath", new Integer(ADDPATH)); mStatementTypeLookup.put("clearpath", new Integer(CLEARPATH)); mStatementTypeLookup.put("samplepath", new Integer(SAMPLEPATH)); mStatementTypeLookup.put("stripepath", new Integer(STRIPEPATH)); mStatementTypeLookup.put("stroke", new Integer(STROKE)); mStatementTypeLookup.put("fill", new Integer(FILL)); mStatementTypeLookup.put("protect", new Integer(PROTECT)); mStatementTypeLookup.put("clip", new Integer(CLIP)); mStatementTypeLookup.put("label", new Integer(LABEL)); mStatementTypeLookup.put("scale", new Integer(SCALE)); mStatementTypeLookup.put("rotate", new Integer(ROTATE)); mStatementTypeLookup.put("worlds", new Integer(WORLDS)); mStatementTypeLookup.put("project", new Integer(PROJECT)); mStatementTypeLookup.put("dataset", new Integer(DATASET)); mStatementTypeLookup.put("import", new Integer(IMPORT)); mStatementTypeLookup.put("fetch", new Integer(FETCH)); mStatementTypeLookup.put("newpage", new Integer(NEWPAGE)); mStatementTypeLookup.put("print", new Integer(PRINT)); mStatementTypeLookup.put("local", new Integer(LOCAL)); mStatementTypeLookup.put("let", new Integer(LET)); } /** * Looks up identifier for a statement name. * @param s is the name of the statement. * @returns numeric code for this statement, or -1 if statement * is unknown. */ private int getStatementType(String s) { int retval; Integer type = (Integer)mStatementTypeLookup.get(s.toLowerCase()); if (type == null) retval = CALL; else retval = type.intValue(); return(retval); } /** * Creates a plain statement, either a built-in command or * a call to a procedure block that the user has defined. * @param keyword is the name statement. * @param expressions are the arguments for this statement. */ public Statement(String keyword, Expression []expressions) { mType = getStatementType(keyword); if (mType == CALL) mBlockName = keyword; mExpressions = expressions; } /** * Creates a procedure, a block of statements to be executed together. * @param blockName is name of procedure block. * @param parameters variable names of parameters to this procedure. * @param statements list of statements that make up this procedure block. */ public Statement(String blockName, ArrayList parameters, ArrayList statements) { mBlockName = blockName; mParameters = parameters; mStatementBlock = statements; mType = BLOCK; } /** * Create an if, then, else, endif block of statements. * @param test is expression to test. * @param thenStatements is statements to execute if expression is true. * @param elseStatements is statements to execute if expression is false, * or null if there is no statement to execute. */ public Statement(Expression test, ArrayList thenStatements, ArrayList elseStatements) { mType = CONDITIONAL; mExpressions = new Expression[1]; mExpressions[0] = test; mThenStatements = thenStatements; mElseStatements = elseStatements; } /** * Create a while loop block of statements. * @param test is expression to test before each iteration of loop. * @param loopStatements is statements to execute for each loop iteration. */ public Statement(Expression test, ArrayList loopStatements) { mType = LOOP; mExpressions = new Expression[1]; mExpressions[0] = test; mLoopStatements = loopStatements; } /** * Sets the filename and line number that this statement was read from. * This is for use in any error message for this statement. * @param filename is name of file this statement was read from. * @param lineNumber is line number within file containing this statement. */ public void setFilenameAndLineNumber(String filename, int lineNumber) { mFilename = filename; mLineNumber = lineNumber; } /** * Returns filename and line number that this statement was read from. * @return string containing filename and line number. */ public String getFilenameAndLineNumber() { return(mFilename + ":" + mLineNumber); } /** * Returns filename that this statement was read from. * @return string containing filename. */ public String getFilename() { return(mFilename); } /** * Returns the type of this statement. * @return statement type. */ public int getType() { return(mType); } public Expression []getExpressions() { return(mExpressions); } /** * Returns list of statements in "then" section of "if" statement. * @return list of statements. */ public ArrayList getThenStatements() { return(mThenStatements); } /** * Returns list of statements in "else" section of "if" statement. * @return list of statements. */ public ArrayList getElseStatements() { return(mElseStatements); } /** * Returns list of statements in while loop statement. * @return list of statements. */ public ArrayList getLoopStatements() { return(mLoopStatements); } /** * Return name of procedure block. * @return name of procedure. */ public String getBlockName() { return(mBlockName); } /** * Return variable names of parameters to a procedure. * @return list of parameter names. */ public ArrayList getBlockParameters() { return(mParameters); } /** * Return statements in a procedure. * @return ArrayList of statements that make up the procedure. */ public ArrayList getStatementBlock() { return(mStatementBlock); } }
package ca.mcgill.mcb.pcingola.bigDataScript; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.LexerNoViableAltException; import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.Tree; import ca.mcgill.mcb.pcingola.bigDataScript.antlr.BigDataScriptLexer; import ca.mcgill.mcb.pcingola.bigDataScript.antlr.BigDataScriptParser; import ca.mcgill.mcb.pcingola.bigDataScript.antlr.BigDataScriptParser.IncludeFileContext; import ca.mcgill.mcb.pcingola.bigDataScript.compile.CompileErrorStrategy; import ca.mcgill.mcb.pcingola.bigDataScript.compile.CompilerMessage.MessageType; import ca.mcgill.mcb.pcingola.bigDataScript.compile.CompilerMessages; import ca.mcgill.mcb.pcingola.bigDataScript.compile.TypeCheckedNodes; import ca.mcgill.mcb.pcingola.bigDataScript.executioner.Executioner; import ca.mcgill.mcb.pcingola.bigDataScript.executioner.Executioners; import ca.mcgill.mcb.pcingola.bigDataScript.executioner.Executioners.ExecutionerType; import ca.mcgill.mcb.pcingola.bigDataScript.lang.BigDataScriptNodeFactory; import ca.mcgill.mcb.pcingola.bigDataScript.lang.ExpressionTask; import ca.mcgill.mcb.pcingola.bigDataScript.lang.FunctionDeclaration; import ca.mcgill.mcb.pcingola.bigDataScript.lang.Literal; import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralBool; import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralInt; import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralListString; import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralReal; import ca.mcgill.mcb.pcingola.bigDataScript.lang.LiteralString; import ca.mcgill.mcb.pcingola.bigDataScript.lang.ProgramUnit; import ca.mcgill.mcb.pcingola.bigDataScript.lang.Statement; import ca.mcgill.mcb.pcingola.bigDataScript.lang.StatementInclude; import ca.mcgill.mcb.pcingola.bigDataScript.lang.Type; import ca.mcgill.mcb.pcingola.bigDataScript.lang.TypeList; import ca.mcgill.mcb.pcingola.bigDataScript.lang.VarDeclaration; import ca.mcgill.mcb.pcingola.bigDataScript.lang.VariableInit; import ca.mcgill.mcb.pcingola.bigDataScript.lang.nativeFunctions.NativeLibraryFunctions; import ca.mcgill.mcb.pcingola.bigDataScript.lang.nativeMethods.NativeLibraryString; import ca.mcgill.mcb.pcingola.bigDataScript.run.BigDataScriptThread; import ca.mcgill.mcb.pcingola.bigDataScript.run.RunState; import ca.mcgill.mcb.pcingola.bigDataScript.scope.Scope; import ca.mcgill.mcb.pcingola.bigDataScript.scope.ScopeSymbol; import ca.mcgill.mcb.pcingola.bigDataScript.serialize.BigDataScriptSerializer; import ca.mcgill.mcb.pcingola.bigDataScript.task.TaskDependecies; import ca.mcgill.mcb.pcingola.bigDataScript.util.Gpr; import ca.mcgill.mcb.pcingola.bigDataScript.util.Timer; /** * BigDataScript command line parser * * @author pcingola */ public class BigDataScript { enum BigDataScriptAction { RUN, RUN_CHECKPOINT, INFO_CHECKPOINT, TEST } public static final String SOFTWARE_NAME = BigDataScript.class.getSimpleName(); public static final String BUILD = "2015-01-27"; public static final String REVISION = "d"; public static final String VERSION_MAJOR = "0.999"; public static final String VERSION_SHORT = VERSION_MAJOR + REVISION; public static final String VERSION = SOFTWARE_NAME + " " + VERSION_SHORT + " (build " + BUILD + "), by " + Pcingola.BY; boolean verbose; boolean debug; boolean checkPidRegex; boolean log; // Log everything boolean dryRun; // Dry run (do not run tasks) boolean noRmOnExit; // Do not remove files on exit boolean createReport; // Create report boolean useDoneFile; // Use files instead of comparing dates boolean extractSource; // Extract source code fmor checkpoint boolean stackCheck; // Check stack size when thread finishes runnig (should be zero) int taskFailCount = -1; String configFile = Config.DEFAULT_CONFIG_FILE; // Config file String chekcpointRestoreFile; // Restore file String programFileName; // Program file name String pidFile; // File to store PIDs String system; // System type String queue; // Queue name BigDataScriptAction bigDataScriptAction; Config config; ProgramUnit programUnit; // Program (parsed nodes) BigDataScriptThread bigDataScriptThread; ArrayList<String> programArgs; // Command line arguments for BigDataScript program /** * Create an AST from a program (using ANTLR lexer & parser) * Returns null if error * Use 'alreadyIncluded' to keep track of from 'include' statements */ public static ParseTree createAst(File file, boolean debug, Set<String> alreadyIncluded) { alreadyIncluded.add(Gpr.getCanonicalFileName(file)); String fileName = file.toString(); String filePath = fileName; BigDataScriptLexer lexer = null; BigDataScriptParser parser = null; try { filePath = file.getCanonicalPath(); // Input stream if (!Gpr.canRead(filePath)) { CompilerMessages.get().addError("Can't read file '" + filePath + "'"); return null; } // Create a CharStream that reads from standard input ANTLRFileStream input = new ANTLRFileStream(fileName); // Create a lexer that feeds off of input CharStream lexer = new BigDataScriptLexer(input) { @Override public void recover(LexerNoViableAltException e) { throw new RuntimeException(e); // Bail out } }; CommonTokenStream tokens = new CommonTokenStream(lexer); parser = new BigDataScriptParser(tokens); parser.setErrorHandler(new CompileErrorStrategy()); // bail out with exception if errors in parser ParseTree tree = parser.programUnit(); // Begin parsing at main rule // Error loading file? if (tree == null) { System.err.println("Can't parse file '" + filePath + "'"); return null; } // Show main nodes if (debug) { Timer.showStdErr("AST:"); for (int childNum = 0; childNum < tree.getChildCount(); childNum++) { Tree child = tree.getChild(childNum); System.err.println("\t\tChild " + childNum + ":\t" + child + "\tTree:'" + child.toStringTree() + "'"); } } // Included files boolean resolveIncludePending = true; while (resolveIncludePending) resolveIncludePending = resolveIncludes(tree, debug, alreadyIncluded); return tree; } catch (Exception e) { String msg = e.getMessage(); CompilerMessages.get().addError("Could not compile " + filePath + (msg != null ? " :" + e.getMessage() : "") ); return null; } } /** * Main */ public static void main(String[] args) { // Create BigDataScript object and run it BigDataScript bigDataScript = new BigDataScript(args); int exitValue = bigDataScript.run(); System.exit(exitValue); } /** * Resolve include statements */ private static boolean resolveIncludes(ParseTree tree, boolean debug, Set<String> alreadyIncluded) { boolean changed = false; if (tree instanceof IncludeFileContext) { // Parent file: The one that is including the other file File parentFile = new File(((IncludeFileContext) tree).getStart().getInputStream().getSourceName()); // Included file name String includedFilename = StatementInclude.includeFileName(tree.getChild(1).getText()); // Find file (look into all include paths) File includedFile = StatementInclude.includeFile(includedFilename, parentFile); if (includedFile == null) { CompilerMessages.get().add(tree, parentFile, "\n\tIncluded file not found: '" + includedFilename + "'\n\tSearch path: " + Config.get().getIncludePath(), MessageType.ERROR); return false; } // Already included? don't bother String canonicalFileName = Gpr.getCanonicalFileName(includedFile); if (alreadyIncluded.contains(canonicalFileName)) { if (debug) Gpr.debug("File already included: '" + includedFilename + "'\tCanonical path: '" + canonicalFileName + "'"); return false; } if (!includedFile.canRead()) { CompilerMessages.get().add(tree, parentFile, "\n\tCannot read included file: '" + includedFilename + "'", MessageType.ERROR); return false; } // Parse ParseTree treeinc = createAst(includedFile, debug, alreadyIncluded); if (treeinc == null) { CompilerMessages.get().add(tree, parentFile, "\n\tFatal error including file '" + includedFilename + "'", MessageType.ERROR); return false; } // Is a child always a RuleContext? for (int i = 0; i < treeinc.getChildCount(); i++) { ((IncludeFileContext) tree).addChild((RuleContext) treeinc.getChild(i)); } } else { for (int i = 0; i < tree.getChildCount(); i++) changed |= resolveIncludes(tree.getChild(i), debug, alreadyIncluded); } return changed; } public BigDataScript(String args[]) { initDefaults(); parse(args); initialize(); } /** * Check 'pidRegex' */ public void checkPidRegex() { // PID regex matcher String pidPatternStr = config.getPidRegex(""); if (pidPatternStr.isEmpty()) { System.err.println("Cannot find 'pidRegex' entry in config file."); System.exit(1); } Executioner executioner = Executioners.getInstance().get(ExecutionerType.CLUSTER); // Show pattern System.out.println("Matching pidRegex '" + pidPatternStr + "'"); // Read STDIN and check pattern try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { String pid = executioner.parsePidLine(line); System.out.println("Input line:\t'" + line + "'\tMatched: '" + pid + "'"); } } catch (IOException e) { e.printStackTrace(); } executioner.kill(); // Kill executioner } /** * Compile program */ public boolean compile() { if (debug) log("Loading file: '" + programFileName + "'"); // Convert to AST if (debug) log("Creating AST."); CompilerMessages.reset(); ParseTree tree = null; try { tree = createAst(); } catch (Exception e) { System.err.println("Fatal error cannot continue - " + e.getMessage()); return false; } // No tree produced? Fatal error if (tree == null) { if (CompilerMessages.get().isEmpty()) { CompilerMessages.get().addError("Fatal error: Could not compile"); } return false; } // Any error? Do not continue if (!CompilerMessages.get().isEmpty()) return false; // Convert to BigDataScriptNodes if (debug) log("Creating BigDataScript tree."); CompilerMessages.reset(); programUnit = (ProgramUnit) BigDataScriptNodeFactory.get().factory(null, tree); // Transform AST to BigDataScript tree if (debug) log("AST:\n" + programUnit.toString()); // Any error messages? if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get()); if (CompilerMessages.get().hasErrors()) return false; // Type-checking if (debug) log("Type checking."); CompilerMessages.reset(); Scope programScope = new Scope(); programUnit.typeChecking(programScope, CompilerMessages.get()); // Any error messages? if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get()); if (CompilerMessages.get().hasErrors()) return false; // Free some memory by reseting structure we won't use any more TypeCheckedNodes.get().reset(); return true; } /** * Create an AST from a program file * @return A parsed tree */ ParseTree createAst() { File file = new File(programFileName); return createAst(file, debug, new HashSet<String>()); } public BigDataScriptThread getBigDataScriptThread() { return bigDataScriptThread; } public CompilerMessages getCompilerMessages() { return CompilerMessages.get(); } public Config getConfig() { return config; } public ProgramUnit getProgramUnit() { return programUnit; } /** * Show information from a checkpoint file */ int infoCheckpoint() { // Load checkpoint file BigDataScriptSerializer bdsSerializer = new BigDataScriptSerializer(chekcpointRestoreFile, config); List<BigDataScriptThread> bdsThreads = bdsSerializer.load(); for (BigDataScriptThread bdsThread : bdsThreads) bdsThread.print(); return 0; } /** * Get default settings */ void initDefaults() { createReport = true; dryRun = false; log = false; useDoneFile = false; } /** * Initialize before running or type-checking */ void initialize() { Type.reset(); // Reset node factory BigDataScriptNodeFactory.reset(); // Startup message if (verbose || debug) Timer.showStdErr(VERSION); // Config config = new Config(configFile); config.setVerbose(verbose); config.setDebug(debug); config.setLog(log); config.setDryRun(dryRun); config.setTaskFailCount(taskFailCount); config.setNoRmOnExit(noRmOnExit); config.setCreateReport(createReport); config.setExtractSource(extractSource); if (pidFile == null) { if (programFileName != null) pidFile = programFileName + ".pid"; else pidFile = chekcpointRestoreFile + ".pid"; } config.setPidFile(pidFile); // Global scope initilaizeGlobalScope(); // Libraries initilaizeLibraries(); } /** * Set command line arguments as global variables * * How it works: - Program is executes as something like: * * java -jar BigDataScript.jar [options] programFile.bds [programOptions] * * - Any command line argument AFTER "programFile.bds" is considered a * command line argument for the BigDataScript program. E.g. * * java -jar BigDataScript.jar -v program.bds -file myFile.txt -verbose -num * 7 * * So our program "program.bds" has command line options: -file myFile.txt * -verbose -num 7 (notice that "-v" is a command line option for * loudScript.jar and not for "program.bds") * * - We look for variables in ProgramUnit that match the name of these * command line arguments * * - Then we add those values to the variable initialization. Thus * overriding any initialization values provided in the program. E.g. * * Our program has the following variable declarations: string file = * "default_file.txt" int num = 3 bool verbose = false * * We execute the program: java -jar BigDataScript.jar -v program.bds -file * myFile.txt -verbose -num 7 * * The variable declarations are replaced as follows: string file = * "myFile.txt" int num = 7 bool verbose = true * * - Note: Only primitive types are supported (i.e.: string, bool, int & * real) * * - Note: Unmatched variables names will be silently ignored (same for * variables that match, but are non-primitive) * * - Note: If a variable is matched, is primitive, but cannot be converted. * An error is thrown. E.g.: Program: int num = 1 * * Command line: java -jar BigDataScript.jar program.bds -num "hello" <- * This is an error because 'num' is an int * * - Note: Unprocessed arguments will be available to the program as an * 'args' list */ void initializeArgs() { // Set program arguments as global variables for (int argNum = 0; argNum < programArgs.size(); argNum++) { String arg = programArgs.get(argNum); // Parse '-OPT' option if (arg.startsWith("-")) { // Get variable name and value String varName = arg.substring(1); // Find all variable declarations that match this command line argument for (Statement s : programUnit.getStatements()) { // Is it a variable declaration? if (s instanceof VarDeclaration) { VarDeclaration varDecl = (VarDeclaration) s; Type varType = varDecl.getType(); // Is is a primitive variable or a primitive list? if (varType.isPrimitiveType() || varType.isList()) { // Find an initialization that matches the command line argument for (VariableInit varInit : varDecl.getVarInit()) if (varInit.getVarName().equals(varName)) { // Name matches? int argNumOri = argNum; boolean useVal = false; if (varType.isList()) { // Create a list of arguments and use them to initialize the variable (list) ArrayList<String> vals = new ArrayList<String>(); for (int i = argNum + 1; i < programArgs.size(); i++) if (programArgs.get(i).startsWith("-")) break; else vals.add(programArgs.get(i)); useVal = initializeArgs(varType, varInit, vals); // Found variable, try to replace or add LITERAL to this VarInit } else if (varType.isBool()) { String valStr = "true"; // Booleans may not have a value (just '-varName' sets them to 'true') if (programArgs.size() > (argNum + 1)) { // Is the next argument 'true' or 'false'? => Set argument String boolVal = programArgs.get(argNum + 1); if (valStr.equalsIgnoreCase("true") || valStr.equalsIgnoreCase("false")) valStr = boolVal; } initializeArgs(varType, varInit, valStr); } else { String val = (argNum < programArgs.size() ? programArgs.get(++argNum) : ""); // Get one argument and use it to initialize the variable useVal = initializeArgs(varType, varInit, val); // Found variable, try to replace or add LITERAL to this VarInit } if (!useVal) argNum = argNumOri; // We did not use the arguments } } } } } } // Make all unprocessed arguments available for the program (in 'args' list) Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_ARGS_LIST, TypeList.get(Type.STRING), programArgs)); // Initialize program name String programPath = programUnit.getFileName(); String progName = Gpr.baseName(programPath); Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_NAME, Type.STRING, progName)); Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_PATH, Type.STRING, programPath)); } /** * Add or replace initialization statement in this VarInit * * Note: We create a Literal node (of the appropriate type) and add it to * "varInit.expression" * * @param varType * : Variable type * @param varInit * : Variable initialization * @param vals * : Value to assign */ boolean initializeArgs(Type varType, VariableInit varInit, ArrayList<String> vals) { boolean usedVal = true; try { Literal literal = null; if (varType.isList(Type.STRING)) { // Create literal LiteralListString lit = new LiteralListString(varInit, null); literal = lit; lit.setValue(vals); // Set literal value } else throw new RuntimeException("Cannot convert command line argument to variable type '" + varType + "'"); // Set varInit to literal varInit.setExpression(literal); } catch (Exception e) { // Error parsing 'val'? throw new RuntimeException("Cannot convert argument '" + vals + "' to type " + varType); } return usedVal; } /** * Add or replace initialization statement in this VarInit * * Note: We create a Literal node (of the appropriate type) and add it to * "varInit.expression" * * @param varType * : Variable type * @param varInit * : Variable initialization * @param valStr * : Value to assign */ boolean initializeArgs(Type varType, VariableInit varInit, String valStr) { boolean usedVal = true; try { Literal literal = null; // Create a different literal for each primitive type if (varType.isBool()) { // Create literal LiteralBool lit = new LiteralBool(varInit, null); literal = lit; // Set literal value boolean valBool = true; // Default value is 'true' if (valStr != null) { // Parse boolean valStr = valStr.toLowerCase(); if (valStr.equals("true") || valStr.equals("t") || valStr.equals("1")) valBool = true; else if (valStr.equals("false") || valStr.equals("f") || valStr.equals("0")) valBool = false; else usedVal = false; // Not any valid value? => This // argument is not used } lit.setValue(valBool); } else if (varType.isInt()) { // Create literal LiteralInt lit = new LiteralInt(varInit, null); literal = lit; // Set literal value long valInt = Long.parseLong(valStr); lit.setValue(valInt); } else if (varType.isReal()) { // Create literal LiteralReal lit = new LiteralReal(varInit, null); literal = lit; // Set literal value double valReal = Double.parseDouble(valStr); lit.setValue(valReal); } else if (varType.isString()) { // Create literal LiteralString lit = new LiteralString(varInit, null); literal = lit; // Set literal value if (valStr == null) valStr = ""; // We should never have 'null' values lit.setValue(valStr); } else throw new RuntimeException("Cannot convert command line argument to variable type '" + varType + "'"); // Set varInit to literal varInit.setExpression(literal); } catch (Exception e) { // Error parsing 'val'? throw new RuntimeException("Cannot convert argument '" + valStr + "' to type " + varType); } return usedVal; } /** * Add symbols to global scope */ void initilaizeGlobalScope() { if (debug) log("Initialize global scope."); // Reset Global scope Scope.resetGlobalScope(); Scope globalScope = Scope.getGlobalScope(); // Get default veluas from command line or config file // Command line parameters override defaults String cpusStr = config.getString(ExpressionTask.TASK_OPTION_CPUS, "1"); // Default number of cpus: 1 long cpus = Gpr.parseIntSafe(cpusStr); if (cpus <= 0) throw new RuntimeException("Number of cpus must be a positive number ('" + cpusStr + "')"); long mem = Gpr.parseIntSafe(config.getString(ExpressionTask.TASK_OPTION_MEM, "-1")); // Default amount of memory: -1 (unrestricted) String node = config.getString(ExpressionTask.TASK_OPTION_NODE, ""); if (queue == null) queue = config.getString(ExpressionTask.TASK_OPTION_QUEUE, ""); if (system == null) system = config.getString(ExpressionTask.TASK_OPTION_SYSTEM, ExecutionerType.LOCAL.toString().toLowerCase()); if (taskFailCount < 0) taskFailCount = Gpr.parseIntSafe(config.getString(ExpressionTask.TASK_OPTION_RETRY, "0")); long oneDay = 1L * 24 * 60 * 60; long timeout = Gpr.parseLongSafe(config.getString(ExpressionTask.TASK_OPTION_TIMEOUT, "" + oneDay)); long wallTimeout = Gpr.parseLongSafe(config.getString(ExpressionTask.TASK_OPTION_WALL_TIMEOUT, "" + oneDay)); // Add global symbols globalScope.add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_NAME, Type.STRING, "")); globalScope.add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_PATH, Type.STRING, "")); // Task related variables: Default values globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_SYSTEM, Type.STRING, system)); // System type: "local", "ssh", "cluster", "aws", etc. globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_CPUS, Type.INT, cpus)); // Default number of cpus globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_MEM, Type.INT, mem)); // Default amount of memory (unrestricted) globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_QUEUE, Type.STRING, queue)); // Default queue: none globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_NODE, Type.STRING, node)); // Default node: none globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_CAN_FAIL, Type.BOOL, false)); // Task fail triggers checkpoint & exit (a task cannot fail) globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_ALLOW_EMPTY, Type.BOOL, false)); // Tasks are allowed to have empty output file/s globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_RETRY, Type.INT, (long) taskFailCount)); // Task fail can be re-tried (re-run) N times before considering failed. globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_TIMEOUT, Type.INT, timeout)); // Task default timeout globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_WALL_TIMEOUT, Type.INT, wallTimeout)); // Task default wall-timeout // Number of local CPUs // Kilo, Mega, Giga, Tera, Peta. LinkedList<ScopeSymbol> constants = new LinkedList<ScopeSymbol>(); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_PROGRAM_NAME, Type.STRING, "")); // Program name, now is empty, but it is filled later constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_LOCAL_CPUS, Type.INT, (long) Gpr.NUM_CORES)); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_K, Type.INT, 1024L)); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_M, Type.INT, 1024L * 1024L)); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_G, Type.INT, 1024L * 1024L * 1024L)); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_T, Type.INT, 1024L * 1024L * 1024L * 1024L)); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_P, Type.INT, 1024L * 1024L * 1024L * 1024L * 1024L)); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_MINUTE, Type.INT, 60L)); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_HOUR, Type.INT, (long) (60 * 60))); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_DAY, Type.INT, (long) (24 * 60 * 60))); constants.add(new ScopeSymbol(Scope.GLOBAL_VAR_WEEK, Type.INT, (long) (7 * 24 * 60 * 60))); // Add all constants for (ScopeSymbol ss : constants) { ss.setConstant(true); globalScope.add(ss); } // Set "physical" path String path; try { path = new File(".").getCanonicalPath(); } catch (IOException e) { throw new RuntimeException("Cannot get cannonical path for current dir"); } globalScope.add(new ScopeSymbol(ExpressionTask.TASK_OPTION_PHYSICAL_PATH, Type.STRING, path)); // Set all environment variables Map<String, String> envMap = System.getenv(); for (String varName : envMap.keySet()) { String varVal = envMap.get(varName); globalScope.add(new ScopeSymbol(varName, Type.STRING, varVal)); } // Command line arguments (default: empty list) // This is properly set in 'initializeArgs()' method, but // we have to set something now, otherwise we'll get a "variable // not found" error at compiler time, if the program attempts // to use 'args'. Scope.getGlobalScope().add(new ScopeSymbol(Scope.GLOBAL_VAR_ARGS_LIST, TypeList.get(Type.STRING), new ArrayList<String>())); } /** * Initialize standard libraries */ void initilaizeLibraries() { if (debug) log("Initialize standard libraries."); // Native functions NativeLibraryFunctions nativeLibraryFunctions = new NativeLibraryFunctions(); if (debug) log("Native library:\n" + nativeLibraryFunctions); // Native library: String NativeLibraryString nativeLibraryString = new NativeLibraryString(); if (debug) log("Native library:\n" + nativeLibraryString); } void log(String msg) { Timer.showStdErr(getClass().getSimpleName() + ": " + msg); } /** * Parse command line arguments * * @param args */ public void parse(String[] args) { // Nothing? Show command line options if (args.length <= 0) usage(null); programArgs = new ArrayList<String>(); bigDataScriptAction = BigDataScriptAction.RUN; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (programFileName != null) programArgs.add(arg); // Everything after 'programFileName' is an command line argument for the BigDataScript program else if (arg.equals("-c") || arg.equalsIgnoreCase("-config")) { // Checkpoint restore if ((i + 1) < args.length) configFile = args[++i]; else usage("Option '-c' without restore file argument"); } else if (arg.equals("-d") || arg.equalsIgnoreCase("-debug")) debug = verbose = true; // Debug implies verbose else if (arg.equalsIgnoreCase("-useDone")) useDoneFile = true; else if (arg.equals("-l") || arg.equalsIgnoreCase("-log")) log = true; else if (arg.equals("-h") || arg.equalsIgnoreCase("-help") || arg.equalsIgnoreCase("--help")) { usage(null); } else if (arg.equalsIgnoreCase("-dryRun")) { dryRun = true; noRmOnExit = true; // Not running, so don't delete files createReport = false; } else if (arg.equalsIgnoreCase("-noRmOnExit")) noRmOnExit = true; else if (arg.equalsIgnoreCase("-noReport")) createReport = false; else if (arg.equalsIgnoreCase("-checkPidRegex")) checkPidRegex = true; else if (arg.equals("-i") || arg.equalsIgnoreCase("-info")) { // Checkpoint info if ((i + 1) < args.length) chekcpointRestoreFile = args[++i]; else usage("Option '-i' without checkpoint file argument"); bigDataScriptAction = BigDataScriptAction.INFO_CHECKPOINT; } else if (arg.equalsIgnoreCase("-extractSource")) { extractSource = true; } else if (arg.equalsIgnoreCase("-pid")) { // PID file if ((i + 1) < args.length) pidFile = args[++i]; else usage("Option '-pid' without file argument"); } else if (arg.equals("-q") || arg.equalsIgnoreCase("-queue")) { // Queue name if ((i + 1) < args.length) queue = args[++i]; else usage("Option '-queue' without file argument"); } else if (arg.equals("-r") || arg.equalsIgnoreCase("-restore")) { // Checkpoint restore if ((i + 1) < args.length) chekcpointRestoreFile = args[++i]; else usage("Option '-r' without checkpoint file argument"); bigDataScriptAction = BigDataScriptAction.RUN_CHECKPOINT; } else if (arg.equals("-s") || arg.equalsIgnoreCase("-system")) { // System type if ((i + 1) < args.length) system = args[++i]; else usage("Option '-system' without file argument"); } else if (arg.equals("-t") || arg.equalsIgnoreCase("-test")) { bigDataScriptAction = BigDataScriptAction.TEST; } else if (arg.equals("-y") || arg.equalsIgnoreCase("-retry")) { // Number of retries if ((i + 1) < args.length) taskFailCount = Gpr.parseIntSafe(args[++i]); else usage("Option '-t' without number argument"); } else if (arg.equals("-v") || arg.equalsIgnoreCase("-verbose")) verbose = true; else if (arg.equalsIgnoreCase("-version")) { System.out.println(VERSION); System.exit(0); } else if (programFileName == null) programFileName = arg; // Get program file name } // Sanity checks if (checkPidRegex) { // OK: Nothing to chek } else if ((programFileName == null) && (chekcpointRestoreFile == null)) { // No file name => Error usage("Missing program file name."); } } /** * Run script */ public int run() { // Initialize Executioners executioners = Executioners.getInstance(config); TaskDependecies.reset(); // Check PID regex if (checkPidRegex) { checkPidRegex(); return 0; } // Run int exitValue = 0; switch (bigDataScriptAction) { case RUN_CHECKPOINT: exitValue = runCheckpoint(); break; case INFO_CHECKPOINT: exitValue = infoCheckpoint(); break; case TEST: exitValue = runTests(); break; default: exitValue = runCompile(); // Compile & run } if (verbose) Timer.showStdErr("Finished. Exit code: " + exitValue); // Kill all executioners for (Executioner executioner : executioners.getAll()) executioner.kill(); config.kill(); // Kill 'tail' and 'monitor' threads return exitValue; } /** * Restore from checkpoint and run */ int runCheckpoint() { // Load checkpoint file BigDataScriptSerializer bdsSerializer = new BigDataScriptSerializer(chekcpointRestoreFile, config); List<BigDataScriptThread> bdsThreads = bdsSerializer.load(); // Set main thread's programUnit running scope (mostly for debugging and test cases) // ProgramUnit's scope it the one before 'global' BigDataScriptThread mainThread = bdsThreads.get(0); programUnit = mainThread.getProgramUnit(); // Set state and recover tasks for (BigDataScriptThread bdsThread : bdsThreads) { if (bdsThread.isFinished()) { // Thread finished before serialization: Nothing to do } else { bdsThread.setRunState(RunState.CHECKPOINT_RECOVER); // Set run state to recovery bdsThread.restoreUnserializedTasks(); // Re-execute or add tasks } } // All set, run main thread return runThread(mainThread); } /** * Compile and run */ int runCompile() { // Compile, abort on errors if (verbose) Timer.showStdErr("Parsing"); if (!compile()) { // Show errors and warnings, if any if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get()); return 1; } if (verbose) Timer.showStdErr("Initializing"); initializeArgs(); // Run the program BigDataScriptThread bdsThread = new BigDataScriptThread(programUnit, config); if (verbose) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); if (verbose) Timer.showStdErr("Running"); int exitCode = runThread(bdsThread); // Check stack if (stackCheck) bdsThread.sanityCheckStack(); return exitCode; } /** * Compile and run */ int runTests() { // Compile, abort on errors if (verbose) Timer.showStdErr("Parsing"); if (!compile()) { // Show errors and warnings, if any if (!CompilerMessages.get().isEmpty()) System.err.println("Compiler messages:\n" + CompilerMessages.get()); return 1; } if (verbose) Timer.showStdErr("Initializing"); initializeArgs(); // Run the program BigDataScriptThread bdsThread = new BigDataScriptThread(programUnit, config); if (verbose) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); if (verbose) Timer.showStdErr("Running tests"); ProgramUnit pu = bdsThread.getProgramUnit(); List<FunctionDeclaration> testFuncs = pu.testsFunctions(); // For each test function, create a thread that executes the function's body int exitCode = 0; int testOk = 0, testError = 0; for (FunctionDeclaration testFunc : testFuncs) { System.out.println(""); BigDataScriptThread bdsTestThread = new BigDataScriptThread(testFunc.getStatement(), bdsThread); // Note: We execute the function's body (not the function declaration) int exitValTest = runThread(bdsTestThread); // Show test result if (exitValTest == 0) { Timer.show("Test '" + testFunc.getFunctionName() + "': OK"); testOk++; } else { Timer.show("Test '" + testFunc.getFunctionName() + "': FAIL"); exitCode = 1; testError++; } } // Show results System.out.println(""); Timer.show("Totals" + "\n OK : " + testOk + "\n ERROR : " + testError ); return exitCode; } /** * Run a thread */ int runThread(BigDataScriptThread bdsThread) { bigDataScriptThread = bdsThread; if (bdsThread.isFinished()) return 0; bdsThread.start(); try { bdsThread.join(); } catch (InterruptedException e) { // Nothing to do? // May be checkpoint? return 1; } // Check stack if (stackCheck) bdsThread.sanityCheckStack(); // OK, we are done return bdsThread.getExitValue(); } public void setStackCheck(boolean stackCheck) { this.stackCheck = stackCheck; } void usage(String err) { if (err != null) System.err.println("Error: " + err); System.out.println(VERSION + "\n"); System.err.println("Usage: " + BigDataScript.class.getSimpleName() + " [options] file.bds"); System.err.println("\nAvailable options: "); System.err.println(" [-c | -config ] bds.config : Config file. Default : " + configFile); System.err.println(" [-checkPidRegex] : Check configuration's 'pidRegex' by matching stdin."); System.err.println(" [-d | -debug ] : Debug mode."); System.err.println(" -done : Use 'done' files: Default: " + useDoneFile); System.err.println(" -dryRun : Do not run any task, just show what would be run."); System.err.println(" [-extractSource] : Extract source code files from checkpoint (only valid combined with '-info')."); System.err.println(" [-i | -info ] checkpoint.chp : Show state information in checkpoint file."); System.err.println(" [-l | -log ] : Log all tasks (do not delete tmp files)."); System.err.println(" -noReport : Do not create report."); System.err.println(" -noRmOnExit : Do not remove files marked for deletion on exit (rmOnExit)."); System.err.println(" [-q | -queue ] queueName : Set default queue name."); System.err.println(" [-r | -restore] checkpoint.chp : Restore state from checkpoint file."); System.err.println(" [-s | -system ] type : Set system type."); System.err.println(" [-t | -test ] : Perform testing (run all test* functions)."); System.err.println(" [-v | -verbose] : Be verbose."); System.err.println(" -version : Show version and exit."); System.err.println(" [-y | -retry ] num : Number of times to retry a failing tasks."); System.err.println(" -pid <file> : Write local processes PIDs to 'file'"); if (err != null) System.exit(1); System.exit(0); } }
package org.mapyrus; import java.util.ArrayList; import java.util.HashMap; /** * A parsed statement. * Can be one of several types. A conditional statement, * a block of statements making a procedure or just a plain command. */ public class Statement { /* * Possible types of statements. */ public static final int CONDITIONAL = 2; public static final int WHILE_LOOP = 3; public static final int FOR_LOOP = 4; public static final int BLOCK = 5; public static final int COLOR = 10; public static final int LINESTYLE = 11; public static final int FONT = 12; public static final int JUSTIFY = 13; public static final int MOVE = 14; public static final int DRAW = 15; public static final int RDRAW = 16; public static final int ARC = 17; public static final int CIRCLE = 18; public static final int BOX = 19; public static final int HEXAGON = 20; public static final int TRIANGLE = 21; public static final int ADDPATH = 22; public static final int CLEARPATH = 23; public static final int CLOSEPATH = 24; public static final int SAMPLEPATH = 25; public static final int STRIPEPATH = 26; public static final int SHIFTPATH = 27; public static final int SINKHOLE = 28; public static final int GUILLOTINE = 29; public static final int ROUNDPATH = 30; public static final int STROKE = 31; public static final int FILL = 32; public static final int PROTECT = 33; public static final int UNPROTECT = 34; public static final int CLIP = 35; public static final int LABEL = 36; public static final int ICON = 37; public static final int SCALE = 38; public static final int ROTATE = 39; public static final int WORLDS = 40; public static final int PROJECT = 41; public static final int DATASET = 42; public static final int FETCH = 43; public static final int NEWPAGE = 44; public static final int PRINT = 45; public static final int LOCAL = 46; public static final int LET = 47; public static final int KEY = 48; public static final int LEGEND = 49; public static final int MIMETYPE = 50; /* * Statement type for call and return to/from user defined procedure block. */ public static final int CALL = 1000; public static final int RETURN = 1001; private int mType; /* * Statements in an if-then-else statement. */ private ArrayList mThenStatements; private ArrayList mElseStatements; /* * Statements in a while loop statement. */ private ArrayList mLoopStatements; /* * Name of procedure block, * variable names of parameters to this procedure * and block of statements in a procedure in order of execution */ private String mBlockName; private ArrayList mStatementBlock; private ArrayList mParameters; private Expression []mExpressions; /* * HashMap to walk through for a 'for' loop. */ private Expression mForHashMapExpression; /* * Filename and line number within file that this * statement was read from. */ private String mFilename; private int mLineNumber; /* * Static statement type lookup table for fast lookup. */ private static HashMap mStatementTypeLookup; static { mStatementTypeLookup = new HashMap(); mStatementTypeLookup.put("color", new Integer(COLOR)); mStatementTypeLookup.put("colour", new Integer(COLOR)); mStatementTypeLookup.put("linestyle", new Integer(LINESTYLE)); mStatementTypeLookup.put("font", new Integer(FONT)); mStatementTypeLookup.put("justify", new Integer(JUSTIFY)); mStatementTypeLookup.put("move", new Integer(MOVE)); mStatementTypeLookup.put("draw", new Integer(DRAW)); mStatementTypeLookup.put("rdraw", new Integer(RDRAW)); mStatementTypeLookup.put("arc", new Integer(ARC)); mStatementTypeLookup.put("circle", new Integer(CIRCLE)); mStatementTypeLookup.put("box", new Integer(BOX)); mStatementTypeLookup.put("hexagon", new Integer(HEXAGON)); mStatementTypeLookup.put("triangle", new Integer(TRIANGLE)); mStatementTypeLookup.put("addpath", new Integer(ADDPATH)); mStatementTypeLookup.put("clearpath", new Integer(CLEARPATH)); mStatementTypeLookup.put("closepath", new Integer(CLOSEPATH)); mStatementTypeLookup.put("samplepath", new Integer(SAMPLEPATH)); mStatementTypeLookup.put("stripepath", new Integer(STRIPEPATH)); mStatementTypeLookup.put("shiftpath", new Integer(SHIFTPATH)); mStatementTypeLookup.put("sinkhole", new Integer(SINKHOLE)); mStatementTypeLookup.put("guillotine", new Integer(GUILLOTINE)); mStatementTypeLookup.put("roundpath", new Integer(ROUNDPATH)); mStatementTypeLookup.put("stroke", new Integer(STROKE)); mStatementTypeLookup.put("fill", new Integer(FILL)); mStatementTypeLookup.put("protect", new Integer(PROTECT)); mStatementTypeLookup.put("unprotect", new Integer(UNPROTECT)); mStatementTypeLookup.put("clip", new Integer(CLIP)); mStatementTypeLookup.put("label", new Integer(LABEL)); mStatementTypeLookup.put("icon", new Integer(ICON)); mStatementTypeLookup.put("scale", new Integer(SCALE)); mStatementTypeLookup.put("rotate", new Integer(ROTATE)); mStatementTypeLookup.put("worlds", new Integer(WORLDS)); mStatementTypeLookup.put("project", new Integer(PROJECT)); mStatementTypeLookup.put("dataset", new Integer(DATASET)); mStatementTypeLookup.put("fetch", new Integer(FETCH)); mStatementTypeLookup.put("newpage", new Integer(NEWPAGE)); mStatementTypeLookup.put("print", new Integer(PRINT)); mStatementTypeLookup.put("local", new Integer(LOCAL)); mStatementTypeLookup.put("let", new Integer(LET)); mStatementTypeLookup.put("key", new Integer(KEY)); mStatementTypeLookup.put("legend", new Integer(LEGEND)); mStatementTypeLookup.put("mimetype", new Integer(MIMETYPE)); } /** * Constant for 'return' statement. */ public static final Statement RETURN_STATEMENT; static { RETURN_STATEMENT = new Statement("", null); RETURN_STATEMENT.mType = RETURN; }; /** * Looks up identifier for a statement name. * @param s is the name of the statement. * @returns numeric code for this statement, or -1 if statement * is unknown. */ private int getStatementType(String s) { int retval; Integer type = (Integer)mStatementTypeLookup.get(s.toLowerCase()); if (type == null) retval = CALL; else retval = type.intValue(); return(retval); } /** * Creates a plain statement, either a built-in command or * a call to a procedure block that the user has defined. * @param keyword is the name statement. * @param expressions are the arguments for this statement. */ public Statement(String keyword, Expression []expressions) { mType = getStatementType(keyword); if (mType == CALL) mBlockName = keyword; mExpressions = expressions; } /** * Creates a procedure, a block of statements to be executed together. * @param blockName is name of procedure block. * @param parameters variable names of parameters to this procedure. * @param statements list of statements that make up this procedure block. */ public Statement(String blockName, ArrayList parameters, ArrayList statements) { mBlockName = blockName; mParameters = parameters; mStatementBlock = statements; mType = BLOCK; } /** * Create an if, then, else, endif block of statements. * @param test is expression to test. * @param thenStatements is statements to execute if expression is true. * @param elseStatements is statements to execute if expression is false, * or null if there is no statement to execute. */ public Statement(Expression test, ArrayList thenStatements, ArrayList elseStatements) { mType = CONDITIONAL; mExpressions = new Expression[1]; mExpressions[0] = test; mThenStatements = thenStatements; mElseStatements = elseStatements; } /** * Create a while loop block of statements. * @param test is expression to test before each iteration of loop. * @param loopStatements is statements to execute for each loop iteration. */ public Statement(Expression test, ArrayList loopStatements) { mType = WHILE_LOOP; mExpressions = new Expression[1]; mExpressions[0] = test; mLoopStatements = loopStatements; } /** * Create a while loop block of statements. * @param test is expression to test before each iteration of loop. * @param loopStatements is statements to execute for each loop iteration. */ public Statement(Expression var, Expression arrayVar, ArrayList loopStatements) { mType = FOR_LOOP; mExpressions = new Expression[1]; mExpressions[0] = var; mForHashMapExpression = arrayVar; mLoopStatements = loopStatements; } /** * Sets the filename and line number that this statement was read from. * This is for use in any error message for this statement. * @param filename is name of file this statement was read from. * @param lineNumber is line number within file containing this statement. */ public void setFilenameAndLineNumber(String filename, int lineNumber) { mFilename = filename; mLineNumber = lineNumber; } /** * Returns filename and line number that this statement was read from. * @return string containing filename and line number. */ public String getFilenameAndLineNumber() { return(mFilename + ":" + mLineNumber); } /** * Returns filename that this statement was read from. * @return string containing filename. */ public String getFilename() { return(mFilename); } /** * Returns the type of this statement. * @return statement type. */ public int getType() { return(mType); } public Expression []getExpressions() { return(mExpressions); } /** * Returns list of statements in "then" section of "if" statement. * @return list of statements. */ public ArrayList getThenStatements() { return(mThenStatements); } /** * Returns list of statements in "else" section of "if" statement. * @return list of statements. */ public ArrayList getElseStatements() { return(mElseStatements); } /** * Returns list of statements in while or for loop statement. * @return list of statements. */ public ArrayList getLoopStatements() { return(mLoopStatements); } /** * Returns hashmap expression to walk through in a for loop statement. * @return expression evaluating to a hashmap. */ public Expression getForHashMap() { return(mForHashMapExpression); } /** * Return name of procedure block. * @return name of procedure. */ public String getBlockName() { return(mBlockName); } /** * Return variable names of parameters to a procedure. * @return list of parameter names. */ public ArrayList getBlockParameters() { return(mParameters); } /** * Return statements in a procedure. * @return ArrayList of statements that make up the procedure. */ public ArrayList getStatementBlock() { return(mStatementBlock); } }
package ch.unibas.cs.dbis.cineast.core.descriptor; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import georegression.struct.homography.Homography2D_F64; import georegression.struct.point.Point2D_F32; import georegression.struct.point.Point2D_F64; import georegression.transform.homography.HomographyPointOps_F64; import boofcv.abst.filter.derivative.ImageGradient; import boofcv.alg.misc.PixelMath; import boofcv.alg.tracker.klt.KltTrackFault; import boofcv.alg.tracker.klt.PkltConfig; import boofcv.alg.tracker.klt.PyramidKltFeature; import boofcv.alg.tracker.klt.PyramidKltTracker; import boofcv.alg.transform.pyramid.PyramidOps; import boofcv.factory.filter.derivative.FactoryDerivative; import boofcv.factory.geo.ConfigRansac; import boofcv.factory.geo.FactoryMultiViewRobust; import boofcv.factory.tracker.FactoryTrackerAlg; import boofcv.factory.transform.pyramid.FactoryPyramid; import boofcv.gui.image.ShowImages; import boofcv.io.image.ConvertBufferedImage; import boofcv.struct.geo.AssociatedPair; import boofcv.struct.image.GrayS16; import boofcv.struct.image.GrayU8; import boofcv.struct.pyramid.PyramidDiscrete; import org.ddogleg.fitting.modelset.ModelMatcher; import ch.unibas.cs.dbis.cineast.core.data.Frame; import ch.unibas.cs.dbis.cineast.core.data.Pair; public class PathList { private PathList(){} public static int samplingInterval = 15; public static int frameInterval = 2; public static double backwardTrackingDistanceThreshold = 5.0; public static double successTrackingRatioThreshold = 0.50; public static double ransacInlierRatioThreshold = 0.65; public static double successFrameSRatioThreshold = 0.70; public static void showBineryImage(GrayU8 image){ PixelMath.multiply(image,255,image); BufferedImage out = ConvertBufferedImage.convertTo(image,null); ShowImages.showWindow(out,"Output"); } public static void separateFgBgPaths(List<Frame> frames, LinkedList<Pair<Integer,ArrayList<AssociatedPair>>> allPaths, List<Pair<Integer, LinkedList<Point2D_F32>>> foregroundPaths, List<Pair<Integer, LinkedList<Point2D_F32>>> backgroundPaths){ ModelMatcher<Homography2D_F64,AssociatedPair> robustF = FactoryMultiViewRobust.homographyRansac(null, new ConfigRansac(200,3.0f)); if (allPaths == null || frames == null || frames.isEmpty()){ return; } int width = frames.get(0).getImage().getWidth(); int height = frames.get(0).getImage().getHeight(); int maxTracksNumber = (width * height) / (samplingInterval*samplingInterval); int failedFrameCount = 0; for(Pair<Integer,ArrayList<AssociatedPair>> pair : allPaths){ List<AssociatedPair> inliers = new ArrayList<AssociatedPair>(); List<AssociatedPair> outliers = new ArrayList<AssociatedPair>(); int frameIdx = pair.first; ArrayList<AssociatedPair> matches = pair.second; if((double)matches.size() < (double)maxTracksNumber * successTrackingRatioThreshold){ failedFrameCount += 1; continue; } Homography2D_F64 curToPrev = new Homography2D_F64(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0); if(robustF.process(matches) && (double)robustF.getMatchSet().size() > (double)matches.size() * ransacInlierRatioThreshold ){ curToPrev = robustF.getModelParameters().invert(null); inliers.addAll(robustF.getMatchSet()); for (int i = 0,j = 0; i < matches.size(); ++i){ if (i == robustF.getInputIndex(j)){ if ( j < inliers.size()-1){ ++j; } } else{ outliers.add(matches.get(i)); } } } else{ curToPrev = new Homography2D_F64(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0); failedFrameCount += 1; } for (AssociatedPair p : inliers){ LinkedList<Point2D_F32> path = new LinkedList<Point2D_F32>(); path.add(new Point2D_F32((float)p.p1.x/(float)width,(float)p.p1.y/(float)height)); path.add(new Point2D_F32((float)p.p2.x/(float)width,(float)p.p2.y/(float)height)); backgroundPaths.add(new Pair<Integer, LinkedList<Point2D_F32>>(frameIdx,path)); } for (AssociatedPair p : outliers){ p.p2 = HomographyPointOps_F64.transform(curToPrev, p.p2, p.p2); LinkedList<Point2D_F32> path = new LinkedList<Point2D_F32>(); path.add(new Point2D_F32((float)p.p1.x/(float)width,(float)p.p1.y/(float)height)); path.add(new Point2D_F32((float)p.p2.x/(float)width,(float)p.p2.y/(float)height)); foregroundPaths.add(new Pair<Integer, LinkedList<Point2D_F32>>(frameIdx,path)); } } int frameNum = allPaths.size(); if((double)(frameNum - failedFrameCount) < (double)frameNum * successFrameSRatioThreshold){ foregroundPaths.clear(); backgroundPaths.clear(); } return; } public static LinkedList<Pair<Integer,ArrayList<AssociatedPair>>> getDensePaths(List<Frame> frames){ if(frames.size() < 2){ return null; } PkltConfig configKlt = new PkltConfig(3, new int[] { 1, 2, 4 }); configKlt.config.maxPerPixelError = 45; ImageGradient<GrayU8, GrayS16> gradient = FactoryDerivative.sobel(GrayU8.class, GrayS16.class); PyramidDiscrete<GrayU8> pyramidForeward = FactoryPyramid.discreteGaussian(configKlt.pyramidScaling,-1,2,true,GrayU8.class); PyramidDiscrete<GrayU8> pyramidBackward = FactoryPyramid.discreteGaussian(configKlt.pyramidScaling,-1,2,true,GrayU8.class); PyramidKltTracker<GrayU8, GrayS16> trackerForeward = FactoryTrackerAlg.kltPyramid(configKlt.config, GrayU8.class, null); PyramidKltTracker<GrayU8, GrayS16> trackerBackward = FactoryTrackerAlg.kltPyramid(configKlt.config, GrayU8.class, null); GrayS16[] derivX = null; GrayS16[] derivY = null; LinkedList<PyramidKltFeature> tracks = new LinkedList<PyramidKltFeature>(); LinkedList<Pair<Integer,ArrayList<AssociatedPair>>> paths = new LinkedList<Pair<Integer,ArrayList<AssociatedPair>>>(); GrayU8 gray = null; int frameIdx = 0; int cnt = 0; for (Frame frame : frames){ ++frameIdx; if(cnt >= frameInterval){ cnt = 0; continue; } cnt += 1; gray = ConvertBufferedImage.convertFrom(frame.getImage().getBufferedImage(), gray); ArrayList<AssociatedPair> tracksPairs = new ArrayList<AssociatedPair>(); if (frameIdx == 0){ tracks = denseSampling(gray, derivX, derivY, samplingInterval, configKlt, gradient, pyramidBackward, trackerBackward); } else{ tracking(gray, derivX, derivY, tracks, tracksPairs, gradient, pyramidForeward, pyramidBackward, trackerForeward, trackerBackward); tracks = denseSampling(gray, derivX, derivY, samplingInterval, configKlt, gradient, pyramidBackward, trackerBackward); } paths.add(new Pair<Integer,ArrayList<AssociatedPair>>(frameIdx,tracksPairs)); } return paths; } public static LinkedList<PyramidKltFeature> denseSampling( GrayU8 image, GrayS16[] derivX, GrayS16[] derivY, int samplingInterval, PkltConfig configKlt, ImageGradient<GrayU8, GrayS16> gradient, PyramidDiscrete<GrayU8> pyramid, PyramidKltTracker<GrayU8, GrayS16> tracker){ LinkedList<PyramidKltFeature> tracks = new LinkedList<PyramidKltFeature>(); pyramid.process(image); derivX = declareOutput(pyramid, derivX); derivY = declareOutput(pyramid, derivY); PyramidOps.gradient(pyramid, gradient, derivX, derivY); tracker.setImage(pyramid,derivX,derivY); for( int y = 0; y < image.height; y+= samplingInterval ) { for( int x = 0; x < image.width; x+= samplingInterval ) { PyramidKltFeature t = new PyramidKltFeature(configKlt.pyramidScaling.length,configKlt.templateRadius); t.setPosition(x,y); tracker.setDescription(t); tracks.add(t); } } return tracks; } public static LinkedList<PyramidKltFeature> tracking( GrayU8 image, GrayS16[] derivX, GrayS16[] derivY, LinkedList<PyramidKltFeature> tracks, ArrayList<AssociatedPair> tracksPairs, ImageGradient<GrayU8, GrayS16> gradient, PyramidDiscrete<GrayU8> pyramidForeward, PyramidDiscrete<GrayU8> pyramidBackward, PyramidKltTracker<GrayU8, GrayS16> trackerForeward, PyramidKltTracker<GrayU8, GrayS16> trackerBackward ){ pyramidForeward.process(image); derivX = declareOutput(pyramidForeward, derivX); derivY = declareOutput(pyramidForeward, derivY); PyramidOps.gradient(pyramidForeward, gradient, derivX, derivY); trackerForeward.setImage(pyramidForeward,derivX,derivY); ListIterator<PyramidKltFeature> listIterator = tracks.listIterator(); while( listIterator.hasNext() ) { PyramidKltFeature track = listIterator.next(); Point2D_F64 pointPrev = new Point2D_F64(track.x,track.y); KltTrackFault ret = trackerForeward.track(track); boolean success = false; if( ret == KltTrackFault.SUCCESS && image.isInBounds((int)track.x,(int)track.y) && trackerForeward.setDescription(track)) { Point2D_F64 pointCur = new Point2D_F64(track.x,track.y); ret = trackerBackward.track(track); if( ret == KltTrackFault.SUCCESS && image.isInBounds((int)track.x,(int)track.y) ) { Point2D_F64 pointCurBack = new Point2D_F64(track.x,track.y); if(normalizedDistance(pointPrev,pointCurBack) < backwardTrackingDistanceThreshold){ tracksPairs.add(new AssociatedPair(pointPrev,pointCur)); success = true; } } } if( !success ) { listIterator.remove(); } } return tracks; } public static GrayS16[] declareOutput(PyramidDiscrete<GrayU8> pyramid,GrayS16[] deriv) { if( deriv == null ) { deriv = PyramidOps.declareOutput(pyramid, GrayS16.class); } else if( deriv[0].width != pyramid.getLayer(0).width || deriv[0].height != pyramid.getLayer(0).height ) { PyramidOps.reshapeOutput(pyramid,deriv); } return deriv; } public static double normalizedDistance(Point2D_F64 pointA, Point2D_F64 pointB){ double dx = (pointA.x - pointB.x); double dy = (pointA.y - pointB.y); return Math.sqrt(Math.pow((dx),2) + Math.pow((dy),2)); } }
package player; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import game.Answer; import game.GameLogic; import game.Question; import game.Scoreboard; import game.Scoreboard.ScoreType; import util.YahtzeeMath; public class SinglePlayerAI implements Player { public double[] boardValues; //Values is the dynamic program cache for the inner search double[] rollValues = new double[1025]; private static final String filename = "testCache.bin"; //A list of all 252 possible different rolls private static ArrayList<int[]> allRolls = new ArrayList<int[]>(); static { for (int a = 1; a <= 6; a++) for (int b = a; b <= 6; b++) for (int c = b; c <= 6; c++) for (int d = c; d <= 6; d++) for (int e = d; e <= 6; e++) allRolls.add(new int[]{a,b,c,d,e}); } @Override public Answer PerformTurn(Question question) { System.out.println("q: " + Arrays.toString(question.roll) + ", " + question.rollsLeft); Answer ans = new Answer(); rollValues = new double[1025]; for (int i = 0; i < 1025; i++){rollValues[i] = -1;} if (question.rollsLeft == 0) ans.selectedScoreEntry = getBestScoreEntry(question.roll, question.scoreboards[question.playerId]); else ans.diceToHold = getBestHold(question.roll, question.rollsLeft, question.scoreboards[question.playerId]); System.out.println("a: " + Arrays.toString(ans.diceToHold) + ", " + ans.selectedScoreEntry); return ans; } private ScoreType getBestScoreEntry(int[] roll, Scoreboard board) { ScoreType best = null; double max = Double.NEGATIVE_INFINITY; for (ScoreType type : board.possibleScoreTypes()) { Scoreboard cloneBoard = board.clone(); cloneBoard.insert(type, GameLogic.valueOfRoll(type, roll)); double newVal = bigDynamicProgramming(cloneBoard); if (newVal > max){ max = newVal; best = type; } } return best; //TODO: Big dynamic program //return ScoreType.BIG_STRAIGHT; } private boolean[] getBestHold(int[] roll, int rollsLeft, Scoreboard board) //Kickoff { double max = Double.NEGATIVE_INFINITY; boolean[] best = null; for (boolean[] hold : getInterestingHolds(roll)) { double sum = 0; for (int[] new_roll : getPossibleRolls(roll, hold)) { sum += getProb(hold, new_roll) * valueOfRoll(new_roll, rollsLeft-1, board); } if (sum > max) { max = sum; best = hold; } } return best; } private double rollFromScoreboard(Scoreboard board) { double s = 0; for (int[] roll: allRolls) { double v = valueOfRoll(roll, 2, board); s += v * YahtzeeMath.prob5(roll); } return s; } private double bigDynamicProgramming(Scoreboard board) { int idx = board.ConvertMapToInt(); if (boardValues[idx] == -1) { boardValues[idx] = rollFromScoreboard(board); } return boardValues[idx]; } private double valueOfRoll(int[] roll, int rollsLeft, Scoreboard board) { if (rollsLeft == 0) { double max = Double.NEGATIVE_INFINITY; for (ScoreType type : board.possibleScoreTypes()) { Scoreboard cloneBoard = board.clone(); cloneBoard.insert(type, GameLogic.valueOfRoll(type, roll)); max = Math.max(max, bigDynamicProgramming(cloneBoard)); } return max; //iterate valid ScoreTypes in scoreboard //return big dynamic program ( Scoreboard.Apply(roll) ); } int idx = rollIdx(roll, rollsLeft); if (rollValues[idx] == -1) { rollValues[idx] = Integer.MIN_VALUE; for (boolean[] hold : getInterestingHolds(roll)) { double sum = 0; for (int[] new_roll : getPossibleRolls(roll, hold)) { sum += getProb(hold, new_roll) * valueOfRoll(new_roll, rollsLeft-1, board); } rollValues[idx] = Math.max(rollValues[idx], sum); } } return rollValues[idx]; } private static double getProb(boolean[] hold, int[] roll) { int c = 0; for (boolean b : hold) if (!b) c++; int[] reducedRoll = new int[c]; c = 0; for (int i=0; i<5; i++){ if (!hold[i]){ reducedRoll[c] = roll[i]; c++; } } return (double)YahtzeeMath.prob(c, reducedRoll); } /* public static void main(String[] args) { SinglePlayerAI ai = new SinglePlayerAI(); ai.doIt(); } public void doIt() { double sum = 0; boolean[] hold = new boolean[]{true,false,false,false,true}; int[] roll = new int[] {1,5,1,3,1}; for (int[] new_roll : getPossibleRolls(roll, hold)) { System.out.println("new_roll: " + Arrays.toString(new_roll)); sum += getProb(hold, new_roll); System.out.println("getProb(hold, new_roll): " + getProb(hold, new_roll)); } System.out.println(sum); } */ private static ArrayList<int[]> getPossibleRolls(int[] roll, boolean[] hold) { //TODO: calculate rolls once. Apply roll,hold dyn ArrayList<int[]> rolls = new ArrayList<int[]>(); for (int[] r_p : allRolls) { int[] r = Arrays.copyOf(r_p, r_p.length); //Apply hold for (int j = 0; j < 5; j++) if (hold[j]) r[j] = roll[j]; //Sort and filter unique boolean has = false; for (int[] ex : rolls) { if (Arrays.equals(ex, r)) { has = true; break; } } if (!has) rolls.add(r); } return rolls; } private static boolean[] holdFromInt(int v) { boolean[] out = new boolean[5]; for (int i = 0; i < 5;i++) { out[i] = (v & (1 << i)) > 0; } return out; } private ArrayList<boolean[]> getInterestingHolds(int[] roll) { ArrayList<boolean[]> holds = new ArrayList<boolean[]>(); //TODO: Filter out uninteresting holds maybe? for (int i = 0; i < (1 << 5); i++) holds.add(holdFromInt(i)); return holds; } private int rollIdx(int[] roll, int rollsLeft) { int v = YahtzeeMath.colex(roll); v |= rollsLeft << 8; return v; } @Override public void reset(int id){ } public void loadArray() { try { FileInputStream fis = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fis); boardValues = (double[]) ois.readObject(); ois.close(); fis.close(); } catch (Exception e) { System.out.println("WARNING! cache not loaded"); boardValues = new double[1000000]; for (int i = 0; i < 1000000; i++){boardValues[i] = -1;} } } @Override public void finalize(){ //Save lookup table to persistent medium try { FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(boardValues); oos.close(); fos.close(); } catch (IOException e) { System.out.println("WARNING! cache not stored"); } } @Override public String getName() { return "Single player AI"; } }
package org.pentaho.di.core.database; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.di.core.Const; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettlePluginException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.plugins.DatabasePluginType; import org.pentaho.di.core.plugins.PluginInterface; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.variables.Variables; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.core.xml.XMLInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.ObjectRevision; import org.pentaho.di.repository.RepositoryDirectory; import org.pentaho.di.repository.RepositoryDirectoryInterface; import org.pentaho.di.repository.RepositoryElementInterface; import org.pentaho.di.repository.RepositoryObjectType; import org.pentaho.di.shared.SharedObjectBase; import org.pentaho.di.shared.SharedObjectInterface; import org.w3c.dom.Node; /** * This class defines the database specific parameters for a certain database type. * It also provides static information regarding a number of well known databases. * * @author Matt * @since 18-05-2003 * */ public class DatabaseMeta extends SharedObjectBase implements Cloneable, XMLInterface, SharedObjectInterface, VariableSpace, RepositoryElementInterface { private static Class<?> PKG = Database.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ public static final String XML_TAG = "connection"; private static final Log logger = LogFactory.getLog(DatabaseMeta.class); public static final RepositoryObjectType REPOSITORY_ELEMENT_TYPE = RepositoryObjectType.DATABASE; // Comparator for sorting databases alphabetically by name public static final Comparator<DatabaseMeta> comparator = new Comparator<DatabaseMeta>(){ public int compare(DatabaseMeta dbm1, DatabaseMeta dbm2) { return dbm1.getName().compareToIgnoreCase(dbm2.getName()); }}; private DatabaseInterface databaseInterface; private static Map<String, DatabaseInterface> allDatabaseInterfaces; private VariableSpace variables = new Variables(); private ObjectRevision objectRevision; /** * Indicates that the connections doesn't point to a type of database yet. * @deprecated */ public static final int TYPE_DATABASE_NONE = 0; /** * Connection to a MySQL database * @deprecated */ public static final int TYPE_DATABASE_MYSQL = 1; /** * Connection to an Oracle database * @deprecated */ public static final int TYPE_DATABASE_ORACLE = 2; /** * Connection to an AS/400 (IBM iSeries) DB400 database * @deprecated */ public static final int TYPE_DATABASE_AS400 = 3; /** * Connection to an Microsoft Access database * @deprecated */ public static final int TYPE_DATABASE_ACCESS = 4; /** * Connection to a Microsoft SQL Server database * @deprecated */ public static final int TYPE_DATABASE_MSSQL = 5; /** * Connection to an IBM DB2 database * @deprecated */ public static final int TYPE_DATABASE_DB2 = 6; /** * Connection to a PostgreSQL database * @deprecated */ public static final int TYPE_DATABASE_POSTGRES = 7; /** * Connection to an Intersystems Cache database * @deprecated */ public static final int TYPE_DATABASE_CACHE = 8; /** * Connection to an IBM Informix database * @deprecated */ public static final int TYPE_DATABASE_INFORMIX = 9; /** * Connection to a Sybase ASE database * @deprecated */ public static final int TYPE_DATABASE_SYBASE = 10; /** * Connection to a Gupta SQLBase database * @deprecated */ public static final int TYPE_DATABASE_GUPTA = 11; /** * Connection to a DBase III/IV/V database through JDBC * @deprecated */ public static final int TYPE_DATABASE_DBASE = 12; /** * Connection to a FireBird database * @deprecated */ public static final int TYPE_DATABASE_FIREBIRD = 13; /** * Connection to a SAP DB database * @deprecated */ public static final int TYPE_DATABASE_SAPDB = 14; /** * Connection to a Hypersonic java database * @deprecated */ public static final int TYPE_DATABASE_HYPERSONIC = 15; /** * Connection to a generic database * @deprecated */ public static final int TYPE_DATABASE_GENERIC = 16; /** * Connection to an SAP R/3 system * @deprecated */ public static final int TYPE_DATABASE_SAPR3 = 17; /** * Connection to an Ingress database * @deprecated */ public static final int TYPE_DATABASE_INGRES = 18; /** * Connection to a Borland Interbase database * @deprecated */ public static final int TYPE_DATABASE_INTERBASE = 19; /** * Connection to an ExtenDB database * @deprecated */ public static final int TYPE_DATABASE_EXTENDB = 20; /** * Connection to a Teradata database * @deprecated */ public static final int TYPE_DATABASE_TERADATA = 21; /** * Connection to an Oracle RDB database * @deprecated */ public static final int TYPE_DATABASE_ORACLE_RDB = 22; /** * Connection to an H2 database * @deprecated */ public static final int TYPE_DATABASE_H2 = 23; /** * Connection to a Netezza database * @deprecated */ public static final int TYPE_DATABASE_NETEZZA = 24; /** * Connection to an IBM UniVerse database * @deprecated */ public static final int TYPE_DATABASE_UNIVERSE = 25; /** * Connection to a SQLite database * @deprecated */ public static final int TYPE_DATABASE_SQLITE = 26; /** * Connection to an Apache Derby database * @deprecated */ public static final int TYPE_DATABASE_DERBY = 27; /** * Connection to a BMC Remedy Action Request System * @deprecated */ public static final int TYPE_DATABASE_REMEDY_AR_SYSTEM = 28; /** * Connection to a Palo MOLAP Server * @deprecated */ public static final int TYPE_DATABASE_PALO = 29; /** * Connection to a SybaseIQ ASE database * @deprecated */ public static final int TYPE_DATABASE_SYBASEIQ = 30; /** * Connection to a Greenplum database * @deprecated */ public static final int TYPE_DATABASE_GREENPLUM = 31; /** * Connection to a MonetDB database * @deprecated */ public static final int TYPE_DATABASE_MONETDB = 32; /** * Connection to a KingbaseES database * @deprecated */ public static final int TYPE_DATABASE_KINGBASEES = 33; /** * Connection to a Vertica database * @deprecated */ public static final int TYPE_DATABASE_VERTICA = 34; /** * Connection to a Neoview database * @deprecated */ public static final int TYPE_DATABASE_NEOVIEW = 35; /** * Connection to a LucidDB database * @deprecated */ public static final int TYPE_DATABASE_LUCIDDB = 36; /** * Connection to an Infobright database * @deprecated */ public static final int TYPE_DATABASE_INFOBRIGHT = 37; /** * Connect natively through JDBC thin driver to the database. */ public static final int TYPE_ACCESS_NATIVE = 0; /** * Connect to the database using ODBC. */ public static final int TYPE_ACCESS_ODBC = 1; /** * Connect to the database using OCI. (Oracle only) */ public static final int TYPE_ACCESS_OCI = 2; /** * Connect to the database using plugin specific method. (SAP ERP) */ public static final int TYPE_ACCESS_PLUGIN = 3; /** * Connect to the database using JNDI. */ public static final int TYPE_ACCESS_JNDI = 4; /** * Short description of the access type, used in XML and the repository. */ public static final String dbAccessTypeCode[] = { "Native", "ODBC", "OCI", "Plugin", "JNDI", }; /** * Longer description for user interactions. */ public static final String dbAccessTypeDesc[] = { "Native (JDBC)", "ODBC", "OCI", "Plugin specific access method", "JNDI", "Custom", }; /** * Use this length in a String value to indicate that you want to use a CLOB in stead of a normal text field. */ public static final int CLOB_LENGTH = 9999999; /** * The value to store in the attributes so that an empty value doesn't get lost... */ public static final String EMPTY_OPTIONS_STRING = "><EMPTY><"; /** * Construct a new database connections. Note that not all these parameters are not always mandatory. * * @param name The database name * @param type The type of database * @param access The type of database access * @param host The hostname or IP address * @param db The database name * @param port The port on which the database listens. * @param user The username * @param pass The password */ public DatabaseMeta(String name, String type, String access, String host, String db, String port, String user, String pass) { setValues(name, type, access, host, db, port, user, pass); addOptions(); } /** * Create an empty database connection * */ public DatabaseMeta() { setDefault(); addOptions(); } /** * Set default values for an Oracle database. * */ public void setDefault() { setValues("", "Oracle", "Native", "", "", "1521", "", ""); } /** * Add a list of common options for some databases. * */ public void addOptions() { PluginInterface mySqlPlugin = PluginRegistry.getInstance().getPlugin(DatabasePluginType.class, "MYSQL"); PluginInterface infoBrightPlugin = PluginRegistry.getInstance().getPlugin(DatabasePluginType.class, new InfobrightDatabaseMeta()); String mySQL = mySqlPlugin.getIds()[0]; addExtraOption(mySQL, "defaultFetchSize", "500"); addExtraOption(mySQL, "useCursorFetch", "true"); String infoBright = infoBrightPlugin.getIds()[0]; addExtraOption(infoBright, "characterEncoding", "UTF-8"); } /** * @return the system dependend database interface for this database metadata definition */ public DatabaseInterface getDatabaseInterface() { return databaseInterface; } /** * Set the system dependend database interface for this database metadata definition * @param databaseInterface the system dependend database interface */ public void setDatabaseInterface(DatabaseInterface databaseInterface) { this.databaseInterface = databaseInterface; } /** * Search for the right type of DatabaseInterface object and clone it. * * @param databaseType the type of DatabaseInterface to look for (description) * @return The requested DatabaseInterface * * @throws KettleDatabaseException when the type could not be found or referenced. */ public static final DatabaseInterface getDatabaseInterface(String databaseType) throws KettleDatabaseException { DatabaseInterface di = findDatabaseInterface(databaseType); if (di == null) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "DatabaseMeta.Error.DatabaseInterfaceNotFound", databaseType)); //$NON-NLS-1$ } return (DatabaseInterface) di.clone(); } /** * Search for the right type of DatabaseInterface object and return it. * * @param databaseType the type of DatabaseInterface to look for (id or description) * @return The requested DatabaseInterface * * @throws KettleDatabaseException when the type could not be found or referenced. */ private static final DatabaseInterface findDatabaseInterface(String databaseTypeDesc) throws KettleDatabaseException { PluginRegistry registry = PluginRegistry.getInstance(); PluginInterface plugin = registry.getPlugin(DatabasePluginType.class, databaseTypeDesc); if (plugin==null) { plugin = registry.findPluginWithName(DatabasePluginType.class, databaseTypeDesc); } if (plugin==null) { throw new KettleDatabaseException("database type with plugin id ["+databaseTypeDesc+"] couldn't be found!"); } return getDatabaseInterfacesMap().get(plugin.getIds()[0]); } /** * Returns the database ID of this database connection if a repository was used before. * * @return the ID of the db connection. */ public ObjectId getObjectId() { return databaseInterface.getObjectId(); } public void setObjectId(ObjectId id) { databaseInterface.setObjectId(id); } public Object clone() { DatabaseMeta databaseMeta = new DatabaseMeta(); databaseMeta.replaceMeta(this); databaseMeta.setObjectId(null); return databaseMeta; } public void replaceMeta(DatabaseMeta databaseMeta) { this.setValues(databaseMeta.getName(), databaseMeta.getPluginId(), databaseMeta.getAccessTypeDesc(), databaseMeta.getHostname(), databaseMeta.getDatabaseName(), databaseMeta.getDatabasePortNumberString(), databaseMeta.getUsername(), databaseMeta.getPassword() ); this.setServername(databaseMeta.getServername()); this.setDataTablespace( databaseMeta.getDataTablespace() ); this.setIndexTablespace( databaseMeta.getIndexTablespace() ); this.databaseInterface = (DatabaseInterface) databaseMeta.databaseInterface.clone(); this.setObjectId(databaseMeta.getObjectId()); this.setChanged(); } public void setValues(String name, String type, String access, String host, String db, String port, String user, String pass) { try { databaseInterface = getDatabaseInterface(type); } catch(KettleDatabaseException kde) { throw new RuntimeException("Database type not found!", kde); } setName(name); setAccessType(getAccessType(access)); setHostname(host); setDBName(db); setDBPort(port); setUsername(user); setPassword(pass); setServername(null); setChanged(false); } public void setDatabaseType(String type) { DatabaseInterface oldInterface = databaseInterface; try { databaseInterface = getDatabaseInterface(type); } catch(KettleDatabaseException kde) { throw new RuntimeException("Database type ["+type+"] not found!", kde); } setName(oldInterface.getName()); setAccessType(oldInterface.getAccessType()); setHostname(oldInterface.getHostname()); setDBName(oldInterface.getDatabaseName()); setDBPort(oldInterface.getDatabasePortNumberString()); setUsername(oldInterface.getUsername()); setPassword(oldInterface.getPassword()); setServername(oldInterface.getServername()); setDataTablespace(oldInterface.getDataTablespace()); setIndexTablespace(oldInterface.getIndexTablespace()); setChanged(oldInterface.isChanged()); } public void setValues(DatabaseMeta info) { databaseInterface = (DatabaseInterface)info.databaseInterface.clone(); } /** * Sets the name of the database connection. This name should be * unique in a transformation and in general in a single repository. * * @param name The name of the database connection */ public void setName(String name) { databaseInterface.setName(name); } /** * Returns the name of the database connection * @return The name of the database connection */ public String getName() { return databaseInterface.getName(); } /** * Returns the type of database, one of <p> * TYPE_DATABASE_MYSQL<p> * TYPE_DATABASE_ORACLE<p> * TYPE_DATABASE_...<p> * * @return the database type @Deprecated public int getDatabaseType() { return databaseInterface.getDatabaseType(); } */ /** * The plugin ID of the database interface */ public String getPluginId() { return databaseInterface.getPluginId(); } /* * Sets the type of database. * @param db_type The database type public void setDatabaseType(int db_type) { databaseInterface this.databaseType = db_type; } */ /** * Return the type of database access. One of <p> * TYPE_ACCESS_NATIVE<p> * TYPE_ACCESS_ODBC<p> * TYPE_ACCESS_OCI<p> * @return The type of database access. */ public int getAccessType() { return databaseInterface.getAccessType(); } /** * Set the type of database access. * @param access_type The access type. */ public void setAccessType(int access_type) { databaseInterface.setAccessType(access_type); } /** * Returns a short description of the type of database. * @return A short description of the type of database. * @deprecated This is actually the plugin ID */ public String getDatabaseTypeDesc() { return getPluginId(); } /** * Gets you a short description of the type of database access. * @return A short description of the type of database access. */ public String getAccessTypeDesc() { return dbAccessTypeCode[getAccessType()]; } /** * Return the hostname of the machine on which the database runs. * @return The hostname of the database. */ public String getHostname() { return databaseInterface.getHostname(); } /** * Sets the hostname of the machine on which the database runs. * @param hostname The hostname of the machine on which the database runs. */ public void setHostname(String hostname) { databaseInterface.setHostname(hostname); } /** * Return the port on which the database listens as a String. Allows for parameterisation. * @return The database port. */ public String getDatabasePortNumberString() { return databaseInterface.getDatabasePortNumberString(); } /** * Sets the port on which the database listens. * * @param db_port The port number on which the database listens */ public void setDBPort(String db_port) { databaseInterface.setDatabasePortNumberString(db_port); } /** * Return the name of the database. * @return The database name. */ public String getDatabaseName() { return databaseInterface.getDatabaseName(); } /** * Set the name of the database. * @param databaseName The new name of the database */ public void setDBName(String databaseName) { databaseInterface.setDatabaseName(databaseName); } /** * Get the username to log into the database on this connection. * @return The username to log into the database on this connection. */ public String getUsername() { return databaseInterface.getUsername(); } /** * Sets the username to log into the database on this connection. * @param username The username */ public void setUsername(String username) { databaseInterface.setUsername(username); } /** * Get the password to log into the database on this connection. * @return the password to log into the database on this connection. */ public String getPassword() { return databaseInterface.getPassword(); } /** * Sets the password to log into the database on this connection. * @param password the password to log into the database on this connection. */ public void setPassword(String password) { databaseInterface.setPassword(password); } /** * @param servername the Informix servername */ public void setServername(String servername) { databaseInterface.setServername(servername); } /** * @return the Informix servername */ public String getServername() { return databaseInterface.getServername(); } public String getDataTablespace() { return databaseInterface.getDataTablespace(); } public void setDataTablespace(String data_tablespace) { databaseInterface.setDataTablespace(data_tablespace); } public String getIndexTablespace() { return databaseInterface.getIndexTablespace(); } public void setIndexTablespace(String index_tablespace) { databaseInterface.setIndexTablespace(index_tablespace); } public void setChanged() { setChanged(true); } public void setChanged(boolean ch) { databaseInterface.setChanged(ch); } public boolean hasChanged() { return databaseInterface.isChanged(); } public void clearChanged() { databaseInterface.setChanged(false); } public String toString() { return getName(); } /** * @return The extra attributes for this database connection */ public Properties getAttributes() { return databaseInterface.getAttributes(); } /** * Set extra attributes on this database connection * @param attributes The extra attributes to set on this database connection. */ public void setAttributes(Properties attributes) { databaseInterface.setAttributes(attributes); } /** * Constructs a new database using an XML string snippet. * It expects the snippet to be enclosed in <code>connection</code> tags. * @param xml The XML string to parse * @throws KettleXMLException in case there is an XML parsing error */ public DatabaseMeta(String xml) throws KettleXMLException { this( XMLHandler.getSubNode(XMLHandler.loadXMLString(xml), "connection") ); } /** * Reads the information from an XML Node into this new database connection. * @param con The Node to read the data from * @throws KettleXMLException */ public DatabaseMeta(Node con) throws KettleXMLException { this(); try { String type = XMLHandler.getTagValue(con, "type"); try { databaseInterface = getDatabaseInterface(type); } catch (KettleDatabaseException kde) { throw new KettleXMLException("Unable to create new database interface", kde); } setName(XMLHandler.getTagValue(con, "name")); setHostname(XMLHandler.getTagValue(con, "server")); String acc = XMLHandler.getTagValue(con, "access"); setAccessType(getAccessType(acc)); setDBName(XMLHandler.getTagValue(con, "database")); // The DB port is read here too for backward compatibility! setDBPort(XMLHandler.getTagValue(con, "port")); setUsername(XMLHandler.getTagValue(con, "username")); setPassword(Encr.decryptPasswordOptionallyEncrypted(XMLHandler.getTagValue(con, "password"))); setServername(XMLHandler.getTagValue(con, "servername")); setDataTablespace(XMLHandler.getTagValue(con, "data_tablespace")); setIndexTablespace(XMLHandler.getTagValue(con, "index_tablespace")); // Also, read the database attributes... Node attrsnode = XMLHandler.getSubNode(con, "attributes"); if (attrsnode != null) { List<Node> attrnodes = XMLHandler.getNodes(attrsnode, "attribute"); for (Node attrnode : attrnodes) { String code = XMLHandler.getTagValue(attrnode, "code"); String attribute = XMLHandler.getTagValue(attrnode, "attribute"); if (code != null && attribute != null) getAttributes().put(code, attribute);getDatabasePortNumberString(); } } } catch (Exception e) { throw new KettleXMLException("Unable to load database connection info from XML node", e); } } @SuppressWarnings("unchecked") public String getXML() { StringBuffer retval = new StringBuffer(250); retval.append(" <").append(XML_TAG).append('>').append(Const.CR); retval.append(" ").append(XMLHandler.addTagValue("name", getName())); retval.append(" ").append(XMLHandler.addTagValue("server", getHostname())); retval.append(" ").append(XMLHandler.addTagValue("type", getPluginId())); retval.append(" ").append(XMLHandler.addTagValue("access", getAccessTypeDesc())); retval.append(" ").append(XMLHandler.addTagValue("database", getDatabaseName())); retval.append(" ").append(XMLHandler.addTagValue("port", getDatabasePortNumberString())); retval.append(" ").append(XMLHandler.addTagValue("username", getUsername())); retval.append(" ").append(XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(getPassword()))); retval.append(" ").append(XMLHandler.addTagValue("servername", getServername())); retval.append(" ").append(XMLHandler.addTagValue("data_tablespace", getDataTablespace())); retval.append(" ").append(XMLHandler.addTagValue("index_tablespace", getIndexTablespace())); retval.append(" <attributes>").append(Const.CR); List list = new ArrayList( getAttributes().keySet() ); Collections.sort(list); // Sort the entry-sets to make sure we can compare XML strings: if the order is different, the XML is different. for (Iterator iter = list.iterator(); iter.hasNext();) { String code = (String) iter.next(); String attribute = getAttributes().getProperty(code); if (!Const.isEmpty(attribute)) { retval.append(" <attribute>"+ XMLHandler.addTagValue("code", code, false)+ XMLHandler.addTagValue("attribute", attribute, false)+ "</attribute>"+Const.CR); } } retval.append(" </attributes>").append(Const.CR); retval.append(" </"+XML_TAG+">").append(Const.CR); return retval.toString(); } public int hashCode() { return getName().hashCode(); // name of connection is unique! } public boolean equals(Object obj) { return getName().equals( ((DatabaseMeta)obj).getName() ); } public String getURL() throws KettleDatabaseException { return getURL(null); } public String getURL(String partitionId) throws KettleDatabaseException { // First see if we're not doing any JNDI... if (getAccessType()==TYPE_ACCESS_JNDI) { // We can't really determine the URL here. } String baseUrl; if (isPartitioned() && !Const.isEmpty(partitionId)) { // Get the cluster information... PartitionDatabaseMeta partition = getPartitionMeta(partitionId); String hostname = partition.getHostname(); String port = partition.getPort(); String databaseName = partition.getDatabaseName(); baseUrl = databaseInterface.getURL(hostname, port, databaseName); } else { baseUrl = databaseInterface.getURL(getHostname(), getDatabasePortNumberString(), getDatabaseName()); } StringBuffer url=new StringBuffer( environmentSubstitute(baseUrl) ); if (databaseInterface.supportsOptionsInURL()) { // OK, now add all the options... String optionIndicator = getExtraOptionIndicator(); String optionSeparator = getExtraOptionSeparator(); String valueSeparator = getExtraOptionValueSeparator(); Map<String, String> map = getExtraOptions(); if (map.size()>0) { Iterator<String> iterator = map.keySet().iterator(); boolean first=true; while (iterator.hasNext()) { String typedParameter=(String)iterator.next(); int dotIndex = typedParameter.indexOf('.'); if (dotIndex>=0) { String typeCode = typedParameter.substring(0,dotIndex); String parameter = typedParameter.substring(dotIndex+1); String value = map.get(typedParameter); // Only add to the URL if it's the same database type code... if (databaseInterface.getPluginId().equals(typeCode)) { if (first && url.indexOf(valueSeparator) == -1) { url.append(optionIndicator); } else { url.append(optionSeparator); } url.append(parameter); if (!Const.isEmpty(value) && !value.equals(EMPTY_OPTIONS_STRING)) { url.append(valueSeparator).append(value); } first=false; } } } } } else { // We need to put all these options in a Properties file later (Oracle & Co.) // This happens at connect time... } return url.toString(); } public Properties getConnectionProperties() { Properties properties =new Properties(); Map<String, String> map = getExtraOptions(); if (map.size()>0) { Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()) { String typedParameter=(String)iterator.next(); int dotIndex = typedParameter.indexOf('.'); if (dotIndex>=0) { String typeCode = typedParameter.substring(0,dotIndex); String parameter = typedParameter.substring(dotIndex+1); String value = (String) map.get(typedParameter); // Only add to the URL if it's the same database type code... if (databaseInterface.getPluginId().equals(typeCode)) { if (value!=null && value.equals(EMPTY_OPTIONS_STRING)) value=""; properties.put(parameter, environmentSubstitute(Const.NVL(value, ""))); } } } } return properties; } public String getExtraOptionIndicator() { return databaseInterface.getExtraOptionIndicator(); } /** * @return The extra option separator in database URL for this platform (usually this is semicolon ; ) */ public String getExtraOptionSeparator() { return databaseInterface.getExtraOptionSeparator(); } /** * @return The extra option value separator in database URL for this platform (usually this is the equal sign = ) */ public String getExtraOptionValueSeparator() { return databaseInterface.getExtraOptionValueSeparator(); } /** * Add an extra option to the attributes list * @param databaseTypeCode The database type code for which the option applies * @param option The option to set * @param value The value of the option */ public void addExtraOption(String databaseTypeCode, String option, String value) { databaseInterface.addExtraOption(databaseTypeCode, option, value); } /** * @deprecated because the same database can support transactions or not. It all depends on the database setup. Therefor, we look at the database metadata * DatabaseMetaData.supportsTransactions() in stead of this. * @return true if the database supports transactions */ public boolean supportsTransactions() { return databaseInterface.supportsTransactions(); } public boolean supportsAutoinc() { return databaseInterface.supportsAutoInc(); } public boolean supportsSequences() { return databaseInterface.supportsSequences(); } public String getSQLSequenceExists(String sequenceName) { return databaseInterface.getSQLSequenceExists(sequenceName); } public boolean supportsBitmapIndex() { return databaseInterface.supportsBitmapIndex(); } public boolean supportsSetLong() { return databaseInterface.supportsSetLong(); } /** * @return true if the database supports schemas */ public boolean supportsSchemas() { return databaseInterface.supportsSchemas(); } /** * @return true if the database supports catalogs */ public boolean supportsCatalogs() { return databaseInterface.supportsCatalogs(); } /** * * @return true when the database engine supports empty transaction. * (for example Informix does not on a non-ANSI database type!) */ public boolean supportsEmptyTransactions() { return databaseInterface.supportsEmptyTransactions(); } /** * See if this database supports the setCharacterStream() method on a PreparedStatement. * * @return true if we can set a Stream on a field in a PreparedStatement. False if not. */ public boolean supportsSetCharacterStream() { return databaseInterface.supportsSetCharacterStream(); } /** * Get the maximum length of a text field for this database connection. * This includes optional CLOB, Memo and Text fields. (the maximum!) * @return The maximum text field length for this database type. (mostly CLOB_LENGTH) */ public int getMaxTextFieldLength() { return databaseInterface.getMaxTextFieldLength(); } /* * Get a string representing the unqiue database type code * @param dbtype the database type to get the code of * @return The database type code * @deprecated please use getDatabaseTypeCode() public final static String getDBTypeDesc(int dbtype) { return getDatabaseTypeCode(dbtype); } */ /* * Get a string representing the unqiue database type code * @param dbtype the database type to get the code of * @return The database type code @Deprecated public final static String getDatabaseTypeCode(int dbtype) { // Find the DatabaseInterface for this type... DatabaseInterface[] di = getDatabaseInterfaces(); for (int i=0;i<di.length;i++) { if (di[i].getDatabaseType() == dbtype) { return di[i].getPluginId(); } } return null; } * Get a description of the database type * @param dbtype the database type to get the description for * @return The database type description public final static String getDatabaseTypeDesc(int dbtype) { // Find the DatabaseInterface for this type... DatabaseInterface[] di = getDatabaseInterfaces(); for (int i=0;i<di.length;i++) { if (di[i].getDatabaseType() == dbtype) return di[i].getDatabaseTypeDescLong(); } return null; } */ public final static int getAccessType(String dbaccess) { int i; if (dbaccess==null) return TYPE_ACCESS_NATIVE; for (i=0;i<dbAccessTypeCode.length;i++) { if (dbAccessTypeCode[i].equalsIgnoreCase(dbaccess)) { return i; } } for (i=0;i<dbAccessTypeDesc.length;i++) { if (dbAccessTypeDesc[i].equalsIgnoreCase(dbaccess)) { return i; } } return TYPE_ACCESS_NATIVE; } public final static String getAccessTypeDesc(int dbaccess) { if (dbaccess<0) return null; if (dbaccess>dbAccessTypeCode.length) return null; return dbAccessTypeCode[dbaccess]; } public final static String getAccessTypeDescLong(int dbaccess) { if (dbaccess<0) return null; if (dbaccess>dbAccessTypeDesc.length) return null; return dbAccessTypeDesc[dbaccess]; } public static final DatabaseInterface[] getDatabaseInterfaces() { List<DatabaseInterface> list = new ArrayList<DatabaseInterface>(getDatabaseInterfacesMap().values()); return list.toArray(new DatabaseInterface[list.size()]); } public static final Map<String, DatabaseInterface> getDatabaseInterfacesMap() { if (allDatabaseInterfaces!=null) { return allDatabaseInterfaces; } // If multiple threads call this method at the same time, there may be extra work done until // the allDatabaseInterfaces is finally set. Before we were not using a local map to populate, // and parallel threads were getting an incomplete list, causing null pointers. PluginRegistry registry = PluginRegistry.getInstance(); List<PluginInterface> plugins = registry.getPlugins(DatabasePluginType.class); HashMap<String, DatabaseInterface> tmpAllDatabaseInterfaces = new HashMap<String, DatabaseInterface>(); for (PluginInterface plugin : plugins) { try { DatabaseInterface databaseInterface = (DatabaseInterface)registry.loadClass(plugin); databaseInterface.setPluginId(plugin.getIds()[0]); databaseInterface.setPluginName(plugin.getName()); tmpAllDatabaseInterfaces.put(plugin.getIds()[0], databaseInterface); } catch (KettlePluginException cnfe) { System.out.println("Could not create connection entry for "+plugin.getName()+". "+cnfe.getCause().getClass().getName()); LogChannel.GENERAL.logError("Could not create connection entry for "+plugin.getName()+". "+cnfe.getCause().getClass().getName()); } catch(Exception e) { logger.error("Error loading plugin: " + plugin, e); //$NON-NLS-1$ } } allDatabaseInterfaces = tmpAllDatabaseInterfaces; return allDatabaseInterfaces; } public final static int[] getAccessTypeList(String dbTypeDesc) { try { DatabaseInterface di = findDatabaseInterface(dbTypeDesc); return di.getAccessTypeList(); } catch(KettleDatabaseException kde) { return null; } } public static final int getPortForDBType(String strtype, String straccess) { try { DatabaseInterface di = getDatabaseInterface(strtype); di.setAccessType(getAccessType(straccess)); return di.getDefaultDatabasePort(); } catch(KettleDatabaseException kde) { return -1; } } public int getDefaultDatabasePort() { return databaseInterface.getDefaultDatabasePort(); } public int getNotFoundTK(boolean use_autoinc) { return databaseInterface.getNotFoundTK(use_autoinc); } public String getDriverClass() { return environmentSubstitute(databaseInterface.getDriverClass()); } public String stripCR(String sbsql) { if (sbsql==null) return null; return stripCR(new StringBuffer(sbsql)); } public String stripCR(StringBuffer sbsql) { // DB2 Can't handle \n in SQL Statements... if (!supportsNewLinesInSQL()) { // Remove CR's for (int i=sbsql.length()-1;i>=0;i { if (sbsql.charAt(i)=='\n' || sbsql.charAt(i)=='\r') sbsql.setCharAt(i, ' '); } } return sbsql.toString(); } public String getSeqNextvalSQL(String sequenceName) { return databaseInterface.getSQLNextSequenceValue(sequenceName); } public String getSQLCurrentSequenceValue(String sequenceName) { return databaseInterface.getSQLCurrentSequenceValue(sequenceName); } public boolean isFetchSizeSupported() { return databaseInterface.isFetchSizeSupported(); } /** * Indicates the need to insert a placeholder (0) for auto increment fields. * @return true if we need a placeholder for auto increment fields in insert statements. */ public boolean needsPlaceHolder() { return databaseInterface.needsPlaceHolder(); } public String getFunctionSum() { return databaseInterface.getFunctionSum(); } public String getFunctionAverage() { return databaseInterface.getFunctionAverage(); } public String getFunctionMaximum() { return databaseInterface.getFunctionMaximum(); } public String getFunctionMinimum() { return databaseInterface.getFunctionMinimum(); } public String getFunctionCount() { return databaseInterface.getFunctionCount(); } /** * Check the database connection parameters and give back an array of remarks * @return an array of remarks Strings */ public String[] checkParameters() { ArrayList<String> remarks = new ArrayList<String>(); if (getDatabaseInterface() == null) { remarks.add("No database type was choosen"); } if (getName()==null || getName().length()==0) { remarks.add("Please give this database connection a name"); } if (!isPartitioned() && !(getDatabaseInterface() instanceof SAPR3DatabaseMeta || getDatabaseInterface() instanceof GenericDatabaseMeta)) { if (getDatabaseName()==null || getDatabaseName().length()==0) { remarks.add("Please specify the name of the database"); } } return remarks.toArray(new String[remarks.size()]); } /** * This is now replaced with getQuotedSchemaTableCombination(), enforcing the use of the quoteFields call * * @param schemaName * @param tableName * @return * @deprecated please use getQuotedSchemaTableCombination() */ public String getSchemaTableCombination(String schemaName, String tableName) { return getQuotedSchemaTableCombination(schemaName, tableName); } /** * Calculate the schema-table combination, usually this is the schema and table separated with a dot. (schema.table) * @param schemaName the schema-name or null if no schema is used. * @param tableName the table name * @return the schemaname-tablename combination */ public String getQuotedSchemaTableCombination(String schemaName, String tableName) { if (Const.isEmpty(schemaName)) { if (Const.isEmpty(getPreferredSchemaName())) { return quoteField(environmentSubstitute(tableName)); // no need to look further } else { return databaseInterface.getSchemaTableCombination(quoteField(environmentSubstitute(getPreferredSchemaName())), quoteField(environmentSubstitute(tableName))); } } else { return databaseInterface.getSchemaTableCombination(quoteField(environmentSubstitute(schemaName)), quoteField(environmentSubstitute(tableName))); } } public boolean isClob(ValueMetaInterface v) { boolean retval=true; if (v==null || v.getLength()<DatabaseMeta.CLOB_LENGTH) { retval=false; } else { return true; } return retval; } public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc) { return getFieldDefinition(v, tk, pk, use_autoinc, true, true); } public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr) { return databaseInterface.getFieldDefinition(v, tk, pk, use_autoinc, add_fieldname, add_cr); } public String getLimitClause(int nrRows) { return databaseInterface.getLimitClause(nrRows); } /** * @param tableName The table or schema-table combination. We expect this to be quoted properly already! * @return the SQL for to get the fields of this table. */ public String getSQLQueryFields(String tableName) { return databaseInterface.getSQLQueryFields(tableName); } public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { String retval = databaseInterface.getAddColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon); retval+=Const.CR; if (semicolon) retval+=";"+Const.CR; return retval; } public String getDropColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { String retval = databaseInterface.getDropColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon); retval+=Const.CR; if (semicolon) retval+=";"+Const.CR; return retval; } public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon) { String retval = databaseInterface.getModifyColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon); retval+=Const.CR; if (semicolon) retval+=";"+Const.CR; return retval; } /** * @return an array of reserved words for the database type... */ public String[] getReservedWords() { return databaseInterface.getReservedWords(); } /** * @return true if reserved words need to be double quoted ("password", "select", ...) */ public boolean quoteReservedWords() { return databaseInterface.quoteReservedWords(); } /** * @return The start quote sequence, mostly just double quote, but sometimes [, ... */ public String getStartQuote() { return databaseInterface.getStartQuote(); } /** * @return The end quote sequence, mostly just double quote, but sometimes ], ... */ public String getEndQuote() { return databaseInterface.getEndQuote(); } /** * Returns a quoted field if this is needed: contains spaces, is a reserved word, ... * @param field The fieldname to check for quoting * @return The quoted field (if this is needed. */ public String quoteField(String field) { if (Const.isEmpty(field)) return null; if (isForcingIdentifiersToLowerCase()) { field=field.toLowerCase(); } else if (isForcingIdentifiersToUpperCase()) { field=field.toUpperCase(); } // If the field already contains quotes, we don't touch it anymore, just return the same string... if (field.indexOf(getStartQuote())>=0 || field.indexOf(getEndQuote())>=0) { return field; } if (isReservedWord(field) && quoteReservedWords()) { return handleCase(getStartQuote()+field+getEndQuote()); } else { if (databaseInterface.isQuoteAllFields() || hasSpacesInField(field) || hasSpecialCharInField(field) || hasDotInField(field)) { return getStartQuote()+field+getEndQuote(); } else { return field; } } } private String handleCase(String field) { if (databaseInterface.isDefaultingToUppercase()) { return field.toUpperCase(); } else { return field.toLowerCase(); } } /** * Determines whether or not this field is in need of quoting:<br> * - When the fieldname contains spaces<br> * - When the fieldname is a reserved word<br> * @param fieldname the fieldname to check if there is a need for quoting * @return true if the fieldname needs to be quoted. */ public boolean isInNeedOfQuoting(String fieldname) { return isReservedWord(fieldname) || hasSpacesInField(fieldname); } /** * Returns true if the string specified is a reserved word on this database type. * @param word The word to check * @return true if word is a reserved word on this database. */ public boolean isReservedWord(String word) { String reserved[] = getReservedWords(); if (Const.indexOfString(word, reserved)>=0) return true; return false; } /** * Detects if a field has spaces in the name. We need to quote the field in that case. * @param fieldname The fieldname to check for spaces * @return true if the fieldname contains spaces */ public boolean hasSpacesInField(String fieldname) { if( fieldname == null ) return false; if (fieldname.indexOf(' ')>=0) return true; return false; } /** * Detects if a field has spaces in the name. We need to quote the field in that case. * @param fieldname The fieldname to check for spaces * @return true if the fieldname contains spaces */ public boolean hasSpecialCharInField(String fieldname) { if(fieldname==null) return false; if (fieldname.indexOf('/')>=0) return true; if (fieldname.indexOf('-')>=0) return true; if (fieldname.indexOf('+')>=0) return true; if (fieldname.indexOf(',')>=0) return true; if (fieldname.indexOf('*')>=0) return true; if (fieldname.indexOf('(')>=0) return true; if (fieldname.indexOf(')')>=0) return true; if (fieldname.indexOf('{')>=0) return true; if (fieldname.indexOf('}')>=0) return true; if (fieldname.indexOf('[')>=0) return true; if (fieldname.indexOf(']')>=0) return true; if (fieldname.indexOf('%')>=0) return true; if (fieldname.indexOf('@')>=0) return true; if (fieldname.indexOf('?')>=0) return true; return false; } public boolean hasDotInField(String fieldname) { if(fieldname==null) return false; if (fieldname.indexOf('.')>=0) return true; return false; } /** * Checks the fields specified for reserved words and quotes them. * @param fields the list of fields to check * @return true if one or more values have a name that is a reserved word on this database type. */ public boolean replaceReservedWords(RowMetaInterface fields) { boolean hasReservedWords=false; for (int i=0;i<fields.size();i++) { ValueMetaInterface v = fields.getValueMeta(i); if (isReservedWord(v.getName())) { hasReservedWords = true; v.setName( quoteField(v.getName()) ); } } return hasReservedWords; } /** * Checks the fields specified for reserved words * @param fields the list of fields to check * @return The nr of reserved words for this database. */ public int getNrReservedWords(RowMetaInterface fields) { int nrReservedWords=0; for (int i=0;i<fields.size();i++) { ValueMetaInterface v = fields.getValueMeta(i); if (isReservedWord(v.getName())) nrReservedWords++; } return nrReservedWords; } /** * @return a list of types to get the available tables */ public String[] getTableTypes() { return databaseInterface.getTableTypes(); } /** * @return a list of types to get the available views */ public String[] getViewTypes() { return databaseInterface.getViewTypes(); } /** * @return a list of types to get the available synonyms */ public String[] getSynonymTypes() { return databaseInterface.getSynonymTypes(); } /** * @return true if we need to supply the schema-name to getTables in order to get a correct list of items. */ public boolean useSchemaNameForTableList() { return databaseInterface.useSchemaNameForTableList(); } /** * @return true if the database supports views */ public boolean supportsViews() { return databaseInterface.supportsViews(); } /** * @return true if the database supports synonyms */ public boolean supportsSynonyms() { return databaseInterface.supportsSynonyms(); } /** * * @return The SQL on this database to get a list of stored procedures. */ public String getSQLListOfProcedures() { return databaseInterface.getSQLListOfProcedures(); } /** * @param tableName The tablename to be truncated * @return The SQL statement to remove all rows from the specified statement, if possible without using transactions */ public String getTruncateTableStatement(String schema, String tableName) { return databaseInterface.getTruncateTableStatement(getQuotedSchemaTableCombination(schema, tableName)); } /** * @return true if the database rounds floating point numbers to the right precision. * For example if the target field is number(7,2) the value 12.399999999 is converted into 12.40 */ public boolean supportsFloatRoundingOnUpdate() { return databaseInterface.supportsFloatRoundingOnUpdate(); } /** * @param tableNames The names of the tables to lock * @return The SQL commands to lock database tables for write purposes. * null is returned in case locking is not supported on the target database. */ public String getSQLLockTables(String tableNames[]) { return databaseInterface.getSQLLockTables(tableNames); } /** * @param tableNames The names of the tables to unlock * @return The SQL commands to unlock databases tables. * null is returned in case locking is not supported on the target database. */ public String getSQLUnlockTables(String tableNames[]) { return databaseInterface.getSQLUnlockTables(tableNames); } /** * @return a feature list for the chosen database type. * */ @SuppressWarnings("unchecked") public List<RowMetaAndData> getFeatureSummary() { List<RowMetaAndData> list = new ArrayList<RowMetaAndData>(); RowMetaAndData r =null; final String par = "Parameter"; final String val = "Value"; ValueMetaInterface testValue = new ValueMeta("FIELD", ValueMetaInterface.TYPE_STRING); testValue.setLength(30); if (databaseInterface!=null) { // Type of database r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Database type"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDatabaseTypeDesc()); list.add(r); // Type of access r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Access type"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getAccessTypeDesc()); list.add(r); // Name of database r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Database name"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDatabaseName()); list.add(r); // server host name r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Server hostname"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getHostname()); list.add(r); // Port number r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Service port"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDatabasePortNumberString()); list.add(r); // Username r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Username"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getUsername()); list.add(r); // Informix server r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Informix server name"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getServername()); list.add(r); // Other properties... Enumeration keys = getAttributes().keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = getAttributes().getProperty(key); r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Extra attribute ["+key+"]"); r.addValue(val, ValueMetaInterface.TYPE_STRING, value); list.add(r); } // driver class r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Driver class"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDriverClass()); list.add(r); // URL String pwd = getPassword(); setPassword("password"); // Don't give away the password in the URL! String url = ""; try { url = getURL(); } catch(Exception e) { url=""; } // SAP etc. r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "URL"); r.addValue(val, ValueMetaInterface.TYPE_STRING, url); list.add(r); setPassword(pwd); // SQL: Next sequence value r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SQL: next sequence value"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getSeqNextvalSQL("SEQUENCE")); list.add(r); // is set fetch size supported r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supported: set fetch size"); r.addValue(val, ValueMetaInterface.TYPE_STRING, isFetchSizeSupported()?"Y":"N"); list.add(r); // needs place holder for auto increment r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "auto increment field needs placeholder"); r.addValue(val, ValueMetaInterface.TYPE_STRING, needsPlaceHolder()?"Y":"N"); list.add(r); // Sum function r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SUM aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionSum()); list.add(r); // Avg function r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "AVG aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionAverage()); list.add(r); // Minimum function r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "MIN aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionMinimum()); list.add(r); // Maximum function r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "MAX aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionMaximum()); list.add(r); // Count function r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "COUNT aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionCount()); list.add(r); // Schema-table combination r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Schema / Table combination"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getQuotedSchemaTableCombination("SCHEMA", "TABLE")); list.add(r); // Limit clause r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "LIMIT clause for 100 rows"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getLimitClause(100)); list.add(r); // add column statement r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Add column statement"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getAddColumnStatement("TABLE", testValue, null, false, null, false)); list.add(r); // drop column statement r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Drop column statement"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDropColumnStatement("TABLE", testValue, null, false, null, false)); list.add(r); // Modify column statement r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Modify column statement"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getModifyColumnStatement("TABLE", testValue, null, false, null, false)); list.add(r); // List of reserved words String reserved = ""; if (getReservedWords()!=null) for (int i=0;i<getReservedWords().length;i++) reserved+=(i>0?", ":"")+getReservedWords()[i]; r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of reserved words"); r.addValue(val, ValueMetaInterface.TYPE_STRING, reserved); list.add(r); // Quote reserved words? r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Quote reserved words?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, quoteReservedWords()?"Y":"N"); list.add(r); // Start Quote r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Start quote for reserved words"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getStartQuote()); list.add(r); // End Quote r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "End quote for reserved words"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getEndQuote()); list.add(r); // List of table types String types = ""; String slist[] = getTableTypes(); if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i]; r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of JDBC table types"); r.addValue(val, ValueMetaInterface.TYPE_STRING, types); list.add(r); // List of view types types = ""; slist = getViewTypes(); if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i]; r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of JDBC view types"); r.addValue(val, ValueMetaInterface.TYPE_STRING, types); list.add(r); // List of synonym types types = ""; slist = getSynonymTypes(); if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i]; r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of JDBC synonym types"); r.addValue(val, ValueMetaInterface.TYPE_STRING, types); list.add(r); // Use schema-name to get list of tables? r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "use schema name to get table list?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, useSchemaNameForTableList()?"Y":"N"); list.add(r); // supports view? r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports views?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsViews()?"Y":"N"); list.add(r); // supports synonyms? r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports synonyms?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsSynonyms()?"Y":"N"); list.add(r); // SQL: get list of procedures? r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SQL: list of procedures"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getSQLListOfProcedures()); list.add(r); // SQL: get truncate table statement? r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SQL: truncate table"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getTruncateTableStatement(null, "TABLE")); list.add(r); // supports float rounding on update? r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports floating point rounding on update/insert"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsFloatRoundingOnUpdate()?"Y":"N"); list.add(r); // supports time stamp to date conversion r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports timestamp-date conversion"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsTimeStampToDateConversion()?"Y":"N"); list.add(r); // supports batch updates r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports batch updates"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsBatchUpdates()?"Y":"N"); list.add(r); // supports boolean values r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports boolean data type"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsBooleanDataType()?"Y":"N"); list.add(r); } return list; } /** * @return true if the database result sets support getTimeStamp() to retrieve date-time. (Date) */ public boolean supportsTimeStampToDateConversion() { return databaseInterface.supportsTimeStampToDateConversion(); } /** * @return true if the database JDBC driver supports batch updates * For example Interbase doesn't support this! */ public boolean supportsBatchUpdates() { return databaseInterface.supportsBatchUpdates(); } /** * @return true if the database supports a boolean, bit, logical, ... datatype */ public boolean supportsBooleanDataType() { return databaseInterface.supportsBooleanDataType(); } /** * * @param b Set to true if the database supports a boolean, bit, logical, ... datatype */ public void setSupportsBooleanDataType(boolean b) { databaseInterface.setSupportsBooleanDataType(b); } /** * Changes the names of the fields to their quoted equivalent if this is needed * @param fields The row of fields to change */ public void quoteReservedWords(RowMetaInterface fields) { for (int i=0;i<fields.size();i++) { ValueMetaInterface v = fields.getValueMeta(i); v.setName( quoteField(v.getName()) ); } } /** * @return a map of all the extra URL options you want to set. */ public Map<String, String> getExtraOptions() { return databaseInterface.getExtraOptions(); } /** * @return true if the database supports connection options in the URL, false if they are put in a Properties object. */ public boolean supportsOptionsInURL() { return databaseInterface.supportsOptionsInURL(); } /** * @return extra help text on the supported options on the selected database platform. */ public String getExtraOptionsHelpText() { return databaseInterface.getExtraOptionsHelpText(); } /** * @return true if the database JDBC driver supports getBlob on the resultset. If not we must use getBytes() to get the data. */ public boolean supportsGetBlob() { return databaseInterface.supportsGetBlob(); } /** * @return The SQL to execute right after connecting */ public String getConnectSQL() { return databaseInterface.getConnectSQL(); } /** * @param sql The SQL to execute right after connecting */ public void setConnectSQL(String sql) { databaseInterface.setConnectSQL(sql); } /** * @return true if the database supports setting the maximum number of return rows in a resultset. */ public boolean supportsSetMaxRows() { return databaseInterface.supportsSetMaxRows(); } /** * Verify the name of the database and if required, change it if it already exists in the list of databases. * @param databases the databases to check against. * @param oldname the old name of the database * @return the new name of the database connection */ public String verifyAndModifyDatabaseName(List<DatabaseMeta> databases, String oldname) { String name = getName(); if (name.equalsIgnoreCase(oldname)) return name; // nothing to see here: move along! int nr = 2; while (DatabaseMeta.findDatabase(databases, getName())!=null) { setName(name+" "+nr); nr++; } return getName(); } /** * @return true if we want to use a database connection pool */ public boolean isUsingConnectionPool() { return databaseInterface.isUsingConnectionPool(); } /** * @param usePool true if we want to use a database connection pool */ public void setUsingConnectionPool(boolean usePool) { databaseInterface.setUsingConnectionPool(usePool); } /** * @return the maximum pool size */ public int getMaximumPoolSize() { return databaseInterface.getMaximumPoolSize(); } /** * @param maximumPoolSize the maximum pool size */ public void setMaximumPoolSize(int maximumPoolSize) { databaseInterface.setMaximumPoolSize(maximumPoolSize); } /** * @return the initial pool size */ public int getInitialPoolSize() { return databaseInterface.getInitialPoolSize(); } /** * @param initalPoolSize the initial pool size */ public void setInitialPoolSize(int initalPoolSize) { databaseInterface.setInitialPoolSize(initalPoolSize); } /** * @return true if the connection contains partitioning information */ public boolean isPartitioned() { return databaseInterface.isPartitioned(); } /** * @param partitioned true if the connection is set to contain partitioning information */ public void setPartitioned(boolean partitioned) { databaseInterface.setPartitioned(partitioned); } /** * @return the available partition/host/databases/port combinations in the cluster */ public PartitionDatabaseMeta[] getPartitioningInformation() { if (!isPartitioned()) return new PartitionDatabaseMeta[] {}; return databaseInterface.getPartitioningInformation(); } /** * @param partitionInfo the available partition/host/databases/port combinations in the cluster */ public void setPartitioningInformation(PartitionDatabaseMeta[] partitionInfo) { databaseInterface.setPartitioningInformation(partitionInfo); } /** * Finds the partition metadata for the given partition iD * @param partitionId The partition ID to look for * @return the partition database metadata or null if nothing was found. */ public PartitionDatabaseMeta getPartitionMeta(String partitionId) { PartitionDatabaseMeta[] partitionInfo = getPartitioningInformation(); for (int i=0;i<partitionInfo.length;i++) { if (partitionInfo[i].getPartitionId().equals(partitionId)) return partitionInfo[i]; } return null; } public Properties getConnectionPoolingProperties() { return databaseInterface.getConnectionPoolingProperties(); } public void setConnectionPoolingProperties(Properties properties) { databaseInterface.setConnectionPoolingProperties(properties); } public String getSQLTableExists(String tablename) { return databaseInterface.getSQLTableExists(tablename); } public String getSQLColumnExists(String columnname, String tablename) { return databaseInterface.getSQLColumnExists(columnname,tablename); } public boolean needsToLockAllTables() { return databaseInterface.needsToLockAllTables(); } /** * @return true if the database is streaming results (normally this is an option just for MySQL). */ public boolean isStreamingResults() { return databaseInterface.isStreamingResults(); } /** * @param useStreaming true if we want the database to stream results (normally this is an option just for MySQL). */ public void setStreamingResults(boolean useStreaming) { databaseInterface.setStreamingResults(useStreaming); } /** * @return true if all fields should always be quoted in db */ public boolean isQuoteAllFields() { return databaseInterface.isQuoteAllFields(); } /** * @param quoteAllFields true if all fields in DB should be quoted. */ public void setQuoteAllFields(boolean quoteAllFields) { databaseInterface.setQuoteAllFields(quoteAllFields); } /** * @return true if all identifiers should be forced to lower case */ public boolean isForcingIdentifiersToLowerCase() { return databaseInterface.isForcingIdentifiersToLowerCase(); } /** * @param forceLowerCase true if all identifiers should be forced to lower case */ public void setForcingIdentifiersToLowerCase(boolean forceLowerCase) { databaseInterface.setForcingIdentifiersToLowerCase(forceLowerCase); } /** * @return true if all identifiers should be forced to upper case */ public boolean isForcingIdentifiersToUpperCase() { return databaseInterface.isForcingIdentifiersToUpperCase(); } /** * @param forceLowerCase true if all identifiers should be forced to upper case */ public void setForcingIdentifiersToUpperCase(boolean forceUpperCase) { databaseInterface.setForcingIdentifiersToUpperCase(forceUpperCase); } /** * Find a database with a certain name in an arraylist of databases. * @param databases The ArrayList of databases * @param dbname The name of the database connection * @return The database object if one was found, null otherwise. */ public static final DatabaseMeta findDatabase(List<? extends SharedObjectInterface> databases, String dbname) { if (databases == null) return null; for (int i = 0; i < databases.size(); i++) { DatabaseMeta ci = (DatabaseMeta) databases.get(i); if (ci.getName().equalsIgnoreCase(dbname)) return ci; } return null; } /** * Find a database with a certain ID in an arraylist of databases. * @param databases The ArrayList of databases * @param id The id of the database connection * @return The database object if one was found, null otherwise. */ public static final DatabaseMeta findDatabase(List<DatabaseMeta> databases, ObjectId id) { if (databases == null) return null; for (DatabaseMeta ci : databases) { if (ci.getObjectId()!=null && ci.getObjectId().equals(id)) { return ci; } } return null; } public void copyVariablesFrom(VariableSpace space) { variables.copyVariablesFrom(space); } public String environmentSubstitute(String aString) { return variables.environmentSubstitute(aString); } public String[] environmentSubstitute(String aString[]) { return variables.environmentSubstitute(aString); } public VariableSpace getParentVariableSpace() { return variables.getParentVariableSpace(); } public void setParentVariableSpace(VariableSpace parent) { variables.setParentVariableSpace(parent); } public String getVariable(String variableName, String defaultValue) { return variables.getVariable(variableName, defaultValue); } public String getVariable(String variableName) { return variables.getVariable(variableName); } public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) { if (!Const.isEmpty(variableName)) { String value = environmentSubstitute(variableName); if (!Const.isEmpty(value)) { return ValueMeta.convertStringToBoolean(value); } } return defaultValue; } public void initializeVariablesFrom(VariableSpace parent) { variables.initializeVariablesFrom(parent); } public String[] listVariables() { return variables.listVariables(); } public void setVariable(String variableName, String variableValue) { variables.setVariable(variableName, variableValue); } public void shareVariablesWith(VariableSpace space) { variables = space; } public void injectVariables(Map<String,String> prop) { variables.injectVariables(prop); } /** * @return the SQL Server instance */ public String getSQLServerInstance() { // This is also covered/persisted by JDBC option MS SQL Server / instancename / <somevalue> // We want to return <somevalue> // --> MSSQL.instancename return (String) getExtraOptions().get("MSSQL.instance"); } /** * @param instanceName the SQL Server instance */ public void setSQLServerInstance(String instanceName) { // This is also covered/persisted by JDBC option MS SQL Server / instancename / <somevalue> // We want to return set <somevalue> // --> MSSQL.instancename addExtraOption("MSSQL", "instance", instanceName); } /** * @return true if the Microsoft SQL server uses two decimals (..) to separate schema and table (default==false). */ public boolean isUsingDoubleDecimalAsSchemaTableSeparator() { return databaseInterface.isUsingDoubleDecimalAsSchemaTableSeparator(); } /** * @param useStreaming true if we want the database to stream results (normally this is an option just for MySQL). */ public void setUsingDoubleDecimalAsSchemaTableSeparator(boolean useDoubleDecimalSeparator) { databaseInterface.setUsingDoubleDecimalAsSchemaTableSeparator(useDoubleDecimalSeparator); } /** * @return true if this database needs a transaction to perform a query (auto-commit turned off). */ public boolean isRequiringTransactionsOnQueries() { return databaseInterface.isRequiringTransactionsOnQueries(); } public String testConnection() { StringBuffer report = new StringBuffer(); // If the plug-in needs to provide connection information, we ask the DatabaseInterface... try { DatabaseFactoryInterface factory = getDatabaseFactory(); return factory.getConnectionTestReport(this); } catch (ClassNotFoundException e) { report.append(BaseMessages.getString(PKG, "BaseDatabaseMeta.TestConnectionReportNotImplemented.Message")).append(Const.CR); // $NON-NLS-1 report.append(BaseMessages.getString(PKG, "DatabaseMeta.report.ConnectionError", getName()) + e.toString() + Const.CR); //$NON-NLS-1$ report.append(Const.getStackTracker(e) + Const.CR); } catch (Exception e) { report.append(BaseMessages.getString(PKG, "DatabaseMeta.report.ConnectionError", getName()) + e.toString() + Const.CR); //$NON-NLS-1$ report.append(Const.getStackTracker(e) + Const.CR); } return report.toString(); } public DatabaseFactoryInterface getDatabaseFactory() throws Exception { Class<?> clazz = Class.forName(databaseInterface.getDatabaseFactoryName()); return (DatabaseFactoryInterface)clazz.newInstance(); } public String getPreferredSchemaName() { return databaseInterface.getPreferredSchemaName(); } public void setPreferredSchemaName(String preferredSchemaName) { databaseInterface.setPreferredSchemaName(preferredSchemaName); } /** * Not used in this case, simply return root / */ public RepositoryDirectoryInterface getRepositoryDirectory() { return new RepositoryDirectory(); } public void setRepositoryDirectory(RepositoryDirectoryInterface repositoryDirectory) { throw new RuntimeException("Setting a directory on a database connection is not supported"); } public RepositoryObjectType getRepositoryElementType() { return REPOSITORY_ELEMENT_TYPE; } public ObjectRevision getObjectRevision() { return objectRevision; } public void setObjectRevision(ObjectRevision objectRevision) { this.objectRevision = objectRevision; } public String getDescription() { // NOT USED return null; } public void setDescription(String description) { // NOT USED } public boolean supportsSequenceNoMaxValueOption() { return databaseInterface.supportsSequenceNoMaxValueOption(); } public boolean requiresCreateTablePrimaryKeyAppend() { return databaseInterface.requiresCreateTablePrimaryKeyAppend(); } public boolean requiresCastToVariousForIsNull() { return databaseInterface.requiresCastToVariousForIsNull(); } public boolean isDisplaySizeTwiceThePrecision() { return databaseInterface.isDisplaySizeTwiceThePrecision(); } public boolean supportsPreparedStatementMetadataRetrieval() { return databaseInterface.supportsPreparedStatementMetadataRetrieval(); } public boolean isSystemTable(String tableName) { return databaseInterface.isSystemTable(tableName); } private boolean supportsNewLinesInSQL() { return databaseInterface.supportsNewLinesInSQL(); } public String getSQLListOfSchemas() { return databaseInterface.getSQLListOfSchemas(); } public int getMaxColumnsInIndex() { return databaseInterface.getMaxColumnsInIndex(); } public boolean supportsErrorHandlingOnBatchUpdates() { return databaseInterface.supportsErrorHandlingOnBatchUpdates(); } /** * Get the SQL to insert a new empty unknown record in a dimension. * * @param schemaTable the schema-table name to insert into * @param keyField The key field * @param versionField the version field * @return the SQL to insert the unknown record into the SCD. */ public String getSQLInsertAutoIncUnknownDimensionRow(String schemaTable, String keyField, String versionField) { return databaseInterface.getSQLInsertAutoIncUnknownDimensionRow(schemaTable, keyField, versionField); } /** * @return true if this is a relational database you can explore. * Return false for SAP, PALO, etc. */ public boolean isExplorable() { return databaseInterface.isExplorable(); } /** * * @return The SQL on this database to get a list of sequences. */ public String getSQLListOfSequences() { return databaseInterface.getSQLListOfSequences(); } public String quoteSQLString(String string) { return databaseInterface.quoteSQLString(string); } /** * @see DatabaseInterface#generateColumnAlias(int, String) */ public String generateColumnAlias(int columnIndex, String suggestedName) { return databaseInterface.generateColumnAlias(columnIndex, suggestedName); } public boolean isMySQLVariant() { return databaseInterface.isMySQLVariant(); } public Long getNextBatchId(Database ldb, String schemaName, String tableName, String fieldName) throws KettleDatabaseException { return databaseInterface.getNextBatchId(this, ldb, schemaName, tableName, fieldName); } }
package org.pentaho.di.ui.i18n.editor; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.Props; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.variables.Variables; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.core.dialog.EnterStringDialog; import org.pentaho.di.ui.core.dialog.EnterTextDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.i18n.KeyOccurrence; import org.pentaho.di.ui.i18n.MessagesSourceCrawler; import org.pentaho.di.ui.i18n.editor.Messages; import org.pentaho.di.ui.i18n.MessagesStore; import org.pentaho.di.ui.i18n.TranslationsStore; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.w3c.dom.Document; import org.w3c.dom.Node; public class Translator2 { public static final String APP_NAME = Messages.getString("i18nDialog.ApplicationName"); private Display display; private Shell shell; private LogWriter log; private PropsUI props; /** The crawler that can find and contain all the keys in the source code */ private MessagesSourceCrawler crawler; /** The translations store containing all the translations for all keys, locale, packages */ private TranslationsStore store; /** derived from the crawler */ private java.util.List<String> messagesPackages; private SashForm sashform; private List wLocale; private TableView wPackages; private List wTodo; private String selectedLocale; private String selectedMessagesPackage; private Text wKey; private Text wMain; private Text wValue; private Text wSource; private Button wReload; private Button wClose; private Button wApply; private Button wRevert; private Button wSave; private Button wZip; private Button wSearch; private Button wNext; private Button wSearchV; private Button wNextV; /* private Button wSearchG; private Button wNextG; */ private Button wAll; private String referenceLocale; private java.util.List<String> rootDirectories; private java.util.List<String> localeList; private java.util.List<String> filesToAvoid; protected String lastValue; protected boolean lastValueChanged; protected String selectedKey; protected String searchString; protected String lastFoundKey; private String singleMessagesFile; public Translator2(Display display) { this.display = display; this.log = LogWriter.getInstance(); this.props = PropsUI.getInstance(); } public boolean showKey(String key, String messagesPackage) { return !key.startsWith("System.") || messagesPackage.equals(BaseMessages.class.getPackage().getName()); } public void readFiles(java.util.List<String> directories) throws KettleFileException { log.logBasic(toString(), Messages.getString("i18n.Log.ScanningSourceDirectories")); try { // crawl through the source directories... crawler = new MessagesSourceCrawler(directories, singleMessagesFile); crawler.setFilesToAvoid(filesToAvoid); crawler.setXulDirectories( new String[] { "ui", } ); crawler.crawl(); // get the packages... messagesPackages = crawler.getMessagesPackagesList(); store = new TranslationsStore(localeList, messagesPackages, referenceLocale); // en_US : main locale store.read(directories); // What are the statistics? int nrKeys = 0; int keyCounts[] = new int[localeList.size()]; for (int i=0;i<localeList.size();i++) { String locale = localeList.get(i); // Count the number of keys available in that locale... keyCounts[i]=0; for (KeyOccurrence keyOccurrence : crawler.getOccurrences()) { // We don't want the system keys, just the regular ones. if (showKey(keyOccurrence.getKey(), keyOccurrence.getMessagesPackage())) { String value = store.lookupKeyValue(locale, keyOccurrence.getMessagesPackage(), keyOccurrence.getKey()); if (!Const.isEmpty(value)) { keyCounts[i]++; } if (locale.equals(referenceLocale)) { nrKeys++; } } } } String[] locales = localeList.toArray(new String[localeList.size()]); for (int i=0;i<locales.length;i++) { for (int j=0;j<locales.length-1;j++) { if (keyCounts[j]<keyCounts[j+1]) { int c = keyCounts[j]; keyCounts[j] = keyCounts[j+1]; keyCounts[j+1] = c; String l = locales[j]; locales[j] = locales[j+1]; locales[j+1] = l; } } } DecimalFormat pctFormat = new DecimalFormat("#00.00"); DecimalFormat nrFormat = new DecimalFormat("00"); System.out.println(Messages.getString("i18n.Log.NumberOfKeysFound",""+nrKeys)); for (int i=0;i<locales.length;i++) { double donePct = 100 * (double)keyCounts[i] / (double)nrKeys; int missingKeys = nrKeys - keyCounts[i]; String statusKeys = "# "+nrFormat.format(i+1)+" : "+locales[i]+" : "+pctFormat.format(donePct)+"% complete ("+keyCounts[i]+")" + (missingKeys!=0 ? ("...missing " + missingKeys) : ""); System.out.println(statusKeys); } } catch(Exception e) { throw new KettleFileException(Messages.getString("i18n.Log.UnableToGetFiles",rootDirectories.toString()), e); } } public void loadConfiguration() { // What are the locale to handle? localeList = new ArrayList<String>(); rootDirectories = new ArrayList<String>(); filesToAvoid = new ArrayList<String>(); File file = new File("translator.xml"); if (file.exists()) { try { Document doc = XMLHandler.loadXMLFile(file); Node configNode = XMLHandler.getSubNode(doc, "translator-config"); referenceLocale = XMLHandler.getTagValue(configNode, "reference-locale"); singleMessagesFile = XMLHandler.getTagValue(configNode, "single-messages-file"); Node localeListNode = XMLHandler.getSubNode(configNode, "locale-list"); int nrLocale = XMLHandler.countNodes(localeListNode, "locale"); if (nrLocale>0) localeList.clear(); for (int i=0;i<nrLocale;i++) { Node localeNode = XMLHandler.getSubNodeByNr(localeListNode, "locale", i); String locale = XMLHandler.getTagValue(localeNode, "code"); localeList.add(locale); } Node rootsNode = XMLHandler.getSubNode(configNode, "source-directories"); int nrRoots = XMLHandler.countNodes(rootsNode, "root"); if (nrRoots>0) rootDirectories.clear(); for (int i=0;i<nrRoots;i++) { Node rootNode = XMLHandler.getSubNodeByNr(rootsNode, "root", i); String directory = XMLHandler.getNodeValue(rootNode); rootDirectories.add(directory); } Node filesNode = XMLHandler.getSubNode(configNode, "files-to-avoid"); int nrFiles = XMLHandler.countNodes(filesNode, "filename"); if (nrFiles>0) filesToAvoid.clear(); for (int i=0;i<nrFiles;i++) { Node fileNode = XMLHandler.getSubNodeByNr(filesNode, "filename", i); String filename = XMLHandler.getNodeValue(fileNode); filesToAvoid.add(filename); } } catch (Exception e) { log.logError("Translator", "Error reading translator.xml", e); } } } public void open() { shell = new Shell(display); shell.setLayout(new FillLayout()); shell.setText(APP_NAME); shell.setImage(GUIResource.getInstance().getImageLogoSmall()); try { readFiles(rootDirectories); } catch(Exception e) { new ErrorDialog(shell, "Error reading translations", "There was an unexpected error reading the translations", e); } // Put something on the screen sashform = new SashForm(shell, SWT.HORIZONTAL); sashform.setLayout(new FormLayout()); addLists(); addGrid(); addListeners(); sashform.setWeights(new int[] { 20, 80 }); sashform.setVisible(true); shell.pack(); refresh(); shell.setSize(1024, 768); shell.open(); } private void addListeners() { // In case someone dares to press the [X] in the corner ;-) shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { e.doit=quitFile(); } } ); wReload.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { int idx[] = wPackages.table.getSelectionIndices(); reload(); wPackages.table.setSelection(idx); } } ); wZip.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { saveFilesToZip(); } } ); wClose.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { quitFile(); } } ); } public void reload() { try { shell.setCursor(display.getSystemCursor(SWT.CURSOR_WAIT)); readFiles(rootDirectories); shell.setCursor(null); refresh(); } catch(Exception e) { new ErrorDialog(shell, "Error loading data", "There was an unexpected error re-loading the data", e); } } public boolean quitFile() { java.util.List<MessagesStore> changedMessagesStores = store.getChangedMessagesStores(); if (changedMessagesStores.size()>0) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_WARNING); mb.setMessage(Messages.getString("i18nDialog.ChangedFilesWhenExit",changedMessagesStores.size()+"")); mb.setText(Messages.getString("i18nDialog.Warning")); int answer = mb.open(); if (answer==SWT.NO) return false; } WindowProperty winprop = new WindowProperty(shell); props.setScreen(winprop); props.saveProps(); shell.dispose(); display.dispose(); return true; } private void addLists() { Composite composite = new Composite(sashform, SWT.NONE); props.setLook(composite); FormLayout formLayout = new FormLayout(); formLayout.marginHeight = Const.FORM_MARGIN; formLayout.marginWidth = Const.FORM_MARGIN; composite.setLayout(formLayout); wLocale = new List(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); FormData fdLocale = new FormData(); fdLocale.left = new FormAttachment(0, 0); fdLocale.right = new FormAttachment(100, 0); fdLocale.top= new FormAttachment(0, 0); fdLocale.bottom= new FormAttachment(20, 0); wLocale.setLayoutData(fdLocale); ColumnInfo[] colinfo=new ColumnInfo[] { new ColumnInfo(Messages.getString("i18nDialog.Packagename"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), }; wPackages = new TableView(new Variables(), composite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, true, null, props); FormData fdPackages = new FormData(); fdPackages.left = new FormAttachment(0, 0); fdPackages.right = new FormAttachment(100, 0); fdPackages.top= new FormAttachment(wLocale, Const.MARGIN); fdPackages.bottom= new FormAttachment(100, 0); wPackages.setLayoutData(fdPackages); wPackages.setSortable(false); FormData fdComposite = new FormData(); fdComposite.left = new FormAttachment(0, 0); fdComposite.right = new FormAttachment(100, 0); fdComposite.top= new FormAttachment(0,0); fdComposite.bottom= new FormAttachment(100, 0); composite.setLayoutData(fdComposite); // Add a selection listener. wLocale.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { refreshGrid(); } } ); wPackages.table.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { refreshGrid(); } } ); composite.layout(); } private void addGrid() { Composite composite = new Composite(sashform, SWT.NONE); props.setLook(composite); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; composite.setLayout(formLayout); wReload = new Button(composite, SWT.NONE); wReload.setText(Messages.getString("i18nDialog.Reload")); wSave= new Button(composite, SWT.NONE); wSave.setText(Messages.getString("i18nDialog.Save")); wZip= new Button(composite, SWT.NONE); wZip.setText(Messages.getString("i18nDialog.Zip")); wZip.setToolTipText(Messages.getString("i18nDialog.Zip.Tip")); wClose = new Button(composite, SWT.NONE); wClose.setText(Messages.getString("i18nDialog.Close")); BaseStepDialog.positionBottomButtons(composite, new Button[] { wReload, wSave, wZip, wClose, } , Const.MARGIN*3, null); /* wSearchG = new Button(composite, SWT.PUSH); wSearchG.setText(" Search &key "); FormData fdSearchG = new FormData(); fdSearchG.left = new FormAttachment(0, 0); fdSearchG.bottom = new FormAttachment(100, 0); wSearchG.setLayoutData(fdSearchG); wNextG = new Button(composite, SWT.PUSH); wNextG.setText(" Next ke&y "); FormData fdNextG = new FormData(); fdNextG.left = new FormAttachment(wSearchG, Const.MARGIN); fdNextG.bottom = new FormAttachment(100, 0); wNextG.setLayoutData(fdNextG); */ int left = 25; int middle = 40; wAll = new Button(composite, SWT.CHECK); wAll.setText(Messages.getString("i18nDialog.ShowAllkeys")); props.setLook(wAll); FormData fdAll = new FormData(); fdAll.left = new FormAttachment(0, 0); fdAll.right = new FormAttachment(left, 0); fdAll.bottom= new FormAttachment(wClose, -Const.MARGIN); wAll.setLayoutData(fdAll); Label wlTodo = new Label(composite, SWT.LEFT); props.setLook(wlTodo); wlTodo.setText(Messages.getString("i18nDialog.ToDoList")); FormData fdlTodo = new FormData(); fdlTodo.left = new FormAttachment(0, 0); fdlTodo.right = new FormAttachment(left, 0); fdlTodo.top= new FormAttachment(0, 0); wlTodo.setLayoutData(fdlTodo); wTodo = new List(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); FormData fdTodo = new FormData(); fdTodo.left = new FormAttachment(0, 0); fdTodo.right = new FormAttachment(left, 0); fdTodo.top= new FormAttachment(wlTodo, Const.MARGIN); fdTodo.bottom= new FormAttachment(wAll, -Const.MARGIN); wTodo.setLayoutData(fdTodo); // The key Label wlKey = new Label(composite, SWT.RIGHT); wlKey.setText(Messages.getString("i18nDialog.TranslationKey")); props.setLook(wlKey); FormData fdlKey = new FormData(); fdlKey.left = new FormAttachment(left, Const.MARGIN); fdlKey.right = new FormAttachment(middle, 0); fdlKey.top= new FormAttachment(wlTodo, Const.MARGIN); wlKey.setLayoutData(fdlKey); wKey = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wKey); FormData fdKey = new FormData(); fdKey.left = new FormAttachment(middle, Const.MARGIN); fdKey.right = new FormAttachment(100, 0); fdKey.top= new FormAttachment(wlTodo, Const.MARGIN); wKey.setLayoutData(fdKey); wKey.setEditable(false); // The Main translation Label wlMain = new Label(composite, SWT.RIGHT); wlMain.setText(Messages.getString("i18nDialog.MainTranslation")); props.setLook(wlMain); FormData fdlMain = new FormData(); fdlMain.left = new FormAttachment(left, Const.MARGIN); fdlMain.right = new FormAttachment(middle, 0); fdlMain.top= new FormAttachment(wKey, Const.MARGIN); wlMain.setLayoutData(fdlMain); wMain = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wMain); FormData fdMain = new FormData(); fdMain.left = new FormAttachment(middle, Const.MARGIN); fdMain.right = new FormAttachment(100, 0); fdMain.top= new FormAttachment(wKey, Const.MARGIN); fdMain.bottom= new FormAttachment(wKey, 150+Const.MARGIN); wMain.setLayoutData(fdMain); wMain.setEditable(false); wSearch = new Button(composite, SWT.PUSH); wSearch.setText(Messages.getString("i18nDialog.Search")); FormData fdSearch = new FormData(); fdSearch.right = new FormAttachment(middle, -Const.MARGIN*2); fdSearch.top = new FormAttachment(wMain, 0, SWT.CENTER); wSearch.setLayoutData(fdSearch); wNext = new Button(composite, SWT.PUSH); wNext.setText(Messages.getString("i18nDialog.Next")); FormData fdNext = new FormData(); fdNext.right = new FormAttachment(middle, -Const.MARGIN*2); fdNext.top = new FormAttachment(wSearch, Const.MARGIN*2); wNext.setLayoutData(fdNext); // A few lines of source code at the bottom... Label wlSource = new Label(composite, SWT.RIGHT); wlSource.setText(Messages.getString("i18nDialog.LineOfSourceCode")); props.setLook(wlSource); FormData fdlSource = new FormData(); fdlSource.left = new FormAttachment(left, Const.MARGIN); fdlSource.right = new FormAttachment(middle, 0); fdlSource.top = new FormAttachment(wClose, -100-Const.MARGIN); wlSource.setLayoutData(fdlSource); wSource = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); props.setLook(wSource); FormData fdSource = new FormData(); fdSource.left = new FormAttachment(middle, Const.MARGIN); fdSource.right = new FormAttachment(100, 0); fdSource.top = new FormAttachment(wClose, -100-Const.MARGIN); fdSource.bottom = new FormAttachment(wClose, -Const.MARGIN); wSource.setLayoutData(fdSource); wSource.setEditable(false); // The translation Label wlValue = new Label(composite, SWT.RIGHT); wlValue.setText(Messages.getString("i18nDialog.Translation")); props.setLook(wlValue); FormData fdlValue = new FormData(); fdlValue.left = new FormAttachment(left, Const.MARGIN); fdlValue.right = new FormAttachment(middle, 0); fdlValue.top = new FormAttachment(wMain, Const.MARGIN); wlValue.setLayoutData(fdlValue); wValue = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL ); props.setLook(wValue); FormData fdValue = new FormData(); fdValue.left = new FormAttachment(middle, Const.MARGIN); fdValue.right = new FormAttachment(100, 0); fdValue.top = new FormAttachment(wMain, Const.MARGIN); fdValue.bottom = new FormAttachment(wSource, -Const.MARGIN); wValue.setLayoutData(fdValue); wValue.setEditable(true); wApply = new Button(composite, SWT.PUSH); wApply.setText(Messages.getString("i18nDialog.Apply")); FormData fdApply = new FormData(); fdApply.right = new FormAttachment(middle, -Const.MARGIN*2); fdApply.top = new FormAttachment(wValue, 0, SWT.CENTER); wApply.setLayoutData(fdApply); wApply.setEnabled(false); wRevert = new Button(composite, SWT.PUSH); wRevert.setText(Messages.getString("i18nDialog.Revert")); FormData fdRevert = new FormData(); fdRevert.right = new FormAttachment(middle, -Const.MARGIN*2); fdRevert.top = new FormAttachment(wApply, Const.MARGIN*2); wRevert.setLayoutData(fdRevert); wRevert.setEnabled(false); wSearchV = new Button(composite, SWT.PUSH); wSearchV.setText(Messages.getString("i18nDialog.Search")); FormData fdSearchV = new FormData(); fdSearchV.right = new FormAttachment(middle, -Const.MARGIN*2); fdSearchV.top = new FormAttachment(wRevert, Const.MARGIN*4); wSearchV.setLayoutData(fdSearchV); wNextV = new Button(composite, SWT.PUSH); wNextV.setText(Messages.getString("i18nDialog.Next")); FormData fdNextV = new FormData(); fdNextV.right = new FormAttachment(middle, -Const.MARGIN*2); fdNextV.top = new FormAttachment(wSearchV, Const.MARGIN*2); wNextV.setLayoutData(fdNextV); wAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { refreshGrid(); } } ); wTodo.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // If someone clicks on the todo list, we set the appropriate values if (wTodo.getSelectionCount()==1) { String key = wTodo.getSelection()[0]; showKeySelection(key); } } } ); wValue.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { // The main value got changed... // Capture this automatically lastValueChanged = true; lastValue = wValue.getText(); wApply.setEnabled(true); wRevert.setEnabled(true); } } ); wApply.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { applyChangedValue(); } } ); wRevert.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { revertChangedValue(); } } ); wSave.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { saveFiles(); } } ); wSearch.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { search(referenceLocale); } } ); wNext.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { searchAgain(referenceLocale); } } ); wSearchV.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { search(selectedLocale); } } ); wNextV.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { searchAgain(selectedLocale); } } ); } protected boolean saveFiles() { java.util.List<MessagesStore> changedMessagesStores = store.getChangedMessagesStores(); if (changedMessagesStores.size()>0) { StringBuffer msg = new StringBuffer(); for (MessagesStore messagesStore : changedMessagesStores) { // Find the main locale variation for this messages store... MessagesStore mainLocaleMessagesStore = store.findMainLocaleMessagesStore(messagesStore.getMessagesPackage()); String sourceDirectory = mainLocaleMessagesStore.getSourceDirectory(rootDirectories); String filename = messagesStore.getSaveFilename(sourceDirectory); messagesStore.setFilename(filename); msg.append(filename).append(Const.CR); } EnterTextDialog dialog = new EnterTextDialog(shell, Messages.getString("i18nDialog.ChangedFiles"), Messages.getString("i18nDialog.ChangedMessagesFiles"), msg.toString()); if (dialog.open()!=null) { try { for (MessagesStore messagesStore : changedMessagesStores) { messagesStore.write(); LogWriter.getInstance().logBasic(toString(), Messages.getString("i18n.Log.SavedMessagesFile",messagesStore.getFilename())); } } catch(KettleException e) { new ErrorDialog(shell, Messages.getString("i18n.UnexpectedError"), "There was an error saving the changed messages files:", e); return false; } return true; } else { return false; } } else { // Nothing was saved. // TODO: disable the button if nothing changed. return true; } } protected void saveFilesToZip() { if (saveFiles()) { java.util.List<MessagesStore> messagesStores = store.getMessagesStores(selectedLocale, null); if (messagesStores.size()>0) { StringBuffer msg = new StringBuffer(); for (MessagesStore messagesStore : messagesStores) { // Find the main locale variation for this messages store... MessagesStore mainLocaleMessagesStore = store.findMainLocaleMessagesStore(messagesStore.getMessagesPackage()); String sourceDirectory = mainLocaleMessagesStore.getSourceDirectory(rootDirectories); String filename = messagesStore.getSaveFilename(sourceDirectory); messagesStore.setFilename(filename); msg.append(filename).append(Const.CR); } // Ask for the target filename if we're still here... FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*.zip", "*"}); dialog.setFilterNames(new String[] {Messages.getString("System.FileType.ZIPFiles"), Messages.getString("System.FileType.AllFiles")}); if (dialog.open()!=null) { String zipFilename = dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName(); try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename)); byte[] buf = new byte[1024]; for (MessagesStore messagesStore : messagesStores) { FileInputStream in = new FileInputStream(messagesStore.getFilename()); out.putNextEntry(new ZipEntry(messagesStore.getFilename())); int len; while ((len=in.read(buf))>0) { out.write(buf,0,len); } out.closeEntry(); in.close(); } out.close(); } catch(Exception e) { new ErrorDialog(shell, Messages.getString("i18n.UnexpectedError"), "There was an error saving the changed messages files:", e); } } } } } protected void search(String searchLocale) { // Ask for the search string... EnterStringDialog dialog = new EnterStringDialog(shell, Const.NVL(searchString, ""), Messages.getString("i18nDialog.SearchKey"),"Search the translated '"+searchLocale+"' strings in this package"); searchString = dialog.open(); lastFoundKey = null; searchAgain(searchLocale); } protected void searchAgain(String searchLocale) { if (searchString!=null) { // We want to search for key in the list here... // That means we'll enter a String to search for in the values String upperSearchString = searchString.toUpperCase(); boolean lastKeyFound = lastFoundKey==null; // Search through all the main locale messages stores for the selected package java.util.List<MessagesStore> mainLocaleMessagesStores = store.getMessagesStores(searchLocale, selectedMessagesPackage); for (MessagesStore messagesStore : mainLocaleMessagesStores) { for (String key : messagesStore.getMessagesMap().keySet()) { String value = messagesStore.getMessagesMap().get(key); String upperValue = value.toUpperCase(); if (upperValue.indexOf(upperSearchString)>=0) { // OK, we found a key worthy of our attention... if (lastKeyFound) { int index = wTodo.indexOf(key); if (index>=0) { lastFoundKey = key; wTodo.setSelection(index); showKeySelection(wTodo.getSelection()[0]); return; } } if (key.equals(lastFoundKey)) { lastKeyFound=true; } } } } } } protected void showKeySelection(String key) { if (!key.equals(selectedKey)) { applyChangedValue(); } if (selectedLocale!=null && key!=null && selectedMessagesPackage!=null) { String mainValue = store.lookupKeyValue(referenceLocale, selectedMessagesPackage, key); String value = store.lookupKeyValue(selectedLocale, selectedMessagesPackage, key); KeyOccurrence keyOccurrence = crawler.getKeyOccurrence(key, selectedMessagesPackage); wKey.setText(key); wMain.setText(Const.NVL(mainValue, "")); wValue.setText(Const.NVL(value, "")); wSource.setText(keyOccurrence.getSourceLine()); // Focus on the entry field // Put the cursor all the way at the back wValue.setFocus(); wValue.setSelection(wValue.getText().length()); wValue.showSelection(); wValue.clearSelection(); selectedKey = key; lastValueChanged=false; wApply.setEnabled(false); wRevert.setEnabled(false); } } public void refreshGrid() { applyChangedValue(); wTodo.removeAll(); wKey.setText(""); wMain.setText(""); wValue.setText(""); wSource.setText(""); selectedLocale = wLocale.getSelectionCount()==0 ? null : wLocale.getSelection()[0]; selectedMessagesPackage = wPackages.table.getSelectionCount()==0 ? null : wPackages.table.getSelection()[0].getText(1); refreshPackages(); // Only continue with a locale & a messages package, otherwise we won't budge ;-) if (selectedLocale!=null && selectedMessagesPackage!=null) { // Get the list of keys that need a translation... java.util.List<KeyOccurrence> todo = getTodoList(selectedLocale, selectedMessagesPackage, false); String[] todoItems = new String[todo.size()]; for (int i=0;i<todoItems.length;i++) todoItems[i] = todo.get(i).getKey(); wTodo.setItems(todoItems); } } private java.util.List<KeyOccurrence> getTodoList(String locale, String messagesPackage, boolean strict) { // Get the list of keys that need a translation... java.util.List<KeyOccurrence> keys = crawler.getOccurrencesForPackage(messagesPackage); java.util.List<KeyOccurrence> todo = new ArrayList<KeyOccurrence>(); for (KeyOccurrence keyOccurrence : keys) { // Avoid the System keys. Those are taken care off in a different package if (showKey(keyOccurrence.getKey(), keyOccurrence.getMessagesPackage())) { String value = store.lookupKeyValue(locale, messagesPackage, keyOccurrence.getKey()); if ( Const.isEmpty(value) || ( wAll.getSelection() && !strict) ) { todo.add(keyOccurrence); } } } return todo; } private void applyChangedValue() { // Hang on, before we clear it all, did we have a previous value? int todoIndex = wTodo.getSelectionIndex(); if (selectedKey!=null && selectedLocale!=null && selectedMessagesPackage!=null && lastValueChanged) { // Store the last modified value if (!Const.isEmpty(lastValue)) { store.storeValue(selectedLocale, selectedMessagesPackage, selectedKey, lastValue); lastValueChanged = false; if (!wAll.getSelection()) { wTodo.remove(selectedKey); if (wTodo.getSelectionIndex()<0) { // Select the next one in the list... if (todoIndex>wTodo.getItemCount()) todoIndex=wTodo.getItemCount()-1; if (todoIndex>=0 && todoIndex<wTodo.getItemCount()) { wTodo.setSelection(todoIndex); showKeySelection(wTodo.getSelection()[0]); } else { refreshGrid(); } } } } lastValue = null; wApply.setEnabled(false); wRevert.setEnabled(false); } } private void revertChangedValue() { lastValueChanged = false; refreshGrid(); } public void refresh() { refreshLocale(); refreshPackages(); refreshGrid(); } public void refreshPackages() { int index = wPackages.getSelectionIndex(); // OK, we have a distinct list of packages to work with... wPackages.table.removeAll(); for (int i=0;i<messagesPackages.size();i++) { String messagesPackage = messagesPackages.get(i); TableItem item = new TableItem(wPackages.table, SWT.NONE); item.setText(1, messagesPackage); // count the number of keys for the package that are NOT yet translated... if (selectedLocale!=null) { java.util.List<KeyOccurrence> todo = getTodoList(selectedLocale, messagesPackage, true); if (todo.size()>50) { item.setBackground(GUIResource.getInstance().getColorRed()); } else if (todo.size()>25) { item.setBackground(GUIResource.getInstance().getColorOrange()); } else if (todo.size()>10) { item.setBackground(GUIResource.getInstance().getColorYellow()); } else if (todo.size()>5) { item.setBackground(GUIResource.getInstance().getColorGray()); } else if (todo.size()>0) { item.setBackground(GUIResource.getInstance().getColorGreen()); } } } if (messagesPackages.size()==0) { new TableItem(wPackages.table, SWT.NONE); } else { wPackages.setRowNums(); wPackages.optWidth(true); } if (index>=0) { wPackages.table.setSelection(index); wPackages.table.showSelection(); } } public void refreshLocale() { // OK, we have a distinct list of locale to work with... wLocale.removeAll(); wLocale.setItems(localeList.toArray(new String[localeList.size()])); } public String toString() { return APP_NAME; } public static void main(String[] args) { Display display = new Display(); LogWriter log = LogWriter.getInstance(); PropsUI.init(display, Props.TYPE_PROPERTIES_SPOON); Translator2 translator = new Translator2(display); translator.loadConfiguration(); translator.open(); try { while (!display.isDisposed ()) { if (!display.readAndDispatch()) display.sleep (); } } catch(Throwable e) { log.logError(APP_NAME, Messages.getString("i18n.UnexpectedError",e.getMessage())); log.logError(APP_NAME, Const.getStackTracker(e)); } } }
package processing_test; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; import net.iharder.dnd.FileDrop; /** * @author nikla_000 */ public class DisplayFrame extends JFrame implements ActionListener { //private final CircleSketch sketch; private final JButton fileChooseButton; private final JButton button; private final JButton fncButton2; private final JButton fncButton3; private final JButton fncButton4; private final JButton clearButton; private final JButton doubleSpeed; private final JButton tripleSpeed; private final JButton saveButton; private final JButton blankButton; private final JButton backButton; private final JButton forwardButton; private final JButton cloneButton; private final JButton setPoints; private final JButton newTab; private final JButton closeTab; private final JComboBox functionChooser; private final JTabbedPane sketchTabs; private final JLabel step2; private final JLabel step3; private final JLabel sliderLabel; private ImageIcon[] functionIcons; private String[] functionNames = {"Original", "Dots", "Squares"}; private final JSlider slider; private final JSlider cloneRadiusSlider; private int tabIndex; private int tabs = 2; private ArrayList<Component> componentList; private SampleSketch currentSketch; /** * Constructor for instances of class DisplayFrame. Initializes all * components of the GUI as well as the processing sketch. */ public DisplayFrame() throws IOException { this.setSize(1670, 850); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); componentList = new ArrayList<>(); button = new JButton("Start"); fncButton2 = new JButton("Pixelate"); fncButton3 = new JButton("Show dots"); fncButton4 = new JButton("MapTo3D"); clearButton = new JButton("Clear Canvas"); doubleSpeed = new JButton("2X Speed"); tripleSpeed = new JButton("3X Speed"); cloneButton = new JButton("Clone"); setPoints = new JButton("Set Points"); newTab = new JButton("New Tab"); closeTab = new JButton(new ImageIcon(ImageIO.read(new File("graphics/X.gif")))); sketchTabs = new JTabbedPane(); functionIcons = new ImageIcon[functionNames.length]; Integer[] intArray = new Integer[functionNames.length]; fileChooseButton = new JButton(new ImageIcon(ImageIO.read(new File("graphics/OpenButton.gif")))); saveButton = new JButton(new ImageIcon(ImageIO.read(new File("graphics/Save-icon.png")))); blankButton = new JButton(new ImageIcon(ImageIO.read(new File("graphics/blank.jpg")))); backButton = new JButton("<"); forwardButton = new JButton(">"); step2 = new JLabel("Step2: Choose a function"); step3 = new JLabel("Step3: Edit the result"); sliderLabel = new JLabel("Change size of \"pixels\""); slider = new JSlider(JSlider.HORIZONTAL, 4, 30, 20); cloneRadiusSlider = new JSlider(JSlider.HORIZONTAL, 1, 50, 25); fncButton3.setToolTipText("Show a dot representation for your picture"); for (int i = 0; i < functionNames.length; i++) { intArray[i] = i; functionIcons[i] = createImageIcon("graphics/" + functionNames[i] + ".png"); if (functionIcons[i] != null) { functionIcons[i].setDescription(functionNames[i]); } } functionChooser = new JComboBox(intArray); ComboBoxRenderer rend = new ComboBoxRenderer(); rend.setPreferredSize(new Dimension(150, 90)); functionChooser.setRenderer(rend); functionChooser.setMaximumRowCount(3); componentList.add(clearButton); componentList.add(backButton); componentList.add(forwardButton); componentList.add(blankButton); componentList.add(cloneButton); componentList.add(setPoints); componentList.add(slider); componentList.add(fileChooseButton); componentList.add(saveButton); componentList.add(functionChooser); arrangeLayout(); sketchTabs.addTab("Sketch 1", createNewSketch()); this.add(fileChooseButton); this.add(clearButton); this.add(step2); this.add(step3); this.add(sliderLabel); this.add(slider); this.add(cloneRadiusSlider); this.add(saveButton); this.add(blankButton); this.add(backButton); this.add(forwardButton); this.add(cloneButton); this.add(setPoints); add(functionChooser); add(sketchTabs); add(newTab); add(closeTab); tabIndex = sketchTabs.getSelectedIndex(); currentSketch = (SampleSketch) sketchTabs.getSelectedComponent(); setActionListeners(currentSketch); setLocalActionListeners(); sketchTabs.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (tabIndex != sketchTabs.getSelectedIndex()) { removeOldActionListeners(currentSketch); SampleSketch newSketch = (SampleSketch) sketchTabs.getSelectedComponent(); setActionListeners(newSketch); currentSketch = newSketch; tabIndex = sketchTabs.getSelectedIndex(); } } }); this.setVisible(true); } private void newTab() { sketchTabs.addTab("Sketch " + tabs, createNewSketch()); sketchTabs.setSelectedIndex(sketchTabs.getTabCount() - 1); tabs++; } /** * Creates and instance of the processing sketch class SampleSketch. * * @return The created sketch. */ private SampleSketch createNewSketch() { SampleSketch newSketch = new SampleSketch(); newSketch.setButtons(forwardButton, backButton); new FileDrop(newSketch, new FileDrop.Listener() { @Override public void filesDropped(File[] files) { String fileName = files[0].getAbsolutePath(); if (fileName.endsWith("jpg") || fileName.endsWith("png") || fileName.endsWith("gif")) { newSketch.loadBgImage(files[0]); } else { JOptionPane.showMessageDialog(newSketch, "This it not a picture. Please drop an image with jpg, png or gif format."); } } }); newSketch.init(); return newSketch; } /** * Creates an ImageIcon * * @param path * @return */ protected static ImageIcon createImageIcon(String path) { ImageIcon icon = null; try { icon = new ImageIcon(ImageIO.read(new File(path))); } catch (IOException ex) { } return icon; } /** * Arranges the layout of the panel and buttons. */ private void arrangeLayout() { setLayout(null); //Position and size for buttons. closeTab.setBounds(1267, 50, 35, 35); newTab.setBounds(600, 10, 100, 50); blankButton.setBounds(20, 10, 50, 50); saveButton.setBounds(80, 10, 50, 50); fileChooseButton.setBounds(140, 10, 50, 50); backButton.setBounds(220, 10, 50, 50); forwardButton.setBounds(280, 10, 50, 50); cloneButton.setBounds(340, 10, 100, 50); setPoints.setBounds(450, 10, 100, 50); fncButton2.setBounds(1320, 275, 100, 50); fncButton3.setBounds(1435, 275, 100, 50); fncButton4.setBounds(1320, 330, 100, 50); sketchTabs.setBounds(20, 70, 1282, 722); button.setBounds(1320, 1445, 100, 50); clearButton.setBounds(1320, 420, 215, 50); doubleSpeed.setBounds(1320, 490, 100, 50); tripleSpeed.setBounds(1435, 490, 100, 50); slider.setBounds(1320, 590, 215, 20); cloneRadiusSlider.setBounds(490, 10, 215, 20); functionChooser.setBounds(1320, 10, 300, 120); //Position and size for labels step2.setBounds(1320, 235, 150, 30); step3.setBounds(1320, 380, 150, 30); sliderLabel.setBounds(1360, 560, 150, 30); //saveButton.setBorder(BorderFactory.createEmptyBorder()); //saveButton.setContentAreaFilled(false); } /** * Removes action listeners for components. * * @param removeFrom A pointer to the instance of the sketch where the * listeners will be removed from */ private void removeOldActionListeners(SampleSketch removeFrom) { for (Component c : componentList) { if (c instanceof JButton) { JButton b = (JButton) c; for (ActionListener a : b.getActionListeners()) { b.removeActionListener(a); } } else if (c instanceof JSlider) { JSlider s = (JSlider) c; for (ChangeListener ch : s.getChangeListeners()) { s.removeChangeListener(ch); } } else if (c instanceof JComboBox) { JComboBox cb = (JComboBox) c; for (ItemListener il : cb.getItemListeners()) { cb.removeItemListener(il); } } } } private void setLocalActionListeners() { newTab.addActionListener(this); newTab.setActionCommand("newTab"); blankButton.addActionListener(this); blankButton.setActionCommand("blank"); closeTab.addActionListener(this); closeTab.setActionCommand("closeTab"); } /** * Adds action listener to all relevant components * * @param s The processing sketch where buttons execute the listener. */ private void setActionListeners(SampleSketch s) { clearButton.addActionListener(s); clearButton.setActionCommand("clear"); backButton.addActionListener(s); backButton.setActionCommand("back"); forwardButton.addActionListener(s); forwardButton.setActionCommand("forward"); cloneButton.addActionListener(s); cloneButton.setActionCommand("clone"); setPoints.addActionListener(s); setPoints.setActionCommand("setPoints"); slider.addChangeListener(s); cloneRadiusSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { currentSketch.cloneRadChanged(cloneRadiusSlider.getValue()); } }); fileChooseButton.addActionListener((ActionEvent arg0) -> { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG, GIF & PNG", "jpg", "gif", "png"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(sketchTabs); if (returnVal == JFileChooser.APPROVE_OPTION) { s.loadBgImage(chooser.getSelectedFile()); } }); saveButton.addActionListener((ActionEvent arg0) -> { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG: png", "png")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG: jpg & jpeg", "jpg", "jpeg")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("TIF: tif", "tif")); int returnVal = chooser.showOpenDialog(sketchTabs); if (returnVal == JFileChooser.APPROVE_OPTION) { s.saveImage(chooser.getSelectedFile()); } }); functionChooser.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { s.selectFunction(functionNames[(int) e.getItem()]); } } }); } /** * Creates a dialog asking the user whether or not they want to reset. * * @return */ private boolean wantToReset() { int dialogButton = JOptionPane.YES_NO_OPTION; int dialogResult = JOptionPane.showConfirmDialog(null, "All unsaved progress will be lost, " + "are you sure you want to do this?", "Warning", dialogButton); return dialogResult == JOptionPane.YES_OPTION; } @Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "blank": if (wantToReset()) { currentSketch.reset(); } break; case "newTab": newTab(); break; case "closeTab": sketchTabs.remove(sketchTabs.getSelectedIndex()); if (sketchTabs.getTabCount() < 1) { newTab(); } } } // public void chooseFile() { // JFileChooser chooser = new JFileChooser(); // FileNameExtensionFilter filter = new FileNameExtensionFilter( // "JPG, GIF & PNG", "jpg", "gif", "png"); // chooser.setFileFilter(filter); // int returnVal = chooser.showOpenDialog(this); // if (returnVal == JFileChooser.APPROVE_OPTION) { // imageProcessor.setCurrentImage(chooser.getSelectedFile().getAbsolutePath()); class ComboBoxRenderer extends JLabel implements ListCellRenderer { private Font uhOhFont; public ComboBoxRenderer() { setOpaque(true); setHorizontalAlignment(CENTER); setVerticalAlignment(CENTER); } /* * This method finds the image and text corresponding * to the selected value and returns the label, set up * to display the text and image. */ public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { //Get the selected index. (The index param isn't //always valid, so just use the value.) int selectedIndex = ((Integer) value).intValue(); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } //Set the icon and text. If icon was null, say so. ImageIcon icon = functionIcons[selectedIndex]; String function = functionNames[selectedIndex]; setIcon(icon); if (icon != null) { setText(function); setFont(list.getFont()); } else { setUhOhText(function + " (no image available)", list.getFont()); } return this; } //Set the font and text when no image was found. protected void setUhOhText(String uhOhText, Font normalFont) { if (uhOhFont == null) { //lazily create this font uhOhFont = normalFont.deriveFont(Font.ITALIC); } setFont(uhOhFont); setText(uhOhText); } } }
package com.legit2.Demigods.Listeners; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.legit2.Demigods.DConfig; import com.legit2.Demigods.DDivineBlocks; import com.legit2.Demigods.Demigods; import com.legit2.Demigods.DTributeValue; import com.legit2.Demigods.Utilities.DCharUtil; import com.legit2.Demigods.Utilities.DDataUtil; import com.legit2.Demigods.Utilities.DPlayerUtil; import com.legit2.Demigods.Utilities.DMiscUtil; public class DDivineBlockListener implements Listener { static Demigods plugin; public static double FAVORMULTIPLIER = DConfig.getSettingDouble("global_favor_multiplier"); public static int RADIUS = 8; public DDivineBlockListener(Demigods instance) { plugin = instance; } @EventHandler(priority = EventPriority.HIGH) public void shrineBlockInteract(PlayerInteractEvent event) { // Return if the player is mortal if(!DCharUtil.isImmortal(event.getPlayer())) return; if(event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Define variables Location location = event.getClickedBlock().getLocation(); Player player = event.getPlayer(); int charID = DPlayerUtil.getCurrentChar(player); String charAlliance = DCharUtil.getAlliance(charID); String charDeity = DCharUtil.getDeity(charID); if(event.getClickedBlock().getType().equals(Material.GOLD_BLOCK) && event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getPlayer().getItemInHand().getType() == Material.BOOK) { try { // Shrine created! ArrayList<Location> locations = new ArrayList<Location>(); locations.add(location); DDivineBlocks.createShrine(charID, locations); location.getWorld().getBlockAt(location).setType(Material.BEDROCK); location.getWorld().spawnEntity(location.add(0.5, 0.0, 0.5), EntityType.ENDER_CRYSTAL); location.getWorld().strikeLightningEffect(location); player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + charAlliance + "s" + ChatColor.GRAY + " are pleased..."); player.sendMessage(ChatColor.GRAY + "A shrine has been created in honor of " + ChatColor.YELLOW + charDeity + ChatColor.GRAY + "!"); } catch(Exception e) { // Creation of shrine failed... e.printStackTrace(); } } } @EventHandler(priority = EventPriority.HIGH) public void shrineEntityInteract(PlayerInteractEntityEvent event) { // Return if the player is mortal if(!DCharUtil.isImmortal(event.getPlayer())) return; // Define variables Location location = event.getRightClicked().getLocation().subtract(0.5, 0, 0.5); Player player = event.getPlayer(); int charID = DPlayerUtil.getCurrentChar(player); try { // Check if block is divine int shrineOwner = DDivineBlocks.getShrineOwner(location); String shrineDeity = DDivineBlocks.getShrineDeity(location); OfflinePlayer charOwner = DCharUtil.getOwner(shrineOwner); if(shrineDeity == null) return; if(DDivineBlocks.isDivineBlock(location)) { // Check if character has deity if(DCharUtil.hasDeity(charID, shrineDeity)) { // Open the tribute inventory Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, charOwner.getName() + "'s Shrine to " + shrineDeity); player.openInventory(ii); DDataUtil.saveCharData(charID, "temp_tributing", shrineOwner); event.setCancelled(true); return; } player.sendMessage(ChatColor.YELLOW + "You must be allied to " + shrineDeity + " in order to tribute here."); } } catch(Exception e) {} } @EventHandler(priority = EventPriority.MONITOR) public void playerTribute(InventoryCloseEvent event) { try { if(!(event.getPlayer() instanceof Player)) return; Player player = (Player)event.getPlayer(); int charID = DPlayerUtil.getCurrentChar(player); if(!DCharUtil.isImmortal(player)) return; // If it isn't a tribute chest then break the method if(!event.getInventory().getName().contains("Shrine")) return; // Get the creator of the shrine //int shrineCreator = DDivineBlocks.getShrineOwner((Location) DDataUtil.getCharData(charID, "temp_tributing")); DDataUtil.removeCharData(charID, "temp_tributing"); //calculate value of chest int tributeValue = 0, items = 0; for(ItemStack ii : event.getInventory().getContents()) { if(ii != null) { tributeValue += DTributeValue.getTributeValue(ii); items ++; } } tributeValue *= FAVORMULTIPLIER; // Give devotion int devotionBefore = DCharUtil.getDevotion(charID); DCharUtil.giveDevotion(charID, tributeValue); DCharUtil.giveDevotion(charID, tributeValue / 7); // Give favor int favorBefore = DCharUtil.getMaxFavor(charID); DCharUtil.addMaxFavor(charID, tributeValue / 5); // Devotion lock TODO String charName = DCharUtil.getName(charID); if(devotionBefore < DCharUtil.getDevotion(charID)) player.sendMessage(ChatColor.YELLOW + "Your devotion to " + charName + " has increased to " + DCharUtil.getDevotion(charID) + "."); if(favorBefore < DCharUtil.getMaxFavor(charID)) player.sendMessage(ChatColor.YELLOW + "Your favor cap has increased to " + DCharUtil.getMaxFavor(charID) + "."); if((favorBefore == DCharUtil.getMaxFavor(charID)) && (devotionBefore == DCharUtil.getDevotion(charID)) && (items > 0)) player.sendMessage(ChatColor.YELLOW + "Your tributes were insufficient for " + charName + "'s blessings."); // Clear the tribute case event.getInventory().clear(); } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGH) public void divineBlockAlerts(PlayerMoveEvent event) { if(event.getFrom().distance(event.getTo()) < 0.1) return; // Define variables for(Location divineBlock : DDivineBlocks.getAllShrines()) { OfflinePlayer charOwner = DCharUtil.getOwner(DDivineBlocks.getShrineOwner(divineBlock)); // Check for world errors if(!divineBlock.getWorld().equals(event.getPlayer().getWorld())) return; if(event.getFrom().getWorld() != divineBlock.getWorld()) return; /* * Entering */ if(event.getFrom().distance(divineBlock) > RADIUS) { if(divineBlock.distance(event.getTo()) <= RADIUS) { event.getPlayer().sendMessage(ChatColor.GRAY + "You have entered " + charOwner.getName() + "'s shrine to " + ChatColor.YELLOW + DDivineBlocks.getShrineDeity(divineBlock) + ChatColor.GRAY + "."); return; } } /* * Leaving */ else if(event.getFrom().distance(divineBlock) <= RADIUS) { if(divineBlock.distance(event.getTo()) > RADIUS) { event.getPlayer().sendMessage(ChatColor.GRAY + "You have left a holy area."); return; } } } } @EventHandler(priority = EventPriority.HIGHEST) public static void stopDestroyEnderCrystal(EntityDamageEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getEntity().getLocation().subtract(0.5, 0, 0.5).equals(divineBlock)) { event.setDamage(0); event.setCancelled(true); return; } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public static void stopDestroyDivineBlock(BlockBreakEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.getPlayer().sendMessage(ChatColor.YELLOW + "Divine blocks cannot be broken by hand."); event.setCancelled(true); return; } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockDamage(BlockDamageEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockIgnite(BlockIgniteEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockBurn(BlockBurnEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockPistonExtend(BlockPistonExtendEvent event) { List<Block> blocks = event.getBlocks(); CHECKBLOCKS: for(Block block : blocks) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(block.getLocation().equals(divineBlock)) { event.setCancelled(true); break CHECKBLOCKS; } } } catch(Exception e) { e.printStackTrace(); } } } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockPistonRetract(BlockPistonRetractEvent event) { // Define variables final Block block = event.getBlock().getRelative(event.getDirection(), 2); try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(block.getLocation().equals((divineBlock)) && event.isSticky()) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void divineBlockExplode(final EntityExplodeEvent event) { try { // Remove divineBlock blocks from explosions Iterator<Block> i = event.blockList().iterator(); while(i.hasNext()) { Block block = i.next(); if(!DMiscUtil.canLocationPVP(block.getLocation())) i.remove(); for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(block.getLocation().equals(divineBlock)) i.remove(); } } } catch (Exception er) {} } }
package com.mrpowergamerbr.loritta.commands; import java.io.File; import java.io.IOException; import java.io.InputStream; import com.mrpowergamerbr.loritta.Loritta; import com.mrpowergamerbr.loritta.userdata.ServerConfig; import com.mrpowergamerbr.loritta.utils.LorittaUser; import lombok.Getter; import net.dv8tion.jda.core.MessageBuilder; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.MessageEmbed; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; /** * Contexto do comando executado */ @Getter public class CommandContext { private LorittaUser lorittaUser; private MessageReceivedEvent event; private CommandBase cmd; private String[] args; public CommandContext(ServerConfig conf, MessageReceivedEvent event, CommandBase cmd, String[] args) { this.lorittaUser = new LorittaUser(event.getMember(), conf); this.event = event; this.cmd = cmd; this.args = args; } public CommandContext(Member member, ServerConfig conf, MessageReceivedEvent event, CommandBase cmd, String[] args) { this.lorittaUser = new LorittaUser(member, conf); this.event = event; this.cmd = cmd; this.args = args; } public void explain() { cmd.explain(lorittaUser.getConfig(), event); } public Message getMessage() { return event.getMessage(); } public ServerConfig getConfig() { return lorittaUser.getConfig(); } public Member getHandle() { return lorittaUser.getMember(); } public User getUserHandle() { return lorittaUser.getMember().getUser(); } public String getAsMention() { return lorittaUser.getAsMention(); } public String getAsMention(boolean addSpace) { return lorittaUser.getAsMention(addSpace); } public Guild getGuild() { return event.getGuild(); } public void sendMessage(String message) { sendMessage(new MessageBuilder().append(message).build()); } public void sendMessage(Message message) { boolean privateReply = getLorittaUser().getConfig().commandOutputInPrivate(); CommandOptions cmdOptions = getLorittaUser().getConfig().getCommandOptionsFor(cmd); if (cmdOptions.commandOutputInPrivate()) { privateReply = cmdOptions.commandOutputInPrivate(); } if (privateReply) { getLorittaUser().getMember().getUser().openPrivateChannel().queue((t) -> { t.sendMessage(message).complete(); }); } else { if (event.getTextChannel().canTalk()) { event.getTextChannel().sendMessage(message).complete(); } else { Loritta.warnOwnerNoPermission(getGuild(), event.getTextChannel(), lorittaUser.getConfig()); } } } public void sendMessage(MessageEmbed embed) { boolean privateReply = getLorittaUser().getConfig().commandOutputInPrivate(); CommandOptions cmdOptions = getLorittaUser().getConfig().getCommandOptionsFor(cmd); if (cmdOptions.commandOutputInPrivate()) { privateReply = cmdOptions.commandOutputInPrivate(); } if (privateReply) { getLorittaUser().getMember().getUser().openPrivateChannel().queue((t) -> { t.sendMessage(embed).complete(); }); } else { if (event.getTextChannel().canTalk()) { event.getTextChannel().sendMessage(embed).complete(); } else { Loritta.warnOwnerNoPermission(getGuild(), event.getTextChannel(), lorittaUser.getConfig()); } } } public void sendFile(InputStream data, String name, String message) { sendFile(data, name, new MessageBuilder().append(message).build()); } public void sendFile(InputStream data, String name, Message message) { boolean privateReply = getLorittaUser().getConfig().commandOutputInPrivate(); CommandOptions cmdOptions = getLorittaUser().getConfig().getCommandOptionsFor(cmd); if (cmdOptions.commandOutputInPrivate()) { privateReply = cmdOptions.commandOutputInPrivate(); } if (privateReply) { getLorittaUser().getMember().getUser().openPrivateChannel().queue((t) -> { t.sendFile(data, name, message).complete(); }); } else { if (event.getTextChannel().canTalk()) { event.getTextChannel().sendFile(data, name, message).complete(); } else { Loritta.warnOwnerNoPermission(getGuild(), event.getTextChannel(), lorittaUser.getConfig()); } } } public void sendFile(File file, String name, String message) throws IOException { sendFile(file, name, new MessageBuilder().append(message).build()); } public void sendFile(File file, String name, Message message) throws IOException { boolean privateReply = getLorittaUser().getConfig().commandOutputInPrivate(); CommandOptions cmdOptions = getLorittaUser().getConfig().getCommandOptionsFor(cmd); if (cmdOptions.commandOutputInPrivate()) { privateReply = cmdOptions.commandOutputInPrivate(); } if (privateReply) { getLorittaUser().getMember().getUser().openPrivateChannel().queue((t) -> { try { t.sendFile(file, name, message).complete(); } catch (IOException e) { e.printStackTrace(); } }); } else { if (event.getTextChannel().canTalk()) { event.getTextChannel().sendFile(file, name, message).complete(); } else { Loritta.warnOwnerNoPermission(getGuild(), event.getTextChannel(), lorittaUser.getConfig()); } } } }
package com.paginate.recycler; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; class WrapperAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int ITEM_VIEW_TYPE_LOADING = Integer.MAX_VALUE - 50; // Magic private final RecyclerView.Adapter<RecyclerView.ViewHolder> wrappedAdapter; private final LoadingListItemCreator loadingListItemCreator; private boolean displayLoadingRow = true; public WrapperAdapter(RecyclerView.Adapter<RecyclerView.ViewHolder> adapter, LoadingListItemCreator creator) { this.wrappedAdapter = adapter; this.loadingListItemCreator = creator; this.setHasStableIds(adapter.hasStableIds()); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == ITEM_VIEW_TYPE_LOADING) { return loadingListItemCreator.onCreateViewHolder(parent, viewType); } else { return wrappedAdapter.onCreateViewHolder(parent, viewType); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { if (isLoadingRow(position)) { loadingListItemCreator.onBindViewHolder(holder, position); } else { wrappedAdapter.onBindViewHolder(holder, position); } } @Override public int getItemCount() { return displayLoadingRow ? wrappedAdapter.getItemCount() + 1 : wrappedAdapter.getItemCount(); } @Override public int getItemViewType(int position) { return isLoadingRow(position) ? ITEM_VIEW_TYPE_LOADING : wrappedAdapter.getItemViewType(position); } @Override public long getItemId(int position) { return isLoadingRow(position) ? RecyclerView.NO_ID : wrappedAdapter.getItemId(position); } public RecyclerView.Adapter<RecyclerView.ViewHolder> getWrappedAdapter() { return wrappedAdapter; } boolean isDisplayLoadingRow() { return displayLoadingRow; } void displayLoadingRow(boolean displayLoadingRow) { if (this.displayLoadingRow != displayLoadingRow) { this.displayLoadingRow = displayLoadingRow; notifyDataSetChanged(); } } boolean isLoadingRow(int position) { return displayLoadingRow && position == getLoadingRowPosition(); } private int getLoadingRowPosition() { return displayLoadingRow ? getItemCount() - 1 : -1; } }
package is.handsome.pixelperfect; import android.app.Activity; import android.app.Service; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.TextView; class Overlay { public interface LayoutListener { void onOverlayMoveX(int dx); void onOverlayMoveY(int dy); void onOverlayUpdate(int imageWidth, int imageHeight); void onOffsetViewMoveX(int dx); void onOffsetViewMoveY(int dy); void hideOffsetView(); void showOffsetView(int xPos, int yPos); void openSettings(boolean goToImages); void setInverseMode(); void onFixOffset(); } public interface SettingsListener { void onSetImageAlpha(float alpha); void onUpdateImage(Bitmap bitmap, boolean resetPosition); void onFixOffset(); boolean onInverseChecked(boolean saveOpacity); } private WindowManager windowManager; private SettingsView settingsView; private OverlayView overlayView; private ViewGroup offsetPixelsView; private TextView offsetXTextView; private TextView offsetYTextView; private WindowManager.LayoutParams offsetPixelsViewParams; private WindowManager.LayoutParams overlayParams; private WindowManager.LayoutParams settingsParams; private int fixedOffsetX = 0; private int fixedOffsetY = 0; private int overlayBorderSize; private int statusBarHeight; private String offsetTextTemplate; private float overlayScaleFactor = 1; private OverlayStateStore overlayStateStore; private OverlayPositionStore overlayPositionStore; public Overlay(Activity activity, boolean restoreState) { initOverlay(activity, restoreState); show(); } public Overlay(Activity activity, PixelPerfect.Config config) { overlayScaleFactor = config.getOverlayScaleFactor(); initOverlay(activity, false); if (!TextUtils.isEmpty(config.getOverlayImageAssetsPath())) { settingsView.setImageAssetsPath(config.getOverlayImageAssetsPath()); } if (!TextUtils.isEmpty(config.getOverlayInitialImageName())) { settingsView.setImageOverlay(config.getOverlayInitialImageName()); } show(); } public void show() { overlayView.setImageVisible(true); overlayView.setVisibility(View.VISIBLE); if (overlayStateStore.getSettingsState() != OverlayStateStore.SettingsState.CLOSED) { displaySettingsView(); if (overlayStateStore.getSettingsState() == OverlayStateStore.SettingsState.OPENED_IMAGES) { settingsView.openImagesSettingsScreen(); } } } public boolean isShown() { return overlayView.getVisibility() == View.VISIBLE; } public void calculatePositionAfterRotation() { if (overlayPositionStore.getPositionX() != 0 && overlayPositionStore.getPositionY() != 0) { overlayParams.x = overlayPositionStore.getPositionX(); overlayParams.y = overlayPositionStore.getPositionY(); fixedOffsetX = overlayPositionStore.getFixedOffsetX(); fixedOffsetY = overlayPositionStore.getFixedOffsetY(); } else { calculateFirstRotationPosition(); } overlayView.updateNoImageTextViewSize(); windowManager.updateViewLayout(overlayView, overlayParams); } public void resetState() { overlayStateStore.reset(); } public void saveState(Activity activity) { overlayStateStore.savePixelPerfectActive(true); overlayStateStore.saveSize(overlayView.getWidth(), overlayView.getHeight()); overlayPositionStore.saveOrientation(activity.getResources().getConfiguration().orientation); overlayPositionStore.savePosition(overlayParams.x, overlayParams.y); overlayPositionStore.saveFixedOffset(fixedOffsetX, fixedOffsetY); if (overlayView.isNoImageOverlay()) { overlayStateStore.saveImageName("no_image"); } else { overlayStateStore.saveImageName(settingsView.currentImageName()); } overlayStateStore.saveAssetsFolderName(settingsView.getOverlayImageAssetsPath()); overlayStateStore.saveOpacity(overlayView.getImageAlpha()); overlayStateStore.saveInverse(settingsView.isInverse()); overlayStateStore.saveSettingsState(settingsView.getSettingsState()); } public void hide() { overlayView.setImageVisible(false); overlayView.setVisibility(View.GONE); offsetPixelsView.setVisibility(View.GONE); settingsView.setVisibility(View.GONE); } public void destroy() { windowManager.removeView(overlayView); windowManager.removeView(offsetPixelsView); windowManager.removeView(settingsView); } private void calculateFirstRotationPosition() { int width = Utils.getWindowWidth(windowManager); int height = Utils.getWindowHeight(windowManager); int overlayMinimumVisibleSize = (int) overlayView.getContext().getResources().getDimension(R.dimen.overlay_minimum_visible_size); overlayParams.x = (overlayParams.x + overlayStateStore.getWidth() / 2) * width / height - overlayStateStore.getWidth() / 2; if (overlayParams.x + overlayStateStore.getWidth() < overlayMinimumVisibleSize) { overlayParams.x = overlayMinimumVisibleSize - overlayStateStore.getWidth(); } else if (overlayParams.x > Utils.getWindowWidth(windowManager) - overlayMinimumVisibleSize) { overlayParams.x = Utils.getWindowWidth(windowManager) - overlayMinimumVisibleSize; } fixedOffsetX = -overlayParams.x; overlayParams.y = (overlayParams.y + overlayStateStore.getHeight() / 2) * height / width - overlayStateStore.getHeight() / 2; if (overlayParams.y + overlayStateStore.getHeight() < overlayMinimumVisibleSize) { overlayParams.y = overlayMinimumVisibleSize - overlayStateStore.getHeight(); } else if (overlayParams.y > Utils.getWindowHeight(windowManager) - overlayMinimumVisibleSize - statusBarHeight) { overlayParams.y = Utils.getWindowHeight(windowManager) - overlayMinimumVisibleSize - statusBarHeight; } fixedOffsetY = -overlayParams.y; } private void restoreState(Activity activity) { if (overlayStateStore.getImageName() != null) { settingsView.setImageAssetsPath(overlayStateStore.getAssetsFolderName()); if (!overlayStateStore.getImageName().equalsIgnoreCase("no_image")) { settingsView.setImageOverlay(overlayStateStore.getImageName()); } if (overlayStateStore.isInverse()) { settingsView.setInverseMode(); } settingsView.updateOpacityProgress(overlayStateStore.getOpacity()); if (overlayPositionStore.getOrientation() != Configuration.ORIENTATION_UNDEFINED && activity.getResources().getConfiguration().orientation != overlayPositionStore.getOrientation()) { overlayPositionStore.saveOrientation(activity.getResources().getConfiguration().orientation); calculatePositionAfterRotation(); } } } private void initOverlay(final Activity activity, boolean restoreState) { Context applicationContext = activity.getApplicationContext(); overlayStateStore = OverlayStateStore.getInstance(applicationContext); overlayPositionStore = OverlayPositionStore.getInstance(applicationContext); if (!restoreState) { overlayStateStore.reset(); overlayPositionStore.reset(); } overlayView = new OverlayView(applicationContext); settingsView = new SettingsView(applicationContext); offsetPixelsView = (ViewGroup) LayoutInflater.from(applicationContext).inflate(R.layout.view_offset_pixels, null); offsetXTextView = (TextView) offsetPixelsView.findViewById(R.id.offset_x_text_view); offsetYTextView = (TextView) offsetPixelsView.findViewById(R.id.offset_y_text_view); overlayBorderSize = (int) applicationContext.getResources().getDimension(R.dimen.overlay_border_size); statusBarHeight = Utils.getStatusBarHeight(activity); offsetTextTemplate = applicationContext.getString(R.string.offset_text); windowManager = (WindowManager) applicationContext.getSystemService(Service.WINDOW_SERVICE); addViewsToWindow(applicationContext); restoreState(activity); } private void addViewsToWindow(Context context) { addOverlayView(context); addOffsetPixelsView(); addSettingsView(); } private void addOverlayView(final Context context) { overlayParams = new WindowManager.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, PixelFormat.TRANSLUCENT); updateInitialOverlayPosition(); disableOverlayAnimations(); windowManager.addView(overlayView, overlayParams); final int overlayMinimumVisibleSize = (int) context.getResources().getDimension(R.dimen.overlay_minimum_visible_size); overlayView.setLayoutListener(new LayoutListener() { @Override public void onOverlayMoveX(int dx) { if (overlayParams.x + dx + overlayView.getWidth() >= overlayMinimumVisibleSize && Utils.getWindowWidth(windowManager) - overlayParams.x - dx >= overlayMinimumVisibleSize) { overlayParams.x += dx; windowManager.updateViewLayout(overlayView, overlayParams); offsetXTextView.setText(String.format(offsetTextTemplate, fixedOffsetX + overlayParams.x)); } } @Override public void onOverlayMoveY(int dy) { if (overlayParams.y + dy + overlayView.getHeight() >= overlayMinimumVisibleSize && Utils.getWindowHeight(windowManager) - statusBarHeight - overlayParams.y - dy >= overlayMinimumVisibleSize) { overlayParams.y += dy; windowManager.updateViewLayout(overlayView, overlayParams); offsetYTextView.setText(String.format(offsetTextTemplate, fixedOffsetY + overlayParams.y)); } } @Override public void onOverlayUpdate(int width, int height) { updateInitialOverlayPosition(width, height); windowManager.updateViewLayout(overlayView, overlayParams); } @Override public void onOffsetViewMoveX(int dx) { offsetPixelsViewParams.x += dx; windowManager.updateViewLayout(offsetPixelsView, offsetPixelsViewParams); } @Override public void onOffsetViewMoveY(int dy) { offsetPixelsViewParams.y += dy; windowManager.updateViewLayout(offsetPixelsView, offsetPixelsViewParams); } @Override public void hideOffsetView() { offsetPixelsView.setVisibility(View.INVISIBLE); } @Override public void showOffsetView(int xPos, int yPos) { if (offsetPixelsView.getVisibility() != View.VISIBLE) { offsetPixelsViewParams.x = xPos - offsetPixelsView.getWidth() / 2; offsetPixelsViewParams.y = yPos - offsetPixelsView.getHeight() * 3; windowManager.updateViewLayout(offsetPixelsView, offsetPixelsViewParams); offsetXTextView.setText(String.format(offsetTextTemplate, fixedOffsetX + overlayParams.x)); offsetYTextView.setText(String.format(offsetTextTemplate, fixedOffsetY + overlayParams.y)); offsetPixelsView.setVisibility(View.VISIBLE); } } @Override public void openSettings(boolean showImages) { displaySettingsView(); if (showImages) { settingsView.openImagesSettingsScreen(); } } @Override public void setInverseMode() { settingsView.setInverseMode(); } @Override public void onFixOffset() { fixOffset(); } }); } private void updateInitialOverlayPosition(int imageWidth, int imageHeight) { overlayParams.gravity = Gravity.TOP | Gravity.START; int screenWidth = Utils.getWindowWidth(windowManager); int screenHeight = Utils.getWindowHeight(windowManager); int marginHorizontal = (screenWidth - imageWidth) / 2; int marginVertical = (screenHeight - imageHeight) / 2; if (overlayStateStore.getImageName() != null) { overlayParams.x = overlayPositionStore.getPositionX(); fixedOffsetX = overlayPositionStore.getFixedOffsetX(); overlayParams.y = overlayPositionStore.getPositionY(); fixedOffsetY = overlayPositionStore.getFixedOffsetY(); } else { overlayParams.x = -1 * overlayBorderSize + (marginHorizontal > 0 ? marginHorizontal : 0); fixedOffsetX = -1 * overlayParams.x; overlayParams.y = -1 * overlayBorderSize - statusBarHeight + (marginVertical > 0 ? marginVertical : 0); fixedOffsetY = -1 * overlayParams.y; } windowManager.updateViewLayout(overlayView, settingsParams); } private void disableOverlayAnimations() { try { int currentFlags = (Integer) overlayParams.getClass().getField("privateFlags").get(overlayParams); overlayParams.getClass().getField("privateFlags").set(overlayParams, currentFlags|0x00000040); } catch (Exception e) { Log.e(Overlay.class.getSimpleName(), "Error trying to disable window scale animation", e); } } private void updateInitialOverlayPosition() { overlayParams.gravity = Gravity.TOP | Gravity.START; if (overlayStateStore.getImageName() != null) { overlayParams.x = overlayPositionStore.getPositionX(); fixedOffsetX = overlayPositionStore.getFixedOffsetX(); overlayParams.y = overlayPositionStore.getPositionY(); fixedOffsetY = overlayPositionStore.getFixedOffsetY(); } else { overlayParams.x = -1 * overlayBorderSize + statusBarHeight; fixedOffsetX = -1 * overlayParams.x; overlayParams.y = -1 * overlayBorderSize + statusBarHeight; fixedOffsetY = -1 * overlayParams.y; } } private void displaySettingsView() { settingsView.updateOpacityProgress(overlayView.getImageAlpha()); settingsView.updateOffset(fixedOffsetX + overlayParams.x, fixedOffsetY + overlayParams.y); settingsView.setVisibility(View.VISIBLE); } private void addSettingsView() { settingsParams = new WindowManager.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, PixelFormat.TRANSLUCENT); settingsParams.gravity = Gravity.TOP | Gravity.START; windowManager.addView(settingsView, settingsParams); settingsView.setVisibility(View.GONE); settingsView.setListener(new SettingsListener() { @Override public void onSetImageAlpha(float alpha) { overlayView.setImageAlpha(alpha); } @Override public void onUpdateImage(Bitmap bitmap, boolean resetPosition) { overlayView.updateImage(bitmap, overlayScaleFactor); if (resetPosition) { overlayPositionStore.reset(); } } @Override public void onFixOffset() { fixOffset(); } @Override public boolean onInverseChecked(boolean saveOpacity) { boolean inverted = overlayView.invertImageBitmap(saveOpacity); settingsView.updateOpacityProgress(overlayView.getImageAlpha()); return inverted; } }); } private void fixOffset() { fixedOffsetX = -1 * overlayParams.x; fixedOffsetY = -1 * overlayParams.y; offsetXTextView.setText(String.format(offsetTextTemplate, fixedOffsetX + overlayParams.x)); offsetYTextView.setText(String.format(offsetTextTemplate, fixedOffsetY + overlayParams.y)); } private void addOffsetPixelsView() { offsetPixelsViewParams = new WindowManager.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ERROR, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, PixelFormat.TRANSLUCENT); offsetPixelsViewParams.gravity = Gravity.TOP | Gravity.START; offsetPixelsView.setVisibility(View.INVISIBLE); windowManager.addView(offsetPixelsView, offsetPixelsViewParams); } }
package polyglot.types; import polyglot.ast.*; import polyglot.util.*; import polyglot.types.Package; /** * A <code>PackageContextResolver</code> is responsible for looking up types * and packages in a packge by name. */ public class PackageContextResolver implements Resolver { Package p; TypeSystem ts; Resolver cr; /** * Create a package context resolver. * @param ts The type system. * @param p The package in whose context to search. * @param cr The resolver to use for looking up types. */ public PackageContextResolver(TypeSystem ts, Package p, Resolver cr) { this.ts = ts; this.p = p; this.cr = cr; } /** * The package in whose context to search. */ public Package package_() { return p; } /** * Find a type object by name. */ public Named find(String name) throws SemanticException { if (! StringUtil.isNameShort(name)) { throw new InternalCompilerError( "Cannot lookup qualified name " + name); } if (cr == null) { return ts.packageForName(p, name); } try { return cr.find(p.fullName() + "." + name); } catch (NoClassException e) { if (!e.getClassName().equals(p.fullName() + "." + name)) { throw e; } return ts.packageForName(p, name); } } public String toString() { return "(package-context " + p.toString() + ")"; } }
package pp2016.team13.client.gui; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JPanel; import pp2016.team13.shared.Monster; import pp2016.team13.shared.Spieler; public class Spielflaeche extends JPanel { private static final long serialVersionUID = 1L; private Image boden, wand, tuerOffen, tuerZu, schluessel, heiltrank,trank, feuerball; private HindiBones fenster; public int wechselX=0; public int wechselY=0; /** * * * Erzeugt ein Panel auf dem die Spielflaeche gezeichnet wird * @author Seyma * @param fenster : Fenster wird festgelegt fuer das Panel */ public Spielflaeche(HindiBones fenster) { this.fenster = fenster; // Lade die Bilder try { boden = ImageIO.read(new File("img//ground.png")); wand = ImageIO.read(new File("img//wand Kopie.png")); tuerZu = ImageIO.read(new File("img//tuer2.png")); tuerOffen = ImageIO.read(new File("img//tueroffen2.png")); schluessel = ImageIO.read(new File("img//schluessel.png")); heiltrank = ImageIO.read(new File("img//heiltrank.png")); feuerball = ImageIO.read(new File("img//feuerball.png")); trank=ImageIO.read(new File("img//heiltrankblau.png")); } catch (IOException e) { System.err.println("Ein Bild konnte nicht geladen werden."); } } //Positionierung von HindiBones in die Mitte //Das Bild wird immer dann neu gezeichnet wenn HindiBones auf den Koordinaten //der GrenzPunkteX/Y kommt, dann wird das ganze aktuelle Bild neu //gezeichnet. Da sich das Bild immer mitbewegt wird durch verschiebenx /y //Das richtige Bild Zentriert /** * * * * * * (Mitscrollend) * Meine Figur Zentriert * Bei jeder Bewegung und Beruehrung der Grenzpunkt Koordinaten wird das Spielfeld neu gezeichnet * Die Grenzpunkte befinden sich jeweils an allen Seiten von meiner Spieler Figur * Durch die Variable verschieben wird die der Hintergrund immer richtig verschoben * (Da mein Spieler die Koordinaten bzw. Spielfeld Pos. immer steigend ist, steigen auch * meine Variablen, sie passen sich meiner Spieler Figur an) * * @author Seyma Keser */ int verschiebenx=0; int verschiebeny=0; int grenzPunktX=4; int grenzPunktY=4; int grenzPunktx=2; int grenzPunkty=2; Monster Gegner=null; int Px; int Py; int anfangszustand= 0; int MonsterStandpunktx; int MonsterStandpunkty; int keinMonsterinSicht=0; int Monsterx; int Monstery; /** * @author Seyma * * Setzt berall im Labirinth wo eine 3 ist ein Monster Objekt in die die monsterliste * (die monsterliste wird dann bei spaeter aufgerufen um die Monster zu zeichnen) * */ public void genMonster(){ for (int i =wechselX ; i <fenster.WIDTH ; i++) { for (int j = wechselY; j < fenster.HEIGHT; j++) { if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 3) { Gegner = new Monster(i, j, fenster, 0); // Monsterx=i; // Monstery=j; // System.out.println("Monster 1: i= "+ i + "j: "+j); fenster.monsterListe.add(Gegner); } if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 5) { Gegner = new Monster(i, j, fenster, 1); fenster.monsterListe.add(Gegner); } } } } /** * @author Seyma * * Die Position der Offenen Tre bei 2 wird als Start Position des Spielers gesetzt * (muss wie genMonster() ausserhalb der paint Methode passieren, damit die monster und Spieler nicht immer auf der Selben * Position gezeichnet werden durch Repaint()) * */ public void posSpieler(){ for (int i =wechselX ; i <fenster.WIDTH ; i++) { for (int j = wechselY; j < fenster.HEIGHT; j++) { if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 2) { fenster.spieler.setPos(i, j); fenster.spieler2.setPos(i,j); } } } } /** * @author Seyma * *Meine Felder Generieren sich im ersten Schritt um meinen Spieler *Grund: Mein Spieler wird in die Mitte gesetzt (d.h Pos X= 3 Pos Y=3 Aber Bezogen auf die Sichtbare Flaeche) * Da sich die Grenzpunkte immer einen Schritt von dem Spieler entfernt befinden * Wird bei jedem Schritt mein Spielfeld um 1 Verschoben und die Stelle neu gezeichnet. * *Rest ist die Generierung der Spielflaeche durch abfrage ueber den Client welcher inhalt sich auf welcher Koordinate *Befindet, wird ein Bild gezeichnet. (Grundgeruest vom urspruenglichen Spiel Code) * * (Mitscrollend) * Meine Figur Zentriert * Bei jeder Bewegung und Beruehrung der Grenzpunkt Koordinaten wird das Spielfeld neu gezeichnet * Die Grenzpunkte befinden sich jeweils an allen Seiten von meiner Spieler Figur * Durch die Variable verschieben wird die der Hintergrund immer richtig verschoben * (Da mein Spieler die Koordinaten bzw. Spielfeld Pos. immer steigend ist, steigen auch * meine Variablen, sie passen sich meiner Spieler Figur an) * * */ public void paint(Graphics g) { if (anfangszustand==0){ this.posSpieler(); this.genMonster(); anfangszustand++; } // Beim neuzeichnen wird zunaechst alles uebermalt g.setColor(Color.BLACK); g.fillRect(0, 0, this.getWidth(), this.getHeight()); // Male die einzelnen Felder for (int i =wechselX ; i < fenster.WIDTH; i++) { for (int j = wechselY; j < fenster.HEIGHT; j++) { if (inRange(i, j)) { if(fenster.spieler.getXPos()>=grenzPunktX ){ verschiebenx+=1; grenzPunktX+=1; grenzPunktx+=1; } if(fenster.spieler.getXPos()<=grenzPunktx ){ verschiebenx-=1; grenzPunktx-=1; grenzPunktX-=1; } if(fenster.spieler.getYPos()<=grenzPunkty ){ verschiebeny-=1; grenzPunkty-=1; grenzPunktY-=1; } if(fenster.spieler.getYPos()>=grenzPunktY){ verschiebeny+=1; grenzPunktY+=1; grenzPunkty+=1; } if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 0) { //Wand==0 // Hier kommt eine Wand hin g.drawImage(wand, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); } else if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 1) { //Boden ==1 // Dieses Feld ist begehbar g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); } else if (fenster.Level.getBestimmtenLevelInhalt(i, j)== 3){ //Monster ==3 g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); // for (int k = 0; k < fenster.monsterListe.size(); k++) { // Monster m = fenster.monsterListe.get(k); // //System.out.println(m.getXPos() +" und i: "+ i + m.getYPos() +" und j: "+ j); // if (m.getXPos()==i && m.getYPos()==j){ // m.setXPos( i -verschiebenx*fenster.BOX); // m.setYPos( j -verschiebeny*fenster.BOX); //Monster werden vor der Paint-Methode in genMonster in eine Lister Getzt ueberall wo Monster==3 ist } else if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 2) { //Offene Tuere == 2 g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); g.drawImage(tuerOffen, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); } else if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 6) { //Geschlossene Tuere== 6 // Hier ist die Tuer g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); g.drawImage(tuerZu, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); } else if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 7 ) { //Blauer Trank== 7 // Hier ist ein Blauer Trank g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); g.drawImage(trank, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); }else if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 4) { //Heiltrank== 4 //Hier ist ein Heiltrank g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); g.drawImage(heiltrank, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); }else if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 5) { //Schluesselmonster == 5 g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); }else if (fenster.Level.getBestimmtenLevelInhalt(i, j) == 8) { //Schluessel == 8 //Hier ist der Schluessel g.drawImage(boden, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); g.drawImage(schluessel, i * fenster.BOX-verschiebenx*fenster.BOX, j * fenster.BOX-verschiebeny*fenster.BOX, null); } } } } // Male die Monster an ihrer Position for (int k = 0; k < fenster.monsterListe.size(); k++) { Monster m = fenster.monsterListe.get(k); // System.out.println( m.getXPos()); // System.out.println( m.getYPos()); boolean event = fenster.spieler.hatSchluessel(); // Da hier alle Monster aufgerufen werden, wird an dieser // Stelle auch ein Angriffsbefehl fuer die Monster // abgegeben, falls der Spieler in der Naehe ist. // Ansonsten soll das Monster laufen double p = m.cooldownProzent(); if (!m.attackiereSpieler(event)) { m.move(); } else { int box = fenster.BOX; Spieler s = fenster.spieler; g.setColor(Color.RED); g.drawImage( feuerball, (int) (((1 - p) * m.getXPos() + (p) * s.getXPos()) * box ) + box / 2 -verschiebenx*fenster.BOX, (int) (((1 - p) * m.getYPos() + (p) * s.getYPos()) * box) + box / 2 -verschiebeny*fenster.BOX, 8, 8, null); keinMonsterinSicht=1; // System.out.println( ((int) (((1 - p) * m.getXPos() + (p) * s.getXPos()) * box ) // + box / 2 -verschiebenx*fenster.BOX)/72); // System.out.println(( (int) (((1 - p) * m.getYPos() + (p) // * s.getYPos()) * box) // + box / 2 -verschiebeny*fenster.BOX)/72); // MonsterStandpunktx=(m.getXPos()-verschiebenx*fenster.BOX); // MonsterStandpunkty=(m.getYPos()-verschiebeny*fenster.BOX); // if(m.getXPos()==0){ // else { // keinMonsterinSicht=0; } // System.out.println( m.getXPos()); // System.out.println( m.getYPos()); // Male die Monstar drawMonster(g, m); } // Male den Spieler an seiner Position g.drawImage(fenster.spieler.getImage(), fenster.spieler.getXPos() * fenster.BOX-verschiebenx*fenster.BOX, fenster.spieler.getYPos() * fenster.BOX-verschiebeny*fenster.BOX, null); if (fenster.verloren) { g.setColor(Color.WHITE); g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 40)); g.drawString("GAME OVER", getWidth() / 2 - 120, getHeight() / 2); } else { if (fenster.spielende) { g.setColor(Color.WHITE); g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 40)); g.drawString("GEWONNEN", getWidth() / 2 - 120, getHeight() / 2); } } } /** * * @author Seyma Keser + (unbekannt) * Methode vom Urspruenglichen Code uebernommen + Erweiterung durch einbauen der Verschiebungen fuer * scrollenden Bildschirm * */ private void drawMonster(Graphics g, Monster m) { // Monster Health Points if (inRange(m.getXPos(), m.getYPos())) { g.drawImage(m.getImage(), m.getXPos() * fenster.BOX -verschiebenx*fenster.BOX, m.getYPos() * fenster.BOX-verschiebeny*fenster.BOX, null); g.setColor(Color.GREEN); g.fillRect(m.getXPos() * fenster.BOX-verschiebenx*fenster.BOX +10, m.getYPos() * fenster.BOX -verschiebeny*fenster.BOX- 2, m.getLebenspunkte()+20, 2); } } /** * @author Unbekannt * * Methode uebernommen nichts veraendert * */ private boolean inRange(int i, int j) { return (Math.sqrt(Math.pow(fenster.spieler.getXPos() - i, 2) + Math.pow(fenster.spieler.getYPos() - j, 2)) < 3 || !fenster.nebelAn); } }
package eu.darken.myolib; import eu.darken.myolib.msgs.ReadMsg; import eu.darken.myolib.processor.classifier.PoseClassifierEvent; import eu.darken.myolib.tools.ByteHelper; public class MyoInfo { /** * Unique serial number of this Myo. */ private final int[] mSerialNumber; /** * Pose that should be interpreted as the unlock pose. */ private PoseClassifierEvent.Pose mUnlockPose; public enum ActiveClassifierType { BUILTIN((byte) 0x0), CUSTOM((byte) 0x1); private final byte mValue; ActiveClassifierType(byte value) { mValue = value; } public byte getValue() { return mValue; } } /** * Whether Myo is currently using a built-in or a custom classifier. */ private final ActiveClassifierType mActiveClassifierType; /** * Index of the classifier that is currently active */ private final int mActiveClassifierIndex; /** * Whether Myo contains a valid custom classifier. 1 if it does, otherwise 0. */ private final boolean mHasCustomClassifier; /** * Set if the Myo uses BLE indicates to stream data, for reliable capture. */ private final int mStreamIndicating; public enum Sku { UNKNOWN((byte) 0x0), BLACK((byte) 0x1), WHITE((byte) 0x2); private final byte mValue; Sku(byte value) { mValue = value; } public byte getValue() { return mValue; } } /** * SKU value of the device. See myohw_sku_t */ private final Sku mSKU; private final byte[] mReservedData; public MyoInfo(ReadMsg msg) { ByteHelper byteHelper = new ByteHelper(msg.getValue()); int[] serialNumberValue = new int[6]; for (int i = 0; i < 6; i++) serialNumberValue[i] = byteHelper.getUInt8(); mSerialNumber = serialNumberValue; int unlockPoseValue = byteHelper.getUInt16(); for (PoseClassifierEvent.Pose pose : PoseClassifierEvent.Pose.values()) { if (pose.getValue() == unlockPoseValue) { mUnlockPose = pose; break; } } if (mUnlockPose == null) mUnlockPose = PoseClassifierEvent.Pose.UNKNOWN; int classifierTypeValue = byteHelper.getUInt8(); ActiveClassifierType classifierType = ActiveClassifierType.BUILTIN; for (ActiveClassifierType type : ActiveClassifierType.values()) { if (type.getValue() == classifierTypeValue) { classifierType = type; break; } } mActiveClassifierType = classifierType; mActiveClassifierIndex = byteHelper.getUInt8(); mHasCustomClassifier = byteHelper.getUInt8() == 1; mStreamIndicating = byteHelper.getUInt8(); int skuValue = byteHelper.getUInt8(); Sku skuType = Sku.UNKNOWN; for (Sku type : Sku.values()) { if (type.getValue() == skuValue) { skuType = type; break; } } mSKU = skuType; mReservedData = new byte[byteHelper.getRemaining()]; int rIndex = 0; while (byteHelper.hasRemaining()) { mReservedData[rIndex] = byteHelper.getByte(); rIndex++; } } public int[] getSerialNumber() { return mSerialNumber; } public PoseClassifierEvent.Pose getUnlockPose() { return mUnlockPose; } public ActiveClassifierType getActiveClassifierType() { return mActiveClassifierType; } public int getActiveClassifierIndex() { return mActiveClassifierIndex; } public boolean isHasCustomClassifier() { return mHasCustomClassifier; } public int getStreamIndicating() { return mStreamIndicating; } public Sku getSKU() { return mSKU; } public byte[] getReservedData() { return mReservedData; } }
package polyglot.ext.jl.ast; import polyglot.ast.*; import polyglot.util.*; import polyglot.visit.*; import polyglot.types.*; /** * A <code>Binary</code> represents a Java binary expression, an * immutable pair of expressions combined with an operator. */ public class Binary_c extends Expr_c implements Binary { protected Expr left; protected Operator op; protected Expr right; protected Precedence precedence; public Binary_c(Del ext, Position pos, Expr left, Operator op, Expr right) { super(ext, pos); this.left = left; this.op = op; this.right = right; this.precedence = op.precedence(); } /** Get the left operand of the expression. */ public Expr left() { return this.left; } /** Set the left operand of the expression. */ public Binary left(Expr left) { Binary_c n = (Binary_c) copy(); n.left = left; return n; } /** Get the operator of the expression. */ public Operator operator() { return this.op; } /** Set the operator of the expression. */ public Binary operator(Operator op) { Binary_c n = (Binary_c) copy(); n.op = op; return n; } /** Get the right operand of the expression. */ public Expr right() { return this.right; } /** Set the right operand of the expression. */ public Binary right(Expr right) { Binary_c n = (Binary_c) copy(); n.right = right; return n; } /** Get the precedence of the expression. */ public Precedence precedence() { return this.precedence; } public Binary precedence(Precedence precedence) { Binary_c n = (Binary_c) copy(); n.precedence = precedence; return n; } /** Reconstruct the expression. */ protected Binary_c reconstruct(Expr left, Expr right) { if (left != this.left || right != this.right) { Binary_c n = (Binary_c) copy(); n.left = left; n.right = right; return n; } return this; } /** Visit the children of the expression. */ public Node visitChildren(NodeVisitor v) { Expr left = (Expr) visitChild(this.left, v); Expr right = (Expr) visitChild(this.right, v); return reconstruct(left, right); } protected Node num(NodeFactory nf, long value) { Position p = position(); Type t = type(); TypeSystem ts = t.typeSystem(); // Binary promotion IntLit.Kind kind = IntLit.INT; if (left instanceof IntLit && ((IntLit) left).kind() == IntLit.LONG) { kind = IntLit.LONG; } if (right instanceof IntLit && ((IntLit) right).kind() == IntLit.LONG) { kind = IntLit.LONG; } return nf.IntLit(p, kind, value).type(t); } protected Node bool(NodeFactory nf, boolean value) { return nf.BooleanLit(position(), value).type(type()); } /** Fold constants for the expression. */ public Node foldConstants(ConstantFolder cf) { NodeFactory nf = cf.nodeFactory(); if (left instanceof NumLit && right instanceof NumLit) { long l = ((NumLit) left).longValue(); long r = ((NumLit) right).longValue(); if (op == ADD) return num(nf, l + r); if (op == SUB) return num(nf, l - r); if (op == MUL) return num(nf, l * r); if (op == DIV && r != 0) return num(nf, l / r); if (op == MOD && r != 0) return num(nf, l % r); if (op == BIT_OR) return num(nf, l | r); if (op == BIT_AND) return num(nf, l & r); if (op == BIT_XOR) return num(nf, l ^ r); if (op == SHL) return num(nf, l << r); if (op == SHR) return num(nf, l >> r); if (op == USHR) return num(nf, l >>> r); if (op == GT) return bool(nf, l > r); if (op == LT) return bool(nf, l < r); if (op == GE) return bool(nf, l >= r); if (op == LE) return bool(nf, l <= r); if (op == NE) return bool(nf, l != r); if (op == EQ) return bool(nf, l == r); } else if (left instanceof NumLit) { long l = ((NumLit) left).longValue(); if (op == ADD && l == 0L) return right; if (op == SUB && l == 0L) return right; if (op == MUL && l == 1L) return right; if (op == BIT_OR && l == 0L) return right; if (op == BIT_XOR && l == 0L) return right; } else if (right instanceof NumLit) { long r = ((NumLit) right).longValue(); if (op == ADD && r == 0L) return left; if (op == SUB && r == 0L) return left; if (op == MUL && r == 1L) return left; if (op == DIV && r == 1L) return left; if (op == MOD && r == 1L) return left; if (op == BIT_OR && r == 0L) return left; if (op == BIT_XOR && r == 0L) return left; if (op == SHL && r == 0L) return left; if (op == SHR && r == 0L) return left; if (op == USHR && r == 0L) return left; } else if (left instanceof BooleanLit && right instanceof BooleanLit) { boolean l = ((BooleanLit) left).value(); boolean r = ((BooleanLit) right).value(); if (op == BIT_OR) return nf.BooleanLit(position(), l | r).type(type()); if (op == BIT_AND) return nf.BooleanLit(position(), l & r).type(type()); if (op == BIT_XOR) return nf.BooleanLit(position(), l ^ r).type(type()); if (op == COND_OR) return nf.BooleanLit(position(), l || r).type(type()); if (op == COND_AND) return nf.BooleanLit(position(), l && r).type(type()); if (op == NE) return nf.BooleanLit(position(), l != r).type(type()); if (op == EQ) return nf.BooleanLit(position(), l == r).type(type()); } else if (left instanceof BooleanLit) { boolean l = ((BooleanLit) left).value(); // These are safe because the right expression would have been // short-circuited. BIT_OR and BIT_AND are not safe here. if (op == COND_OR && l) return nf.BooleanLit(position(), true).type(type()); if (op == COND_AND && ! l) return nf.BooleanLit(position(), false).type(type()); // Here, the non-literal is always evaluated, so this is safe. if (op == COND_OR && ! l) return right; if (op == COND_AND && l) return right; if (op == BIT_OR && ! l) return right; if (op == BIT_AND && l) return right; } else if (left instanceof StringLit && right instanceof StringLit) { String l = ((StringLit) left).value(); String r = ((StringLit) right).value(); // Don't do this. Strings literals are usually broken for // formatting reasons. /* if (op == ADD) return nf.StringLit(position(), l + r); */ } return this; } /** Type check the expression. */ public Node typeCheck(TypeChecker tc) throws SemanticException { Type l = left.type(); Type r = right.type(); TypeSystem ts = tc.typeSystem(); if (op == GT || op == LT || op == GE || op == LE) { if (! l.isNumeric()) { throw new SemanticException("The " + op + " operator must have numeric operands.", left.position()); } if (! r.isNumeric()) { throw new SemanticException("The " + op + " operator must have numeric operands.", right.position()); } return type(ts.Boolean()); } if (op == EQ || op == NE) { if (! ts.isCastValid(l, r) && ! ts.isCastValid(r, l)) { throw new SemanticException("The " + op + " operator must have operands of similar type.", position()); } return type(ts.Boolean()); } if (op == COND_OR || op == COND_AND) { if (! l.isBoolean()) { throw new SemanticException("The " + op + " operator must have boolean operands.", left.position()); } if (! r.isBoolean()) { throw new SemanticException("The " + op + " operator must have boolean operands.", right.position()); } return type(ts.Boolean()); } if (op == ADD) { if (ts.isSame(l, ts.String()) || ts.isSame(r, ts.String())) { return precedence(Precedence.STRING_ADD).type(ts.String()); } } if (op == BIT_AND || op == BIT_OR || op == BIT_XOR) { if (l.isBoolean() && r.isBoolean()) { return type(ts.Boolean()); } } if (op == ADD) { if (! l.isNumeric()) { throw new SemanticException("The " + op + " operator must have numeric or String operands.", left.position()); } if (! r.isNumeric()) { throw new SemanticException("The " + op + " operator must have numeric or String operands.", right.position()); } } if (op == BIT_AND || op == BIT_OR || op == BIT_XOR) { if (! ts.isImplicitCastValid(l, ts.Long())) { throw new SemanticException("The " + op + " operator must have numeric or boolean operands.", left.position()); } if (! ts.isImplicitCastValid(r, ts.Long())) { throw new SemanticException("The " + op + " operator must have numeric or boolean operands.", right.position()); } } if (op == SUB || op == MUL || op == DIV || op == MOD) { if (! l.isNumeric()) { throw new SemanticException("The " + op + " operator must have numeric operands.", left.position()); } if (! r.isNumeric()) { throw new SemanticException("The " + op + " operator must have numeric operands.", right.position()); } } if (op == SHL || op == SHR || op == USHR) { if (! ts.isImplicitCastValid(l, ts.Long())) { throw new SemanticException("The " + op + " operator must have numeric operands.", left.position()); } if (! ts.isImplicitCastValid(r, ts.Long())) { throw new SemanticException("The " + op + " operator must have numeric operands.", right.position()); } } if (op == SHL || op == SHR || op == USHR) { // For shift, only promote the left operand. return type(ts.promote(l)); } return type(ts.promote(l, r)); } public Type childExpectedType(Expr child, AscriptionVisitor av) { Expr other; if (child == left) { other = right; } else if (child == right) { other = left; } else { return child.type(); } TypeSystem ts = av.typeSystem(); if (op == EQ || op == NE) { // Coercion to compatible types. if (other.type().isReference() || other.type().isNull()) { return ts.Object(); } if (other.type().isBoolean()) { return ts.Boolean(); } if (other.type().isNumeric()) { return ts.Double(); } } if (op == ADD && ts.isSame(type, ts.String())) { // Implicit coercion to String. return ts.String(); } if (op == GT || op == LT || op == GE || op == LE) { if (other.type().isNumeric()) { return ts.Double(); } } if (op == COND_OR || op == COND_AND) { return ts.Boolean(); } if (op == BIT_AND || op == BIT_OR || op == BIT_XOR) { if (other.type().isBoolean()) { return ts.Boolean(); } return ts.Long(); } if (op == SUB || op == MUL || op == DIV || op == MOD) { return ts.Double(); } if (op == SHL || op == SHR || op == USHR) { return ts.Long(); } return child.type(); } /** Check exceptions thrown by the expression. */ public Node exceptionCheck(ExceptionChecker ec) throws SemanticException { TypeSystem ts = ec.typeSystem(); if (throwsArithmeticException()) { ec.throwsException(ts.ArithmeticException()); } return this; } /** Get the throwsArithmeticException of the expression. */ public boolean throwsArithmeticException() { // conservatively assume that any division or mod may throw // ArithmeticException this is NOT true-- floats and doubles don't // throw any exceptions ever... return op == DIV || op == MOD; } public String toString() { return left + " " + op + " " + right; } /** Write the expression to an output file. */ public void prettyPrint(CodeWriter w, PrettyPrinter tr) { printSubExpr(left, true, w, tr); w.write(" "); w.write(op.toString()); w.allowBreak(type() == null || type().isPrimitive() ? 2 : 0, " "); printSubExpr(right, false, w, tr); } public void dump(CodeWriter w) { super.dump(w); if (type != null) { w.allowBreak(4, " "); w.begin(0); w.write("(type " + type + ")"); w.end(); } w.allowBreak(4, " "); w.begin(0); w.write("(operator " + op + ")"); w.end(); } }
/** * @author Pranava Raparla, Monica Choe * Created: October 4th, 2014 * Modified: October 9th, 2014 */ package application; import java.io.*; import java.util.*; import application.Actions.AbstractAction; import application.slogonode.SLogoNode; import javafx.geometry.Point2D; public class Model { public List<Workspace> workspaces; public Map<String, String> myCommands; public Model() throws IOException { System.out.println("Starting constructor"); PropertiesFactory factory = new PropertiesFactory(); System.out.println("Initialized Factory"); try { myCommands = factory .getPropertyValues("resources/languages/English.properties"); // loadCommandsbyLanguage("Chinese.properties"); System.out.println("Factory loaded"); System.out.println(myCommands); } catch (Exception e) { System.out.println("An Error occured in the loading of the properties File!"); } } public void loadCommandsbyLanguage(String fileName) { Properties languageProperties = new Properties(); Scanner myScanner = null; try { System.out.println("Loading another language"); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); languageProperties.load(inputStream); myScanner = new Scanner(new File(fileName)); System.out.println(myScanner); while (myScanner.hasNextLine()) { String str = myScanner.nextLine(); System.out.println("Current string: " + str); if (str.substring(0, 1).equalsIgnoreCase(" continue; else if (str.startsWith(" continue; else { System.out.println("Adding?"); String keyword = myScanner.next(); String equalsSign = myScanner.next(); String commandReference1 = myScanner.next(); String commandReference2 = myScanner.next(); myCommands.put(commandReference1, keyword); myCommands.put(commandReference2, keyword); } } System.out.println("Done loading new language"); } catch (Exception e) { System.out.println("Error occured in loading a new language"); } finally { if (myScanner != null) myScanner.close(); } } /** * pass parseInput the input string, and parseInput will return a List of * AbstractActions to the View, which the View will handle applying to the * correct AbstractDrawer. List can have NullActions if the input is parsed * to create no Actions. * * @param inputString * @return */ public List<AbstractAction> parseInput(String inputString) { List<AbstractAction> listOfActions = new ArrayList<AbstractAction>(); List<SLogoNode> listOfNodes = new ArrayList<SLogoNode>(); String[] inputStringArray = inputString.split(" SLogoNodeFactory nodeFactory = new SLogoNodeFactory(); if (inputString.isEmpty()) return listOfActions; for (String str : inputStringArray) { SLogoNode node = nodeFactory.getSLogoNodeFromString(str); listOfNodes.add(node); } for (int i = 0; i < listOfNodes.size(); i++) { listOfNodes.get(i).addChild(listOfNodes.get(i + 1)); } return listOfActions; } /** * Similar to parseInput, but the input String is contained within a File. * Parse accordingly, and and return a List of AbstractActions. We will have * NullActions to represent if the input is parsed and returns a non Action. * * @param inputFile * @return */ public List<AbstractAction> parseFile(File inputFile) { Scanner myScanner = null; String inputString = ""; try { myScanner = new Scanner(inputFile); inputString = myScanner.useDelimiter("\\Z").next(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (myScanner != null) myScanner.close(); } return parseInput(inputString); } /** * Pass in a workspace and store it in the Model * * @param workspace */ public void storeWorkspace(Workspace workspace) { for (Workspace wk : workspaces) if (wk.equals(workspace)) return; else workspaces.add(workspace); } /** * Change the language the the back-end parser for parsing. * * @param language */ public void setLanguage(String language) { } /** * If a point on the Canvas is clicked, make the Drawer go to this point. * Pass in the start location, the end location, and the starting * orientation and a List of Actions will be returned to correctly complete * this Action. * * @param action */ public List<AbstractAction> handleManualDrawerClickEvent(Point2D start, double orientation, Point2D end) { return null; } }
package akechi.projectl; import android.accounts.Account; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import android.os.RemoteException; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.api.client.repackaged.com.google.common.base.Strings; import com.google.api.client.util.DateTime; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.io.FileDescriptor; import java.io.IOException; import java.io.Serializable; import java.text.DateFormat; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import javax.annotation.Nullable; import akechi.projectl.async.LingrTaskLoader; import jp.michikusa.chitose.lingr.Events; import jp.michikusa.chitose.lingr.LingrClient; import jp.michikusa.chitose.lingr.LingrException; import jp.michikusa.chitose.lingr.Room; public class CometService extends Service { public static interface OnCometEventListener { void onCometEvent(Events events); } @Override public IBinder onBind(Intent intent) { throw new AssertionError("Cannot bind this service"); } @Override public void onCreate() { super.onCreate(); this.notifMan= NotificationManagerCompat.from(this.getApplicationContext()); final Notification notif= new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon_logo) .setContentTitle("ProjectL ...started") .setContentInfo("Info") .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, HomeActivity.class), 0)) .build() ; this.notifMan.notify(0, notif); this.loader= this.newSubscribeLoader(); final LocalBroadcastManager lbMan= LocalBroadcastManager.getInstance(this.getApplicationContext()); { final IntentFilter ifilter= new IntentFilter(Event.AccountChange.ACTION); final BroadcastReceiver receiver= new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { final CometService that= CometService.this; final Loader<Void> oldLoader= that.loader; oldLoader.abandon(); that.loader= that.newSubscribeLoader(); that.loader.forceLoad(); } }; lbMan.registerReceiver(receiver, ifilter); this.receivers.add(receiver); } { final IntentFilter ifilter= new IntentFilter(Event.PreferenceChange.ACTION); final BroadcastReceiver receiver= new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { final CometService that= CometService.this; final Loader<Void> oldLoader= that.loader; oldLoader.abandon(); that.loader= that.newSubscribeLoader(); that.loader.forceLoad(); } }; lbMan.registerReceiver(receiver, ifilter); this.receivers.add(receiver); } { final IntentFilter ifilter= new IntentFilter(CometService.class.getCanonicalName()); final BroadcastReceiver receiver= new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { final AppContext appContext= (AppContext)CometService.this.getApplicationContext(); final Iterable<String> accountNames= Iterables.transform(appContext.getAccounts(), new Function<Account, String>(){ @Override public String apply(Account input) { return Pattern.quote(input.name); } }); final Pattern mentionPattern= Pattern.compile("@(?:" + Joiner.on('|').join(accountNames) + ")\\b"); final Events events= (Events)intent.getSerializableExtra("events"); for(final Events.Event event : events.getEvents()) { if(event.getMessage() == null) { continue; } final Room.Message message= event.getMessage(); final boolean mentioned= mentionPattern.matcher(message.getText()).find(); if(mentioned) { final Notification notif= new NotificationCompat.Builder(CometService.this) .setSmallIcon(R.drawable.icon_logo) .setContentTitle("ProjectL") .setContentText(message.getRoom()) .setSubText(message.getText()) .setContentInfo(message.getNickname()) .setTicker(DateFormat.getDateTimeInstance().format(new Date(new DateTime(message.getTimestamp()).getValue()))) .build() ; CometService.this.notifMan.notify(0, notif); } } } }; lbMan.registerReceiver(receiver, ifilter); this.receivers.add(receiver); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.i("CometService", "forceLoad()"); this.loader.forceLoad(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); final LocalBroadcastManager lbMan= LocalBroadcastManager.getInstance(this.getApplicationContext()); for(final BroadcastReceiver receiver : this.receivers) { lbMan.unregisterReceiver(receiver); } this.receivers.clear(); } private void scheduleNext() { final PendingIntent intent= PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0); final AlarmManager alarmMan= (AlarmManager)this.getSystemService(ALARM_SERVICE); // re-invoke myself every 500ms alarmMan.set(AlarmManager.RTC, System.currentTimeMillis() + 500, intent); } private SubscribeLoader newSubscribeLoader() { return new SubscribeLoader(this){ @Override protected Void onLoadInBackground() { try { return super.onLoadInBackground(); } finally { CometService.this.scheduleNext(); return null; } } }; } private ObserveLoader newObserveLoader() { return new ObserveLoader(this){ @Override protected Void onLoadInBackground() { try { return super.onLoadInBackground(); } finally { CometService.this.scheduleNext(); return null; } } }; } private class SubscribeLoader extends LingrTaskLoader<Void> { public SubscribeLoader(Context context) { super(context); } @Override public Void loadInBackground(CharSequence authToken, LingrClient lingr) throws IOException, LingrException { final AppContext appContext= this.getApplicationContext(); final Account account= appContext.getAccount(); final Iterable<String> ids= appContext.getRoomIds(account); final Iterable<String> roomIds; if(Iterables.isEmpty(ids)) { roomIds= lingr.getRooms(authToken); } else { roomIds= ids; } lingr.unsubscribe(authToken, roomIds); final long counter= lingr.subscribe(authToken, true, roomIds); // sometimes, lingr returns 0 value for counter // and observe with counter = 0, cause errors Log.i("CometService", "counter = " + counter); if(counter <= 0) { // retry return null; } CometService.this.counter= counter; CometService.this.loader= CometService.this.newObserveLoader(); return null; } @Override protected void showMessage(CharSequence message) { // suppress message Log.i("CometService", "" + message); } } private class ObserveLoader extends LingrTaskLoader<Void> { public ObserveLoader(Context context) { super(context); } @Override public Void loadInBackground(CharSequence authToken, LingrClient lingr) throws IOException, LingrException { Log.i("CometService", "counter = " + CometService.this.counter); final Events events= lingr.observe(authToken, CometService.this.counter, 30, TimeUnit.MINUTES); // sometimes, lingr returns 0 value for counter // and observe with counter = 0, cause errors final long counter= events.getCounter(); Log.i("CometService", "counter = " + counter); if(counter <= 0) { // retry return null; } CometService.this.counter= events.getCounter(); final Intent intent= new Intent(CometService.class.getCanonicalName()); intent.putExtra("events", (Serializable) events); if(CometService.this.loader == this) { final LocalBroadcastManager lbMan= LocalBroadcastManager.getInstance(CometService.this.getApplicationContext()); lbMan.sendBroadcast(intent); } return null; } @Override protected void showMessage(CharSequence message) { // suppress message Log.i("CometService", "" + message); } } private NotificationManagerCompat notifMan; private long counter; private Loader<Void> loader; private final List<BroadcastReceiver> receivers= Lists.newLinkedList(); }
package com.tlongdev.bktf.model; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import com.tlongdev.bktf.R; import com.tlongdev.bktf.data.DatabaseContract; import com.tlongdev.bktf.data.DatabaseContract.ItemSchemaEntry; import com.tlongdev.bktf.util.Utility; import java.io.Serializable; /** * Item class */ public class Item implements Serializable { /** * Log tag for logging. */ @SuppressWarnings("unused") private static final String LOG_TAG = Item.class.getSimpleName(); private int defindex; private String name; private int quality; private boolean tradable; private boolean craftable; private boolean australium; private int priceIndex; private int weaponWear; private Price price; public Item() { this(0, null, 0, false, false, false, 0, null); } public Item(int defindex, String name, int quality, boolean tradable, boolean craftable, boolean australium, int priceIndex, Price price) { this(defindex, name, quality, tradable, craftable, australium, priceIndex, 0, price); } public Item(int defindex, String name, int quality, boolean tradable, boolean craftable, boolean australium, int priceIndex, int weaponWear, Price price) { this.defindex = defindex; this.name = name; this.quality = quality; this.tradable = tradable; this.craftable = craftable; this.australium = australium; this.priceIndex = priceIndex; this.weaponWear = weaponWear; this.price = price; } public int getDefindex() { return defindex; } public void setDefindex(int defindex) { this.defindex = defindex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuality() { return quality; } public void setQuality(int quality) { this.quality = quality; } public boolean isTradable() { return tradable; } public void setTradable(boolean tradable) { this.tradable = tradable; } public boolean isCraftable() { return craftable; } public void setCraftable(boolean craftable) { this.craftable = craftable; } public boolean isAustralium() { return australium; } public void setAustralium(boolean australium) { this.australium = australium; } public int getPriceIndex() { return priceIndex; } public void setPriceIndex(int priceIndex) { this.priceIndex = priceIndex; } public int getWeaponWear() { return weaponWear; } public void setWeaponWear(int weaponWear) { this.weaponWear = weaponWear; } public Price getPrice() { return price; } public void setPrice(Price price) { this.price = price; } /** * Properly formats the item name according to its properties. * * @param context the context * @param isProper whether the name needs the definite article (The) * @return the formatted name */ public String getFormattedName(Context context, boolean isProper) { //Empty string that will be appended. String formattedName = ""; //Check tradability if (!tradable) { formattedName += context.getString(R.string.quality_non_tradable) + " "; } //Check craftability if (!craftable) { formattedName += context.getString(R.string.quality_non_craftable) + " "; } //Handle strangifier names differently if (defindex == 6522) { Cursor itemCursor = context.getContentResolver().query( DatabaseContract.ItemSchemaEntry.CONTENT_URI, new String[]{ItemSchemaEntry.COLUMN_ITEM_NAME, ItemSchemaEntry.COLUMN_TYPE_NAME, ItemSchemaEntry.COLUMN_PROPER_NAME}, ItemSchemaEntry.TABLE_NAME + "." + ItemSchemaEntry.COLUMN_DEFINDEX + " = ?", new String[]{String.valueOf(defindex)}, null ); if (itemCursor != null) { if (itemCursor.moveToFirst()) { formattedName += itemCursor.getString(0) + " " + name; } itemCursor.close(); } return formattedName; } else //TODO Handle chemistry set names differently if (defindex == 20001) { } //Switch case for the quality switch (quality) { case Quality.NORMAL: formattedName += context.getString(R.string.quality_normal) + " "; break; case Quality.GENUINE: formattedName += context.getString(R.string.quality_genuine) + " "; break; case Quality.VINTAGE: formattedName += context.getString(R.string.quality_vintage) + " "; break; case Quality.UNIQUE: if (priceIndex > 0) //A unique item with a number name = name + " #" + priceIndex; break; case Quality.UNUSUAL: //Get the unusual effect name by its index formattedName += Utility.getUnusualEffectName(context, priceIndex) + " "; break; case Quality.COMMUNITY: formattedName += context.getString(R.string.quality_community) + " "; break; case Quality.VALVE: formattedName += context.getString(R.string.quality_valve) + " "; break; case Quality.SELF_MADE: formattedName += context.getString(R.string.quality_self_made) + " "; break; case Quality.STRANGE: formattedName += context.getString(R.string.quality_strange) + " "; break; case Quality.HAUNTED: formattedName += context.getString(R.string.quality_haunted) + " "; break; case Quality.COLLECTORS: formattedName += context.getString(R.string.quality_collectors) + " "; break; default: formattedName += context.getString(R.string.quality_normal) + " "; break; } if (australium) { formattedName += "Australium "; } //Append the item name to the end. return isProper ? formattedName + "The " + name : formattedName + name; } /** * Properly formats the item name according to its properties. * * @param context the context * @return the formatted name */ public String getFormattedName(Context context) { return getFormattedName(context, false); } /** * Properly formats the item name according to its properties. Simple version. * * @param context the context * @param isProper whether the name needs the definite article (The) * @return the formatted name */ public String getSimpleFormattedName(Context context, boolean isProper) { if (quality == Quality.UNUSUAL) { return context.getString(R.string.quality_unusual) + " " + name; } else if (isProper && quality == Quality.UNIQUE) { return getFormattedName(context, true); } else { return getFormattedName(context, false); } } /** * Properly formats the item name according to its properties. Simple version. * * @param context the context * @return the formatted name */ public String getSimpleFormattedName(Context context) { return getSimpleFormattedName(context, false); } /** * Check whether the item can have particle effects. * * @return true if the item can have particle effects */ public boolean canHaveEffects() { if (defindex >= 15000 && defindex <= 15059) { return false; //TODO weapon effects disabled for now } //Unusuals, self-made and community items if (quality == 5 || quality == 7 || quality == 9) { return defindex != 267 && defindex != 266; } else if (defindex == 1899 || defindex == 125) { //Cheater's Lament and Traveler's Hat return true; } return false; } /** * Returns quality color of the item. * * @param context the context * @param isDark whether to return the dark version of the color * @return the color of the item */ public int getColor(Context context, boolean isDark) { switch (quality) { case Quality.GENUINE: return isDark ? Utility.getColor(context, R.color.tf2_genuine_color_dark) : Utility.getColor(context, R.color.tf2_genuine_color); case Quality.VINTAGE: return isDark ? Utility.getColor(context, R.color.tf2_vintage_color_dark) : Utility.getColor(context, R.color.tf2_vintage_color); case Quality.UNUSUAL: return isDark ? Utility.getColor(context, R.color.tf2_unusual_color_dark) : Utility.getColor(context, R.color.tf2_unusual_color); case Quality.UNIQUE: return isDark ? Utility.getColor(context, R.color.tf2_unique_color_dark) : Utility.getColor(context, R.color.tf2_unique_color); case Quality.COMMUNITY: return isDark ? Utility.getColor(context, R.color.tf2_community_color_dark) : Utility.getColor(context, R.color.tf2_community_color); case Quality.VALVE: return isDark ? Utility.getColor(context, R.color.tf2_valve_color_dark) : Utility.getColor(context, R.color.tf2_valve_color); case Quality.SELF_MADE: return isDark ? Utility.getColor(context, R.color.tf2_community_color_dark) : Utility.getColor(context, R.color.tf2_community_color); case Quality.STRANGE: return isDark ? Utility.getColor(context, R.color.tf2_strange_color_dark) : Utility.getColor(context, R.color.tf2_strange_color); case Quality.HAUNTED: return isDark ? Utility.getColor(context, R.color.tf2_haunted_color_dark) : Utility.getColor(context, R.color.tf2_haunted_color); case Quality.COLLECTORS: return isDark ? Utility.getColor(context, R.color.tf2_collectors_color_dark) : Utility.getColor(context, R.color.tf2_collectors_color); case Quality.PAINTKITWEAPON: return getDecoratedWeaponColor(context, isDark); default: return isDark ? Utility.getColor(context, R.color.tf2_normal_color_dark) : Utility.getColor(context, R.color.tf2_normal_color); } } /** * Gets the quality color of a decorated weapon color. * * @param context the context * @param isDark whether to return the dark version * @return the desired color */ private int getDecoratedWeaponColor(Context context, boolean isDark) { int colorResource = 0; switch (defindex) { case 15025: case 15026: case 15027: case 15028: case 15029: case 15039: case 15040: case 15041: case 15042: case 15043: case 15044: colorResource = isDark ? R.color.tf2_decorated_weapon_civilian_dark : R.color.tf2_decorated_weapon_civilian; break; case 15020: case 15021: case 15022: case 15023: case 15024: case 15035: case 15036: case 15037: case 15038: colorResource = isDark ? R.color.tf2_decorated_weapon_freelance_dark : R.color.tf2_decorated_weapon_freelance; break; case 15000: case 15001: case 15003: case 15004: case 15005: case 15008: case 15016: case 15017: case 15018: case 15032: case 15033: case 15034: case 15047: case 15054: case 15055: case 15057: case 15058: colorResource = isDark ? R.color.tf2_decorated_weapon_mercenary_dark : R.color.tf2_decorated_weapon_mercenary; break; case 15002: case 15006: case 15010: case 15012: case 15015: case 15019: case 15030: case 15031: case 15046: case 15049: case 15050: case 15051: case 15056: colorResource = isDark ? R.color.tf2_decorated_weapon_commando_dark : R.color.tf2_decorated_weapon_commando; break; case 15007: case 15009: case 15011: case 15048: case 15052: case 15053: colorResource = isDark ? R.color.tf2_decorated_weapon_assassin_dark : R.color.tf2_decorated_weapon_assassin; break; case 15013: case 15014: case 15045: case 15059: colorResource = isDark ? R.color.tf2_decorated_weapon_elite_dark : R.color.tf2_decorated_weapon_elite; break; } return colorResource == 0 ? Utility.getColor(context, R.color.tf2_normal_color) : Utility.getColor(context, colorResource); } /** * Gets the decorated weapon description. * * @param type the type of the decorated weapon * @return the formatted description string */ public String getDecoratedWeaponDesc(String type) { String wearStr; switch (weaponWear) { case 1045220557: wearStr = "Factory New"; break; case 1053609165: wearStr = "Minimal Wear"; break; case 1058642330: wearStr = "Field-Tested"; break; case 1061997773: wearStr = "Well Worn"; break; case 1065353216: wearStr = "Battle Scarred"; break; default: throw new IllegalArgumentException("Invalid wear: " + weaponWear); } switch (defindex) { case 15025: case 15026: case 15027: case 15028: case 15029: case 15039: case 15040: case 15041: case 15042: case 15043: case 15044: return "Civilian Grade " + type + " " + wearStr; case 15020: case 15021: case 15022: case 15023: case 15024: case 15035: case 15036: case 15037: case 15038: return "Freelance Grade " + type + " " + wearStr; case 15000: case 15001: case 15003: case 15004: case 15005: case 15008: case 15016: case 15017: case 15018: case 15032: case 15033: case 15034: case 15047: case 15054: case 15055: case 15057: case 15058: return "Mercenary Grade " + type + " " + wearStr; case 15002: case 15006: case 15010: case 15012: case 15015: case 15019: case 15030: case 15031: case 15046: case 15049: case 15050: case 15051: case 15056: return "Commando Grade " + type + " " + wearStr; case 15007: case 15009: case 15011: case 15048: case 15052: case 15053: return "Assassin Grade " + type + " " + wearStr; case 15013: case 15014: case 15045: case 15059: return "Elite Grade " + type + " " + wearStr; default: throw new IllegalArgumentException("Invalid defindex: " + defindex); } } /** * This method is for achieving consistency between GetPrices defindexes and GetPlayerItems * defindexes. There are some duplicate items, resulting in no prices in backpack. * * @return common defindex */ public int getFixedDefindex() { // TODO: 2015. 10. 26. create a way to auto generate this method //Check if the defindex is of a duplicate defindex to provide the proper price for it. switch (defindex) { case 9: case 10: case 11: case 12: //duplicate shotguns return 9; case 23: //duplicate pistol return 22; case 28: //duplicate destruction tool return 26; case 190: case 191: case 192: case 193: case 194: //duplicate stock weapons case 195: case 196: case 197: case 198: case 199: return defindex - 190; case 200: case 201: case 202: case 203: case 204: //duplicate stock weapons case 205: case 206: case 207: case 208: case 209: return defindex - 187; case 210: return defindex - 186; case 211: case 212: return defindex - 182; case 736: //duplicate sapper return 735; case 737: //duplicate construction pda return 25; case 5041: case 5045: //duplicate crates return 5022; case 5735: case 5742: case 5752: case 5781: case 5802: //duplicate munitions return 5734; default: return defindex; } } /** * Returns the url link for the icon if the item. * * @param context the context * @return Uri object */ public Uri getIconUrl(Context context) { String BASE_URL = "http://tlongdev.com/api/tf2_icon.php"; Uri.Builder builder = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter("defindex", String.valueOf(defindex)) .appendQueryParameter("filetype", "webp"); // TODO: 2015. 11. 09. boolean large = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("dummy", false); if (large) { builder.appendQueryParameter("large", "1"); } if (australium) { builder.appendQueryParameter("australium", "1"); } else if (weaponWear > 0) { builder.appendQueryParameter("wear", String.valueOf(weaponWear)); } return builder.build(); } /** * Returns the url link for the effect if the item. * * @param context the context * @return Uri object */ public Uri getEffectUrl(Context context) { String BASE_URL = "http://tlongdev.com/api/tf2_icon.php"; Uri.Builder builder = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter("effect", String.valueOf(priceIndex)) .appendQueryParameter("filetype", "webp"); // TODO: 2015. 11. 09. boolean large = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("dummy", false); if (large) { builder.appendQueryParameter("large", "1"); } return builder.build(); } public String getBackpackTfUrl() { String url = String.format("http://backpack.tf/stats/%d/%d/%d/%d", quality, defindex, tradable ? 1 : 0, craftable ? 1 : 0); return priceIndex > 0 ? url + "/" + priceIndex : url; } }
package com.zsx.util; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import com.zsx.debug.LogUtil; import java.io.File; public class Lib_Util_Intent { /** * * * @param mContext * @param smstext * @return */ public static void sendSms(Context mContext, String smstext) { Uri smsToUri = Uri.parse("smsto:"); Intent mIntent = new Intent(Intent.ACTION_SENDTO, smsToUri); mIntent.putExtra("sms_body", smstext); mContext.startActivity(mIntent); } /** * * * @param mContext Context * @param toUser * @param title * @param text * @return */ public static void sendMail(Context mContext, String[] toUser, String title, String text) { Intent emailIntent = new Intent(Intent.ACTION_SEND); // emailIntent.setType("text/plain"); // emailIntent.setType("message/rfc822"); emailIntent.putExtra(Intent.EXTRA_EMAIL, toUser); emailIntent.putExtra(Intent.EXTRA_SUBJECT, title); emailIntent.putExtra(Intent.EXTRA_TEXT, text); mContext.startActivity(Intent.createChooser(emailIntent, "Choose Email Client")); } /** * App * * @param context * @param packageName * @throws ActivityNotFoundException * @throws SecurityException */ public static void uninstallApp(Context context, String packageName) throws ActivityNotFoundException, SecurityException { Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName)); context.startActivity(uninstallIntent); } /** * * * @param activityTitle Activity * @param msgTitle * @param msgText * @param imgPath null */ public void shareMsg(Context context, String activityTitle, String msgTitle, String msgText, String imgPath) { Intent intent = new Intent(Intent.ACTION_SEND); if (imgPath == null || imgPath.equals("")) { intent.setType("text/plain"); } else { File f = new File(imgPath); if (f != null && f.exists() && f.isFile()) { intent.setType("image/jpg"); Uri u = Uri.fromFile(f); intent.putExtra(Intent.EXTRA_STREAM, u); } } intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle); intent.putExtra(Intent.EXTRA_TEXT, msgText); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(Intent.createChooser(intent, activityTitle)); } catch (ActivityNotFoundException ex) { Toast.makeText(context, "", Toast.LENGTH_SHORT).show(); } } public static void startInstallAPK(Context context, String apkPath) { File apk = new File(apkPath); if (!apk.exists()) { LogUtil.e(Lib_Util_Intent.class, "" + apkPath); return; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive"); context.startActivity(intent); } public void a() { Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); /** --Task */ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } public static boolean installFromMarket(Context activity) { try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + activity.getPackageName()))); return true; } catch (ActivityNotFoundException e) { return false; } } }
package peter.mathclock; import android.os.Bundle; import android.os.Handler; import android.support.annotation.IdRes; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.google.common.collect.ListMultimap; import org.joda.time.LocalTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class MainActivity extends AppCompatActivity { private final DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss"); private Clock clock; private TextView clockText; private UpdateTask updateTask; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); MappingParser parser = new MappingParser(this); ListMultimap<Integer, Integer> mapping = parser.loadMapping("mapping.properties"); clock = new Clock(getImage(R.id.clockHours), getImage(R.id.clockMinutes), getImage(R.id.clockSeconds), mapping); clockText = (TextView) findViewById(R.id.clockText); updateTask = new UpdateTask(); handler = new Handler(); updateClock(); schedule(); } private ImageView getImage(@IdRes int id) { return (ImageView) findViewById(id); } private class UpdateTask implements Runnable { @Override public void run() { updateClock(); schedule(); } } private void schedule() { handler.postDelayed(updateTask, 1000); } private void updateClock() { LocalTime now = LocalTime.now(); clock.show(now); clockText.setText(format.print(now)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement // if (id == R.id.action_settings) { // return true; return super.onOptionsItemSelected(item); } }
package org.commcare.activities; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import org.commcare.CommCareApplication; import org.commcare.dalvik.BuildConfig; import org.commcare.engine.resource.AppInstallStatus; import org.commcare.engine.resource.ResourceInstallUtils; import org.commcare.interfaces.CommCareActivityUIController; import org.commcare.interfaces.WithUIController; import org.commcare.tasks.InstallStagedUpdateTask; import org.commcare.tasks.TaskListener; import org.commcare.tasks.TaskListenerRegistrationException; import org.commcare.tasks.UpdateTask; import org.commcare.utils.ConnectivityStatus; import org.commcare.utils.ConsumerAppsUtil; import org.commcare.views.dialogs.CustomProgressDialog; import org.javarosa.core.services.locale.Localization; /** * Allow user to manage app updating: * - Check and download the latest update * - Stop a downloading update * - Apply a downloaded update * * @author Phillip Mates (pmates@dimagi.com) */ public class UpdateActivity extends CommCareActivity<UpdateActivity> implements TaskListener<Integer, AppInstallStatus>, WithUIController { public static final String KEY_FROM_LATEST_BUILD_ACTIVITY = "from-test-latest-build-util"; // Options menu codes private static final int MENU_UPDATE_FROM_CCZ = 0; // Activity request codes private static final int OFFLINE_UPDATE = 0; private static final String TAG = UpdateActivity.class.getSimpleName(); private static final String TASK_CANCELLING_KEY = "update_task_cancelling"; private static final String IS_APPLYING_UPDATE_KEY = "applying_update_task_running"; private static final int DIALOG_UPGRADE_INSTALL = 6; private static final int DIALOG_CONSUMER_APP_UPGRADE = 7; private boolean taskIsCancelling; private boolean isApplyingUpdate; private UpdateTask updateTask; private UpdateUIController uiController; private boolean proceedAutomatically; private boolean isLocalUpdate; private String offlineUpdateRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiController.setupUI(); if (getIntent().getBooleanExtra(KEY_FROM_LATEST_BUILD_ACTIVITY, false)) { proceedAutomatically = true; } else if (CommCareApplication._().isConsumerApp()) { proceedAutomatically = true; isLocalUpdate = true; } loadSavedInstanceState(savedInstanceState); boolean isRotation = savedInstanceState != null; setupUpdateTask(isRotation); } private void loadSavedInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { taskIsCancelling = savedInstanceState.getBoolean(TASK_CANCELLING_KEY, false); isApplyingUpdate = savedInstanceState.getBoolean(IS_APPLYING_UPDATE_KEY, false); uiController.loadSavedUIState(savedInstanceState); } } private void setupUpdateTask(boolean isRotation) { updateTask = UpdateTask.getRunningInstance(); if (updateTask != null) { try { updateTask.registerTaskListener(this); } catch (TaskListenerRegistrationException e) { Log.e(TAG, "Attempting to register a TaskListener to an already " + "registered task."); uiController.errorUiState(); } } else if (!isRotation && !taskIsCancelling && (ConnectivityStatus.isNetworkAvailable(this) || offlineUpdateRef != null)) { startUpdateCheck(); } } @Override protected void onResume() { super.onResume(); if (!ConnectivityStatus.isNetworkAvailable(this) && offlineUpdateRef == null) { uiController.noConnectivityUiState(); return; } setUiFromTask(); } private void setUiFromTask() { if (updateTask != null) { if (taskIsCancelling) { uiController.cancellingUiState(); } else { setUiStateFromTaskStatus(updateTask.getStatus()); } int currentProgress = updateTask.getProgress(); int maxProgress = updateTask.getMaxProgress(); uiController.updateProgressBar(currentProgress, maxProgress); } else { setPendingUpdate(); } uiController.refreshView(); } private void setUiStateFromTaskStatus(AsyncTask.Status taskStatus) { switch (taskStatus) { case RUNNING: uiController.downloadingUiState(); break; case PENDING: break; case FINISHED: uiController.errorUiState(); break; default: uiController.errorUiState(); } } private void setPendingUpdate() { if (!isApplyingUpdate && ResourceInstallUtils.isUpdateReadyToInstall()) { uiController.unappliedUpdateAvailableUiState(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterTask(); } private void unregisterTask() { if (updateTask != null) { try { updateTask.unregisterTaskListener(this); } catch (TaskListenerRegistrationException e) { Log.e(TAG, "Attempting to unregister a not previously " + "registered TaskListener."); } updateTask = null; } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(TASK_CANCELLING_KEY, taskIsCancelling); outState.putBoolean(IS_APPLYING_UPDATE_KEY, isApplyingUpdate); uiController.saveCurrentUIState(outState); } @Override public void handleTaskUpdate(Integer... vals) { int progress = vals[0]; int max = vals[1]; uiController.updateProgressBar(progress, max); String msg = Localization.get("updates.found", new String[]{"" + progress, "" + max}); uiController.updateProgressText(msg); } @Override public void handleTaskCompletion(AppInstallStatus result) { if (CommCareApplication._().isConsumerApp()) { dismissProgressDialog(); } if (result == AppInstallStatus.UpdateStaged) { uiController.unappliedUpdateAvailableUiState(); if (proceedAutomatically) { launchUpdateInstallTask(); } } else if (result == AppInstallStatus.UpToDate) { uiController.upToDateUiState(); if (proceedAutomatically) { finishWithResult(RefreshToLatestBuildActivity.ALREADY_UP_TO_DATE); } } else { // Gives user generic failure warning; even if update staging // failed for a specific reason like xml syntax uiController.checkFailedUiState(); if (proceedAutomatically) { finishWithResult(RefreshToLatestBuildActivity.UPDATE_ERROR); } } unregisterTask(); uiController.refreshView(); } private void finishWithResult(String result) { Intent i = new Intent(); setResult(RESULT_OK, i); i.putExtra(RefreshToLatestBuildActivity.KEY_UPDATE_ATTEMPT_RESULT, result); finish(); } @Override public void handleTaskCancellation() { unregisterTask(); uiController.idleUiState(); } protected void startUpdateCheck() { try { updateTask = UpdateTask.getNewInstance(); initUpdateTaskProgressDisplay(); if (isLocalUpdate) { updateTask.setLocalAuthority(); } updateTask.registerTaskListener(this); } catch (IllegalStateException e) { connectToRunningTask(); return; } catch (TaskListenerRegistrationException e) { enterErrorState("Attempting to register a TaskListener to an " + "already registered task."); return; } String profileRef; if (offlineUpdateRef != null) { profileRef = offlineUpdateRef; offlineUpdateRef = null; } else { profileRef = ResourceInstallUtils.getDefaultProfileRef(); } updateTask.executeParallel(profileRef); uiController.downloadingUiState(); } /** * Since updates in a consumer app do not use the normal UpdateActivity UI, use an * alternative method of displaying the update check's progress in that case */ private void initUpdateTaskProgressDisplay() { if (CommCareApplication._().isConsumerApp()) { showProgressDialog(DIALOG_CONSUMER_APP_UPGRADE); } else { updateTask.startPinnedNotification(this); } } private void connectToRunningTask() { setupUpdateTask(false); setUiFromTask(); } private void enterErrorState(String errorMsg) { Log.e(TAG, errorMsg); uiController.errorUiState(); } public void stopUpdateCheck() { if (updateTask != null) { updateTask.cancelWasUserTriggered(); updateTask.cancel(true); taskIsCancelling = true; uiController.cancellingUiState(); } else { uiController.idleUiState(); } if (proceedAutomatically) { finishWithResult(RefreshToLatestBuildActivity.UPDATE_CANCELED); } } /** * Block the user with a dialog while the update is finalized. */ protected void launchUpdateInstallTask() { InstallStagedUpdateTask<UpdateActivity> task = new InstallStagedUpdateTask<UpdateActivity>(DIALOG_UPGRADE_INSTALL) { @Override protected void deliverResult(UpdateActivity receiver, AppInstallStatus result) { if (result == AppInstallStatus.Installed) { receiver.logoutOnSuccessfulUpdate(); } else { if (proceedAutomatically) { finishWithResult(RefreshToLatestBuildActivity.UPDATE_ERROR); return; } receiver.uiController.errorUiState(); } receiver.isApplyingUpdate = false; } @Override protected void deliverUpdate(UpdateActivity receiver, int[]... update) { } @Override protected void deliverError(UpdateActivity receiver, Exception e) { receiver.uiController.errorUiState(); receiver.isApplyingUpdate = false; } }; task.connect(this); task.executeParallel(); isApplyingUpdate = true; uiController.applyingUpdateUiState(); } @Override public CustomProgressDialog generateProgressDialog(int taskId) { if (CommCareApplication._().isConsumerApp()) { return ConsumerAppsUtil.getGenericConsumerAppsProgressDialog(taskId, false); } else if (taskId != DIALOG_UPGRADE_INSTALL) { Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareSetupActivity"); return null; } else { return generateNormalUpdateInstallDialog(taskId); } } private static CustomProgressDialog generateNormalUpdateInstallDialog(int taskId) { String title = Localization.get("updates.installing.title"); String message = Localization.get("updates.installing.message"); CustomProgressDialog dialog = CustomProgressDialog.newInstance(title, message, taskId); dialog.setCancelable(false); return dialog; } private void logoutOnSuccessfulUpdate() { final String upgradeFinishedText = Localization.get("updates.install.finished"); CommCareApplication._().expireUserSession(); if (proceedAutomatically) { finishWithResult(RefreshToLatestBuildActivity.UPDATE_SUCCESS); } else { Toast.makeText(this, upgradeFinishedText, Toast.LENGTH_LONG).show(); setResult(RESULT_OK); this.finish(); } } @Override public String getActivityTitle() { return "Update" + super.getActivityTitle(); } @Override public void initUIController() { boolean fromAppManager = getIntent().getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false); if (CommCareApplication._().isConsumerApp()) { uiController = new BlankUpdateUIController(this, fromAppManager); } else { uiController = new UpdateUIController(this, fromAppManager); } } @Override public CommCareActivityUIController getUIController() { return this.uiController; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_UPDATE_FROM_CCZ, 0, Localization.get("menu.update.from.ccz")); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(MENU_UPDATE_FROM_CCZ).setVisible(BuildConfig.DEBUG || !getIntent().getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false)); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_UPDATE_FROM_CCZ: Intent i = new Intent(getApplicationContext(), InstallArchiveActivity.class); i.putExtra(InstallArchiveActivity.FROM_UPDATE, true); startActivityForResult(i, OFFLINE_UPDATE); return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch(requestCode) { case OFFLINE_UPDATE: if (resultCode == Activity.RESULT_OK) { offlineUpdateRef = intent.getStringExtra(InstallArchiveActivity.ARCHIVE_JR_REFERENCE); if (offlineUpdateRef != null) { isLocalUpdate = true; setupUpdateTask(false); } } break; } } }
package verification.platu.logicAnalysis; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import javax.swing.JOptionPane; import lpn.parser.Abstraction; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.LpnDecomposition.LpnProcess; import main.Gui; import verification.platu.MDD.MDT; import verification.platu.MDD.Mdd; import verification.platu.MDD.mddNode; import verification.platu.common.IndexObjMap; import verification.platu.lpn.LPNTranRelation; import verification.platu.lpn.LpnTranList; import verification.platu.main.Options; import verification.platu.markovianAnalysis.ProbGlobalState; import verification.platu.markovianAnalysis.ProbGlobalStateSet; import verification.platu.markovianAnalysis.ProbLocalStateGraph; import verification.platu.partialOrders.DependentSet; import verification.platu.partialOrders.DependentSetComparator; import verification.platu.partialOrders.StaticSets; import verification.platu.por1.AmpleSet; import verification.platu.project.PrjState; import verification.platu.stategraph.State; import verification.platu.stategraph.StateGraph; import verification.timed_state_exploration.zoneProject.EventSet; import verification.timed_state_exploration.zoneProject.TimedPrjState; import verification.timed_state_exploration.zoneProject.TimedStateSet; import verification.timed_state_exploration.zoneProject.Zone; public class Analysis { private LinkedList<Transition> traceCex; protected Mdd mddMgr = null; private HashMap<Transition, HashSet<Transition>> cachedNecessarySets = new HashMap<Transition, HashSet<Transition>>(); /* * visitedTrans is used in computeNecessary for a disabled transition of interest, to keep track of all transitions visited during trace-back. */ private HashSet<Transition> visitedTrans; HashMap<Transition, StaticSets> staticDependency = new HashMap<Transition, StaticSets>(); public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) { traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); if (method.equals("dfs")) { //if (Options.getPOR().equals("off")) { //this.search_dfs(lpnList, initStateArray); //this.search_dfs_mdd_1(lpnList, initStateArray); //this.search_dfs_mdd_2(lpnList, initStateArray); //else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); } else if (method.equals("bfs")==true) this.search_bfs(lpnList, initStateArray); else if (method == "dfs_noDisabling") //this.search_dfs_noDisabling(lpnList, initStateArray); this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * This constructor performs dfs. * @param lpnList */ public Analysis(StateGraph[] lpnList){ traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); // if (method.equals("dfs")) { // if (Options.getPOR().equals("off")) { // //this.search_dfs(lpnList, initStateArray); // this.search_dfsNative(lpnList, initStateArray); // //this.search_dfs_mdd_1(lpnList, initStateArray); // //this.search_dfs_mdd_2(lpnList, initStateArray); // else // //behavior analysis // boolean BA = true; // if(BA==true) // CompositionalAnalysis.searchCompositional(lpnList); // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); // else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "lpn"); // else if (method.equals("bfs")==true) // this.search_bfs(lpnList, initStateArray); // else if (method == "dfs_noDisabling") // //this.search_dfs_noDisabling(lpnList, initStateArray); // this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * Recursively find all reachable project states. */ int iterations = 0; int stack_depth = 0; int max_stack_depth = 0; public void search_recursive(final StateGraph[] lpnList, final State[] curPrjState, final ArrayList<LinkedList<Transition>> enabledList, HashSet<PrjState> stateTrace) { int lpnCnt = lpnList.length; HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); stack_depth++; if (stack_depth > max_stack_depth) max_stack_depth = stack_depth; iterations++; if (iterations % 50000 == 0) System.out.println("iterations: " + iterations + ", # of prjStates found: " + prjStateSet.size() + ", max_stack_depth: " + max_stack_depth); for (int index = 0; index < lpnCnt; index++) { LinkedList<Transition> curEnabledSet = enabledList.get(index); if (curEnabledSet == null) continue; for (Transition firedTran : curEnabledSet) { // while(curEnabledSet.size() != 0) { // LPNTran firedTran = curEnabledSet.removeFirst(); // TODO: (check) Not sure if lpnList[index] is correct State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran); // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. PrjState nextPrjState = new PrjState(nextStateArray); if (stateTrace.contains(nextPrjState) == true) ;// System.out.println("found a cycle"); if (prjStateSet.add(nextPrjState) == false) { continue; } // Get the list of enabled transition sets, and call // findsg_recursive. ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>(); for (int i = 0; i < lpnCnt; i++) { if (curPrjState[i] != nextStateArray[i]) { StateGraph Lpn_tmp = lpnList[i]; nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran, // enabledList.get(i), // false)); } else { nextEnabledList.add(i, enabledList.get(i)); } } stateTrace.add(nextPrjState); search_recursive(lpnList, nextStateArray, nextEnabledList, stateTrace); stateTrace.remove(nextPrjState); } } } /** * An iterative implement of findsg_recursive(). * * @param sgList * @param start * @param curLocalStateArray * @param enabledArray */ @SuppressWarnings("unchecked") public StateSetInterface search_dfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println(" System.out.println("---> calling function search_dfs"); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; //Stack<State[]> stateStack = new Stack<State[]>(); HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); //HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // Set of PrjStates that have been seen before. Set class documentation // for how it behaves. Timing Change. // HashMap<PrjState, PrjState> prjStateSet = generateStateSet(); StateSetInterface prjStateSet = generateStateSet(); PrjState initPrjState; // Create the appropriate type for the PrjState depending on whether timing is // being used or not. Timing Change. if(!Options.getTimingAnalysisFlag()){ // If not doing timing. if (!Options.getMarkovianModelFlag()) initPrjState = new PrjState(initStateArray); else initPrjState = new ProbGlobalState(initStateArray); } else{ // If timing is enabled. initPrjState = new TimedPrjState(initStateArray); // Set the initial values of the inequality variables. //((TimedPrjState) initPrjState).updateInequalityVariables(); } prjStateSet.add(initPrjState); //prjStateSet.put(initPrjState, initPrjState); if(Options.getMarkovianModelFlag()) ((ProbGlobalStateSet) prjStateSet).setInitState(initPrjState); PrjState stateStackTop; stateStackTop = initPrjState; if (Options.getDebugMode()) printStateArray(stateStackTop.toStateArray(), "~~~~ stateStackTop ~~~~"); stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) printDstLpnList(sgList); LpnTranList initEnabled; if(!Options.getTimingAnalysisFlag()){ // Timing Change. initEnabled = sgList[0].getEnabledFromTranVector(initStateArray[0]); // The init } else { // When timing is enabled, it is the project state that will determine // what is enabled since it contains the zone. This indicates the zeroth zone // contained in the project and the zeroth LPN to get the transitions from. initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0); } lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); if (Options.getDebugMode()) { System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); printTransList(initEnabled, "initEnabled"); } main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); if (failureTranIsEnabled(curEnabled)) { return null; } if (Options.getDebugMode()) { printStateArray(curStateArray, " printTransList(curEnabled, "+++++++ curEnabled trans ++++++++"); } // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); if (Options.getDebugMode()) { System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); printTranStack(lpnTranStack, "***** lpnTranStack *****"); } curIndexStack.pop(); curIndex++; while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); if(!Options.getTimingAnalysisFlag()){ // Timing Change curEnabled = sgList[curIndex].getEnabledFromTranVector(curStateArray[curIndex]).clone(); } else{ // Get the enabled transitions from the zone that are associated with // the current LPN. curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex); } if (curEnabled.size() > 0) { if (Options.getDebugMode()) { printTransList(curEnabled, "+++++++ Push trans onto lpnTranStack ++++++++"); } lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); break; } curIndex++; } } if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "~~~~ Remove stateStackTop from stateStack ~~~~"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curEnabled.removeLast(); if (Options.getDebugMode()) { System.out.println(" System.out.println("Fired transition: " + firedTran.getFullLabel()); System.out.println(" } State[] nextStateArray; PrjState nextPrjState; // Moved this definition up. Timing Change. // The next state depends on whether timing is in use or not. // Timing Change. if(!Options.getTimingAnalysisFlag()){ nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); if (!Options.getMarkovianModelFlag()) nextPrjState = new PrjState(nextStateArray); else nextPrjState = new ProbGlobalState(nextStateArray); } else{ // Get the next timed state and extract the next un-timed states. nextPrjState = sgList[curIndex].fire(sgList, stateStackTop, (EventSet) firedTran); nextStateArray = nextPrjState.toStateArray(); } tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns]; LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns]; for (int i = 0; i < numLpns; i++) { LinkedList<Transition> enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sgList[i].getEnabledFromTranVector(curStateArray[i]); } else{ // Get the enabled transitions from the Zone for the appropriate // LPN. //enabledList = ((TimedPrjState) stateStackTop).getEnabled(i); enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i); } curEnabledArray[i] = enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sgList[i].getEnabledFromTranVector(nextStateArray[i]); } else{ //enabledList = ((TimedPrjState) nextPrjState).getEnabled(i); enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i); } nextEnabledArray[i] = enabledList; // TODO: (temp) Stochastic model does not need disabling error? if (Options.getReportDisablingError() && !Options.getMarkovianModelFlag()) { Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } if(!Options.getTimingAnalysisFlag()){ if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } } else{ if (Analysis.deadLock(nextEnabledArray)){ System.out.println("*** Verification failed: deadlock."); failure = true; JOptionPane.showMessageDialog(Gui.frame, "The system deadlocked.", "Error", JOptionPane.ERROR_MESSAGE); break main_while_loop; } } //PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change. Boolean existingState; existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState); //existingState = prjStateSet.keySet().contains(nextPrjState); //|| stateStack.contains(nextPrjState); if (existingState == false) { prjStateSet.add(nextPrjState); //prjStateSet.put(nextPrjState,nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getMarkovianModelFlag()) { if (Options.getBuildGlobalStateGraph()) { // Add <firedTran, nextPrjState> to stateStackTop's nextGlobalStateMap. ((ProbGlobalState) stateStackTop).addNextGlobalState(firedTran, nextPrjState); } } else { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // printNextStateMap(stateStackTop.getNextStateMap()); } } stateStackTop = nextPrjState; stateStack.add(stateStackTop); lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); curIndexStack.push(0); totalStates++; if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "~~~~~~~ Add global state to stateStack ~~~~~~~"); System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); printTransList(nextEnabledArray[0], ""); printTranStack(lpnTranStack, "******** lpnTranStack ***********"); } } else { // existingState == true if (Options.getMarkovianModelFlag()) { if (Options.getBuildGlobalStateGraph()) { // Add <firedTran, nextPrjState> to stateStackTop's nextGlobalStateMap. ((ProbGlobalState) stateStackTop).addNextGlobalState(firedTran, nextPrjState); } } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { printStateArray(curStateArray, "******* curStateArray *******"); printStateArray(nextStateArray, "******* nextStateArray *******"); printStateArray(stateStackTop.toStateArray(), "stateStackTop: "); System.out.println("firedTran = " + firedTran.getFullLabel()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextGlobalStateMap(stateStackTop.getNextStateMap()); } } } } } double totalStateCnt =0; totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStateCnt + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if(Options.getTimingAnalysisFlag() && !failure){ JOptionPane.showMessageDialog(Gui.frame, "Verification was successful.", "Success", JOptionPane.INFORMATION_MESSAGE); System.out.println(prjStateSet.toString()); } if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { System.out.println("outputSGPath = " + Options.getPrjSgPath()); // TODO: Andrew: I don't think you need the toHashSet() now. //drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true); drawGlobalStateGraph(sgList, initPrjState, prjStateSet, true); } // try{ // File stateFile = new File(Options.getPrjSgPath() + Options.getLogName() + ".txt"); // FileWriter fileWritter = new FileWriter(stateFile,true); // BufferedWriter bufferWritter = new BufferedWriter(fileWritter); // // TODO: Need to merge variable vectors from different local states. // ArrayList<Integer> vector; // String curPrjStInfo = ""; // for (PrjState prjSt : prjStateSet) { // // marking // curPrjStInfo += "marking: "; // for (State localSt : prjSt.toStateArray()) // curPrjStInfo += intArrayToString("markings", localSt) + "\n"; // // variable vector // curPrjStInfo += "var values: "; // for (State localSt : prjSt.toStateArray()) { // localSt.getLpn().getAllVarsWithValuesAsInt(localSt.getVariableVector()); // //curPrjStInfo += intArrayToString("vars", localSt)+ "\n"; // // tranVector // curPrjStInfo += "tran vector: "; // for (State localSt : prjSt.toStateArray()) // curPrjStInfo += boolArrayToString("enabled trans", localSt)+ "\n"; // bufferWritter.write(curPrjStInfo); // //bufferWritter.flush(); // bufferWritter.close(); // System.out.println("Done writing state file."); // }catch(IOException e){ // e.printStackTrace(); //return sgList; return prjStateSet; } // private boolean failureCheck(LinkedList<Transition> curEnabled) { // boolean failureTranIsEnabled = false; // for (Transition tran : curEnabled) { // if (tran.isFail()) { // JOptionPane.showMessageDialog(Gui.frame, // "Failure transition " + tran.getLabel() + " is enabled.", "Error", // JOptionPane.ERROR_MESSAGE); // failureTranIsEnabled = true; // break; // return failureTranIsEnabled; // /** // * Generates the appropriate version of a HashSet<PrjState> for storing // * the "already seen" set of project states. // * @return // * Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet // * depending on the type. // */ // private HashSet<PrjState> generateStateSet(){ // boolean timed = Options.getTimingAnalysisFlag(); // boolean subsets = Zone.getSubsetFlag(); // boolean supersets = Zone.getSupersetFlag(); // if(Options.getMarkovianModelFlag()){ // return new ProbGlobalStateSet(); // else if(timed && (subsets || supersets)){ // return new TimedStateSet(); // return new HashSet<PrjState>(); /** * Generates the appropriate version of a HashSet<PrjState> for storing * the "already seen" set of project states. * @return * Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet * depending on the type. */ private StateSetInterface generateStateSet(){ boolean timed = Options.getTimingAnalysisFlag(); boolean subsets = Zone.getSubsetFlag(); boolean supersets = Zone.getSupersetFlag(); if(Options.getMarkovianModelFlag()){ return new ProbGlobalStateSet(); } else if(timed && (subsets || supersets)){ return new TimedStateSet(); } return new HashSetWrapper(); } private boolean failureTranIsEnabled(LinkedList<Transition> curAmpleTrans) { boolean failureTranIsEnabled = false; for (Transition tran : curAmpleTrans) { if (tran.isFail()) { if(Zone.get_writeLogFile() != null){ try { Zone.get_writeLogFile().write(tran.getLabel()); Zone.get_writeLogFile().newLine(); } catch (IOException e) { e.printStackTrace(); } } JOptionPane.showMessageDialog(Gui.frame, "Failure transition " + tran.getLabel() + " is enabled.", "Error", JOptionPane.ERROR_MESSAGE); failureTranIsEnabled = true; break; } } return failureTranIsEnabled; } public void drawGlobalStateGraph(StateGraph[] sgList, PrjState initGlobalState, StateSetInterface prjStateSet, boolean fullSG) { try { String fileName = null; if (fullSG) { fileName = Options.getPrjSgPath() + "full_sg.dot"; } else { fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_" + Options.getCycleClosingMthd().toLowerCase() + "_" + Options.getCycleClosingAmpleMethd().toLowerCase() + "_sg.dot"; } BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); NumberFormat num = NumberFormat.getNumberInstance();//NumberFormat.getInstance(); num.setMaximumFractionDigits(6); num.setGroupingUsed(false); out.write("digraph G {\n"); for (PrjState curGlobalState : prjStateSet) { // Build composite current global state. String curVarNames = ""; String curVarValues = ""; String curMarkings = ""; String curEnabledTrans = ""; String curGlobalStateIndex = ""; String curGlobalStateProb = null; HashMap<String, Integer> vars = new HashMap<String, Integer>(); for (State curLocalState : curGlobalState.toStateArray()) { curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex(); curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length()); LhpnFile curLpn = curLocalState.getLpn(); for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) { vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVariableVector()[i]); } curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState); if (!boolArrayToString("enabled trans", curLocalState).equals("")) curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); curVarValues = curVarValues + vValue + ", "; curVarNames = curVarNames + vName + ", "; } if (!curVarNames.isEmpty() && !curVarValues.isEmpty()) { curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(",")); curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(",")); } curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length()); curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length()); if (Options.getMarkovianModelFlag()) { // State probability after steady state analysis. curGlobalStateProb = num.format(((ProbGlobalState) curGlobalState).getCurrentProb()); } if (curGlobalState.equals(initGlobalState)) { out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n"); if (!Options.getMarkovianModelFlag()) out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\", style=filled]\n"); else out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\", style=filled]\n"); } else { if (!Options.getMarkovianModelFlag()) out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n"); else out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\"]\n"); } //curGlobalState // Build composite next global states. for (Transition outTran : curGlobalState.getOutgoingTrans()) { PrjState nextGlobalState = curGlobalState.getNextPrjState(outTran, (HashMap<PrjState, PrjState>) prjStateSet); String nextVarNames = ""; String nextVarValues = ""; String nextMarkings = ""; String nextEnabledTrans = ""; String nextGlobalStateIndex = ""; String nextGlobalStateProb = null; for (State nextLocalState : nextGlobalState.toStateArray()) { LhpnFile nextLpn = nextLocalState.getLpn(); for(int i = 0; i < nextLpn.getVarIndexMap().size(); i++) { vars.put(nextLpn.getVarIndexMap().getKey(i), nextLocalState.getVariableVector()[i]); } nextMarkings = nextMarkings + "," + intArrayToString("markings", nextLocalState); if (!boolArrayToString("enabled trans", nextLocalState).equals("")) nextEnabledTrans = nextEnabledTrans + "," + boolArrayToString("enabled trans", nextLocalState); nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); nextVarValues = nextVarValues + vValue + ", "; nextVarNames = nextVarNames + vName + ", "; } if (!nextVarNames.isEmpty() && !nextVarValues.isEmpty()) { nextVarNames = nextVarNames.substring(0, nextVarNames.lastIndexOf(",")); nextVarValues = nextVarValues.substring(0, nextVarValues.lastIndexOf(",")); } nextMarkings = nextMarkings.substring(nextMarkings.indexOf(",")+1, nextMarkings.length()); nextEnabledTrans = nextEnabledTrans.substring(nextEnabledTrans.indexOf(",")+1, nextEnabledTrans.length()); nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length()); if (Options.getMarkovianModelFlag()) { // State probability after steady state analysis. nextGlobalStateProb = num.format(((ProbGlobalState) nextGlobalState).getCurrentProb()); out.write(nextGlobalStateIndex + "[shape=ellipse,label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\\nProb = " + nextGlobalStateProb + "\"]\n"); } else out.write(nextGlobalStateIndex + "[shape=ellipse,label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\"]\n"); String outTranName = outTran.getLabel(); if (!Options.getMarkovianModelFlag()) { if (outTran.isFail() && !outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n"); else if (!outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n"); else if (outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n"); else out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n"); } else { State localState = curGlobalState.toStateArray()[outTran.getLpn().getLpnIndex()]; String outTranRate = num.format(((ProbLocalStateGraph) localState.getStateGraph()).getTranRate(localState, outTran)); if (outTran.isFail() && !outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=red]\n"); else if (!outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=blue]\n"); else if (outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=purple]\n"); else out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\"]\n"); } } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void drawDependencyGraphs(LhpnFile[] lpnList) { String fileName = Options.getPrjSgPath() + "dependencyGraph.dot"; BufferedWriter out; try { out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (Transition curTran : staticDependency.keySet()) { String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel(); out.write(curTranStr + "[shape=\"box\"];"); out.newLine(); } for (Transition curTran : staticDependency.keySet()) { StaticSets curStaticSets = staticDependency.get(curTran); String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel(); for (Transition curTranInDisable : curStaticSets.getOtherTransDisableCurTranSet()) { String curTranInDisableStr = curTranInDisable.getLpn().getLabel() + "_" + curTranInDisable.getLabel(); out.write(curTranInDisableStr + "->" + curTranStr + "[color=\"chocolate\"];"); out.newLine(); } // for (Transition curTranInDisable : curStaticSets.getCurTranDisableOtherTransSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"chocolate\"];"); // out.newLine(); // for (Transition curTranInDisable : curStaticSets.getDisableSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"blue\"];"); // out.newLine(); HashSet<Transition> enableByBringingToken = new HashSet<Transition>(); for (Place p : curTran.getPreset()) { for (Transition presetTran : p.getPreset()) { enableByBringingToken.add(presetTran); } } for (Transition curTranInCanEnable : enableByBringingToken) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"mediumaquamarine\"];"); out.newLine(); } for (HashSet<Transition> canEnableOneConjunctSet : curStaticSets.getOtherTransSetCurTranEnablingTrue()) { for (Transition curTranInCanEnable : canEnableOneConjunctSet) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"deepskyblue\"];"); out.newLine(); } } } out.write("}"); out.close(); } catch (IOException e) { e.printStackTrace(); } } private String intArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("markings")) { for (int i=0; i< curState.getMarking().length; i++) { if (curState.getMarking()[i] == 1) { arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ","; } // String tranName = curState.getLpn().getAllTransitions()[i].getName(); // if (curState.getTranVector()[i]) // System.out.println(tranName + " " + "Enabled"); // else // System.out.println(tranName + " " + "Not Enabled"); } arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } else if (type.equals("vars")) { for (int i=0; i< curState.getVariableVector().length; i++) { arrayStr = arrayStr + curState.getVariableVector()[i] + ","; } if (arrayStr.contains(",")) arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private String boolArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("enabled trans")) { for (int i=0; i< curState.getTranVector().length; i++) { if (curState.getTranVector()[i]) { //arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getFullLabel() + ", "; arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getLabel() + ", "; } } if (arrayStr != "") arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private void printStateArray(State[] stateArray, String title) { if (title != null) System.out.println(title); for (int i=0; i<stateArray.length; i++) { System.out.println("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +"): "); System.out.println("\tmarkings: " + intArrayToString("markings", stateArray[i])); System.out.println("\tvar values: " + intArrayToString("vars", stateArray[i])); System.out.println("\tenabled trans: " + boolArrayToString("enabled trans", stateArray[i])); } System.out.println(" } private void printTransList(LinkedList<Transition> tranList, String title) { if (title != null) System.out.println("+++++++" + title + "+++++++"); for (int i=0; i< tranList.size(); i++) System.out.println(tranList.get(i).getFullLabel() + ", "); System.out.println("+++++++++++++"); } // private void writeIntegerStackToDebugFile(Stack<Integer> curIndexStack, String title) { // if (title != null) // System.out.println(title); // for (int i=0; i < curIndexStack.size(); i++) { // System.out.println(title + "[" + i + "]" + curIndexStack.get(i)); private void printDstLpnList(StateGraph[] lpnList) { System.out.println("++++++ dstLpnList ++++++"); for (int i=0; i<lpnList.length; i++) { LhpnFile curLPN = lpnList[i].getLpn(); System.out.println("LPN: " + curLPN.getLabel()); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j< allTrans.length; j++) { System.out.println(allTrans[j].getLabel() + ": "); for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) { System.out.println(allTrans[j].getDstLpnList().get(k).getLabel() + ","); } System.out.print("\n"); } System.out.println(" } System.out.println("++++++++++++++++++++"); } private void constructDstLpnList(StateGraph[] sgList) { for (int i=0; i<sgList.length; i++) { LhpnFile curLPN = sgList[i].getLpn(); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j<allTrans.length; j++) { Transition curTran = allTrans[j]; for (int k=0; k<sgList.length; k++) { curTran.setDstLpnList(sgList[k].getLpn()); } } } } /** * This method performs first-depth search on an array of LPNs and applies partial order reduction technique with trace-back on LPNs. * @param sgList * @param initStateArray * @param cycleClosingMthdIndex * @return */ @SuppressWarnings("unchecked") public StateGraph[] searchPOR_taceback(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function searchPOR_traceback"); System.out.println("---> " + Options.getPOR()); System.out.println("---> " + Options.getCycleClosingMthd()); System.out.println("---> " + Options.getCycleClosingAmpleMethd()); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; LhpnFile[] lpnList = new LhpnFile[numLpns]; for (int i=0; i<numLpns; i++) { lpnList[i] = sgList[i].getLpn(); } HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); prjStateSet.add(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) printStateArray(stateStackTop.toStateArray(), "%%%%%%% stateStackTop %%%%%%%%"); stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) printDstLpnList(sgList); // Find static pieces for POR. HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length); //HashMap<Transition, StaticSets> staticSetsMap = new HashMap<Transition, StaticSets>(); HashMap<Transition, Integer> allProcessTransInOneLpn = new HashMap<Transition, Integer>(); HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses = new HashMap<Transition, LpnProcess>(); for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { allTransitions.put(lpnIndex, lpnList[lpnIndex].getAllTransitions()); Abstraction abs = new Abstraction(lpnList[lpnIndex]); abs.decomposeLpnIntoProcesses(); allProcessTransInOneLpn = (HashMap<Transition, Integer>)abs.getTransWithProcIDs(); HashMap<Integer, LpnProcess> processMapForOneLpn = new HashMap<Integer, LpnProcess>(); for (Transition curTran: allProcessTransInOneLpn.keySet()) { Integer procId = allProcessTransInOneLpn.get(curTran); if (!processMapForOneLpn.containsKey(procId)) { LpnProcess newProcess = new LpnProcess(procId); newProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (newProcess.getStateMachineFlag() && ((curTran.getPreset().length > 1) || (curTran.getPostset().length > 1))) { newProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { newProcess.addPlaceToProcess(p); } } processMapForOneLpn.put(procId, newProcess); allTransitionsToLpnProcesses.put(curTran, newProcess); } else { LpnProcess curProcess = processMapForOneLpn.get(procId); curProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (curProcess.getStateMachineFlag() && (curTran.getPreset().length > 1 || curTran.getPostset().length > 1)) { curProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { curProcess.addPlaceToProcess(p); } } allTransitionsToLpnProcesses.put(curTran, curProcess); } } } HashMap<Transition, Integer> tranFiringFreq = null; if (Options.getUseDependentQueue()) tranFiringFreq = new HashMap<Transition, Integer>(allTransitions.keySet().size()); // Need to build conjuncts for each transition's enabling condition first before dealing with dependency and enable sets. for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { for (Transition curTran: allTransitions.get(lpnIndex)) { if (curTran.getEnablingTree() != null) curTran.buildConjunctsOfEnabling(curTran.getEnablingTree()); } } for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { if (Options.getDebugMode()) { System.out.println("=======LPN = " + lpnList[lpnIndex].getLabel() + "======="); } for (Transition curTran: allTransitions.get(lpnIndex)) { StaticSets curStatic = new StaticSets(curTran, allTransitionsToLpnProcesses); curStatic.buildOtherTransSetCurTranEnablingTrue(); curStatic.buildCurTranDisableOtherTransSet(); if (Options.getPORdeadlockPreserve()) curStatic.buildOtherTransDisableCurTranSet(); else curStatic.buildModifyAssignSet(); staticDependency.put(curTran, curStatic); if (Options.getUseDependentQueue()) tranFiringFreq.put(curTran, 0); } } if (Options.getDebugMode()) { printStaticSetsMap(lpnList); } //boolean init = true; //LpnTranList initAmpleTrans = new LpnTranList(); LpnTranList initAmpleTrans = getAmple(initStateArray, null, tranFiringFreq, sgList, lpnList, stateStack, stateStackTop); lpnTranStack.push(initAmpleTrans); //init = false; if (Options.getDebugMode()) { printTransList(initAmpleTrans, "+++++++ Push trans onto lpnTranStack @ 1++++++++"); drawDependencyGraphs(lpnList); } // HashSet<Transition> initAmple = new HashSet<Transition>(); // for (Transition t: initAmpleTrans) { // initAmple.add(t); updateLocalAmpleTbl(initAmpleTrans, sgList, initStateArray); main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); if (failureTranIsEnabled(curAmpleTrans)) { return null; } if (curAmpleTrans.size() == 0) { lpnTranStack.pop(); prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); printTranStack(lpnTranStack, " System.out.println(" printPrjStateSet(prjStateSet); System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curAmpleTrans.removeLast(); //Transition firedTran = curAmpleTrans.removelast(); if (Options.getDebugMode()) { System.out.println(" System.out.println("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getLabel() + ")"); System.out.println(" } if (Options.getUseDependentQueue()) { Integer freq = tranFiringFreq.get(firedTran) + 1; tranFiringFreq.put(firedTran, freq); // if (Options.getDebugMode()) { // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, sgList); } State[] nextStateArray = sgList[firedTran.getLpn().getLpnIndex()].fire(sgList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. if (Options.getReportDisablingError()) { for (int i=0; i<numLpns; i++) { Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } LpnTranList nextAmpleTrans = new LpnTranList(); nextAmpleTrans = getAmple(curStateArray, nextStateArray, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop); // check for possible deadlock if (nextAmpleTrans.size() == 0) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } PrjState nextPrjState = new PrjState(nextStateArray); Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); if (existingState == false) { if (Options.getDebugMode()) { System.out.println("%%%%%%% existingSate == false %%%%%%%%"); printStateArray(curStateArray, "******* curStateArray *******"); printStateArray(nextStateArray, "******* nextStateArray *******"); printStateArray(stateStackTop.toStateArray(), "stateStackTop"); System.out.println("firedTran = " + firedTran.getFullLabel()); // printNextGlobalStateMap(stateStackTop.getNextStateMap()); System.out.println(" } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add global state to stateStack %%%%%%%%"); printTransList(nextAmpleTrans, "+++++++ Push trans onto lpnTranStack @ 2++++++++"); } lpnTranStack.push((LinkedList<Transition>) nextAmpleTrans.clone()); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { printStateArray(curStateArray, "******* curStateArray *******"); printStateArray(nextStateArray, "******* nextStateArray *******"); System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray(), "stateStackTop: "); System.out.println("firedTran = " + firedTran.getFullLabel()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextGlobalStateMap(stateStackTop.getNextStateMap()); System.out.println(" } } if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) { // Cycle closing check if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) { if (Options.getDebugMode()) { System.out.println("%%%%%%% Cycle Closing %%%%%%%%"); } HashSet<Transition> nextAmpleSet = new HashSet<Transition>(); HashSet<Transition> curAmpleSet = new HashSet<Transition>(); for (Transition t : nextAmpleTrans) nextAmpleSet.add(t); for (Transition t: curAmpleTrans) curAmpleSet.add(t); curAmpleSet.add(firedTran); HashSet<Transition> newNextAmple = new HashSet<Transition>(); newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticDependency, tranFiringFreq, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack); if (newNextAmple != null && !newNextAmple.isEmpty()) { //LpnTranList newNextAmpleTrans = getLpnTranList(newNextAmple, sgList); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getDebugMode()) { printStateArray(nextPrjState.toStateArray(), "nextPrjState"); // System.out.println( "nextStateMap for nextPrjState"); // printNextGlobalStateMap(nextPrjState.getNextStateMap()); } stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add state to stateStack %%%%%%%%"); System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray(), "stateStackTop"); // System.out.println("nextStateMap for stateStackTop: "); // printNextGlobalStateMap(nextPrjState.getNextStateMap()); } lpnTranStack.push((LinkedList<Transition>) newNextAmple.clone()); if (Options.getDebugMode()) { printTransList((LinkedList<Transition>) newNextAmple.clone(), "+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++"); printTranStack(lpnTranStack, "******* lpnTranStack ***************"); } } } } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStateCnt + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { //drawGlobalStateGraph(sgList, prjStateSet, false); } return sgList; } private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt, double peakTotalMem, double peakUsedMem) { try { String fileName = null; if (isPOR) { fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; } else fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log"; BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n"); out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t" + peakUsedMem + "\n"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void printTranStack(Stack<LinkedList<Transition>> lpnTranStack, String title) { if (title != null) System.out.println(title); for (int i=0; i<lpnTranStack.size(); i++) { LinkedList<Transition> tranList = lpnTranStack.get(i); for (int j=0; j<tranList.size(); j++) { System.out.println(tranList.get(j).getFullLabel()); } System.out.println(" } } private void printNextGlobalStateMap(HashMap<Transition, PrjState> nextStateMap) { for (Transition t: nextStateMap.keySet()) { System.out.println(t.getFullLabel() + " -> "); State[] stateArray = nextStateMap.get(t).getStateArray(); for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +")" +", "); } System.out.println(""); } } private LpnTranList convertToLpnTranList(HashSet<Transition> newNextAmple) { LpnTranList newNextAmpleTrans = new LpnTranList(); for (Transition lpnTran : newNextAmple) { newNextAmpleTrans.add(lpnTran); } return newNextAmpleTrans; } private HashSet<Transition> computeCycleClosingTrans(State[] curStateArray, State[] nextStateArray, HashMap<Transition, StaticSets> staticSetsMap, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> prjStateSet, PrjState nextPrjState, HashSet<Transition> nextAmple, HashSet<Transition> curAmple, HashSet<PrjState> stateStack) { for (State s : nextStateArray) if (s == null) throw new NullPointerException(); String cycleClosingMthd = Options.getCycleClosingMthd(); HashSet<Transition> newNextAmple = new HashSet<Transition>(); HashSet<Transition> nextEnabled = new HashSet<Transition>(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { Transition tran = curLpn.getAllTransitions()[i]; if (nextStateArray[lpnIndex].getTranVector()[i]) nextEnabled.add(tran); if (curStateArray[lpnIndex].getTranVector()[i]) curEnabled.add(tran); } } // Cycle closing on global state graph if (Options.getDebugMode()) { //System.out.println("~~~~~~~ existing global state ~~~~~~~~"); } if (cycleClosingMthd.equals("strong")) { newNextAmple.addAll(setSubstraction(curEnabled, nextAmple)); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } else if (cycleClosingMthd.equals("behavioral")) { if (Options.getDebugMode()) { } HashSet<Transition> curReduced = setSubstraction(curEnabled, curAmple); HashSet<Transition> oldNextAmple = new HashSet<Transition>(); DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // TODO: Is oldNextAmple correctly obtained below? if (Options.getDebugMode()) printStateArray(nextStateArray,"******* nextStateArray *******"); for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) { if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) { LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]); if (Options.getDebugMode()) { // printTransitionSet(oldLocalNextAmpleTrans, "oldLocalNextAmpleTrans"); } for (Transition oldLocalTran : oldLocalNextAmpleTrans) oldNextAmple.add(oldLocalTran); } } HashSet<Transition> ignored = setSubstraction(curReduced, oldNextAmple); boolean isCycleClosingAmpleComputation = true; for (Transition seed : ignored) { HashSet<Transition> dependent = new HashSet<Transition>(); dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); } // TODO: Is this still necessary? // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if ((newNextAmple.size() == 0 || dependent.size() < newNextAmple.size()) && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); DependentSet dependentSet = new DependentSet(dependent, seed,isDummyTran(seed.getLabel())); dependentSetQueue.add(dependentSet); } cachedNecessarySets.clear(); if (!dependentSetQueue.isEmpty()) { // System.out.println("depdentSetQueue is NOT empty."); // newNextAmple = dependentSetQueue.poll().getDependent(); // TODO: Will newNextAmpleTmp - oldNextAmple be safe? HashSet<Transition> newNextAmpleTmp = dependentSetQueue.poll().getDependent(); newNextAmple = setSubstraction(newNextAmpleTmp, oldNextAmple); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } if (Options.getDebugMode()) { // printIntegerSet(newNextAmple, sgList, "newNextAmple"); } } else if (cycleClosingMthd.equals("state_search")) { // TODO: complete cycle closing check for state search. } return newNextAmple; } private void updateLocalAmpleTbl(LpnTranList nextAmpleTrans, StateGraph[] sgList, State[] nextStateArray) { // Ample set at each state is stored in the enabledSetTbl in each state graph. for (Transition lpnTran : nextAmpleTrans) { State nextState = nextStateArray[lpnTran.getLpn().getLpnIndex()]; LpnTranList a = sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().get(nextState); if (a != null) { if (!a.contains(lpnTran)) a.add(lpnTran); } else { LpnTranList newLpnTranList = new LpnTranList(); newLpnTranList.add(lpnTran); sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().put(nextStateArray[lpnTran.getLpn().getLpnIndex()], newLpnTranList); if (Options.getDebugMode()) { // System.out.println("@ updateLocalAmpleTbl: "); // System.out.println("Add S" + nextStateArray[lpnTran.getLpnIndex()].getIndex() + " to the enabledSetTbl of " // + sgList[lpnTran.getLpnIndex()].getLpn().getLabel() + "."); } } } if (Options.getDebugMode()) { // printEnabledSetTbl(sgList); } } private void printPrjStateSet(HashSet<PrjState> prjStateSet) { for (PrjState curGlobal : prjStateSet) { State[] curStateArray = curGlobal.toStateArray(); printStateArray(curStateArray, null); System.out.println(" } } // /** // * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back. // * @param sgList // * @param initStateArray // * @param cycleClosingMthdIndex // * @return // */ // public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) { // if (cycleClosingMthdIndex == 1) // else if (cycleClosingMthdIndex == 2) // else if (cycleClosingMthdIndex == 4) // double peakUsedMem = 0; // double peakTotalMem = 0; // boolean failure = false; // int tranFiringCnt = 0; // int totalStates = 1; // int numLpns = sgList.length; // HashSet<PrjState> stateStack = new HashSet<PrjState>(); // Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); // Stack<Integer> curIndexStack = new Stack<Integer>(); // HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // PrjState initPrjState = new PrjState(initStateArray); // prjStateSet.add(initPrjState); // PrjState stateStackTop = initPrjState; // System.out.println("%%%%%%% Add states to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.add(stateStackTop); // // Prepare static pieces for POR // HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>(); // Transition[] allTransitions = sgList[0].getLpn().getAllTransitions(); // HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>(); // HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length); // for (Transition curTran: allTransitions) { // StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions); // curStatic.buildDisableSet(); // curStatic.buildEnableSet(); // curStatic.buildModifyAssignSet(); // tmpMap.put(curTran.getIndex(), curStatic); // tranFiringFreq.put(curTran.getIndex(), 0); // staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap); // printStaticSetMap(staticSetsMap); // System.out.println("call getAmple on initStateArray at 0: "); // boolean init = true; // AmpleSet initAmple = new AmpleSet(); // initAmple = sgList[0].getAmple(initStateArray[0], staticSetsMap, init, tranFiringFreq); // HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl(); // lpnTranStack.push(initAmple.getAmpleSet()); // curIndexStack.push(0); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) initAmple.getAmpleSet(), ""); // main_while_loop: while (failure == false && stateStack.size() != 0) { // System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); // long curTotalMem = Runtime.getRuntime().totalMemory(); // long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); // if (curTotalMem > peakTotalMem) // peakTotalMem = curTotalMem; // if (curUsedMem > peakUsedMem) // peakUsedMem = curUsedMem; // if (stateStack.size() > max_stack_depth) // max_stack_depth = stateStack.size(); // iterations++; // if (iterations % 100000 == 0) { // System.out.println("---> #iteration " + iterations // + "> # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStates // + ", stack_depth: " + stateStack.size() // + " used memory: " + (float) curUsedMem / 1000000 // + " free memory: " // + (float) Runtime.getRuntime().freeMemory() / 1000000); // State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); // int curIndex = curIndexStack.peek(); //// System.out.println("curIndex = " + curIndex); // //AmpleSet curAmple = new AmpleSet(); // //LinkedList<Transition> curAmpleTrans = curAmple.getAmpleSet(); // LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); //// printStateArray(curStateArray); //// System.out.println("+++++++ curAmple trans ++++++++"); //// printTransLinkedList(curAmpleTrans); // // If all enabled transitions of the current LPN are considered, // // then consider the next LPN // // by increasing the curIndex. // // Otherwise, if all enabled transitions of all LPNs are considered, // // then pop the stacks. // if (curAmpleTrans.size() == 0) { // lpnTranStack.pop(); //// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // curIndexStack.pop(); //// System.out.println("+++++++ Pop index off curIndexStack ++++++++"); // curIndex++; //// System.out.println("curIndex = " + curIndex); // while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); // LpnTranList tmpAmpleTrans = (LpnTranList) (sgList[curIndex].getAmple(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getAmpleSet(); // curAmpleTrans = tmpAmpleTrans.clone(); // //printTransitionSet(curEnabled, "curEnabled set"); // if (curAmpleTrans.size() > 0) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransLinkedList(curAmpleTrans); // lpnTranStack.push(curAmpleTrans); // curIndexStack.push(curIndex); // printIntegerStack("curIndexStack after push 1", curIndexStack); // break; // curIndex++; // if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.remove(stateStackTop); // stateStackTop = stateStackTop.getFather(); // continue; // Transition firedTran = curAmpleTrans.removeLast(); // System.out.println(" // System.out.println("Fired transition: " + firedTran.getName()); // System.out.println(" // Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1; // tranFiringFreq.put(firedTran.getIndex(), freq); // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, allTransitions); // State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); // tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. // @SuppressWarnings("unchecked") // LinkedList<Transition>[] curAmpleArray = new LinkedList[numLpns]; // @SuppressWarnings("unchecked") // LinkedList<Transition>[] nextAmpleArray = new LinkedList[numLpns]; // boolean updatedAmpleDueToCycleRule = false; // for (int i = 0; i < numLpns; i++) { // StateGraph sg_tmp = sgList[i]; // System.out.println("call getAmple on curStateArray at 2: i = " + i); // AmpleSet ampleList = new AmpleSet(); // if (init) { // ampleList = initAmple; // sg_tmp.setEnabledSetTbl(initEnabledSetTbl); // init = false; // else // ampleList = sg_tmp.getAmple(curStateArray[i], staticSetsMap, init, tranFiringFreq); // curAmpleArray[i] = ampleList.getAmpleSet(); // System.out.println("call getAmpleRefinedCycleRule on nextStateArray at 3: i = " + i); // ampleList = sg_tmp.getAmpleRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq); // nextAmpleArray[i] = ampleList.getAmpleSet(); // if (!updatedAmpleDueToCycleRule && ampleList.getAmpleChanged()) { // updatedAmpleDueToCycleRule = true; // for (LinkedList<Transition> tranList : curAmpleArray) { // printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : curAmpleArray) { //// printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : nextAmpleArray) { //// printTransLinkedList(tranList); // Transition disabledTran = firedTran.disablingError( // curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); // if (disabledTran != null) { // System.err.println("Disabling Error: " // + disabledTran.getFullLabel() + " is disabled by " // + firedTran.getFullLabel()); // failure = true; // break main_while_loop; // if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) { // failure = true; // break main_while_loop; // PrjState nextPrjState = new PrjState(nextStateArray); // Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); // if (existingState == true && updatedAmpleDueToCycleRule) { // // cycle closing // System.out.println("%%%%%%% existingSate == true %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // if (existingState == false) { // System.out.println("%%%%%%% existingSate == false %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // totalStates++; // // end of main_while_loop // double totalStateCnt = prjStateSet.size(); // System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStateCnt // + ", max_stack_depth: " + max_stack_depth // + ", peak total memory: " + peakTotalMem / 1000000 + " MB" // + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); // // This currently works for a single LPN. // return sgList; // return null; private void printStaticSetsMap( LhpnFile[] lpnList) { System.out.println(" for (Transition lpnTranPair : staticDependency.keySet()) { StaticSets statSets = staticDependency.get(lpnTranPair); printLpnTranPair(statSets.getTran(), statSets.getDisableSet(), "disableSet"); for (HashSet<Transition> setOneConjunctTrue : statSets.getOtherTransSetCurTranEnablingTrue()) { printLpnTranPair(statSets.getTran(), setOneConjunctTrue, "enableBySetingEnablingTrue for one conjunct"); } } } // private Transition[] assignStickyTransitions(LhpnFile lpn) { // // allProcessTrans is a hashmap from a transition to its process color (integer). // HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>(); // // create an Abstraction object to call the divideProcesses method. // Abstraction abs = new Abstraction(lpn); // abs.decomposeLpnIntoProcesses(); // allProcessTrans.putAll( // (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone()); // HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>(); // for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) { // Transition curTran = tranIter.next(); // Integer procId = allProcessTrans.get(curTran); // if (!processMap.containsKey(procId)) { // LpnProcess newProcess = new LpnProcess(procId); // newProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // newProcess.addPlaceToProcess(p); // processMap.put(procId, newProcess); // else { // LpnProcess curProcess = processMap.get(procId); // curProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // curProcess.addPlaceToProcess(p); // for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) { // LpnProcess curProc = processMap.get(processMapIter.next()); // curProc.assignStickyTransitions(); // curProc.printProcWithStickyTrans(); // return lpn.getAllTransitions(); // private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran, // HashSet<Transition> curDisable, String setName) { // System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); // if (curDisable.isEmpty()) { // System.out.println("empty"); // else { // for (Transition lpnTranPair: curDisable) { // System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() // + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); // System.out.print("\n"); private void printLpnTranPair(Transition curTran, HashSet<Transition> TransitionSet, String setName) { System.out.println(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getLabel() + ") is: "); if (TransitionSet.isEmpty()) { System.out.println("empty"); } else { for (Transition lpnTranPair: TransitionSet) System.out.print("(" + lpnTranPair.getLpn().getLabel() + ", " + lpnTranPair.getLabel() + ")," + " "); System.out.println(); } } /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. The enabledSetTbl (for each StateGraph obj) stores the AMPLE set for each state of each LPN. * @param stateArray * @param stateStack * @param enable * @param disableByStealingToken * @param disable * @param sgList * @return */ private LpnTranList getAmple(State[] curStateArray, State[] nextStateArray, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, LhpnFile[] lpnList, HashSet<PrjState> stateStack, PrjState stateStackTop) { State[] stateArray = null; if (nextStateArray == null) stateArray = curStateArray; else stateArray = nextStateArray; for (State s : stateArray) if (s == null) throw new NullPointerException(); LpnTranList ample = new LpnTranList(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { if (stateArray[lpnIndex].getTranVector()[i]) { curEnabled.add(curLpn.getAllTransitions()[i]); } } } if (Options.getDebugMode()) { System.out.println("******* Partial Order Reduction *******"); printIntegerSet(curEnabled, "Enabled set"); System.out.println("******* Begin POR *******"); } if (curEnabled.isEmpty()) { return ample; } HashSet<Transition> ready = partialOrderReduction(stateArray, curEnabled, tranFiringFreq, sgList); if (Options.getDebugMode()) { System.out.println("******* End POR *******"); printIntegerSet(ready, "Ample set"); System.out.println("********************"); } if (tranFiringFreq != null) { LinkedList<Transition> readyList = new LinkedList<Transition>(); for (Transition inReady : ready) { readyList.add(inReady); } mergeSort(readyList, tranFiringFreq); for (Transition inReady : readyList) { ample.addFirst(inReady); } } else { for (Transition tran : ready) { ample.add(tran); } } return ample; } private LinkedList<Transition> mergeSort(LinkedList<Transition> array, HashMap<Transition, Integer> tranFiringFreq) { if (array.size() == 1) return array; int middle = array.size() / 2; LinkedList<Transition> left = new LinkedList<Transition>(); LinkedList<Transition> right = new LinkedList<Transition>(); for (int i=0; i<middle; i++) { left.add(i, array.get(i)); } for (int i=middle; i<array.size();i++) { right.add(i-middle, array.get(i)); } left = mergeSort(left, tranFiringFreq); right = mergeSort(right, tranFiringFreq); return merge(left, right, tranFiringFreq); } private LinkedList<Transition> merge(LinkedList<Transition> left, LinkedList<Transition> right, HashMap<Transition, Integer> tranFiringFreq) { LinkedList<Transition> result = new LinkedList<Transition>(); while (left.size() > 0 || right.size() > 0) { if (left.size() > 0 && right.size() > 0) { if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) { result.addLast(left.poll()); } else { result.addLast(right.poll()); } } else if (left.size()>0) { result.addLast(left.poll()); } else if (right.size()>0) { result.addLast(right.poll()); } } return result; } /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. * @param nextState * @param stateStackTop * @param enable * @param disableByStealingToken * @param disable * @param init * @param cycleClosingMthdIndex * @param lpnIndex * @param isNextState * @return */ private LpnTranList getAmpleRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<Transition,StaticSets> staticSetsMap, boolean init, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> stateStack, PrjState stateStackTop) { // AmpleSet nextAmple = new AmpleSet(); // if (nextState == null) { // throw new NullPointerException(); // if(ampleSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) { // System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~"); // printTransitionSet((LpnTranList)ampleSetTbl.get(nextState), "Old ample at this state: "); // // Cycle closing check // LpnTranList nextAmpleTransOld = (LpnTranList) nextAmple.getAmpleSet(); // nextAmpleTransOld = ampleSetTbl.get(nextState); // LpnTranList curAmpleTrans = ampleSetTbl.get(curState); // LpnTranList curReduced = new LpnTranList(); // LpnTranList curEnabled = curState.getEnabledTransitions(); // for (int i=0; i<curEnabled.size(); i++) { // if (!curAmpleTrans.contains(curEnabled.get(i))) { // curReduced.add(curEnabled.get(i)); // if (!nextAmpleTransOld.containsAll(curReduced)) { // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // printTransitionSet(curEnabled, "curEnabled:"); // printTransitionSet(curAmpleTrans, "curAmpleTrans:"); // printTransitionSet(curReduced, "curReduced:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:"); // printTransitionSet(nextAmpleTransOld, "nextAmpleTransOld:"); // nextAmple.setAmpleChanged(); // HashSet<Transition> curEnabledIndicies = new HashSet<Transition>(); // for (int i=0; i<curEnabled.size(); i++) { // curEnabledIndicies.add(curEnabled.get(i).getIndex()); // // transToAdd = curReduced - nextAmpleOld // LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextAmpleTransOld); // HashSet<Integer> transToAddIndices = new HashSet<Integer>(); // for (int i=0; i<overlyReducedTrans.size(); i++) { // transToAddIndices.add(overlyReducedTrans.get(i).getIndex()); // HashSet<Integer> nextAmpleNewIndices = (HashSet<Integer>) curEnabledIndicies.clone(); // for (Integer tranToAdd : transToAddIndices) { // HashSet<Transition> dependent = new HashSet<Transition>(); // //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd]; // dependent = computeDependent(curState,tranToAdd,dependent,curEnabledIndicies,staticMap); // // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]); // boolean dependentOnlyHasDummyTrans = true; // for (Integer curTranIndex : dependent) { // Transition curTran = this.lpn.getAllTransitions()[curTranIndex]; // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName()); // if (dependent.size() < nextAmpleNewIndices.size() && !dependentOnlyHasDummyTrans) // nextAmpleNewIndices = (HashSet<Integer>) dependent.clone(); // if (nextAmpleNewIndices.size() == 1) // break; // LpnTranList nextAmpleNew = new LpnTranList(); // for (Integer nextAmpleNewIndex : nextAmpleNewIndices) { // nextAmpleNew.add(this.getLpn().getTransition(nextAmpleNewIndex)); // LpnTranList transToAdd = getSetSubtraction(nextAmpleNew, nextAmpleTransOld); // boolean allTransToAddFired = false; // if (cycleClosingMthdIndex == 2) { // // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. // if (transToAdd != null) { // LpnTranList transToAddCopy = transToAdd.copy(); // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // allTransToAddFired = allTransToAddFired(transToAddCopy, // allTransToAddFired, stateVisited, stateStackTop, lpnIndex); // // Update the old ample of the next state // if (!allTransToAddFired || cycleClosingMthdIndex == 1) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(transToAdd); // ampleSetTbl.get(nextState).addAll(transToAdd); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // if (cycleClosingMthdIndex == 4) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(overlyReducedTrans); // ampleSetTbl.get(nextState).addAll(overlyReducedTrans); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // // enabledSetTble stores the ample set at curState. // // The fully enabled set at each state is stored in the tranVector in each state. // return (AmpleSet) nextAmple; // for (State s : nextStateArray) // if (s == null) // throw new NullPointerException(); // cachedNecessarySets.clear(); // String cycleClosingMthd = Options.getCycleClosingMthd(); // AmpleSet nextAmple = new AmpleSet(); // HashSet<Transition> nextEnabled = new HashSet<Transition>(); //// boolean allEnabledAreSticky = false; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State nextState = nextStateArray[lpnIndex]; // if (init) { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // //allEnabledAreSticky = true; // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (sgList[lpnIndex].isEnabled(tran,nextState)){ // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // else { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (nextStateArray[lpnIndex].getTranVector()[i]) { // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // LhpnFile[] lpnList = new LhpnFile[sgList.length]; // for (int i=0; i<sgList.length; i++) // lpnList[i] = sgList[i].getLpn(); // HashMap<Transition, LpnTranList> transToAddMap = new HashMap<Transition, LpnTranList>(); // Integer cycleClosingLpnIndex = -1; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State curState = curStateArray[lpnIndex]; // State nextState = nextStateArray[lpnIndex]; // if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true // && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty() // && stateOnStack(lpnIndex, nextState, stateStack) // && nextState.getIndex() != curState.getIndex()) { // cycleClosingLpnIndex = lpnIndex; // System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~"); // printAmpleSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old ample at this state: "); // LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState); // LpnTranList curLocalAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState); // LpnTranList reducedLocalTrans = new LpnTranList(); // LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions(); // System.out.println("The firedTran is a cycle closing transition."); // if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) { // // firedTran is a cycle closing transition. // for (int i=0; i<curLocalEnabledTrans.size(); i++) { // if (!curLocalAmpleTrans.contains(curLocalEnabledTrans.get(i))) { // reducedLocalTrans.add(curLocalEnabledTrans.get(i)); // if (!oldLocalNextAmpleTrans.containsAll(reducedLocalTrans)) { // printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:"); // printTransitionSet(curLocalAmpleTrans, "curAmpleTrans:"); // printTransitionSet(reducedLocalTrans, "reducedLocalTrans:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:"); // printTransitionSet(oldLocalNextAmpleTrans, "nextAmpleTransOld:"); // // nextAmple.setAmpleChanged(); // // ignoredTrans should not be empty here. // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // if (cycleClosingMthd.toLowerCase().equals("behavioral")) { // for (Transition seed : ignored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); //// if (nextAmpleNewIndices.size() == 1) //// break; // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else if (cycleClosingMthd.toLowerCase().equals("state_search")) { // // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new ample of nextState. // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // LpnTranList trulyIgnoredTrans = ignoredTrans.copy(); // trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]); // if (!trulyIgnoredTrans.isEmpty()) { // HashSet<Transition> trulyIgnored = new HashSet<Transition>(); // for (Transition tran : trulyIgnoredTrans) { // trulyIgnored.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : trulyIgnored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else { // All ignored transitions were fired before. It is safe to close the current cycle. // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // // oldNextAmpleTrans.containsAll(curReducedTrans) == true (safe to close the current cycle) // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else if (cycleClosingMthd.toLowerCase().equals("strong")) { // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> allNewNextAmple = new HashSet<Transition>(); // for (Transition seed : ignored) { // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // allNewNextAmple.addAll(newNextAmple); // // The strong cycle condition requires all seeds in ignored to be included in the allNewNextAmple, as well as dependent set for each seed. // // So each seed should have the same new ample set. // for (Transition seed : ignored) { // DependentSet dependentSet = new DependentSet(allNewNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // firedTran is not a cycle closing transition. Compute next ample. //// if (nextEnabled.size() == 1) //// return nextEnabled; // System.out.println("The firedTran is NOT a cycle closing transition."); // HashSet<Transition> ready = null; // for (Transition seed : nextEnabled) { // System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")"); // HashSet<Transition> dependent = new HashSet<Transition>(); // Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()]; // boolean enabledIsDummy = false; //// if (enabledTransition.isSticky()) { //// dependent = (HashSet<Transition>) nextEnabled.clone(); //// else { //// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList); // dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // if (isDummyTran(enabledTransition.getName())) // enabledIsDummy = true; // for (Transition inDependent : dependent) { // if(inDependent.getLpnIndex() == cycleClosingLpnIndex) { // // check cycle closing condition // break; // DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy); // dependentSetQueue.add(dependentSet); // ready = dependentSetQueue.poll().getDependent(); //// // Update the old ample of the next state //// boolean allTransToAddFired = false; //// if (cycleClosingMthdIndex == 2) { //// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. //// if (transToAdd != null) { //// LpnTranList transToAddCopy = transToAdd.copy(); //// HashSet<Integer> stateVisited = new HashSet<Integer>(); //// stateVisited.add(nextState.getIndex()); //// allTransToAddFired = allTransToAddFired(transToAddCopy, //// allTransToAddFired, stateVisited, stateStackTop, lpnIndex); //// // Update the old ample of the next state //// if (!allTransToAddFired || cycleClosingMthdIndex == 1) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(transToAdd); //// ampleSetTbl.get(nextState).addAll(transToAdd); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// if (cycleClosingMthdIndex == 4) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(ignoredTrans); //// ampleSetTbl.get(nextState).addAll(ignoredTrans); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// // enabledSetTble stores the ample set at curState. //// // The fully enabled set at each state is stored in the tranVector in each state. //// return (AmpleSet) nextAmple; return null; } private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans, HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) { State state = stateStackEntry.get(lpnIndex); System.out.println("state = " + state.getIndex()); State predecessor = stateStackEntry.getFather().get(lpnIndex); if (predecessor != null) System.out.println("predecessor = " + predecessor.getIndex()); if (predecessor == null || stateVisited.contains(predecessor.getIndex())) { return ignoredTrans; } else stateVisited.add(predecessor.getIndex()); LpnTranList predecessorOldAmple = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor); for (Transition oldAmpleTran : predecessorOldAmple) { State tmpState = sg.getNextStateMap().get(predecessor).get(oldAmpleTran); if (tmpState.getIndex() == state.getIndex()) { ignoredTrans.remove(oldAmpleTran); break; } } if (ignoredTrans.size()==0) { return ignoredTrans; } else { ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg); } return ignoredTrans; } // for (Transition oldAmpleTran : oldAmple) { // State successor = nextStateMap.get(nextState).get(oldAmpleTran); // if (stateVisited.contains(successor.getIndex())) { // break; // else // stateVisited.add(successor.getIndex()); // LpnTranList successorOldAmple = enabledSetTbl.get(successor); // // Either successor or sucessorOldAmple should not be null for a nonterminal state graph. // HashSet<Transition> transToAddFired = new HashSet<Transition>(); // for (Transition tran : transToAddCopy) { // if (successorOldAmple.contains(tran)) // transToAddFired.add(tran); // transToAddCopy.removeAll(transToAddFired); // if (transToAddCopy.size() == 0) { // allTransFired = true; // break; // else { // allTransFired = allTransToAddFired(successorOldAmple, nextState, successor, // transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex); // return allTransFired; /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) { boolean firingOrder = false; long peakUsedMem = 0; long peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length; HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>(); @SuppressWarnings("unchecked") IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize]; //HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize]; Stack<LpnState[]> stateStack = new Stack<LpnState[]>(); Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>(); //get initial enable transition set LpnTranList initEnabled = new LpnTranList(); LpnTranList initFireFirst = new LpnTranList(); LpnState[] initLpnStateArray = new LpnState[arraySize]; for (int i = 0; i < arraySize; i++) { lpnStateCache[i] = new IndexObjMap<LpnState>(); LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]); HashSet<Transition> enabledSet = new HashSet<Transition>(); if(!enabledTrans.isEmpty()) { for(Transition tran : enabledTrans) { enabledSet.add(tran); initEnabled.add(tran); } } LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet); lpnStateCache[i].add(curLpnState); initLpnStateArray[i] = curLpnState; } LpnTranList[] initEnabledSet = new LpnTranList[2]; initEnabledSet[0] = initFireFirst; initEnabledSet[1] = initEnabled; lpnTranStack.push(initEnabledSet); stateStack.push(initLpnStateArray); globalStateTbl.add(new PrjLpnState(initLpnStateArray)); main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; //if(iterations>2)break; if (iterations % 100000 == 0) System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", current_stack_depth: " + stateStack.size() + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); LpnTranList[] curEnabled = lpnTranStack.peek(); LpnState[] curLpnStateArray = stateStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if(curEnabled[0].size()==0 && curEnabled[1].size()==0){ lpnTranStack.pop(); stateStack.pop(); continue; } Transition firedTran = null; if(curEnabled[0].size() != 0) firedTran = curEnabled[0].removeFirst(); else firedTran = curEnabled[1].removeFirst(); traceCex.addLast(firedTran); State[] curStateArray = new State[arraySize]; for( int i = 0; i < arraySize; i++) curStateArray[i] = curLpnStateArray[i].getState(); StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled(); LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]); HashSet<Transition> nextEnabledSet = new HashSet<Transition>(); for(Transition tran : nextEnabledList) { nextEnabledSet.add(tran); } extendedNextEnabledArray[i] = nextEnabledSet; //non_disabling for(Transition curTran : curEnabledSet) { if(curTran == firedTran) continue; if(nextEnabledSet.contains(curTran) == false) { int[] nextMarking = nextStateArray[i].getMarking(); // Not sure if the code below is correct. int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getLabel()); boolean included = true; if (preset != null && preset.length > 0) { for (int pp : preset) { boolean temp = false; for (int mi = 0; mi < nextMarking.length; mi++) { if (nextMarking[mi] == pp) { temp = true; break; } } if (temp == false) { included = false; break; } } } if(preset==null || preset.length==0 || included==true) { extendedNextEnabledArray[i].add(curTran); } } } } boolean deadlock=true; for(int i = 0; i < arraySize; i++) { if(extendedNextEnabledArray[i].size() != 0){ deadlock = false; break; } } if(deadlock==true) { failure = true; break main_while_loop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. LpnState[] nextLpnStateArray = new LpnState[arraySize]; for(int i = 0; i < arraySize; i++) { HashSet<Transition> lpnEnabledSet = new HashSet<Transition>(); for(Transition tran : extendedNextEnabledArray[i]) { lpnEnabledSet.add(tran); } LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet); LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp)); nextLpnStateArray[i] = tmpCached; } boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray)); if(newState == false) { traceCex.removeLast(); continue; } stateStack.push(nextLpnStateArray); LpnTranList[] nextEnabledSet = new LpnTranList[2]; LpnTranList fireFirstTrans = new LpnTranList(); LpnTranList otherTrans = new LpnTranList(); for(int i = 0; i < arraySize; i++) { for(Transition tran : nextLpnStateArray[i].getEnabled()) { if(firingOrder == true) if(curLpnStateArray[i].getEnabled().contains(tran)) otherTrans.add(tran); else fireFirstTrans.add(tran); else fireFirstTrans.add(tran); } } nextEnabledSet[0] = fireFirstTrans; nextEnabledSet[1] = otherTrans; lpnTranStack.push(nextEnabledSet); }// END while (stateStack.empty() == false) // graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt, // prjStateSet.size())); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth); /* * by looking at stateStack, generate the trace showing the counter-example. */ if (failure == true) { System.out.println(" System.out.println("the deadlock trace:"); //update traceCex from stateStack // LpnState[] cur = null; // LpnState[] next = null; for(Transition tran : traceCex) System.out.println(tran.getFullLabel()); } System.out.println("Modules' local states: "); for (int i = 0; i < arraySize; i++) { System.out.println("module " + lpnList[i].getLpn().getLabel() + ": " + lpnList[i].reachSize()); } return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * When a state is considered during DFS, only one enabled transition is * selected to fire in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_1"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 500; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean compressed = false; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int arraySize = lpnList.length; int newStateCnt = 0; Stack<State[]> stateStack = new Stack<State[]>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); mddNode reachAll = null; mddNode reach = mddMgr.newNode(); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true); mddMgr.add(reach, localIdxArray, compressed); stateStack.push(initStateArray); LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]); lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); int numMddCompression = 0; main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack depth: " + stateStack.size() + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); numMddCompression++; if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); if(memUpBound < 1500) memUpBound *= numMddCompression; } } State[] curStateArray = stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); curIndexStack.pop(); curIndex++; while (curIndex < arraySize) { LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex])); if (enabledCached.size() > 0) { curEnabled = enabledCached.clone(); lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); break; } else curIndex++; } } if (curIndex == arraySize) { stateStack.pop(); continue; } Transition firedTran = curEnabled.removeLast(); State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. * if not, add it into reachable set, and push it onto stack. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; if (existingState == false) { mddMgr.add(reach, localIdxArray, compressed); newStateCnt++; stateStack.push(nextStateArray); lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); curIndexStack.push(0); totalStates++; } } double totalStateCnt = mddMgr.numberOfStates(reach); System.out.println("---> run statistics: \n" + "# LPN transition firings: " + tranFiringCnt + "\n" + "# of prjStates found: " + totalStateCnt + "\n" + "max_stack_depth: " + max_stack_depth + "\n" + "peak MDD nodes: " + peakMddNodeCnt + "\n" + "peak used memory: " + peakUsedMem / 1000000 + " MB\n" + "peak total memory: " + peakTotalMem / 1000000 + " MB\n"); return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * It is similar to findsg_dfs_mdd_1 except that when a state is considered * during DFS, all enabled transition are fired, and all its successor * states are found in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_2"); int tranFiringCnt = 0; int totalStates = 0; int arraySize = lpnList.length; long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean failure = false; MDT state2Explore = new MDT(arraySize); state2Explore.push(initStateArray); totalStates++; long peakState2Explore = 0; Stack<Integer> searchDepth = new Stack<Integer>(); searchDepth.push(1); boolean compressed = false; mddNode reachAll = null; mddNode reach = mddMgr.newNode(); main_while_loop: while (failure == false && state2Explore.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; iterations++; if (iterations % 100000 == 0) { int mddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt; int state2ExploreSize = state2Explore.size(); peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", # states to explore: " + state2ExploreSize + ", # MDT nodes: " + state2Explore.nodeCnt() + ", total MDD nodes: " + mddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } } State[] curStateArray = state2Explore.pop(); State[] nextStateArray = null; int states2ExploreCurLevel = searchDepth.pop(); if(states2ExploreCurLevel > 1) searchDepth.push(states2ExploreCurLevel-1); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false); mddMgr.add(reach, localIdxArray, compressed); int nextStates2Explore = 0; for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; State curState = curStateArray[index]; LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState); LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone(); while (curEnabled.size() > 0) { Transition firedTran = curEnabled.removeLast(); // TODO: (check) Not sure if curLpn.fire is correct. nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; if (curStateArray[i] == nextStateArray[i]) continue; LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.err.println("Verification failed: deadlock."); failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; else if(state2Explore.contains(nextStateArray)==true) existingState = true; if (existingState == false) { totalStates++; //mddMgr.add(reach, localIdxArray, compressed); state2Explore.push(nextStateArray); nextStates2Explore++; } } } if(nextStates2Explore > 0) searchDepth.push(nextStates2Explore); } System.out.println(" + "---> run statistics: \n" + " # Depth of search (Length of Cex): " + searchDepth.size() + "\n" + " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n" + " # of prjStates found: " + (double)totalStates / 1000000 + " M\n" + " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n" + " peak MDD nodes: " + peakMddNodeCnt + "\n" + " peak used memory: " + peakUsedMem / 1000000 + " MB\n" + " peak total memory: " + peakTotalMem /1000000 + " MB\n" + "_____________________________________"); return null; } public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. int arraySize = sgList.length; for (int i = 0; i < arraySize; i++) sgList[i].addState(initStateArray[i]); mddNode reachSet = null; mddNode reach = mddMgr.newNode(); MDT frontier = new MDT(arraySize); MDT image = new MDT(arraySize); frontier.push(initStateArray); State[] curStateArray = null; int tranFiringCnt = 0; int totalStates = 0; int imageSize = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachSet == null) reachSet = reach; else { mddNode newReachSet = mddMgr.union(reachSet, reach); if (newReachSet != reachSet) { mddMgr.remove(reachSet); reachSet = newReachSet; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } while(frontier.empty() == false) { boolean deadlock = true; // Stack<State[]> curStateArrayList = frontier.pop(); // while(curStateArrayList.empty() == false) { // curStateArray = curStateArrayList.pop(); { curStateArray = frontier.pop(); int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false); mddMgr.add(reach, localIdxArray, false); totalStates++; for (int i = 0; i < arraySize; i++) { LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]); if (curEnabled.size() > 0) deadlock = false; for (Transition firedTran : curEnabled) { // TODO: (check) Not sure if sgList[i].fire is correct. State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran); tranFiringCnt++; /* * Check if any transitions can be disabled by fireTran. */ LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled); if (disabledTran != null) { System.err.println("*** Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false); if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) { if(image.contains(nextStateArray)==false) { image.push(nextStateArray); imageSize++; } } } } } /* * If curStateArray deadlocks (no enabled transitions), terminate. */ if (deadlock == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } } if(image.empty()==true) break; System.out.println("---> size of image: " + imageSize); frontier = image; image = new MDT(arraySize); imageSize = 0; } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n" + "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MDD nodes: " + peakMddNodeCnt); return null; } /** * BFS findsg using iterative approach. THe states found are stored in MDD. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; int arraySize = lpnList.length; for (int i = 0; i < arraySize; i++) lpnList[i].addState(initStateArray[i]); // mddNode reachSet = mddMgr.newNode(); // mddMgr.add(reachSet, curLocalStateArray); mddNode reachSet = null; mddNode exploredSet = null; LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]); for (int i = 0; i < arraySize; i++) nextSetArray[i] = new LinkedList<State>(); mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null); mddNode curMdd = initMdd; reachSet = curMdd; mddNode nextMdd = null; int[] curStateArray = null; int tranFiringCnt = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; curStateArray = mddMgr.next(curMdd, curStateArray); if (curStateArray == null) { // Break the loop if no new next states are found. // System.out.println("nextSet size " + nextSet.size()); if (nextMdd == null) break bfsWhileLoop; if (exploredSet == null) exploredSet = curMdd; else { mddNode newExplored = mddMgr.union(exploredSet, curMdd); if (newExplored != exploredSet) mddMgr.remove(exploredSet); exploredSet = newExplored; } mddMgr.remove(curMdd); curMdd = nextMdd; nextMdd = null; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of union calls: " + mddNode.numCalls + ", # of union cache nodes: " + mddNode.cacheNodes + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet) + ", CurSet.Size = " + mddMgr.numberOfStates(curMdd)); continue; } if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true) continue; // If curStateArray deadlocks (no enabled transitions), terminate. if (Analysis.deadLock(lpnList, curStateArray) == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } // Do firings of non-local LPN transitions. for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]); if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true) continue; for (Transition firedTran : curLocalEnabled) { if (firedTran.isLocal() == true) continue; // TODO: (check) Not sure if curLpn.fire is correct. State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; @SuppressWarnings("unused") ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1); for (int i = 0; i < arraySize; i++) { if (curStateArray[i] == nextStateArray[i].getIndex()) continue; StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex()); Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + ": is disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { verifyError = true; break bfsWhileLoop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the // next // enabled transition. int[] nextIdxArray = Analysis.getIdxArray(nextStateArray); if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true) continue; mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet); mddNode newReachSet = mddMgr.union(reachSet, newNextMdd); if (newReachSet != reachSet) mddMgr.remove(reachSet); reachSet = newReachSet; if (nextMdd == null) nextMdd = newNextMdd; else { mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd); if (tmpNextMdd != nextMdd) mddMgr.remove(nextMdd); nextMdd = tmpNextMdd; mddMgr.remove(newNextMdd); } } } } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + "\n" + "---> # of prjStates found: " + (mddMgr.numberOfStates(reachSet)) + "\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt()); return null; } /** * partial order reduction (Original version of Hao's POR with behavioral analysis) * This method is not used anywhere. See searchPOR_behavioral for POR with behavioral analysis. * * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> Calling search_dfs with partial order reduction"); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; boolean useMdd = true; mddNode reach = mddMgr.newNode(); //init por verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); //System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel()); // TODO: (??) Not sure if the state graph sg below is correct. StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return null; } /** * partial order reduction with behavioral analysis. (Adapted from search_dfs_por.) * * @param sgList * @param curLocalStateArray * @param enabledArray */ public StateGraph[] searchPOR_behavioral(final StateGraph[] sgList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> calling function searchPOR_behavioral"); System.out.println("---> " + Options.getPOR()); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; //boolean useMdd = true; boolean useMdd = false; mddNode reach = mddMgr.newNode(); //init por AmpleSet ampleClass = new AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(sgList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(sgList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = sgList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { sgList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = sgList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); StateGraph sg = null; for (int i=0; i<sgList.length; i++) { if (sgList[i].getLpn().equals(firedTran.getLpn())) { sg = sgList[i]; } } State[] nextStateArray = sg.fire(sgList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { sgList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = sgList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + sgList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + sgList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return sgList; } // /** // * Check if this project deadlocks in the current state 'stateArray'. // * @param sgList // * @param stateArray // * @param staticSetsMap // * @param enableSet // * @param disableByStealingToken // * @param disableSet // * @param init // * @return // */ // // Called by search search_dfsPOR // public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<Transition,StaticSets> staticSetsMap, // boolean init, HashMap<Transition, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) { // boolean deadlock = true; // System.out.println("@ deadlock:"); //// for (int i = 0; i < stateArray.length; i++) { //// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); //// if (tmp.size() > 0) { //// deadlock = false; //// break; // LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); // if (tmp.size() > 0) { // deadlock = false; // System.out.println("@ end of deadlock"); // return deadlock; public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) { boolean deadlock = true; for (int i = 0; i < stateArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) { boolean deadlock = true; for (int i = 0; i < stateIdxArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } public static boolean deadLock(LinkedList<Transition>[] lpnList) { boolean deadlock = true; for (int i = 0; i < lpnList.length; i++) { LinkedList<Transition> tmp = lpnList[i]; if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } // /* // * Scan enabledArray, identify all sticky transitions other the firedTran, and return them. // * // * Arguments remain constant. // */ // public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) { // int arraySize = enabledArray.length; // LpnTranList[] stickyTranArray = new LpnTranList[arraySize]; // for (int i = 0; i < arraySize; i++) { // stickyTranArray[i] = new LpnTranList(); // for (Transition tran : enabledArray[i]) { // if (tran != firedTran) // stickyTranArray[i].add(tran); // if(stickyTranArray[i].size()==0) // stickyTranArray[i] = null; // return stickyTranArray; /** * Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to * nextStickyTransArray. * * Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions * from curStickyTransArray. * * Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState. */ public static LpnTranList[] checkStickyTrans( LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray, LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) { int arraySize = curStickyTransArray.length; LpnTranList[] stickyTransArray = new LpnTranList[arraySize]; boolean[] hasStickyTrans = new boolean[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> tmp = new HashSet<Transition>(); if(nextStickyTransArray[i] != null) for(Transition tran : nextStickyTransArray[i]) tmp.add(tran); stickyTransArray[i] = new LpnTranList(); hasStickyTrans[i] = false; for (Transition tran : curStickyTransArray[i]) { if (tran.isPersistent() == true && tmp.contains(tran)==false) { int[] nextMarking = nextState.getMarking(); int[] preset = LPN.getPresetIndex(tran.getLabel());//tran.getPreSet(); boolean included = false; if (preset != null && preset.length > 0) { for (int pp : preset) { for (int mi = 0; i < nextMarking.length; i++) { if (nextMarking[mi] == pp) { included = true; break; } } if (included == false) break; } } if(preset==null || preset.length==0 || included==true) { stickyTransArray[i].add(tran); hasStickyTrans[i] = true; } } } if(stickyTransArray[i].size()==0) stickyTransArray[i] = null; } return stickyTransArray; } /* * Return an array of indices for the given stateArray. */ private static int[] getIdxArray(State[] stateArray) { int[] idxArray = new int[stateArray.length]; for(int i = 0; i < stateArray.length; i++) { idxArray[i] = stateArray[i].getIndex(); } return idxArray; } private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) { int arraySize = sgList.length; int[] localIdxArray = new int[arraySize]; for(int i = 0; i < arraySize; i++) { if(reverse == false) localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex(); else localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex(); //System.out.print(localIdxArray[i] + " "); } //System.out.println(); return localIdxArray; } // private void printEnabledSetTbl(StateGraph[] sgList) { // for (int i=0; i<sgList.length; i++) { // for (State s : sgList[i].getEnabledSetTbl().keySet()) { // System.out.print("S" + s.getIndex() + " -> "); // printTransList(sgList[i].getEnabledSetTbl().get(s), ""); private HashSet<Transition> partialOrderReduction(State[] curStateArray, HashSet<Transition> curEnabled, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; if (Options.getUseDependentQueue()) { DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()) System.out.println("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); HashSet<Transition> dependent = new HashSet<Transition>(); boolean enabledIsDummy = false; boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) if(isDummyTran(enabledTran.getLabel())) enabledIsDummy = true; DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); dependentSetQueue.add(dependentSet); } //cachedNecessarySets.clear(); ready = dependentSetQueue.poll().getDependent(); //return ready; } else { for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()) System.out.print("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); HashSet<Transition> dependent = new HashSet<Transition>(); boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); } if (ready.isEmpty() || dependent.size() < ready.size()) ready = dependent; if (ready.size() == 1) { cachedNecessarySets.clear(); return ready; } } } cachedNecessarySets.clear(); return ready; } // private HashSet<Transition> partialOrderReduction(State[] curStateArray, // HashSet<Transition> curEnabled, HashMap<Transition, StaticSets> staticMap, // HashMap<Transition,Integer> tranFiringFreqMap, StateGraph[] sgList, LhpnFile[] lpnList) { // if (curEnabled.size() == 1) // return curEnabled; // HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; // if (Options.getUseDependentQueue()) { // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean enabledIsDummy = false; // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) // if(isDummyTran(enabledTran.getName())) // enabledIsDummy = true; // DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); // dependentSetQueue.add(dependentSet); // //cachedNecessarySets.clear(); // ready = dependentSetQueue.poll().getDependent(); // //return ready; // else { // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // if (ready.isEmpty() || dependent.size() < ready.size()) // ready = dependent;//(HashSet<Transition>) dependent.clone(); // if (ready.size() == 1) { // cachedNecessarySets.clear(); // return ready; // cachedNecessarySets.clear(); // return ready; private boolean isDummyTran(String tranName) { if (tranName.contains("_dummy")) return true; else return false; } private HashSet<Transition> computeDependent(State[] curStateArray, Transition seedTran, HashSet<Transition> dependent, HashSet<Transition> curEnabled, boolean isCycleClosingAmpleComputation) { // disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran. HashSet<Transition> disableSet = staticDependency.get(seedTran).getDisableSet(); HashSet<Transition> otherTransDisableEnabledTran = staticDependency.get(seedTran).getOtherTransDisableCurTranSet(); if (Options.getDebugMode()) { System.out.println("@ beginning of computeDependent, consider transition " + getNamesOfLPNandTrans(seedTran)); printIntegerSet(disableSet, "Disable set for " + getNamesOfLPNandTrans(seedTran)); } dependent.add(seedTran); // for (Transition lpnTranPair : canModifyAssign) { // if (curEnabled.contains(lpnTranPair)) // dependent.add(lpnTranPair); if (Options.getDebugMode()) printIntegerSet(dependent, "@ computeDependent at 0, dependent set for " + getNamesOfLPNandTrans(seedTran)); // dependent is equal to enabled. Terminate. if (dependent.size() == curEnabled.size()) { if (Options.getDebugMode()) { System.out.println("Check 0: Size of dependent is equal to enabled. Return dependent."); } return dependent; } for (Transition tranInDisableSet : disableSet) { if (Options.getDebugMode()) System.out.println("Consider transition in the disable set of " + getNamesOfLPNandTrans(seedTran) + ": " + getNamesOfLPNandTrans(tranInDisableSet)); if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet) && (!tranInDisableSet.isPersistent() || otherTransDisableEnabledTran.contains(tranInDisableSet))) { dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,isCycleClosingAmpleComputation)); if (Options.getDebugMode()) { printIntegerSet(dependent, "@ computeDependent at 1 for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (!curEnabled.contains(tranInDisableSet)) { if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back || (Options.getCycleClosingAmpleMethd().toLowerCase().equals("cctboff") && isCycleClosingAmpleComputation)) { dependent.addAll(curEnabled); break; } HashSet<Transition> necessary = null; if (Options.getDebugMode()) { printCachedNecessarySets(); } if (cachedNecessarySets.containsKey(tranInDisableSet)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@ computeDependent: Found transition " + getNamesOfLPNandTrans(tranInDisableSet) + "in the cached necessary sets."); } necessary = cachedNecessarySets.get(tranInDisableSet); } else { if (Options.getDebugMode()) System.out.println("==== Compute necessary using DFS ===="); if (visitedTrans == null) visitedTrans = new HashSet<Transition>(); else visitedTrans.clear(); necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled);//, tranInDisableSet.getFullLabel()); } if (necessary != null && !necessary.isEmpty()) { cachedNecessarySets.put(tranInDisableSet, necessary); if (Options.getDebugMode()) printIntegerSet(necessary, "@ computeDependent, necessary set for transition " + getNamesOfLPNandTrans(tranInDisableSet)); for (Transition tranNecessary : necessary) { if (!dependent.contains(tranNecessary)) { if (Options.getDebugMode()) { printIntegerSet(dependent,"Check if the newly found necessary transition is in the dependent set of " + getNamesOfLPNandTrans(seedTran)); System.out.println("It does not contain this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + ". Compute its dependent set."); } dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,isCycleClosingAmpleComputation)); } else { if (Options.getDebugMode()) { printIntegerSet(dependent, "Check if the newly found necessary transition is in the dependent set. Dependent set for " + getNamesOfLPNandTrans(seedTran)); System.out.println("It already contains this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + "."); } } } } else { if (Options.getDebugMode()) { if (necessary == null) System.out.println("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is null."); else System.out.println("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is empty."); } //dependent.addAll(curEnabled); return curEnabled; } if (Options.getDebugMode()) { printIntegerSet(dependent,"@ computeDependent at 2, dependent set for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (dependent.contains(tranInDisableSet)) { if (Options.getDebugMode()) { printIntegerSet(dependent,"@ computeDependent at 3 for transition " + getNamesOfLPNandTrans(seedTran)); System.out.println("Transition " + getNamesOfLPNandTrans(tranInDisableSet) + " is already in the dependent set of " + getNamesOfLPNandTrans(seedTran) + "."); } } } return dependent; } private String getNamesOfLPNandTrans(Transition tran) { return tran.getLpn().getLabel() + "(" + tran.getLabel() + ")"; } private HashSet<Transition> computeNecessary(State[] curStateArray, Transition tran, HashSet<Transition> dependent, HashSet<Transition> curEnabled) { if (Options.getDebugMode()) { System.out.println("@ computeNecessary, consider transition: " + getNamesOfLPNandTrans(tran)); } if (cachedNecessarySets.containsKey(tran)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@ computeNecessary: Found transition " + getNamesOfLPNandTrans(tran) + "'s necessary set in the cached necessary sets. Return the cached necessary set."); } return cachedNecessarySets.get(tran); } // Search for transition(s) that can help to bring the marking(s). HashSet<Transition> nMarking = null; //Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()); //int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName()); for (int i=0; i < tran.getPreset().length; i++) { int placeIndex = tran.getLpn().getPresetIndex(tran.getLabel())[i]; if (curStateArray[tran.getLpn().getLpnIndex()].getMarking()[placeIndex]==0) { if (Options.getDebugMode()) { System.out.println(" } HashSet<Transition> nMarkingTemp = new HashSet<Transition>(); String placeName = tran.getLpn().getPlaceList()[placeIndex]; Transition[] presetTrans = tran.getLpn().getPlace(placeName).getPreset(); if (Options.getDebugMode()) { System.out.println("@ nMarking: Consider preset place of " + getNamesOfLPNandTrans(tran) + ": " + placeName); } for (int j=0; j < presetTrans.length; j++) { Transition presetTran = presetTrans[j]; if (Options.getDebugMode()) { System.out.println("@ nMarking: Preset of place " + placeName + " has transition(s): "); for (int k=0; k<presetTrans.length; k++) { System.out.print(getNamesOfLPNandTrans(presetTrans[k]) + ", "); } System.out.println(""); System.out.println("@ nMarking: Consider transition of " + getNamesOfLPNandTrans(presetTran)); } if (curEnabled.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + getNamesOfLPNandTrans(presetTran) + "). Add to nMarkingTmp."); } nMarkingTemp.add(presetTran); } else { if (visitedTrans.contains(presetTran)) {//seedTranInDisableSet.getVisitedTrans().contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: Transition " + getNamesOfLPNandTrans(presetTran) + " was visted before"); } if (cachedNecessarySets.containsKey(presetTran)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@nMarking: Found transition " + getNamesOfLPNandTrans(presetTran) + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nMarkingTemp = cachedNecessarySets.get(presetTran); } continue; } else visitedTrans.add(presetTran); if (Options.getDebugMode()) { System.out.println("~~~~~~~~~ transVisited ~~~~~~~~~"); for (Transition visitedTran :visitedTrans) { System.out.println(getNamesOfLPNandTrans(visitedTran)); } System.out.println("@ nMarking, before call computeNecessary: consider transition: " + getNamesOfLPNandTrans(presetTran)); System.out.println("@ nMarking: transition " + getNamesOfLPNandTrans(presetTran) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabled); if (tmp != null) { nMarkingTemp.addAll(tmp); if (Options.getDebugMode()) { System.out.println("@ nMarking: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(presetTran) + " is not null."); printIntegerSet(nMarkingTemp, getNamesOfLPNandTrans(presetTran) + "'s nMarkingTemp"); } } else if (Options.getDebugMode()) { System.out.println("@ nMarking: necessary set for transition " + getNamesOfLPNandTrans(presetTran) + " is null."); } } } if (!nMarkingTemp.isEmpty()) //if (nMarking == null || nMarkingTemp.size() < nMarking.size()) if (nMarking == null || setSubstraction(nMarkingTemp, dependent).size() < setSubstraction(nMarking, dependent).size()) nMarking = nMarkingTemp; } else if (Options.getDebugMode()) { System.out.println("@ nMarking: Place " + tran.getLpn().getLabel() + "(" + tran.getLpn().getPlaceList()[placeIndex] + ") is marked."); } } if (nMarking != null && nMarking.size() ==1 && setSubstraction(nMarking, dependent).size() == 0) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { System.out.println("Return nMarking as necessary set."); printCachedNecessarySets(); } return nMarking; } // Search for transition(s) that can help to enable the current transition. HashSet<Transition> nEnable = null; int[] varValueVector = curStateArray[tran.getLpn().getLpnIndex()].getVariableVector(); //HashSet<Transition> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue(); ArrayList<HashSet<Transition>> canEnable = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue(); if (Options.getDebugMode()) { System.out.println(" printIntegerSet(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); } if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && !canEnable.isEmpty()) { for(int index=0; index < tran.getConjunctsOfEnabling().size(); index++) { ExprTree conjunctExprTree = tran.getConjunctsOfEnabling().get(index); HashSet<Transition> nEnableForOneConjunct = null; if (Options.getDebugMode()) { printIntegerSet(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); System.out.println("@ nEnable: Consider conjunct for transition " + getNamesOfLPNandTrans(tran) + ": " + conjunctExprTree.toString()); } if (conjunctExprTree.evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0) { HashSet<Transition> canEnableOneConjunctSet = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue().get(index); nEnableForOneConjunct = new HashSet<Transition>(); if (Options.getDebugMode()) { System.out.println("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to FALSE."); printIntegerSet(canEnableOneConjunctSet, "@ nEnable: Transitions that can enable this conjunct are"); } for (Transition tranCanEnable : canEnableOneConjunctSet) { if (curEnabled.contains(tranCanEnable)) { nEnableForOneConjunct.add(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: curEnabled contains transition " + getNamesOfLPNandTrans(tranCanEnable) + ". Add to nEnableOfOneConjunct."); } } else { if (visitedTrans.contains(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " was visted before."); } if (cachedNecessarySets.containsKey(tranCanEnable)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@ nEnable: Found transition " + getNamesOfLPNandTrans(tranCanEnable) + "'s necessary set in the cached necessary sets. Add it to nEnableOfOneConjunct."); } nEnableForOneConjunct.addAll(cachedNecessarySets.get(tranCanEnable)); } continue; } else visitedTrans.add(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabled); if (tmp != null) { nEnableForOneConjunct.addAll(tmp); if (Options.getDebugMode()) { System.out.println("@ nEnable: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(tranCanEnable) + ": "); printIntegerSet(tmp, ""); printIntegerSet(nEnableForOneConjunct, getNamesOfLPNandTrans(tranCanEnable) + "'s nEnableOfOneConjunct"); } } else if (Options.getDebugMode()) { System.out.println("@ nEnable: necessary set for transition " + getNamesOfLPNandTrans(tranCanEnable) + " is null."); } } } if (!nEnableForOneConjunct.isEmpty()) { if (nEnable == null || setSubstraction(nEnableForOneConjunct, dependent).size() < setSubstraction(nEnable, dependent).size()) { //&& !nEnableForOneConjunct.isEmpty())) { if (Options.getDebugMode()) { System.out.println("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" is replaced by nEnableForOneConjunct."); printIntegerSet(nEnable, "nEnable"); printIntegerSet(nEnableForOneConjunct, "nEnableForOneConjunct"); } nEnable = nEnableForOneConjunct; } else { if (Options.getDebugMode()) { System.out.println("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" remains unchanged."); printIntegerSet(nEnable, "nEnable"); } } } } else { if (Options.getDebugMode()) { System.out.println("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to TRUE. No need to trace back on it."); } } } } else { if (Options.getDebugMode()) { if (tran.getEnablingTree() == null) { System.out.println("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + " has no enabling condition."); } else if (tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) !=0.0) { System.out.println("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is true."); } else if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && canEnable.isEmpty()) { System.out.println("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is false, but no other transitions that can help to enable it were found ."); } printIntegerSet(nMarking, "=== nMarking for transition " + getNamesOfLPNandTrans(tran)); printIntegerSet(nEnable, "=== nEnable for transition " + getNamesOfLPNandTrans(tran)); } } if (nMarking != null && nEnable == null) { if (!nMarking.isEmpty()) cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nMarking; } else if (nMarking == null && nEnable != null) { if (!nEnable.isEmpty()) cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nEnable; } else if (nMarking == null && nEnable == null) { return null; } else { if (!nMarking.isEmpty() && !nEnable.isEmpty()) { if (setSubstraction(nMarking, dependent).size() < setSubstraction(nEnable, dependent).size()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nMarking; } else { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nEnable; } } else if (nMarking.isEmpty() && !nEnable.isEmpty()) { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nEnable; } else if (!nMarking.isEmpty() && nEnable.isEmpty()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nMarking; } else { return null; } } } // private HashSet<Transition> computeNecessaryUsingDependencyGraphs(State[] curStateArray, // Transition tran, HashSet<Transition> curEnabled, // HashMap<Transition, StaticSets> staticMap, // LhpnFile[] lpnList, Transition seedTran) { // if (Options.getDebugMode()) { //// System.out.println("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // // Use breadth-first search to find the shorted path from the seed transition to an enabled transition. // LinkedList<Transition> exploredTransQueue = new LinkedList<Transition>(); // HashSet<Transition> allExploredTrans = new HashSet<Transition>(); // exploredTransQueue.add(tran); // //boolean foundEnabledTran = false; // HashSet<Transition> canEnable = new HashSet<Transition>(); // while(!exploredTransQueue.isEmpty()){ // Transition curTran = exploredTransQueue.poll(); // allExploredTrans.add(curTran); // if (cachedNecessarySets.containsKey(curTran)) { // if (Options.getDebugMode()) { // writeStringWithEndOfLineToPORDebugFile("Found transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" // + "'s necessary set in the cached necessary sets. Terminate BFS."); // return cachedNecessarySets.get(curTran); // canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // // Decide if canSetEnablingTrue set can help to enable curTran. // Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); // int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector(); // if (curTransition.getEnablingTree() != null // && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) { // canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue()); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to set the enabling of transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // printIntegerSet(staticMap.get(curTran).getEnableBySettingEnablingTrue(), lpnList, "Neighbors that can help to set the enabling transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // for (Transition neighborTran : canEnable) { // if (curEnabled.contains(neighborTran)) { // if (!neighborTran.equals(seedTran)) { // HashSet<Transition> necessarySet = new HashSet<Transition>(); // necessarySet.add(neighborTran); // // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed? // cachedNecessarySets.put(tran, necessarySet); // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // return necessarySet; // else if (neighborTran.equals(seedTran) && canEnable.size()==1) { // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // return null; //// if (exploredTransQueue.isEmpty()) { //// System.out.println("exploredTransQueue is empty. Return null necessary set."); //// writeStringWithNewLineToPORDebugFile("exploredTransQueue is empty. Return null necessary set."); //// return null; // if (!allExploredTrans.contains(neighborTran)) { // allExploredTrans.add(neighborTran); // exploredTransQueue.add(neighborTran); // canEnable.clear(); // return null; private void printCachedNecessarySets() { System.out.println("================ cached necessary sets ================="); for (Transition key : cachedNecessarySets.keySet()) { System.out.print(key.getLpn().getLabel() + "(" + key.getLabel() + ") => "); for (Transition necessary : cachedNecessarySets.get(key)) { System.out.print(necessary.getLpn().getLabel() + "(" + necessary.getLabel() + ") "); } System.out.println(""); } } private HashSet<Transition> setSubstraction( HashSet<Transition> left, HashSet<Transition> right) { HashSet<Transition> sub = new HashSet<Transition>(); for (Transition lpnTranPair : left) { if (!right.contains(lpnTranPair)) sub.add(lpnTranPair); } return sub; } public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); if(stateArray[lpnIndex].equals(curState)) {// (stateArray[lpnIndex] == curState) { isStateOnStack = true; break; } } return isStateOnStack; } private void printIntegerSet(HashSet<Transition> Trans, String setName) { if (!setName.isEmpty()) System.out.print(setName + ": "); if (Trans == null) { System.out.println("null"); } else if (Trans.isEmpty()) { System.out.println("empty"); } else { for (Transition lpnTranPair : Trans) { System.out.print(lpnTranPair.getLabel() + "(" + lpnTranPair.getLpn().getLabel() + "),"); } System.out.println(); } } private void printIntegerSet(ArrayList<HashSet<Transition>> transSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + ": "); if (transSet == null) { System.out.println("null"); } else if (transSet.isEmpty()) { System.out.println("empty"); } else { for (HashSet<Transition> lpnTranPairSet : transSet) { for (Transition lpnTranPair : lpnTranPairSet) System.out.print(lpnTranPair.getLpn().getLabel() + "(" + lpnTranPair.getLabel() + "),"); } System.out.println(); } } }
import static java.lang.Math.PI; import static java.lang.Math.abs; import static java.lang.Math.sin; import static org.jenetics.engine.EvolutionResult.toBestPhenotype; import static org.jenetics.engine.limit.bySteadyFitness; import java.util.stream.IntStream; import org.jenetics.EnumGene; import org.jenetics.Genotype; import org.jenetics.Optimize; import org.jenetics.PartiallyMatchedCrossover; import org.jenetics.PermutationChromosome; import org.jenetics.Phenotype; import org.jenetics.SwapMutator; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionStatistics; public class TravelingSalesman { // Problem initialization: // Calculating the adjacence matrix of the "city" distances. private static final int STOPS = 20; private static final double[][] ADJACENCE = matrix(STOPS); private static double[][] matrix(int stops) { final double radius = 10.0; double[][] matrix = new double[stops][stops]; for (int i = 0; i < stops; ++i) { for (int j = 0; j < stops; ++j) { matrix[i][j] = chord(stops, abs(i - j), radius); } } return matrix; } private static double chord(int stops, int i, double r) { return 2.0*r*abs(sin((PI*i)/stops)); } // Calculate the path length of the current genotype. private static Double dist(final Genotype<EnumGene<Integer>> gt) { // Convert the genotype to the traveling path. final int[] path = gt.getChromosome().stream() .mapToInt(EnumGene<Integer>::getAllele) .toArray(); // Calculate the path distance. return IntStream.range(0, STOPS) .mapToDouble(i -> ADJACENCE[path[i]][path[(i + 1)%STOPS]]) .sum(); } public static void main(String[] args) { final Engine<EnumGene<Integer>, Double> engine = Engine .builder( TravelingSalesman::dist, PermutationChromosome.ofInteger(STOPS)) .optimize(Optimize.MINIMUM) .maximalPhenotypeAge(11) .populationSize(500) .alterers( new SwapMutator<>(0.2), new PartiallyMatchedCrossover<>(0.35)) .build(); // Create evolution statistics consumer. final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber(); final Phenotype<EnumGene<Integer>, Double> best = engine.stream() // Truncate the evolution stream after 15 "steady" // generations. .limit(bySteadyFitness(15)) // The evolution will stop after maximal 250 // generations. .limit(250) // Update the evaluation statistics after // each generation .peek(statistics) // Collect (reduce) the evolution stream to // its best phenotype. .collect(toBestPhenotype()); System.out.println(statistics); System.out.println(best); } }
import Music.MusicManager; import com.neovisionaries.ws.client.WebSocketFactory; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.impl.GuildImpl; import net.dv8tion.jda.core.entities.impl.JDAImpl; import net.dv8tion.jda.core.entities.impl.TextChannelImpl; import net.dv8tion.jda.core.entities.impl.UserImpl; import net.dv8tion.jda.core.utils.SessionController; import net.dv8tion.jda.core.utils.SessionControllerAdapter; import okhttp3.OkHttpClient; import org.junit.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static Resources.TestValues.*; import static org.junit.Assert.*; @SuppressWarnings("FieldCanBeLocal") public class MusicLoadResultHandlerTests { private MessageChannel channel; private MusicManager manager; private User author; private SessionController controller; private OkHttpClient.Builder clientBuilder; private WebSocketFactory webSocketFactory; private ConcurrentMap<String, String> map; private JDAImpl testJDA; @Before public void setUp() { controller = new SessionControllerAdapter(); clientBuilder = new OkHttpClient.Builder(); webSocketFactory = new WebSocketFactory(); map = new ConcurrentHashMap<>(); testJDA = new JDAImpl(BOT_ACCOUNT, BOT_TOKEN, controller, clientBuilder, webSocketFactory, AUTO_RECONNECT, ENABLE_AUDIO, USE_SHUTDOWN_HOOK, ENABLE_DELETE_SPLITTING, RETRY_ON_TIMEOUT, ENABLE_MDC, CORE_POOL_SIZE, MAX_RECONNECT_DELAY, map); channel = new TextChannelImpl(MY_CHANNEL_ID, new GuildImpl(testJDA, MY_GUILD_ID)); manager = new MusicManager(new DefaultAudioPlayerManager()); author = new UserImpl(MY_USER_ID, testJDA); } @After public void tearDown() { controller = null; clientBuilder = null; webSocketFactory = null; map = null; testJDA = null; channel = null; manager = null; author = null; } }
package cn.hjmao.dao.minor; import org.testng.annotations.Test; import static org.testng.Assert.*; public class MainTest { @Test public void testConstruct() throws Exception { assertNotNull(new Main()); } @Test public void testAdd() throws Exception { int a = 3; int b = 4; assertEquals(Main.add(a, b), a + b); } }
package joptsimple; import static java.lang.Boolean.*; import static java.util.Arrays.*; import static java.util.Collections.*; import org.junit.Test; import static joptsimple.ExceptionMatchers.*; import static org.junit.Assert.*; /** * @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a> */ public class OptionParserTest extends AbstractOptionParserFixture { @Test public void optionsAndNonOptionsInterspersed() { parser.accepts( "i" ).withOptionalArg(); parser.accepts( "j" ).withOptionalArg(); parser.accepts( "k" ); OptionSet options = parser.parse( "-ibar", "-i", "junk", "xyz", "-jixnay", "foo", "-k", "blah", "--", "yermom" ); assertOptionDetected( options, "i" ); assertOptionDetected( options, "j" ); assertOptionDetected( options, "k" ); assertEquals( asList( "bar", "junk" ), options.valuesOf( "i" ) ); assertEquals( singletonList( "ixnay" ), options.valuesOf( "j" ) ); assertEquals( emptyList(), options.valuesOf( "k" ) ); assertEquals( asList( "xyz", "foo", "blah", "yermom" ), options.nonOptionArguments() ); } @Test public void shortOptionSpecifiedAsLongOptionWithoutArgument() { parser.accepts( "x" ); OptionSet options = parser.parse( "--x" ); assertOptionDetected( options, "x" ); assertEquals( emptyList(), options.valuesOf( "x" ) ); assertEquals( emptyList(), options.nonOptionArguments() ); } @Test public void longOptionLeadsWithSingleDash() { parser.accepts( "quiet" ); parser.accepts( "queen" ); OptionSet options = parser.parse( "-quiet" ); assertOptionDetected( options, "quiet" ); assertEquals( emptyList(), options.valuesOf( "quiet" ) ); assertEquals( emptyList(), options.nonOptionArguments() ); } @Test public void longOptionLeadsWithSingleDashAmbiguous() { parser.accepts( "quiet" ); parser.accepts( "queen" ); thrown.expect( UnrecognizedOptionException.class ); thrown.expect( withOption( "q" ) ); parser.parse( "-q" ); } @Test public void longOptionLeadsWithSingleDashAmbiguousButShortsAreLegal() { parser.accepts( "quiet" ); parser.accepts( "queen" ); parser.accepts( "q" ); parser.accepts( "u" ); OptionSet options = parser.parse( "-qu" ); assertOptionDetected( options, "q" ); assertOptionDetected( options, "u" ); assertOptionNotDetected( options, "quiet" ); assertOptionNotDetected( options, "queen" ); assertEquals( emptyList(), options.valuesOf( "q" ) ); assertEquals( emptyList(), options.valuesOf( "u" ) ); assertEquals( emptyList(), options.nonOptionArguments() ); } @Test public void longOptionLeadsWithSingleDashAmbiguousButAShortIsIllegal() { parser.accepts( "quiet" ); parser.accepts( "queen" ); parser.accepts( "q" ); thrown.expect( UnrecognizedOptionException.class ); thrown.expect( withOption( "u" ) ); parser.parse( "-qu" ); } @Test public void longOptionLeadsWithSingleDashAmbiguousButAShortAcceptsAnArgument() { parser.accepts( "quiet" ); parser.accepts( "queen" ); parser.accepts( "q" ).withOptionalArg(); OptionSet options = parser.parse( "-qu" ); assertOptionDetected( options, "q" ); assertOptionNotDetected( options, "quiet" ); assertOptionNotDetected( options, "queen" ); assertEquals( singletonList( "u" ), options.valuesOf( "q" ) ); assertEquals( emptyList(), options.nonOptionArguments() ); } @Test public void resetHappensAfterParsing() { parser.accepts( "i" ).withOptionalArg(); parser.accepts( "j" ).withOptionalArg(); parser.accepts( "k" ); String[] args = { "-ibar", "-i", "junk", "xyz", "-jixnay", "foo", "-k", "blah", "--", "yermom" }; OptionSet options = parser.parse( args ); assertEquals( options, parser.parse( args ) ); } @Test public void typedArguments() { parser.accepts( "a" ).withRequiredArg().ofType( Boolean.class ); parser.accepts( "b" ).withOptionalArg().ofType( Integer.class ); OptionSet options = parser.parse( "-a", "false", "-b", "3", "extra" ); assertOptionDetected( options, "a" ); assertOptionDetected( options, "b" ); assertEquals( FALSE, options.valueOf( "a" ) ); assertEquals( singletonList( FALSE ), options.valuesOf( "a" ) ); assertEquals( Integer.valueOf( "3" ), options.valueOf( "b" ) ); assertEquals( singletonList( Integer.valueOf( "3" ) ), options.valuesOf( "b" ) ); assertEquals( singletonList( "extra" ), options.nonOptionArguments() ); } @Test public void allowsMixingOfOptionsAndNonOptions() { parser.accepts( "i" ).withRequiredArg(); parser.accepts( "j" ).withOptionalArg(); parser.accepts( "k" ); OptionSet options = parser.parse( "a", "b", "c", "-i", "boo", "d", "e", "-k", "f", "-j" ); assertOptionDetected( options, "i" ); assertEquals( singletonList( "boo" ), options.valuesOf( "i" ) ); assertOptionDetected( options, "j" ); assertEquals( emptyList(), options.valuesOf( "j" ) ); assertOptionDetected( options, "k" ); assertEquals( emptyList(), options.valuesOf( "k" ) ); assertEquals( asList( "a", "b", "c", "d", "e", "f" ), options.nonOptionArguments() ); } @Test public void disallowsMixingOfOptionsAndNonOptionsUnderPosixlyCorrect() { parser.accepts( "i" ).withRequiredArg(); parser.accepts( "j" ).withOptionalArg(); parser.accepts( "k" ); parser.posixlyCorrect( true ); OptionSet options = parser.parse( "a", "b", "c", "-i", "boo", "d", "e", "-k", "f", "-j" ); assertOptionNotDetected( options, "i" ); assertEquals( emptyList(), options.valuesOf( "i" ) ); assertOptionNotDetected( options, "j" ); assertEquals( emptyList(), options.valuesOf( "j" ) ); assertOptionNotDetected( options, "k" ); assertEquals( emptyList(), options.valuesOf( "j" ) ); assertEquals( asList( "a", "b", "c", "-i", "boo", "d", "e", "-k", "f", "-j" ), options.nonOptionArguments() ); } @Test public void doubleHyphenSignalsEndsOfOptions() { OptionSet options = new OptionParser( "ab:c::de:f::" ) { { accepts( "verbose" ); } }.parse( "-a", "-b=foo", "-c=bar", "--", "-d", "-verbose", "-e", "baz", "-f", "biz" ); assertOptionDetected( options, "a" ); assertEquals( emptyList(), options.valuesOf( "a" ) ); assertOptionDetected( options, "b" ); assertEquals( singletonList( "foo" ), options.valuesOf( "b" ) ); assertOptionDetected( options, "c" ); assertEquals( singletonList( "bar" ), options.valuesOf( "c" ) ); assertOptionNotDetected( options, "d" ); assertOptionNotDetected( options, "verbose" ); assertOptionNotDetected( options, "e" ); assertOptionNotDetected( options, "f" ); assertEquals( asList( "-d", "-verbose", "-e", "baz", "-f", "biz" ), options.nonOptionArguments() ); } @Test public void allowsEmptyStringAsArgumentOfOption() { OptionSpec<String> optionI = parser.accepts( "i" ).withOptionalArg(); OptionSet options = parser.parse( "-i", "" ); assertOptionDetected( options, "i" ); assertEquals( "", optionI.value( options ) ); } @Test public void allowsWhitespaceyStringAsArgumentOfOption() { String whitespace = " \t\t\n\n\f\f \r\r "; OptionSpec<String> optionJ = parser.accepts( "j" ).withRequiredArg(); OptionSet options = parser.parse( "-j", whitespace ); assertOptionDetected( options, "j" ); assertEquals( whitespace, optionJ.value( options ) ); } @Test public void allowsEmbeddedWhitespaceInArgumentOfOption() { String withEmbeddedWhitespace = " look at me, I'm flaunting the rules! "; OptionSpec<String> optionJ = parser.accepts( "j" ).withRequiredArg(); OptionSet options = parser.parse( "-j", withEmbeddedWhitespace ); assertOptionDetected( options, "j" ); assertEquals( withEmbeddedWhitespace, optionJ.value( options ) ); } @Test public void requiredOptionWithArgMissing() { parser.accepts( "t" ).withOptionalArg().required(); thrown.expect( MissingRequiredOptionsException.class ); thrown.expect( withOption( "t" ) ); parser.parse(); } @Test public void requiredOptionButHelpOptionPresent() { parser.accepts( "t" ).withOptionalArg().required(); parser.accepts( "h" ).forHelp(); parser.parse( "-h" ); } @Test public void optionSpecsDefinedLaterOverrideThoseDefinedEarlier() { parser.accepts( "t" ).withRequiredArg(); parser.accepts( "t" ).withOptionalArg(); parser.parse( "-t" ); } }
package org.monarch.sim; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.tooling.GlobalGraphOperations; public class TraverserIT { static GraphDatabaseService db; static MappedDB mapped; @BeforeClass public static void setUpBeforeClass() throws Exception { db = new GraphFactory().buildOntologyDB("http://purl.obolibrary.org/obo/upheno/monarch.owl", "target/monarch", false); mapped = new MappedDB(db); } @AfterClass public static void tearDownAfterClass() throws Exception { mapped.close(); db.shutdown(); } private void printPath(List<Node> path) { LinkedList<Node> copy = new LinkedList<>(path); Node prev = copy.removeFirst(); System.out.println("~~ " + mapped.nodeToString(prev) + "~~"); // Find all edges between each pair of successive nodes. while (!copy.isEmpty()) { Node next = copy.removeFirst(); for (Relationship edge : prev.getRelationships()) { if (edge.getOtherNode(prev).equals(next)) { Node start = edge.getStartNode(); Node end = edge.getEndNode(); String toPrint = ""; toPrint += mapped.nodeToString(start); toPrint += " toPrint += edge.getType(); toPrint += " toPrint += mapped.nodeToString(end); System.out.println(toPrint); } } System.out.println("~~ " + mapped.nodeToString(next) + "~~"); prev = next; } } @Test public void test() throws IOException { SciGraphTraverser traverser = new SciGraphTraverser(db, "test"); Set<String> excluded = new HashSet<String>(); excluded.add("SUPERCLASS_OF"); excluded.add("PROPERTY"); excluded.add("inSubset"); for (RelationshipType rt : GlobalGraphOperations.at(db).getAllRelationshipTypes()) { if (!excluded.contains(rt.name())) { traverser.relationships(rt.name(), Direction.INCOMING); } } BufferedReader reader = new BufferedReader(new FileReader("HPGO_non_obvious.tsv")); String line; while ((line = reader.readLine()) != null) { String [] pieces = line.split("\t"); Node first = mapped.getNodeByFragment(pieces[0]); Node second = mapped.getNodeByFragment(pieces[3]); if (first == null) { System.out.println("Node " + pieces[0] + " does not exist."); continue; } if (second == null) { System.out.println("Node " + pieces[3] + " does not exist."); continue; } Node lcs = traverser.getDummyLCS(first, second); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println(mapped.nodeToString(first)); System.out.println(mapped.nodeToString(second)); System.out.println("LCS: " + mapped.nodeToString(lcs)); System.out.println(); // FIXME: Add shortest path calculation to traverser. List<Node> firstPath = Neo4jTraversals.getShortestPath(first, lcs); List<Node> secondPath = Neo4jTraversals.getShortestPath(second, lcs); System.out.println("" + mapped.nodeToString(first) + "--[" + (firstPath.size() - 1) + " edges]--> " + mapped.nodeToString(lcs) + "<--[" + (secondPath.size() - 1) + " edges]-- " + mapped.nodeToString(second) ); System.out.println((firstPath.size() + secondPath.size() - 2) + " edges total"); System.out.println(); printPath(firstPath); System.out.println(); printPath(secondPath); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } reader.close(); } }
package org.robolectric; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.robolectric.annotation.Config; import org.robolectric.bytecode.AndroidTranslatorClassInstrumentedTest; import org.robolectric.bytecode.ClassInfo; import org.robolectric.bytecode.Setup; import org.robolectric.bytecode.ShadowMap; import org.robolectric.internal.ParallelUniverseInterface; import org.robolectric.res.FsFile; import org.robolectric.res.ResourceLoader; import org.robolectric.shadows.ShadowSystemProperties; import java.lang.reflect.Method; import java.util.Locale; import static org.robolectric.util.TestUtil.resourceFile; public class TestRunners { public static class WithCustomClassList extends RobolectricTestRunner { public WithCustomClassList(@SuppressWarnings("rawtypes") Class testClass) throws InitializationError { super(testClass); } @Override protected AndroidManifest createAppManifest(FsFile manifestFile, FsFile resDir, FsFile assetsDir) { return new AndroidManifest(resourceFile("TestAndroidManifest.xml"), resourceFile("res"), resourceFile("assets")); } @Override public Setup createSetup() { return new Setup() { @Override public boolean shouldInstrument(ClassInfo classInfo) { String name = classInfo.getName(); if (name.equals(AndroidTranslatorClassInstrumentedTest.CustomPaint.class.getName()) || name.equals(AndroidTranslatorClassInstrumentedTest.ClassWithPrivateConstructor.class.getName())) { return true; } return super.shouldInstrument(classInfo); } }; } } public static class WithoutDefaults extends RobolectricTestRunner { public WithoutDefaults(Class<?> testClass) throws InitializationError { super(testClass); } @Override protected ShadowMap createShadowMap() { // Don't do any class binding except the bare minimum, because that's what we're trying to test here. return new ShadowMap.Builder() .addShadowClass(ShadowSystemProperties.class) .build(); } @Override protected AndroidManifest createAppManifest(FsFile manifestFile, FsFile resDir, FsFile assetsDir) { return null; } @Override protected void setUpApplicationState(Method method, ParallelUniverseInterface parallelUniverseInterface, boolean strictI18n, ResourceLoader systemResourceLoader, AndroidManifest appManifest, Config config) { // Don't do any resource loading or app init, because that's what we're trying to test here. } } public static class WithDefaults extends RobolectricTestRunner { public WithDefaults(Class<?> testClass) throws InitializationError { super(testClass); Locale.setDefault(Locale.ENGLISH); } @Override public Setup createSetup() { return new Setup() { @Override public boolean shouldAcquire(String name) { // todo: whyyyyy!?!? if this isn't there, tests after TestRunnerSequenceTest start failing bad. if (name.startsWith("org.mockito.")) return false; return super.shouldAcquire(name); } }; } @Override protected AndroidManifest createAppManifest(FsFile manifestFile, FsFile resDir, FsFile assetsDir) { return new AndroidManifest(resourceFile("TestAndroidManifest.xml"), resourceFile("res"), resourceFile("assets")); } } public static class RealApisWithoutDefaults extends RobolectricTestRunner { public RealApisWithoutDefaults(Class<?> testClass) throws InitializationError { super(testClass); } @Override protected ShadowMap createShadowMap() { // Don't do any class binding, because that's what we're trying to test here. return ShadowMap.EMPTY; } @Override public AndroidManifest getAppManifest(Config config) { // Don't do any resource loading or app init, because that's what we're trying to test here. return null; } @Override protected void setUpApplicationState(Method method, ParallelUniverseInterface parallelUniverseInterface, boolean strictI18n, ResourceLoader systemResourceLoader, AndroidManifest appManifest, Config config) { // Don't do any resource loading or app init, because that's what we're trying to test here. } } }
package ui; import java.util.List; import java.util.function.Consumer; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import storage.DataManager; public class RepositorySelector extends HBox { private final ComboBox<String> comboBox = new ComboBox<>(); private final Label label = new Label(); private Consumer<String> onValueChangeCallback = null; public RepositorySelector() { setupLayout(); setupComboBox(); getChildren().addAll(comboBox); getChildren().addAll(label); } /** * Meant as a replacement for {@link #isInFocus isInFocus} (which is final). * @return true if the combobox portion of this element is in focus */ public boolean isInFocus() { return comboBox.isFocused(); } private void setupLayout() { setSpacing(5); setPadding(new Insets(5)); setAlignment(Pos.BASELINE_LEFT); comboBox.setPrefWidth(250); } private void setupComboBox() { comboBox.setFocusTraversable(false); comboBox.setEditable(true); loadComboBoxContents(); comboBox.valueProperty().addListener((observable, old, newVal) -> { if (onValueChangeCallback != null) { onValueChangeCallback.accept(newVal); } }); } public void setLabelText(String text) { label.setText(text); } public void setValue(String val) { comboBox.setValue(val); } public void enable() { comboBox.setDisable(false); } public void disable() { comboBox.setDisable(true); } public void setOnValueChange(Consumer<String> callback) { onValueChangeCallback = callback; } private void loadComboBoxContents() { List<String> items = DataManager.getInstance().getLastViewedRepositories(); comboBox.getItems().addAll(items); } public void refreshComboBoxContents() { comboBox.getItems().clear(); loadComboBoxContents(); } }
package dr.evomodel.branchratemodel; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeParameterModel; import dr.evomodelxml.branchratemodel.DiscretizedBranchRatesParser; import dr.inference.distribution.ParametricDistributionModel; import dr.inference.model.Model; import dr.inference.model.ModelListener; import dr.inference.model.Parameter; import dr.inference.model.Variable; /** * @author Alexei Drummond * @author Andrew Rambaut * @author Michael Defoin Platel * @version $Id: DiscretizedBranchRates.java,v 1.11 2006/01/09 17:44:30 rambaut Exp $ */ public class DiscretizedBranchRates extends AbstractBranchRateModel { // Turn on an off the caching on rates for categories - // if off then the rates will be flagged to update on // a restore. // Currently turned off as it is not working with multiple partitions for // some reason. private static final boolean CACHE_RATES = false; private final ParametricDistributionModel distributionModel; // The rate categories of each branch final TreeParameterModel rateCategories; private final int categoryCount; private final double step; private final double[][] rates; private final boolean normalize; private final double normalizeBranchRateTo; private final TreeModel treeModel; private final double logDensityNormalizationConstant; private double scaleFactor = 1.0; private double storedScaleFactor; private boolean updateRateCategories = true; private int currentRateArrayIndex = 0; private int storedRateArrayIndex; //overSampling control the number of effective categories public DiscretizedBranchRates( TreeModel tree, Parameter rateCategoryParameter, ParametricDistributionModel model, int overSampling) { this(tree, rateCategoryParameter, model, overSampling, false, Double.NaN); } public DiscretizedBranchRates( TreeModel tree, Parameter rateCategoryParameter, ParametricDistributionModel model, int overSampling, boolean normalize, double normalizeBranchRateTo) { super(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES); this.rateCategories = new TreeParameterModel(tree, rateCategoryParameter, false); categoryCount = (tree.getNodeCount() - 1) * overSampling; step = 1.0 / (double) categoryCount; rates = new double[2][categoryCount]; this.normalize = normalize; this.treeModel = tree; this.distributionModel = model; this.normalizeBranchRateTo = normalizeBranchRateTo; //Force the boundaries of rateCategoryParameter to match the category count Parameter.DefaultBounds bound = new Parameter.DefaultBounds(categoryCount - 1, 0, rateCategoryParameter.getDimension()); rateCategoryParameter.addBounds(bound); for (int i = 0; i < rateCategoryParameter.getDimension(); i++) { int index = (int) Math.floor((i + 0.5) * overSampling); rateCategoryParameter.setParameterValue(i, index); } addModel(model); addModel(rateCategories); updateRateCategories = true; // Each parameter take any value in [1, \ldots, categoryCount] // NB But this depends on the transition kernel employed. Using swap-only results in a different constant logDensityNormalizationConstant = -rateCategoryParameter.getDimension() * Math.log(categoryCount); } // compute scale factor private void computeFactor() { //scale mean rate to 1.0 or separate parameter double treeRate = 0.0; double treeTime = 0.0; //normalizeBranchRateTo = 1.0; for (int i = 0; i < treeModel.getNodeCount(); i++) { NodeRef node = treeModel.getNode(i); if (!treeModel.isRoot(node)) { int rateCategory = (int) Math.round(rateCategories.getNodeValue(treeModel, node)); treeRate += rates[currentRateArrayIndex][rateCategory] * treeModel.getBranchLength(node); treeTime += treeModel.getBranchLength(node); //System.out.println("rates and time\t" + rates[rateCategory] + "\t" + treeModel.getBranchLength(node)); } } //treeRate /= treeTime; scaleFactor = normalizeBranchRateTo / (treeRate / treeTime); //System.out.println("scaleFactor\t\t\t\t\t" + scaleFactor); } public void handleModelChangedEvent(Model model, Object object, int index) { if (model == distributionModel) { updateRateCategories = true; fireModelChanged(); } else if (model == rateCategories) { fireModelChanged(null, index); } } protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { // nothing to do here } protected void storeState() { if (CACHE_RATES) { storedRateArrayIndex = currentRateArrayIndex; storedScaleFactor = scaleFactor; } } protected void restoreState() { if (CACHE_RATES) { currentRateArrayIndex = storedRateArrayIndex; scaleFactor = storedScaleFactor; } else { updateRateCategories = true; } } protected void acceptState() { } public final double getBranchRate(final Tree tree, final NodeRef node) { assert !tree.isRoot(node) : "root node doesn't have a rate!"; if (updateRateCategories) { setupRates(); } int rateCategory = (int) Math.round(rateCategories.getNodeValue(tree, node)); //System.out.println(rates[rateCategory] + "\t" + rateCategory); return rates[currentRateArrayIndex][rateCategory] * scaleFactor; } /** * Calculates the actual rates corresponding to the category indices. */ private void setupRates() { if (CACHE_RATES) { // flip the current array index currentRateArrayIndex = 1 - currentRateArrayIndex; } double z = step / 2.0; for (int i = 0; i < categoryCount; i++) { rates[currentRateArrayIndex][i] = distributionModel.quantile(z); //System.out.print(rates[i]+"\t"); z += step; } if (normalize) computeFactor(); updateRateCategories = false; } public double getLogLikelihood() { return logDensityNormalizationConstant; } }
package edu.macalester.tagrelatedness; import edu.cmu.lti.lexical_db.ILexicalDatabase; import edu.cmu.lti.lexical_db.NictWordNet; import edu.cmu.lti.ws4j.RelatednessCalculator; import edu.cmu.lti.ws4j.WS4J; import edu.cmu.lti.ws4j.impl.JiangConrath; import edu.cmu.lti.ws4j.util.WS4JConfiguration; import org.apache.commons.cli.*; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; public class CalculateCorrelation { public static void main(String[] args){ CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("input-file") .withDescription("Input file to calculate the correlation of") .hasArg() .withArgName("FILE") .create()); options.addOption(OptionBuilder.withLongOpt("measure") .withDescription("wordnet") .hasArg() .withArgName("NAME") .create()); HelpFormatter formatter = new HelpFormatter(); try { File input = null; CommandLine line = parser.parse(options, args); if(!options.hasOption("input-file")){ System.out.println("An input file needs to be specified."); formatter.printHelp("Correlation calculator", options); System.exit(1); }else{ input = new File(line.getOptionValue("input-file")); } // If other correlation measures are needed, identify them here with line.getOption("measure") assert null != input; tauBetweenCSVandWordnet(input); } catch (ParseException e) { e.printStackTrace(); } } public static void tauBetweenCSVandWordnet(File file, int threads){ long start = System.nanoTime(); final ArrayList<Double> measurementSimilarities = new ArrayList<Double>(); final ArrayList<Double> wordnetSimilarities = new ArrayList<Double>(); java.util.List<String> lines = null; try { lines = Files.readAllLines(Paths.get(file.getAbsolutePath()), Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } System.out.println("Similarities to add: "+lines.size()); ParallelForEach.loop(lines.subList(0, lines.size()), threads, new Procedure<String>() { public void call(String line){ String[] column = line.split(","); String word1 = column[0].replace("\"", "").replace(" ", ""); String word2 = column[1].replace("\"", "").replace(" ", ""); double jc = WS4J.runJCN(word1, word2); double cc = Double.parseDouble(column[2]); if(jc != 0){ // check that wordnet does have a result for this word pair synchronized (measurementSimilarities) { measurementSimilarities.add(cc); wordnetSimilarities.add(jc); } } } }); System.out.println("Tau: "+KendallsCorrelation.correlation(measurementSimilarities, wordnetSimilarities)); } public static void tauBetweenCSVandWordnet(File file){ tauBetweenCSVandWordnet(file, Runtime.getRuntime().availableProcessors()); } }
package edu.washington.escience.myriad.api; import java.io.IOException; import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.ObjectMapper; import edu.washington.escience.myriad.RelationKey; import edu.washington.escience.myriad.Schema; import edu.washington.escience.myriad.coordinator.catalog.CatalogException; /** * This is the class that handles API calls that return relation schemas. * * @author dhalperi */ @Produces(MediaType.APPLICATION_JSON) @Path("/dataset") public final class DatasetResource { /** * @param userName the user who owns the target relation. * @param programName the program to which the target relation belongs. * @param relationName the name of the target relation. * @return the schema of the specified relation. */ @GET @Path("/user-{userName}/program-{programName}/relation-{relationName}") public Schema getDataset(@PathParam("userName") final String userName, @PathParam("programName") final String programName, @PathParam("relationName") final String relationName) { try { Schema schema = MyriaApiUtils.getServer().getSchema(RelationKey.of(userName, programName, relationName)); if (schema == null) { /* Not found, throw a 404 (Not Found) */ throw new WebApplicationException(Response.status(Status.NOT_FOUND).build()); } /* Yay, worked! */ return schema; } catch (final CatalogException e) { /* Throw a 500 (Internal Server Error) */ throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).build()); } } /** * @param uriInfo information about the current URL. * @param payload the request payload. * @return the created dataset resource. */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response newDataset(final byte[] payload, @Context final UriInfo uriInfo) { if (payload == null || payload.length == 0) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity("Payload cannot be empty.\n") .build()); } /* Attempt to deserialize the object. */ DatasetEncoding dataset; try { final ObjectMapper mapper = new ObjectMapper(); dataset = mapper.readValue(payload, DatasetEncoding.class); } catch (IOException e) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build()); } /* If we already have a dataset by this name, tell the user there's a conflict. */ try { if (MyriaApiUtils.getServer().getSchema(dataset.relationKey) != null) { /* Found, throw a 409 (Conflict) */ throw new WebApplicationException(Response.status(Status.CONFLICT).build()); } } catch (final CatalogException e) { /* Throw a 500 (Internal Server Error) */ throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build()); } /* If we don't have any workers alive right now, tell the user we're busy. */ Set<Integer> workers = MyriaApiUtils.getServer().getAliveWorkers(); if (workers.size() == 0) { /* Throw a 503 (Service Unavailable) */ throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE).build()); } /* Do the work. */ try { MyriaApiUtils.getServer().ingestDataset(dataset.relationKey, dataset.schema, dataset.data); } catch (CatalogException e) { throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build()); } /* In the response, tell the client the path to the relation. */ UriBuilder queryUri = uriInfo.getBaseUriBuilder(); return Response.created( queryUri.path("dataset").path("user-" + dataset.relationKey.getUserName()).path( "program-" + dataset.relationKey.getProgramName()) .path("relation-" + dataset.relationKey.getRelationName()).build()).build(); } /** * A JSON-able wrapper for the expected wire message for a new dataset. * */ static class DatasetEncoding { /** The name of the dataset. */ @JsonProperty("relation_key") public RelationKey relationKey; /** The Schema of its tuples. */ @JsonProperty("schema") public Schema schema; /** The data it contains. */ @JsonProperty("data") public byte[] data; } }
package hex.psvm.psvm; import water.MRTask; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.FrameCreator; import water.fvec.Vec; import water.util.ArrayUtils; import water.util.FrameUtils; import java.util.Arrays; public class MatrixUtils { /** * Calculates matrix product M'DM * @param m Frame representing the M matrix (m x n), M' is expected to be lower triangular * @param diagonal Vec representation of a diagonal matrix (m x m) * @return lower triangular portion of the product (the product is a symmetrical matrix, only the lower portion is represented) */ public static LLMatrix productMtDM(Frame m, Vec diagonal) { Vec[] vecs = ArrayUtils.append(m.vecs(), diagonal); double result[] = new ProductMMTask().doAll(vecs)._result; LLMatrix product = new LLMatrix(m.numCols()); int pos = 0; for (int i = 0; i < m.numCols(); i++) { for (int j = 0; j <= i; j++) { product.set(i, j, result[pos++]); } } return product; } /** * Calculates matrix-vector product M'v * @param m Frame representing matrix M (m x n) * @param v Vec representing vector v (n x 1) - TODO avalenta NOT WORKING, dimension must be m x 1 * @return m-element array representing the result of the product */ public static double[] productMtv(Frame m, Vec v) { Vec[] vecs = ArrayUtils.append(m.vecs(), v); return new ProductMtvTask().doAll(vecs)._result; } /** * Previous Mtv method is not working. * * Calculates matrix-vector product M'v * * @param m Frame representing matrix M (m x n) * @param v Vec representing vector v (n x 1) * @return m-element array representing the result of the product */ public static Vec workingProductMtv(Frame m, Vec v) { // TODO avalenta better vec creation Vec result = new ProductMtvTask2(v, m.numRows()).doAll(m)._result; // System.out.println(Arrays.toString(FrameUtils.asDoubles(result))); return result; } /** * Calculates vector-vector product v1*v2 * * @param v1 vec representing first element (1 x n) * @param v2 Vec representing second element (n x 1) * @return double value (vector 1 x 1) */ public static double productVtV(Vec v1, Vec v2) { return new ProductMtvTask().doAll(v1, v2)._result[0]; } /** * Calculates matrix-vector subtraction M'v * * @param m Frame representing matrix M (m x n) * @param v Vec representing vector v (n x 1) * @return m-element array representing the result of the subtraction */ public static Frame subtractionMtv(Frame m, Vec v) { if (v.length() != m.numCols()) { throw new UnsupportedOperationException("Vector elements number must be the same as matrix column number"); } Frame result = new SubMtvTask(v).doAll(m.deepCopy("newKey"))._fr; return result; } private static class ProductMMTask extends MRTask<ProductMMTask> { // OUT private double[] _result; @Override public void map(Chunk[] cs) { final int column = cs.length - 1; final Chunk diagonal = cs[column]; _result = new double[(column + 1) * column / 2]; double[] buff = new double[cs[0]._len]; int offset = 0; for (int i = 0; i < column; i++) { offset += i; for (int p = 0; p < buff.length; p++) { buff[p] = cs[i].atd(p) * diagonal.atd(p); } for (int j = 0; j <= i; j++) { double sum = 0; for (int p = 0; p < buff.length; p++) { sum += buff[p] * cs[j].atd(p); } _result[offset+j] = sum; } } } @Override public void reduce(ProductMMTask mrt) { ArrayUtils.add(_result, mrt._result); } } static class ProductMtvTask extends MRTask<ProductMtvTask> { // OUT private double[] _result; @Override public void map(Chunk[] cs) { final int column = cs.length - 1; final Chunk v = cs[column]; _result = new double[column]; for (int j = 0; j < column; ++j) { double sum = 0.0; for (int i = 0; i < cs[0]._len; i++) { sum += cs[j].atd(i) * v.atd(i); } _result[j] = sum; } } @Override public void reduce(ProductMtvTask mrt) { ArrayUtils.add(_result, mrt._result); } } static class SubMtvTask extends MRTask<SubMtvTask> { private Vec v; public SubMtvTask(Vec v) { this.v = v; } @Override public void map(Chunk[] cs) { for (int column = 0; column < cs.length; column++) { for (int row = 0; row < cs[0]._len; row++) { cs[column].set(row, cs[column].atd(row) - v.at(column)); } } } } static class ProductMtvTask2 extends MRTask<ProductMtvTask2> { private final Vec v; private Vec _result; public ProductMtvTask2(Vec v, long length) { this.v = v; _result = Vec.makeZero(length); } @Override public void map(Chunk[] cs) { for (int row = 0; row < cs[0]._len; row++) { double sum = 0.0; for (int column = 0; column < cs.length; ++column) { sum += cs[column].atd(row) * v.at(column); } _result.set(cs[0].start() + row, sum); } } } }
package gate.plugin.evaluation.resources; import gate.plugin.evaluation.api.ContainmentType; import gate.plugin.evaluation.api.NilTreatment; import gate.Annotation; import gate.AnnotationSet; import gate.Controller; import gate.FeatureMap; import gate.Resource; import gate.Utils; import gate.annotation.AnnotationSetImpl; import gate.creole.ControllerAwarePR; import gate.creole.ExecutionException; import gate.creole.metadata.CreoleParameter; import gate.creole.metadata.CreoleResource; import gate.creole.metadata.Optional; import gate.creole.metadata.RunTime; import gate.plugin.evaluation.api.AnnotationDifferTagging; import gate.plugin.evaluation.api.AnnotationDifferTagging.CandidateList; import gate.plugin.evaluation.api.AnnotationTypeSpec; import gate.plugin.evaluation.api.AnnotationTypeSpecs; import gate.plugin.evaluation.api.EvalStatsTagging; import gate.util.GateRuntimeException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; /** * * @author Johann Petrak */ @CreoleResource( name = "EvaluateMaxRecall", helpURL ="https://github.com/johann-petrak/gateplugin-Evaluation/wiki/EvaluateMaxRecall-PR", comment = "Calculate maximum recall for annotations with candidate lists") public class EvaluateMaxRecall extends EvaluateTaggingBase implements ControllerAwarePR //, CustomDuplication { /// PR PARAMETERS protected String edgeFeatureName; @CreoleParameter(comment="The name of the feature that contains the list of candidate/element annotation ids",defaultValue="") @RunTime @Optional public void setEdgeFeatureName(String value) { edgeFeatureName = value; } public String getEdgeFeatureName() { return edgeFeatureName; } public String getExpandedEdgeFeatureName() { return Utils.replaceVariablesInString(getEdgeFeatureName()); } protected String listType; @CreoleParameter(comment="The annotation type of the list annotations",defaultValue="LookupList") @RunTime public void setListType(String value) { listType = value; } public String getListType() { return listType; } public String getExpandedListType() { return Utils.replaceVariablesInString(getListType()); } protected String keyType; @CreoleParameter(comment="The annotation type of the key/target annotations",defaultValue="Mention") @RunTime public void setKeyType(String value) { keyType = value; } public String getKeyType() { return keyType; } public String getExpandedKeyType() { return Utils.replaceVariablesInString(getKeyType()); } protected String elementType; @CreoleParameter(comment="The annotation type of the list element annotations",defaultValue="Lookup") @RunTime public void setElementType(String value) { elementType = value; } public String getElementType() { return elementType; } public String getExpandedElementType() { return Utils.replaceVariablesInString(getElementType()); } // PR METHODS @Override public Resource init() { return this; } @Override public void reInit() { init(); } @Override public void cleanup() { } /// API methods to return the crucial measurements and values private int nTargets; /** * Number of total targets over all processed documents * @return */ public int getTargets() { return nTargets; } private int nTargetsWithList; /** * Number of total targets that have at least one non-empty response list */ public int getTargetsWithList() { return nTargetsWithList; } private List<Integer> nCorrectStrictByRank; /** * Number of correct strict responses for a target at rank i */ public List<Integer> getCorrectStrictByRank() { return new ArrayList<Integer>(nCorrectStrictByRank); } // convenience method to increment the count for a specific // index by the given value and make sure that all // new elements are set to zero. // returns the new value private int incCorrectStrictByRank(int index, int byValue) { return incHelper(nCorrectStrictByRank,index,byValue); } private int incCorrectLenientByRank(int index, int byValue) { return incHelper(nCorrectLenientByRank,index,byValue); } private int incHelper(List<Integer> what, int index, int byValue) { int val = 0; // if the index is not in the array yet, then we need to add index-size elements if(index >= what.size()) { for(int i = what.size(); i <= index; i++) { what.add(0); } what.set(index, byValue); val = byValue; } else { val = what.get(index); val += byValue; what.set(index,val); } return val; } // convenience method to initialize all counts private void initializeCounts() { nTargets = 0; nTargetsWithList = 0; nCorrectLenient = 0; nCorrectLenientByRank = new ArrayList<Integer>(1000); nCorrectStrict = 0; nCorrectStrictByRank = new ArrayList<Integer>(1000); nResponseLists = 0; nResponseListsWithTarget = 0; } private List<Integer> nCorrectLenientByRank; /** * Number of crrect lenient responses for a target at rank i * @return */ private List<Integer> getCorrectLenientByRank() { return new ArrayList<Integer>(nCorrectLenientByRank); } private int nCorrectStrict; private int nCorrectLenient; public double getMaxRecallStrict() { return recall(nTargets,nCorrectStrict); } public double getMaxRecallLenient() { return recall(nTargets,nCorrectLenient); } public double getMaxRecall4ListsStrict() { return recall(nTargetsWithList,nCorrectStrict); } public double getMaxRecall4ListsLenient() { return recall(nTargetsWithList,nCorrectLenient); } public List<Double> getMaxRecallStrictByRank() { List<Double> ret = new ArrayList<Double>(nCorrectStrictByRank.size()); int sum = 0; for(int corr : nCorrectStrictByRank) { sum += corr; ret.add(recall(nTargets,sum)); } return ret; } public List<Double> getMaxRecallLenientByRank() { List<Double> ret = new ArrayList<Double>(nCorrectLenientByRank.size()); int sum = 0; for(int corr : nCorrectLenientByRank) { sum += corr; ret.add(recall(nTargets,sum)); } return ret; } public List<Double> getMaxRecallStrict4ListByRank() { List<Double> ret = new ArrayList<Double>(nCorrectStrictByRank.size()); int sum = 0; for(int corr : nCorrectStrictByRank) { sum += corr; ret.add(recall(nTargetsWithList,sum)); } return ret; } public List<Double> getMaxRecallLenient4ListByRank() { List<Double> ret = new ArrayList<Double>(nCorrectLenientByRank.size()); int sum = 0; for(int corr : nCorrectLenientByRank) { sum += corr; ret.add(recall(nTargetsWithList,sum)); } return ret; } private int nResponseLists; private int nResponseListsWithTarget; /// Helper functions private double recall(int targets, int correct) { if(targets == 0 && correct == 0) { return 1.0; } else if(targets == 0) { return 0.0; } else { return (double)correct / targets; } } AnnotationTypeSpecs annotationTypeSpecs4Best; String expandedEdgeName; protected static final String initialFeaturePrefixResponse = "evaluateTagging4Lists.response."; protected static final String initialFeaturePrefixReference = "evaluateTagging4Lists.reference."; protected static final Logger logger = Logger.getLogger(EvaluateMaxRecall.class); protected PrintStream maxrecallTsvPrintStream; @Override public void execute() throws ExecutionException { //System.out.println("DEBUG: running tagging4lists execute"); if(needInitialization) { needInitialization = false; initializeCounts(); initializeForRunning(); } if(isInterrupted()) { throw new ExecutionException("PR was interrupted!"); } //System.out.println("DOC: "+document); // This should iterate exactly once because we created the annotationTypeSpecs from // single key and list annotation types this PR uses. for(AnnotationTypeSpec typeSpec : annotationTypeSpecs.getSpecs()) { AnnotationSet keySet = document.getAnnotations(expandedKeySetName).get(typeSpec.getKeyType()); //System.out.println("DEBUG: getting anns for set "+expandedResponseSetName+" and type "+typeSpec.getResponseType()); AnnotationSet responseSet = document.getAnnotations(expandedResponseSetName).get(typeSpec.getResponseType()); // for now, no support for a reference set!! evaluateForType(keySet,responseSet,null,typeSpec); } } protected void evaluateForType( AnnotationSet keySet, AnnotationSet responseSet, AnnotationSet referenceSet, AnnotationTypeSpec typeSpec) { String type = typeSpec.getKeyType(); //System.out.println("DEBUG: evaluating for type "+typeSpec+" keysize="+keySet.size()+" resSize="+responseSet.size()); if(!expandedContainingNameAndType.isEmpty()) { String[] setAndType = expandedContainingNameAndType.split(":",2); if(setAndType.length != 2 || setAndType[0].isEmpty() || setAndType[1].isEmpty()) { throw new GateRuntimeException("Runtime Parameter containingASAndName not of the form setname:typename"); } String containingSetName = setAndType[0]; String containingType = setAndType[1]; AnnotationSet containingSet = document.getAnnotations(setAndType[0]).get(setAndType[1]); // now filter the keys and responses. If the containing set/type is the same as the key set/type, // do not filter the keys. ContainmentType ct = containmentType; if(ct == null) ct = ContainmentType.OVERLAPPING; responseSet = selectOverlappingBy(responseSet,containingSet,ct); if(containingSetName.equals(expandedKeySetName) && containingType.equals(type)) { // no need to do anything for the key set } else { keySet = selectOverlappingBy(keySet,containingSet,ct); } // if we have a reference set, we need to apply the same filtering to that one too if(referenceSet != null) { referenceSet = selectOverlappingBy(referenceSet,containingSet,ct); } } // have a containing set and type boolean filterNils = false; if(getNilTreatment().equals(NilTreatment.NIL_IS_ABSENT)) { filterNils = true; removeNilAnns(keySet); } //System.out.println("DEBUG: after NIL filtering, keysize="+keySet.size()); // counts for measuring overall (not by rank) document max recall int nDocTargets = 0; int nDocTargetsWithList = 0; int nDocStrictMatches = 0; int nDocLenientMatches = 0; int nDocResponseLists = 0; int nDocResponseListsWithList = 0; AnnotationSet listAnns = responseSet; // Create the candidate lists, with the candidates sorted by the given score feature, // and with empty response lists removed. List<CandidateList> candLists = AnnotationDifferTagging.createCandidateLists( document.getAnnotations(expandedResponseSetName), listAnns, expandedEdgeName, expandedScoreFeatureName, // this should be null if we evaluate for ranks getExpandedElementType(), filterNils,getNilValue(),getFeatureNames().get(0)); nResponseLists += candLists.size(); nDocResponseLists += candLists.size(); // This set is used to record the listAnns that do have a target so we can count them later Set<Annotation> listAnnsWithTarget = new HashSet<Annotation>(listAnns.size()); for(Annotation keyAnn : keySet.inDocumentOrder()) { // each key annotation is a target so count it nTargets += 1; nDocTargets += 1; // get all the candidate lists that overlap with the key. At the moment this // is done a bit clumsily by checking the list annotations for all candidate lists // separatel and putting all that overlap in a list. List<CandidateList> overlaps = new ArrayList<CandidateList>(); for(CandidateList cl : candLists) { if(cl.getListAnnotation().overlaps(keyAnn)) { overlaps.add(cl); } } // if there are no overlapping lists, we are done, all the interesting stuff // only happens if we have at least one response list if(overlaps.size() > 0) { // count as a target that has at least one response list nTargetsWithList += 1; nDocTargetsWithList += 1; // find the lowest index among all response lists where we have a strict or a lenient (strict or partial) // match. For this we initialize an index for those matches with MAXINT and // lower it for each match we find with a lower index in any of the overlapping lists. int strictMatchIndex = Integer.MAX_VALUE; int lenientMatchIndex = Integer.MAX_VALUE; for(CandidateList cl : overlaps) { // record that this list overlaps with a target listAnnsWithTarget.add(cl.getListAnnotation()); for(int i = 0; i < cl.sizeAll(); i++) { // first check if the response overlaps with the key at all, only do something // if that is the case Annotation resp = cl.get(i); if(resp.overlaps(keyAnn)) { //System.out.println("DEBUG: got an overlap, matching "+keyAnn.getFeatures().get("inst")+" and "+resp.getFeatures().get("inst")); boolean match = AnnotationDifferTagging.isAnnotationsMatch(keyAnn, resp, featureSet, featureComparison, true, annotationTypeSpecs); // if we have a match, it is definitely lenient (strict or partial) // but we have to check if the response is also coextensive if(match) { //System.out.println("DEBUG: got match"); if(i < lenientMatchIndex) lenientMatchIndex = i; if(resp.coextensive(keyAnn)) { if(i < strictMatchIndex) strictMatchIndex = i; // we have found and checked a strict match, so any other match at a higher // index will not change anything any more, we can terminate the loop break; } } else { // if match //System.out.println("DEBUG: got NO match"); } } } // for i=0..cl.size } // for cl : overlaps // Now the match indices are either still MAXINT because no match was found, or // they are the index of the lowest match found. If not maxint, we can also // increase the overall (not by rank) max recall counts // We only can have a strict match if there was a lenient match because each strict // match is also a lenient one if(lenientMatchIndex < Integer.MAX_VALUE) { nCorrectLenient += 1; nDocLenientMatches += 1; //System.out.println("DEBUG: incrementing lenient at index "+lenientMatchIndex); incCorrectLenientByRank(lenientMatchIndex, 1); if(strictMatchIndex < Integer.MAX_VALUE) { nCorrectStrict += 1; nDocStrictMatches += 1; //System.out.println("DEBUG: incrementing strict at index "+strictMatchIndex); incCorrectStrictByRank(strictMatchIndex, 1); } else { // TODO: maybe set to -1 instead? } } // create annotation in the output set, if we have one if(!outputASResName.isEmpty()) { // figure out which suffix to use for the indicator annotation depending on the kind of // match we found: // _NM : we had a response list but no match at all // _SM : we found a strict match somewhere // _PM : we found a partial match but no strict match // _NR : there is not even a response list String suf = "NM"; if(strictMatchIndex < Integer.MAX_VALUE) { suf = "SM"; } else if(lenientMatchIndex < Integer.MAX_VALUE) { suf = "PM"; } AnnotationSet outSet = document.getAnnotations(outputASResName); Utils.addAnn(outSet, keyAnn, keyAnn.getType()+suf, Utils.toFeatureMap(keyAnn.getFeatures())); } // TODO: maybe replace MAX_VALUE with -1 for the tsv output. // TODO: output line for this target to TSV file if we have one } else { // if we have candidate lists that overlap with the target // no we do not have a list, so create an indicator annotation if wanted if(!outputASResName.isEmpty()) { AnnotationSet outSet = document.getAnnotations(outputASResName); Utils.addAnn(outSet, keyAnn, keyAnn.getType()+"_NR", Utils.toFeatureMap(keyAnn.getFeatures())); } } } // end for keyAnn in keySet nResponseListsWithTarget += listAnnsWithTarget.size(); nDocResponseListsWithList += listAnnsWithTarget.size(); if(mainTsvPrintStream != null) { String line = outputTsvLine( "list-maxrecall", document.getName(), annotationTypeSpecs.getSpecs().get(0), expandedResponseSetName, -1, nDocTargets, nDocTargetsWithList, nDocStrictMatches, nDocLenientMatches, nDocResponseLists, nDocResponseListsWithList); mainTsvPrintStream.println(line); } // TODO: maybe do the same for the reference set! // Store the counts and measures as document feature values FeatureMap docFm = document.getFeatures(); // TODO: store as document features! /* if (getAddDocumentFeatures()) { String featurePrefixResponseT = featurePrefixResponse; featurePrefixResponseT += type; docFm.put(featurePrefixResponseT + "FMeasureStrict", es.getFMeasureStrict(1.0)); docFm.put(featurePrefixResponseT + "FMeasureLenient", es.getFMeasureLenient(1.0)); docFm.put(featurePrefixResponseT + "PrecisionStrict", es.getPrecisionStrict()); docFm.put(featurePrefixResponseT + "PrecisionLenient", es.getPrecisionLenient()); docFm.put(featurePrefixResponseT + "RecallStrict", es.getRecallStrict()); docFm.put(featurePrefixResponseT + "RecallLenient", es.getRecallLenient()); docFm.put(featurePrefixResponseT + "SingleCorrectAccuracyStrict", es.getSingleCorrectAccuracyStrict()); docFm.put(featurePrefixResponseT + "SingleCorrectAccuracyLenient", es.getSingleCorrectAccuracyLenient()); docFm.put(featurePrefixResponseT + "CorrectStrict", es.getCorrectStrict()); docFm.put(featurePrefixResponseT + "CorrectPartial", es.getCorrectPartial()); docFm.put(featurePrefixResponseT + "IncorrectStrict", es.getIncorrectStrict()); docFm.put(featurePrefixResponseT + "IncorrectPartial", es.getIncorrectPartial()); docFm.put(featurePrefixResponseT + "TrueMissingStrict", es.getTrueMissingStrict()); docFm.put(featurePrefixResponseT + "TrueMissingLenient", es.getTrueMissingLenient()); docFm.put(featurePrefixResponseT + "TrueSpuriousStrict", es.getTrueSpuriousStrict()); docFm.put(featurePrefixResponseT + "TrueSpuriousLenient", es.getTrueSpuriousLenient()); docFm.put(featurePrefixResponseT + "Targets", es.getTargets()); docFm.put(featurePrefixResponseT + "Responses", es.getResponses()); } */ } /// HELPER METHODS /** * Return a new set with all the NIL annotations removed. * @param set */ private AnnotationSet removeNilAnns(AnnotationSet set) { String nilStr = ""; if(getNilValue() != null) { nilStr = getNilValue(); } // NOTE: this method only gets invoked if feature names is non-null and contains at least // one element (does not make sense to invoke it otherwise!) String idFeature = getFeatureNames().get(0); Set<Annotation> nils = new HashSet<Annotation>(); for (Annotation ann : set) { Object val = ann.getFeatures().get(idFeature); String valStr = val == null ? "" : val.toString(); if (valStr.equals(nilStr)) { nils.add(ann); } } AnnotationSet newset = new AnnotationSetImpl(set); newset.removeAll(nils); return newset; } // This needs to run as part of the first execute, since at the moment, the parametrization // does not work correctly with the controller callbacks. @Override protected void initializeForRunning() { //System.out.println("DEBUG: reinitializing"); super.initializeForRunning(); //System.out.println("DEBUG: running tagging4lists initialize"); expandedEdgeName = getStringOrElse(getExpandedEdgeFeatureName(),""); expandedScoreFeatureName = getStringOrElse(getExpandedScoreFeatureName(),""); if(getExpandedListType() == null || getExpandedListType().isEmpty()) { throw new GateRuntimeException("List annotation type is not specified or empty!"); } if(getExpandedElementType() == null || getExpandedElementType().isEmpty()) { throw new GateRuntimeException("Element annotation type is not specified or empty!"); } if(getExpandedKeyType() == null || getExpandedKeyType().isEmpty()) { throw new GateRuntimeException("Key annotation type is not specified or empty!"); } if(getFeatureNames() != null) { for(String t : getFeatureNames()) { if(t == null || t.isEmpty()) { throw new GateRuntimeException("List of feature names to use contains a null or empty type name!"); } } } // If the featureNames list is null, this has the special meaning that the features in // the key/target annotation should be used. In that case the featureNameSet will also // be left null. Otherwise the list will get converted to a set. // Convert the feature list into a set if(featureNames != null) { if(0 == featureNames.size()) { throw new GateRuntimeException("Need at least one feature for list evaluation"); } for(String t : getFeatureNames()) { if(t == null || t.isEmpty()) { throw new GateRuntimeException("List of feature names to use contains a null or empty type name!"); } } Set<String> featureNameSet = new HashSet<String>(); featureNameSet.addAll(featureNames); // check if we have duplicate entries in the featureNames if(featureNameSet.size() != featureNames.size()) { throw new GateRuntimeException("Duplicate feature in the feature name list"); } } else { throw new GateRuntimeException("Need at least one feature for list evaluation"); } List<String> types = new ArrayList<String>(); types.add(getExpandedKeyType()+"="+getExpandedListType()); annotationTypeSpecs = new AnnotationTypeSpecs(types); types = new ArrayList<String>(); types.add(getExpandedKeyType()+"="+getExpandedElementType()); annotationTypeSpecs4Best = new AnnotationTypeSpecs(types); // Establish the default containment type if it was not specified. if(getContainmentType() == null) { containmentType = ContainmentType.OVERLAPPING; } if(getNilTreatment() == null) { nilTreatment = NilTreatment.NO_NILS; } if(!(getExpandedReferenceASName() == null || getExpandedReferenceASName().isEmpty())) { System.err.println("WARNING: Reference set cannot be used with List evaluation (yet?), ignored!"); expandedReferenceSetName = null; referenceASName = null; } featurePrefixResponse = initialFeaturePrefixResponse + getExpandedEvaluationId() + "." + getResponseASName() + "." ; featurePrefixReference = initialFeaturePrefixReference + getExpandedEvaluationId() + "." + getReferenceASName() + "."; if(!expandedOutputASPrefix.isEmpty()) { outputASResName = expandedOutputASPrefix+"_MaxRecall"; } else { outputASResName = ""; } mainTsvPrintStream = getOutputStream("maxrec"); if(mainTsvPrintStream != null) { mainTsvPrintStream.print("evaluationId"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("evaluationType"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("docName"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("setName"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("annotationType"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("thresholdType"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("threshold"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("maxRecallStrict"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("maxRecallLenient"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("maxRecallListStrict"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("maxRecallListLenient"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("targets"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("targets"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("targetsWithList"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("correctStrict"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("correctLenient"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("lists"); mainTsvPrintStream.print("\t"); mainTsvPrintStream.print("listsWithTarget"); mainTsvPrintStream.print("\t"); } } public void finishRunning() { outputDefaultResults(); if(mainTsvPrintStream != null) { mainTsvPrintStream.close(); } } protected String outputTsvLine( String evalType, String docName, AnnotationTypeSpec typeSpec, String setName, int rank, // the rank or -1 for overall counts/measures int targets, int targetsWithList, int correctStrict, int correctLenient, int lists, int listsWithTarget ) { StringBuilder sb = new StringBuilder(); sb.append(expandedEvaluationId); sb.append("\t"); sb.append(evalType); sb.append("\t"); if(docName == null) { sb.append("[doc:all:micro]"); } else { sb.append(docName); } sb.append("\t"); if(setName == null || setName.isEmpty()) { sb.append(expandedResponseSetName); } else { sb.append(setName); } sb.append("\t"); if(typeSpec == null) { sb.append("[type:all:micro]"); } else { sb.append(typeSpec); } sb.append("\t"); sb.append("rank"); sb.append("\t"); // the threshold type is always rank! sb.append(rank); sb.append("\t"); // -1 for overall // the stuff that is specific to max recall sb.append(recall(targets,correctStrict)); sb.append("\t"); sb.append(recall(targets,correctLenient)); sb.append("\t"); sb.append(recall(targetsWithList,correctStrict)); sb.append("\t"); sb.append(recall(targetsWithList,correctLenient)); sb.append("\t"); sb.append(targets); sb.append("\t"); sb.append(targetsWithList); sb.append("\t"); sb.append(correctStrict); sb.append("\t"); sb.append(correctLenient); sb.append("\t"); sb.append(lists); sb.append("\t"); sb.append(listsWithTarget); sb.append("\t"); return sb.toString(); } public void outputDefaultResults() { AnnotationTypeSpec typeSpecNormal = annotationTypeSpecs.getSpecs().get(0); AnnotationTypeSpec typeSpecList = annotationTypeSpecs.getSpecs().get(0); System.out.println(evaluationId+" MaxRecall Recall Strict: "+r4(recall(nTargets,nCorrectStrict))); System.out.println(evaluationId+" MaxRecall Recall Lenient: "+r4(recall(nTargets,nCorrectLenient))); System.out.println(evaluationId+" MaxRecall Recall In Responses Strict: "+r4(recall(nTargetsWithList,nCorrectStrict))); System.out.println(evaluationId+" MaxRecall Recall In Responses Lenient: "+r4(recall(nTargetsWithList,nCorrectLenient))); System.out.println(evaluationId+" Targets: "+nTargets); System.out.println(evaluationId+" Targets without responses: "+(nTargets-nTargetsWithList)); System.out.println(evaluationId+" Targets with strict match: "+nCorrectStrict); System.out.println(evaluationId+" Targets with only partial match: "+(nCorrectLenient-nCorrectStrict)); System.out.println(evaluationId+" Targets with responses: "+nTargetsWithList); System.out.println(evaluationId+" Lists: "+nResponseLists); System.out.println(evaluationId+" Lists with target: "+nResponseListsWithTarget); System.out.println(evaluationId+" Spurious lists (no target): "+(nResponseLists-nResponseListsWithTarget)); // Now also output the by rank recall strict and recall lenient for lists and overall List<Double> maxrecS = getMaxRecallStrictByRank(); for(int i = 0; i<maxrecS.size(); i++) { System.out.println(evaluationId+" MaxRecall strict at rank: "+i+" "+r4(maxrecS.get(i))); } List<Double> maxrecL = getMaxRecallLenientByRank(); for(int i = 0; i<maxrecL.size(); i++) { System.out.println(evaluationId+" MaxRecall lenient at rank: "+i+" "+r4(maxrecL.get(i))); } List<Double> maxrecSL = getMaxRecallStrict4ListByRank(); for(int i = 0; i<maxrecSL.size(); i++) { System.out.println(evaluationId+" MaxRecall4List strict at rank: "+i+" "+r4(maxrecSL.get(i))); } List<Double> maxrecLL = getMaxRecallLenient4ListByRank(); for(int i = 0; i<maxrecLL.size(); i++) { System.out.println(evaluationId+" MaxRecall4List lenient at rank: "+i+" "+r4(maxrecLL.get(i))); } if(mainTsvPrintStream != null) { // The lines for each possible rank .... int n = Math.max(nCorrectLenientByRank.size(),nCorrectStrictByRank.size()); int nSumCS = 0; int nSumCL = 0; for(int i = 0; i<n; i++) { if(i<nCorrectStrictByRank.size()) { nSumCS += nCorrectStrictByRank.get(i); } if(i<nCorrectLenientByRank.size()) { nSumCL += nCorrectLenientByRank.get(i); } String line = outputTsvLine( "list-maxrecall", null, typeSpecList, expandedResponseSetName, i, nTargets, nTargetsWithList, nSumCS, nSumCL, nResponseLists, nResponseListsWithTarget); mainTsvPrintStream.println(line); } // Now one line for overall String line = outputTsvLine( "list-maxrecall", null, typeSpecList, expandedResponseSetName, -1, nTargets, nTargetsWithList, nCorrectStrict, nCorrectLenient, nResponseLists, nResponseListsWithTarget); mainTsvPrintStream.println(line); } } /// CONTROLLER AWARE PR methods @Override public void controllerExecutionStarted(Controller cntrlr) throws ExecutionException { needInitialization = true; } @Override public void controllerExecutionFinished(Controller cntrlr) throws ExecutionException { // only do anything at all if we had actually been executed once. The callback gets also // invoked if the PR was disabled, so we have to check ... // needInitialization is set in the started callback and reset in execute, so if it is still // on, we never were in execute. if(!needInitialization) { finishRunning(); needInitialization = true; } } @Override public void controllerExecutionAborted(Controller cntrlr, Throwable thrwbl) throws ExecutionException { if(!needInitialization) { System.err.println("Processing was aborted: "+thrwbl.getMessage()); thrwbl.printStackTrace(System.err); System.err.println("Here are the summary stats for what was processed: "); finishRunning(); needInitialization = true; } } /* @Override public Resource duplicate(Factory.DuplicationContext dc) throws ResourceInstantiationException { throw new UnsupportedOperationException("At the moment, this PR may not be duplicated and must be run single-threaded"); // TODO: duplicate such that all duplicates get a flag set which indicates that they are // duplicates, and only the original has the flag not set. // Also, use a shared object to give all PRs access to everyone elses's statistics objects. // Also, use a shared obejcts to give all PRs access to a singleton object for writing to // the output files. // Finally, implement the controllerExecutionFinished() method such that only the original // will do the actual summarization: it will access all stats objects from all other PRs and // summarize them and } */ }
package gov.nih.nci.cananolab.ui.core; import gov.nih.nci.cananolab.domain.particle.NanoparticleSample; import gov.nih.nci.cananolab.dto.common.LabFileBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.dto.particle.ParticleDataLinkBean; import gov.nih.nci.cananolab.dto.particle.composition.FunctionalizingEntityBean; import gov.nih.nci.cananolab.dto.particle.composition.NanoparticleEntityBean; import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException; import gov.nih.nci.cananolab.service.common.FileService; import gov.nih.nci.cananolab.service.particle.NanoparticleCompositionService; import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService; import gov.nih.nci.cananolab.ui.particle.InitNanoparticleSetup; import gov.nih.nci.cananolab.ui.report.InitReportSetup; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import gov.nih.nci.cananolab.util.ClassUtils; import gov.nih.nci.cananolab.util.PropertyReader; import java.io.File; import java.io.FileInputStream; import java.util.Map; import java.util.SortedSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * Base action for all annotation actions * * @author pansu * */ public abstract class BaseAnnotationAction extends AbstractDispatchAction { public ParticleBean setupParticle(DynaValidatorForm theForm, HttpServletRequest request) throws Exception { String particleId = request.getParameter("particleId"); if (particleId == null) { particleId = theForm.getString("particleId"); } HttpSession session = request.getSession(); UserBean user = (UserBean) session.getAttribute("user"); NanoparticleSampleService service = new NanoparticleSampleService(); ParticleBean particleBean = service .findNanoparticleSampleById(particleId); request.setAttribute("theParticle", particleBean); InitNanoparticleSetup.getInstance().getOtherParticleNames( request, particleBean.getDomainParticleSample().getName(), particleBean.getDomainParticleSample().getSource() .getOrganizationName(), user); return particleBean; } public boolean loginRequired() { return false; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } public Map<String, SortedSet<ParticleDataLinkBean>> setupDataTree( DynaValidatorForm theForm, HttpServletRequest request) throws Exception { request.setAttribute("updateDataTree", "true"); String particleId = request.getParameter("particleId"); if (particleId == null) { particleId = theForm.getString("particleId"); } InitReportSetup.getInstance().getReportCategories(request); return InitNanoparticleSetup.getInstance().getDataTree(particleId, request); } public ActionForward setupDeleteAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String submitType = request.getParameter("submitType"); DynaValidatorForm theForm = (DynaValidatorForm) form; Map<String, SortedSet<ParticleDataLinkBean>> dataTree = setupDataTree( theForm, request); SortedSet<ParticleDataLinkBean> dataToDelete = dataTree.get(submitType); request.getSession().setAttribute("actionName", dataToDelete.first().getDataLink()); request.getSession().setAttribute("dataToDelete", dataToDelete); return mapping.findForward("annotationDeleteView"); } // check for cases where delete can't happen protected boolean checkDelete(HttpServletRequest request, ActionMessages msgs, String id) throws Exception { return true; } public ActionForward deleteAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String submitType = request.getParameter("submitType"); String className = InitSetup.getInstance().getObjectName(submitType, request.getSession().getServletContext()); String fullClassName = ClassUtils.getFullClass(className) .getCanonicalName(); String[] dataIds = (String[]) theForm.get("idsToDelete"); NanoparticleSampleService sampleService = new NanoparticleSampleService(); ActionMessages msgs = new ActionMessages(); for (String id : dataIds) { if (!checkDelete(request, msgs, id)) { return mapping.findForward("annotationDeleteView"); } sampleService.deleteAnnotationById(fullClassName, new Long(id)); } setupDataTree(theForm, request); ActionMessage msg = new ActionMessage("message.deleteAnnotations", submitType); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); return mapping.findForward("success"); } /** * Download action to handle file downloading and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService service = new FileService(); LabFileBean fileBean = service.findFile(fileId, user); if (fileBean.getDomainFile().getUriExternal()) { response.sendRedirect(fileBean.getDomainFile().getUri()); return null; } String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getDomainFile().getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getDomainFile().getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("error.noFile"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); this.saveErrors(request, msgs); return mapping.findForward("fileMessage"); } return null; } protected NanoparticleSample[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { String[] otherParticles = (String[]) theForm.get("otherParticles"); if (otherParticles.length == 0) { return null; } NanoparticleSample[] particleSamples = new NanoparticleSample[otherParticles.length]; NanoparticleSampleService sampleService = new NanoparticleSampleService(); int i = 0; for (String other : otherParticles) { NanoparticleSample particleSample = sampleService .findNanoparticleSampleByName(other); particleSamples[i] = particleSample; i++; } // retrieve file contents // FileService fileService = new FileService(); // for (DerivedBioAssayDataBean file : entityBean.getFiles()) { // byte[] content = fileService.getFileContent(new Long(file.getId())); // file.setFileContent(content); // NanoparticleSampleService service = new NanoparticleSampleService(); // UserBean user = (UserBean) request.getSession().getAttribute("user"); // int i = 0; // for (String particleName : otherParticles) { // NanoparticleEntityBean newEntityBean = entityBean.copy(); // // overwrite particle // ParticleBean otherParticle = service.findNanoparticleSampleByName( // particleName, user); // newrBean.setParticle(otherParticle); // // reset view title // String timeStamp = StringUtils.convertDateToString(new Date(), // "MMddyyHHmmssSSS"); // String autoTitle = // CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX // + timeStamp; // newCharBean.setViewTitle(autoTitle); // List<DerivedBioAssayDataBean> dataList = newCharBean // .getDerivedBioAssayDataList(); // // replace particleName in path and uri with new particleName // for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { // String origUri = derivedBioAssayData.getUri(); // if (origUri != null) // derivedBioAssayData.setUri(origUri.replace(particle // .getSampleName(), particleName)); // charBeans[i] = newCharBean; return particleSamples; } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.util.*; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; /** * Dialog displaying all configurable User Preferences. * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class PreferenceDialog extends JDialog implements ActionListener { private JCheckBox associationBox = new JCheckBox(PropertyAccessor.getProperty("preference.view.association")), umlDescriptionBox = new JCheckBox(PropertyAccessor.getProperty("preference.uml.description")), evsAutoSearchBox = new JCheckBox(PropertyAccessor.getProperty("preference.auto.evs")), privateApiSearchBox = new JCheckBox(PropertyAccessor.getProperty("preference.private.api")), orderOfConceptsBox = new JCheckBox(PropertyAccessor.getProperty("preference.concept.order")), showInheritedAttributesBox = new JCheckBox(PropertyAccessor.getProperty("preference.inherited.attributes")), sortElementsBox = new JCheckBox(PropertyAccessor.getProperty("preference.sort.elements")), preTBox = new JCheckBox(PropertyAccessor.getProperty("preference.concept.validator.preT")), inheritedCDEMappingBox = new JCheckBox(PropertyAccessor.getProperty("preference.inherited.cde.warning")), showGMETagsBox = new JCheckBox(PropertyAccessor.getProperty("show.gme.tags")); private JButton apply = new JButton("Apply"); private JButton cancel = new JButton("Cancel"); private JButton ok = new JButton("OK"); private static final String APPLY = "Apply"; private static final String CANCEL = "Cancel"; private static final String OK = "OK"; public PreferenceDialog(JFrame owner) { super(owner, "Preferences"); JPanel southPanel = new JPanel(); southPanel.add(ok); southPanel.add(cancel); southPanel.add(apply); JPanel centerPanel = new JPanel(); centerPanel.add(associationBox); centerPanel.add(umlDescriptionBox); centerPanel.add(evsAutoSearchBox); centerPanel.add(privateApiSearchBox); centerPanel.add(orderOfConceptsBox); centerPanel.add(showInheritedAttributesBox); centerPanel.add(sortElementsBox); centerPanel.add(preTBox); // centerPanel.add(inheritedCDEMappingBox); // centerPanel.add(showGMETagsBox); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(centerPanel); this.getContentPane().add(southPanel,BorderLayout.SOUTH); this.setSize(300,350); apply.setActionCommand(APPLY); cancel.setActionCommand(CANCEL); ok.setActionCommand(OK); apply.addActionListener(this); cancel.addActionListener(this); ok.addActionListener(this); UserSelections selections = UserSelections.getInstance(); RunMode runMode = (RunMode)(selections.getProperty("MODE")); if(runMode.equals(RunMode.Curator)) { associationBox.setVisible(false); } } public void updatePreferences() { UserPreferences prefs = UserPreferences.getInstance(); associationBox.setSelected(prefs.getViewAssociationType().equalsIgnoreCase("true")); umlDescriptionBox.setSelected(!prefs.getUmlDescriptionOrder().equals("first")); orderOfConceptsBox.setSelected(prefs.getOrderOfConcepts().equalsIgnoreCase("first")); evsAutoSearchBox.setSelected(prefs.getEvsAutoSearch()); privateApiSearchBox.setSelected(prefs.isUsePrivateApi()); showInheritedAttributesBox.setSelected(prefs.getShowInheritedAttributes()); sortElementsBox.setSelected(prefs.getSortElements()); preTBox.setSelected(prefs.getPreTBox()); inheritedCDEMappingBox.setSelected(prefs.getBoolean("de.over.vd.mapping.warning")); showGMETagsBox.setSelected(prefs.getShowGMETags()); } public void actionPerformed(ActionEvent event) { JButton button = (JButton)event.getSource(); if(button.getActionCommand().equals(OK) || button.getActionCommand().equals(APPLY)) { UserPreferences prefs = UserPreferences.getInstance(); if(associationBox.isSelected()) prefs.setViewAssociationType("true"); else prefs.setViewAssociationType("false"); if(umlDescriptionBox.isSelected()) prefs.setUmlDescriptionOrder("last"); else prefs.setUmlDescriptionOrder("first"); if(orderOfConceptsBox.isSelected()) prefs.setOrderOfConcepts("first"); else prefs.setOrderOfConcepts("last"); prefs.setEvsAutoSeatch(evsAutoSearchBox.isSelected()); prefs.setUsePrivateApi(privateApiSearchBox.isSelected()); prefs.setShowInheritedAttributes(showInheritedAttributesBox.isSelected()); prefs.setSortElements(sortElementsBox.isSelected()); prefs.setPreTBox(preTBox.isSelected()); prefs.setBoolean("de.over.vd.mapping.warning", inheritedCDEMappingBox.isSelected()); prefs.setShowGMETags(showGMETagsBox.isSelected()); if(button.getActionCommand().equals(OK)) this.dispose(); } if(button.getActionCommand().equals(CANCEL)) this.dispose(); } }
package com.esotericsoftware.kryo; import java.lang.reflect.Constructor; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Currency; import java.util.Date; import java.util.EnumSet; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; import org.objenesis.instantiator.ObjectInstantiator; import org.objenesis.strategy.InstantiatorStrategy; import org.objenesis.strategy.SerializingInstantiatorStrategy; import org.objenesis.strategy.StdInstantiatorStrategy; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.serializers.CollectionSerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.BooleanArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.ByteArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.CharArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.DoubleArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.FloatArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.IntArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.LongArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.ObjectArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.ShortArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.StringArraySerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.BigDecimalSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.BigIntegerSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.BooleanSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.ByteSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CalendarSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CharSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.ClassSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsEmptyListSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsEmptyMapSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsEmptySetSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsSingletonListSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsSingletonMapSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsSingletonSetSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.CurrencySerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.DateSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.DoubleSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.EnumSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.EnumSetSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.FloatSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.IntSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.KryoSerializableSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.LongSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.ShortSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.StringBufferSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.StringBuilderSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.StringSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.TimeZoneSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.TreeMapSerializer; import com.esotericsoftware.kryo.serializers.FieldSerializer; import com.esotericsoftware.kryo.serializers.MapSerializer; import com.esotericsoftware.kryo.util.DefaultClassResolver; import com.esotericsoftware.kryo.util.DefaultStreamFactory; import com.esotericsoftware.kryo.util.FastestStreamFactory; import com.esotericsoftware.kryo.util.IdentityMap; import com.esotericsoftware.kryo.util.IntArray; import com.esotericsoftware.kryo.util.MapReferenceResolver; import com.esotericsoftware.kryo.util.ObjectMap; import com.esotericsoftware.kryo.util.Util; import com.esotericsoftware.reflectasm.ConstructorAccess; import static com.esotericsoftware.kryo.util.Util.*; import static com.esotericsoftware.minlog.Log.*; /** Maps classes to serializers so object graphs can be serialized automatically. * @author Nathan Sweet <misc@n4te.com> */ public class Kryo { static public final byte NULL = 0; static public final byte NOT_NULL = 1; static private final int REF = -1; static private final int NO_REF = -2; private Class<? extends Serializer> defaultSerializer = FieldSerializer.class; private final ArrayList<DefaultSerializerEntry> defaultSerializers = new ArrayList(32); private final int lowPriorityDefaultSerializerCount; private final ClassResolver classResolver; private int nextRegisterID; private ClassLoader classLoader = getClass().getClassLoader(); private InstantiatorStrategy strategy; private boolean registrationRequired; private int depth, maxDepth = Integer.MAX_VALUE; private boolean autoReset = true; private volatile Thread thread; private ObjectMap context, graphContext; private ReferenceResolver referenceResolver; private final IntArray readReferenceIds = new IntArray(0); private boolean references; private Object readObject; private int copyDepth; private boolean copyShallow; private IdentityMap originalToCopy; private Object needsCopyReference; private Generics genericsScope; /** Tells if ASM-based backend should be used by new serializer instances created using this Kryo instance. */ private boolean asmEnabled = false; private StreamFactory streamFactory; /** Creates a new Kryo with a {@link DefaultClassResolver} and a {@link MapReferenceResolver}. */ public Kryo () { this(new DefaultClassResolver(), new MapReferenceResolver(), new DefaultStreamFactory()); } /** Creates a new Kryo with a {@link DefaultClassResolver}. * @param referenceResolver May be null to disable references. */ public Kryo (ReferenceResolver referenceResolver) { this(new DefaultClassResolver(), referenceResolver, new DefaultStreamFactory()); } /** @param referenceResolver May be null to disable references. */ public Kryo (ClassResolver classResolver, ReferenceResolver referenceResolver, StreamFactory streamFactory) { if (classResolver == null) throw new IllegalArgumentException("classResolver cannot be null."); this.classResolver = classResolver; classResolver.setKryo(this); this.streamFactory = streamFactory; streamFactory.setKryo(this); this.referenceResolver = referenceResolver; if (referenceResolver != null) { referenceResolver.setKryo(this); references = true; } addDefaultSerializer(byte[].class, ByteArraySerializer.class); addDefaultSerializer(char[].class, CharArraySerializer.class); addDefaultSerializer(short[].class, ShortArraySerializer.class); addDefaultSerializer(int[].class, IntArraySerializer.class); addDefaultSerializer(long[].class, LongArraySerializer.class); addDefaultSerializer(float[].class, FloatArraySerializer.class); addDefaultSerializer(double[].class, DoubleArraySerializer.class); addDefaultSerializer(boolean[].class, BooleanArraySerializer.class); addDefaultSerializer(String[].class, StringArraySerializer.class); addDefaultSerializer(Object[].class, ObjectArraySerializer.class); addDefaultSerializer(BigInteger.class, BigIntegerSerializer.class); addDefaultSerializer(BigDecimal.class, BigDecimalSerializer.class); addDefaultSerializer(Class.class, ClassSerializer.class); addDefaultSerializer(Date.class, DateSerializer.class); addDefaultSerializer(Enum.class, EnumSerializer.class); addDefaultSerializer(EnumSet.class, EnumSetSerializer.class); addDefaultSerializer(Currency.class, CurrencySerializer.class); addDefaultSerializer(StringBuffer.class, StringBufferSerializer.class); addDefaultSerializer(StringBuilder.class, StringBuilderSerializer.class); addDefaultSerializer(Collections.EMPTY_LIST.getClass(), CollectionsEmptyListSerializer.class); addDefaultSerializer(Collections.EMPTY_MAP.getClass(), CollectionsEmptyMapSerializer.class); addDefaultSerializer(Collections.EMPTY_SET.getClass(), CollectionsEmptySetSerializer.class); addDefaultSerializer(Collections.singletonList(null).getClass(), CollectionsSingletonListSerializer.class); addDefaultSerializer(Collections.singletonMap(null, null).getClass(), CollectionsSingletonMapSerializer.class); addDefaultSerializer(Collections.singleton(null).getClass(), CollectionsSingletonSetSerializer.class); addDefaultSerializer(Collection.class, CollectionSerializer.class); addDefaultSerializer(TreeMap.class, TreeMapSerializer.class); addDefaultSerializer(Map.class, MapSerializer.class); addDefaultSerializer(KryoSerializable.class, KryoSerializableSerializer.class); addDefaultSerializer(TimeZone.class, TimeZoneSerializer.class); addDefaultSerializer(Calendar.class, CalendarSerializer.class); lowPriorityDefaultSerializerCount = defaultSerializers.size(); // Primitives and string. Primitive wrappers automatically use the same registration as primitives. register(int.class, new IntSerializer()); register(String.class, new StringSerializer()); register(float.class, new FloatSerializer()); register(boolean.class, new BooleanSerializer()); register(byte.class, new ByteSerializer()); register(char.class, new CharSerializer()); register(short.class, new ShortSerializer()); register(long.class, new LongSerializer()); register(double.class, new DoubleSerializer()); } /** Sets the serailzer to use when no {@link #addDefaultSerializer(Class, Class) default serializers} match an object's type. * Default is {@link FieldSerializer}. * @see #newDefaultSerializer(Class) */ public void setDefaultSerializer (Class<? extends Serializer> serializer) { if (serializer == null) throw new IllegalArgumentException("serializer cannot be null."); defaultSerializer = serializer; } /** Instances of the specified class will use the specified serializer. * @see #setDefaultSerializer(Class) */ public void addDefaultSerializer (Class type, Serializer serializer) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (serializer == null) throw new IllegalArgumentException("serializer cannot be null."); DefaultSerializerEntry entry = new DefaultSerializerEntry(); entry.type = type; entry.serializer = serializer; defaultSerializers.add(defaultSerializers.size() - lowPriorityDefaultSerializerCount, entry); } /** Instances of the specified class will use the specified serializer. Serializer instances are created as needed via * {@link #newSerializer(Class, Class)}. By default, the following classes have a default serializer set: * <p> * <table> * <tr> * <td>boolean</td> * <td>Boolean</td> * <td>byte</td> * <td>Byte</td> * <td>char</td> * <tr> * </tr> * <td>Character</td> * <td>short</td> * <td>Short</td> * <td>int</td> * <td>Integer</td> * <tr> * </tr> * <td>long</td> * <td>Long</td> * <td>float</td> * <td>Float</td> * <td>double</td> * <tr> * </tr> * <td>Double</td> * <td>String</td> * <td>byte[]</td> * <td>char[]</td> * <td>short[]</td> * <tr> * </tr> * <td>int[]</td> * <td>long[]</td> * <td>float[]</td> * <td>double[]</td> * <td>String[]</td> * <tr> * </tr> * <td>Object[]</td> * <td>Map</td> * <td>BigInteger</td> * <td>BigDecimal</td> * <td>KryoSerializable</td> * </tr> * <tr> * <td>Collection</td> * <td>Date</td> * <td>Collections.emptyList</td> * <td>Collections.singleton</td> * <td>Currency</td> * </tr> * <tr> * <td>StringBuilder</td> * <td>Enum</td> * <td>Collections.emptyMap</td> * <td>Collections.emptySet</td> * <td>Calendar</td> * </tr> * <tr> * <td>StringBuffer</td> * <td>Class</td> * <td>Collections.singletonList</td> * <td>Collections.singletonMap</td> * <td>TimeZone</td> * </tr> * <tr> * <td>TreeMap</td> * <td>EnumSet</td> * </tr> * </table> * <p> * Note that the order default serializers are added is important for a class that may match multiple types. The above default * serializers always have a lower priority than subsequent default serializers that are added. */ public void addDefaultSerializer (Class type, Class<? extends Serializer> serializerClass) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (serializerClass == null) throw new IllegalArgumentException("serializerClass cannot be null."); DefaultSerializerEntry entry = new DefaultSerializerEntry(); entry.type = type; entry.serializerClass = serializerClass; defaultSerializers.add(defaultSerializers.size() - lowPriorityDefaultSerializerCount, entry); } /** Returns the best matching serializer for a class. This method can be overridden to implement custom logic to choose a * serializer. */ public Serializer getDefaultSerializer (Class type) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (type.isAnnotationPresent(DefaultSerializer.class)) return newSerializer(((DefaultSerializer)type.getAnnotation(DefaultSerializer.class)).value(), type); for (int i = 0, n = defaultSerializers.size(); i < n; i++) { DefaultSerializerEntry entry = defaultSerializers.get(i); if (entry.type.isAssignableFrom(type)) { if (entry.serializer != null) return entry.serializer; return newSerializer(entry.serializerClass, type); } } return newDefaultSerializer(type); } /** Called by {@link #getDefaultSerializer(Class)} when no default serializers matched the type. Subclasses can override this * method to customize behavior. The default implementation calls {@link #newSerializer(Class, Class)} using the * {@link #setDefaultSerializer(Class) default serializer}. */ protected Serializer newDefaultSerializer (Class type) { return newSerializer(defaultSerializer, type); } /** Creates a new instance of the specified serializer for serializing the specified class. Serializers must have a zero * argument constructor or one that takes (Kryo), (Class), or (Kryo, Class). */ public Serializer newSerializer (Class<? extends Serializer> serializerClass, Class type) { try { try { return serializerClass.getConstructor(Kryo.class, Class.class).newInstance(this, type); } catch (NoSuchMethodException ex1) { try { return serializerClass.getConstructor(Kryo.class).newInstance(this); } catch (NoSuchMethodException ex2) { try { return serializerClass.getConstructor(Class.class).newInstance(type); } catch (NoSuchMethodException ex3) { return serializerClass.newInstance(); } } } } catch (Exception ex) { throw new IllegalArgumentException("Unable to create serializer \"" + serializerClass.getName() + "\" for class: " + className(type), ex); } } /** Registers the class using the lowest, next available integer ID and the {@link Kryo#getDefaultSerializer(Class) default * serializer}. If the class is already registered, the existing entry is updated with the new serializer. Registering a * primitive also affects the corresponding primitive wrapper. * <p> * Because the ID assigned is affected by the IDs registered before it, the order classes are registered is important when * using this method. The order must be the same at deserialization as it was for serialization. */ public Registration register (Class type) { Registration registration = classResolver.getRegistration(type); if (registration != null) return registration; return register(type, getDefaultSerializer(type)); } /** Registers the class using the specified ID and the {@link Kryo#getDefaultSerializer(Class) default serializer}. If the ID is * already in use by the same type, the old entry is overwritten. If the ID is already in use by a different type, a * {@link KryoException} is thrown. Registering a primitive also affects the corresponding primitive wrapper. * <p> * IDs must be the same at deserialization as they were for serialization. * @param id Must be >= 0. Smaller IDs are serialized more efficiently. */ public Registration register (Class type, int id) { Registration registration = classResolver.getRegistration(type); if (registration != null) return registration; return register(type, getDefaultSerializer(type), id); } /** Registers the class using the lowest, next available integer ID and the specified serializer. If the class is already * registered, the existing entry is updated with the new serializer. Registering a primitive also affects the corresponding * primitive wrapper. * <p> * Because the ID assigned is affected by the IDs registered before it, the order classes are registered is important when * using this method. The order must be the same at deserialization as it was for serialization. */ public Registration register (Class type, Serializer serializer) { Registration registration = classResolver.getRegistration(type); if (registration != null) { registration.setSerializer(serializer); return registration; } return classResolver.register(new Registration(type, serializer, getNextRegistrationId())); } /** Registers the class using the specified ID and serializer. If the ID is already in use by the same type, the old entry is * overwritten. If the ID is already in use by a different type, a {@link KryoException} is thrown. Registering a primitive * also affects the corresponding primitive wrapper. * <p> * IDs must be the same at deserialization as they were for serialization. * @param id Must be >= 0. Smaller IDs are serialized more efficiently. */ public Registration register (Class type, Serializer serializer, int id) { if (id < 0) throw new IllegalArgumentException("id must be >= 0: " + id); return register(new Registration(type, serializer, id)); } /** Stores the specified registration. If the ID is already in use by the same type, the old entry is overwritten. If the ID is * already in use by a different type, a {@link KryoException} is thrown. Registering a primitive also affects the * corresponding primitive wrapper. * <p> * IDs must be the same at deserialization as they were for serialization. * <p> * Registration can be suclassed to efficiently store per type information, accessible in serializers via * {@link Kryo#getRegistration(Class)}. */ public Registration register (Registration registration) { int id = registration.getId(); if (id < 0) throw new IllegalArgumentException("id must be > 0: " + id); Registration existing = getRegistration(registration.getId()); if (existing != null && existing.getType() != registration.getType()) { throw new KryoException("An existing registration with a different type already uses ID: " + registration.getId() + "\nExisting registration: " + existing + "\nUnable to set registration: " + registration); } return classResolver.register(registration); } /** Returns the lowest, next available integer ID. */ public int getNextRegistrationId () { while (nextRegisterID != -2) { if (classResolver.getRegistration(nextRegisterID) == null) return nextRegisterID; nextRegisterID++; } throw new KryoException("No registration IDs are available."); } public Registration getRegistration (Class type) { if (type == null) throw new IllegalArgumentException("type cannot be null."); Registration registration = classResolver.getRegistration(type); if (registration == null) { if (Proxy.isProxyClass(type)) { // If a Proxy class, treat it like an InvocationHandler because the concrete class for a proxy is generated. registration = getRegistration(InvocationHandler.class); } else if (!type.isEnum() && Enum.class.isAssignableFrom(type)) { // This handles an enum value that is an inner class. Eg: enum A {b{}}; registration = getRegistration(type.getEnclosingClass()); } else if (EnumSet.class.isAssignableFrom(type)) { registration = classResolver.getRegistration(EnumSet.class); } if (registration == null) { if (registrationRequired) { throw new IllegalArgumentException("Class is not registered: " + className(type) + "\nNote: To register this class use: kryo.register(" + className(type) + ".class);"); } registration = classResolver.registerImplicit(type); } } return registration; } /** @see ClassResolver#getRegistration(int) */ public Registration getRegistration (int classID) { return classResolver.getRegistration(classID); } /** Returns the serializer for the registration for the specified class. * @see #getRegistration(Class) * @see Registration#getSerializer() */ public Serializer getSerializer (Class type) { return getRegistration(type).getSerializer(); } /** Writes a class and returns its registration. * @param type May be null. * @return Will be null if type is null. * @see ClassResolver#writeClass(Output, Class) */ public Registration writeClass (Output output, Class type) { if (output == null) throw new IllegalArgumentException("output cannot be null."); try { return classResolver.writeClass(output, type); } finally { if (depth == 0 && autoReset) reset(); } } /** Writes an object using the registered serializer. */ public void writeObject (Output output, Object object) { if (output == null) throw new IllegalArgumentException("output cannot be null."); if (object == null) throw new IllegalArgumentException("object cannot be null."); beginObject(); try { if (references && writeReferenceOrNull(output, object, false)) return; if (TRACE || (DEBUG && depth == 1)) log("Write", object); getRegistration(object.getClass()).getSerializer().write(this, output, object); } finally { if (--depth == 0 && autoReset) reset(); } } /** Writes an object using the specified serializer. The registered serializer is ignored. */ public void writeObject (Output output, Object object, Serializer serializer) { if (output == null) throw new IllegalArgumentException("output cannot be null."); if (object == null) throw new IllegalArgumentException("object cannot be null."); if (serializer == null) throw new IllegalArgumentException("serializer cannot be null."); beginObject(); try { if (references && writeReferenceOrNull(output, object, false)) return; if (TRACE || (DEBUG && depth == 1)) log("Write", object); serializer.write(this, output, object); } finally { if (--depth == 0 && autoReset) reset(); } } /** Writes an object or null using the registered serializer for the specified type. * @param object May be null. */ public void writeObjectOrNull (Output output, Object object, Class type) { if (output == null) throw new IllegalArgumentException("output cannot be null."); beginObject(); try { Serializer serializer = getRegistration(type).getSerializer(); if (references) { if (writeReferenceOrNull(output, object, true)) return; } else if (!serializer.getAcceptsNull()) { if (object == null) { if (TRACE || (DEBUG && depth == 1)) log("Write", object); output.writeByte(NULL); return; } output.writeByte(NOT_NULL); } if (TRACE || (DEBUG && depth == 1)) log("Write", object); serializer.write(this, output, object); } finally { if (--depth == 0 && autoReset) reset(); } } /** Writes an object or null using the specified serializer. The registered serializer is ignored. * @param object May be null. */ public void writeObjectOrNull (Output output, Object object, Serializer serializer) { if (output == null) throw new IllegalArgumentException("output cannot be null."); if (serializer == null) throw new IllegalArgumentException("serializer cannot be null."); beginObject(); try { if (references) { if (writeReferenceOrNull(output, object, true)) return; } else if (!serializer.getAcceptsNull()) { if (object == null) { if (TRACE || (DEBUG && depth == 1)) log("Write", null); output.writeByte(NULL); return; } output.writeByte(NOT_NULL); } if (TRACE || (DEBUG && depth == 1)) log("Write", object); serializer.write(this, output, object); } finally { if (--depth == 0 && autoReset) reset(); } } /** Writes the class and object or null using the registered serializer. * @param object May be null. */ public void writeClassAndObject (Output output, Object object) { if (output == null) throw new IllegalArgumentException("output cannot be null."); beginObject(); try { if (object == null) { writeClass(output, null); return; } Registration registration = writeClass(output, object.getClass()); if (references && writeReferenceOrNull(output, object, false)) return; if (TRACE || (DEBUG && depth == 1)) log("Write", object); registration.getSerializer().write(this, output, object); } finally { if (--depth == 0 && autoReset) reset(); } } /** @param object May be null if mayBeNull is true. * @return true if no bytes need to be written for the object. */ boolean writeReferenceOrNull (Output output, Object object, boolean mayBeNull) { if (object == null) { if (TRACE || (DEBUG && depth == 1)) log("Write", null); output.writeVarInt(Kryo.NULL, true); return true; } if (!referenceResolver.useReferences(object.getClass())) { if (mayBeNull) output.writeVarInt(Kryo.NOT_NULL, true); return false; } // Determine if this object has already been seen in this object graph. int id = referenceResolver.getWrittenId(object); // If not the first time encountered, only write reference ID. if (id != -1) { if (DEBUG) debug("kryo", "Write object reference " + id + ": " + string(object)); output.writeVarInt(id + 2, true); // + 2 because 0 and 1 are used for NULL and NOT_NULL. return true; } // Otherwise write NOT_NULL and then the object bytes. id = referenceResolver.addWrittenObject(object); output.writeVarInt(NOT_NULL, true); if (TRACE) trace("kryo", "Write initial object reference " + id + ": " + string(object)); return false; } /** Reads a class and returns its registration. * @return May be null. * @see ClassResolver#readClass(Input) */ public Registration readClass (Input input) { if (input == null) throw new IllegalArgumentException("input cannot be null."); try { return classResolver.readClass(input); } finally { if (depth == 0 && autoReset) reset(); } } /** Reads an object using the registered serializer. */ public <T> T readObject (Input input, Class<T> type) { if (input == null) throw new IllegalArgumentException("input cannot be null."); if (type == null) throw new IllegalArgumentException("type cannot be null."); beginObject(); try { T object; if (references) { int stackSize = readReferenceOrNull(input, type, false); if (stackSize == REF) return (T)readObject; object = (T)getRegistration(type).getSerializer().read(this, input, type); if (stackSize == readReferenceIds.size) reference(object); } else object = (T)getRegistration(type).getSerializer().read(this, input, type); if (TRACE || (DEBUG && depth == 1)) log("Read", object); return object; } finally { if (--depth == 0 && autoReset) reset(); } } /** Reads an object using the specified serializer. The registered serializer is ignored. */ public <T> T readObject (Input input, Class<T> type, Serializer serializer) { if (input == null) throw new IllegalArgumentException("input cannot be null."); if (type == null) throw new IllegalArgumentException("type cannot be null."); if (serializer == null) throw new IllegalArgumentException("serializer cannot be null."); beginObject(); try { T object; if (references) { int stackSize = readReferenceOrNull(input, type, false); if (stackSize == REF) return (T)readObject; object = (T)serializer.read(this, input, type); if (stackSize == readReferenceIds.size) reference(object); } else object = (T)serializer.read(this, input, type); if (TRACE || (DEBUG && depth == 1)) log("Read", object); return object; } finally { if (--depth == 0 && autoReset) reset(); } } /** Reads an object or null using the registered serializer. * @return May be null. */ public <T> T readObjectOrNull (Input input, Class<T> type) { if (input == null) throw new IllegalArgumentException("input cannot be null."); if (type == null) throw new IllegalArgumentException("type cannot be null."); beginObject(); try { T object; if (references) { int stackSize = readReferenceOrNull(input, type, true); if (stackSize == REF) return (T)readObject; object = (T)getRegistration(type).getSerializer().read(this, input, type); if (stackSize == readReferenceIds.size) reference(object); } else { Serializer serializer = getRegistration(type).getSerializer(); if (!serializer.getAcceptsNull() && input.readByte() == NULL) { if (TRACE || (DEBUG && depth == 1)) log("Read", null); return null; } object = (T)serializer.read(this, input, type); } if (TRACE || (DEBUG && depth == 1)) log("Read", object); return object; } finally { if (--depth == 0 && autoReset) reset(); } } /** Reads an object or null using the specified serializer. The registered serializer is ignored. * @return May be null. */ public <T> T readObjectOrNull (Input input, Class<T> type, Serializer serializer) { if (input == null) throw new IllegalArgumentException("input cannot be null."); if (type == null) throw new IllegalArgumentException("type cannot be null."); if (serializer == null) throw new IllegalArgumentException("serializer cannot be null."); beginObject(); try { T object; if (references) { int stackSize = readReferenceOrNull(input, type, true); if (stackSize == REF) return (T)readObject; object = (T)serializer.read(this, input, type); if (stackSize == readReferenceIds.size) reference(object); } else { if (!serializer.getAcceptsNull() && input.readByte() == NULL) { if (TRACE || (DEBUG && depth == 1)) log("Read", null); return null; } object = (T)serializer.read(this, input, type); } if (TRACE || (DEBUG && depth == 1)) log("Read", object); return object; } finally { if (--depth == 0 && autoReset) reset(); } } /** Reads the class and object or null using the registered serializer. * @return May be null. */ public Object readClassAndObject (Input input) { if (input == null) throw new IllegalArgumentException("input cannot be null."); beginObject(); try { Registration registration = readClass(input); if (registration == null) return null; Class type = registration.getType(); Object object; if (references) { int stackSize = readReferenceOrNull(input, type, false); if (stackSize == REF) return readObject; object = registration.getSerializer().read(this, input, type); if (stackSize == readReferenceIds.size) reference(object); } else object = registration.getSerializer().read(this, input, type); if (TRACE || (DEBUG && depth == 1)) log("Read", object); return object; } finally { if (--depth == 0 && autoReset) reset(); } } /** Returns {@link #REF} if a reference to a previously read object was read, which is stored in {@link #readObject}. Returns a * stack size (> 0) if a reference ID has been put on the stack. */ int readReferenceOrNull (Input input, Class type, boolean mayBeNull) { if (type.isPrimitive()) type = getWrapperClass(type); boolean referencesSupported = referenceResolver.useReferences(type); int id; if (mayBeNull) { id = input.readVarInt(true); if (id == Kryo.NULL) { if (TRACE || (DEBUG && depth == 1)) log("Read", null); readObject = null; return REF; } if (!referencesSupported) { readReferenceIds.add(NO_REF); return readReferenceIds.size; } } else { if (!referencesSupported) { readReferenceIds.add(NO_REF); return readReferenceIds.size; } id = input.readVarInt(true); } if (id == NOT_NULL) { // First time object has been encountered. id = referenceResolver.nextReadId(type); if (TRACE) trace("kryo", "Read initial object reference " + id + ": " + className(type)); readReferenceIds.add(id); return readReferenceIds.size; } // The id is an object reference. id -= 2; // - 2 because 0 and 1 are used for NULL and NOT_NULL. readObject = referenceResolver.getReadObject(type, id); if (DEBUG) debug("kryo", "Read object reference " + id + ": " + string(readObject)); return REF; } /** Called by {@link Serializer#read(Kryo, Input, Class)} and {@link Serializer#copy(Kryo, Object)} before Kryo can be used to * deserialize or copy child objects. Calling this method is unnecessary if Kryo is not used to deserialize or copy child * objects. * @param object May be null, unless calling this method from {@link Serializer#copy(Kryo, Object)}. */ public void reference (Object object) { if (copyDepth > 0) { if (needsCopyReference != null) { if (object == null) throw new IllegalArgumentException("object cannot be null."); originalToCopy.put(needsCopyReference, object); needsCopyReference = null; } } else if (references && object != null) { int id = readReferenceIds.pop(); if (id != NO_REF) referenceResolver.setReadObject(id, object); } } /** Resets unregistered class names, references to previously serialized or deserialized objects, and the * {@link #getGraphContext() graph context}. If {@link #setAutoReset(boolean) auto reset} is true, this method is called * automatically when an object graph has been completely serialized or deserialized. If overridden, the super method must be * called. */ public void reset () { depth = 0; if (graphContext != null) graphContext.clear(); classResolver.reset(); if (references) { referenceResolver.reset(); readObject = null; } copyDepth = 0; if (originalToCopy != null) originalToCopy.clear(2048); if (TRACE) trace("kryo", "Object graph complete."); } /** Returns a deep copy of the object. Serializers for the classes involved must support {@link Serializer#copy(Kryo, Object)}. * @param object May be null. */ public <T> T copy (T object) { if (object == null) return null; if (copyShallow) return object; copyDepth++; try { if (originalToCopy == null) originalToCopy = new IdentityMap(); Object existingCopy = originalToCopy.get(object); if (existingCopy != null) return (T)existingCopy; needsCopyReference = object; Object copy; if (object instanceof KryoCopyable) copy = ((KryoCopyable)object).copy(this); else copy = getSerializer(object.getClass()).copy(this, object); if (needsCopyReference != null) reference(copy); if (TRACE || (DEBUG && copyDepth == 1)) log("Copy", copy); return (T)copy; } finally { if (--copyDepth == 0) reset(); } } /** Returns a deep copy of the object using the specified serializer. Serializers for the classes involved must support * {@link Serializer#copy(Kryo, Object)}. * @param object May be null. */ public <T> T copy (T object, Serializer serializer) { if (object == null) return null; if (copyShallow) return object; copyDepth++; try { if (originalToCopy == null) originalToCopy = new IdentityMap(); Object existingCopy = originalToCopy.get(object); if (existingCopy != null) return (T)existingCopy; needsCopyReference = object; Object copy; if (object instanceof KryoCopyable) copy = ((KryoCopyable)object).copy(this); else copy = serializer.copy(this, object); if (needsCopyReference != null) reference(copy); if (TRACE || (DEBUG && copyDepth == 1)) log("Copy", copy); return (T)copy; } finally { if (--copyDepth == 0) reset(); } } /** Returns a shallow copy of the object. Serializers for the classes involved must support * {@link Serializer#copy(Kryo, Object)}. * @param object May be null. */ public <T> T copyShallow (T object) { if (object == null) return null; copyDepth++; copyShallow = true; try { if (originalToCopy == null) originalToCopy = new IdentityMap(); Object existingCopy = originalToCopy.get(object); if (existingCopy != null) return (T)existingCopy; needsCopyReference = object; Object copy; if (object instanceof KryoCopyable) copy = ((KryoCopyable)object).copy(this); else copy = getSerializer(object.getClass()).copy(this, object); if (needsCopyReference != null) reference(copy); if (TRACE || (DEBUG && copyDepth == 1)) log("Shallow copy", copy); return (T)copy; } finally { copyShallow = false; if (--copyDepth == 0) reset(); } } /** Returns a shallow copy of the object using the specified serializer. Serializers for the classes involved must support * {@link Serializer#copy(Kryo, Object)}. * @param object May be null. */ public <T> T copyShallow (T object, Serializer serializer) { if (object == null) return null; copyDepth++; copyShallow = true; try { if (originalToCopy == null) originalToCopy = new IdentityMap(); Object existingCopy = originalToCopy.get(object); if (existingCopy != null) return (T)existingCopy; needsCopyReference = object; Object copy; if (object instanceof KryoCopyable) copy = ((KryoCopyable)object).copy(this); else copy = serializer.copy(this, object); if (needsCopyReference != null) reference(copy); if (TRACE || (DEBUG && copyDepth == 1)) log("Shallow copy", copy); return (T)copy; } finally { copyShallow = false; if (--copyDepth == 0) reset(); } } private void beginObject () { if (DEBUG) { if (depth == 0) thread = Thread.currentThread(); else if (thread != Thread.currentThread()) throw new ConcurrentModificationException("Kryo must not be accessed concurrently by multiple threads."); } if (depth == maxDepth) throw new KryoException("Max depth exceeded: " + depth); depth++; } public ClassResolver getClassResolver () { return classResolver; } /** @return May be null. */ public ReferenceResolver getReferenceResolver () { return referenceResolver; } /** Sets the classloader to resolve unregistered class names to classes. The default is the loader that loaded the Kryo class. */ public void setClassLoader (ClassLoader classLoader) { if (classLoader == null) throw new IllegalArgumentException("classLoader cannot be null."); this.classLoader = classLoader; } public ClassLoader getClassLoader () { return classLoader; } /** If true, an exception is thrown when an unregistered class is encountered. Default is false. * <p> * If false, when an unregistered class is encountered, its fully qualified class name will be serialized and the * {@link #addDefaultSerializer(Class, Class) default serializer} for the class used to serialize the object. Subsequent * appearances of the class within the same object graph are serialized as an int id. * <p> * Registered classes are serialized as an int id, avoiding the overhead of serializing the class name, but have the drawback * of needing to know the classes to be serialized up front. */ public void setRegistrationRequired (boolean registrationRequired) { this.registrationRequired = registrationRequired; if (TRACE) trace("kryo", "Registration required: " + registrationRequired); } public boolean isRegistrationRequired () { return registrationRequired; } /** If true, each appearance of an object in the graph after the first is stored as an integer ordinal. When set to true, * {@link MapReferenceResolver} is used. This enables references to the same object and cyclic graphs to be serialized, but * typically adds overhead of one byte per object. Default is true. * @return The previous value. */ public boolean setReferences (boolean references) { if (references == this.references) return references; this.references = references; if (references && referenceResolver == null) referenceResolver = new MapReferenceResolver(); if (TRACE) trace("kryo", "References: " + references); return !references; } /** Sets the reference resolver and enables references. */ public void setReferenceResolver (ReferenceResolver referenceResolver) { if (referenceResolver == null) throw new IllegalArgumentException("referenceResolver cannot be null."); this.references = true; this.referenceResolver = referenceResolver; if (TRACE) trace("kryo", "Reference resolver: " + referenceResolver.getClass().getName()); } public boolean getReferences () { return references; } /** Sets the strategy used by {@link #newInstantiator(Class)} for creating objects. See {@link StdInstantiatorStrategy} to * create objects via without calling any constructor. See {@link SerializingInstantiatorStrategy} to mimic Java's built-in * serialization. * @param strategy May be null. */ public void setInstantiatorStrategy (InstantiatorStrategy strategy) { this.strategy = strategy; } /** Returns a new instantiator for creating new instances of the specified type. By default, an instantiator is returned that * uses reflection if the class has a zero argument constructor, an exception is thrown. If a * {@link #setInstantiatorStrategy(InstantiatorStrategy) strategy} is set, it will be used instead of throwing an exception. */ protected ObjectInstantiator newInstantiator (final Class type) { if (!Util.isAndroid) { // Use ReflectASM if the class is not a non-static member class. Class enclosingType = type.getEnclosingClass(); boolean isNonStaticMemberClass = enclosingType != null && type.isMemberClass() && !Modifier.isStatic(type.getModifiers()); if (!isNonStaticMemberClass) { try { final ConstructorAccess access = ConstructorAccess.get(type); return new ObjectInstantiator() { public Object newInstance () { try { return access.newInstance(); } catch (Exception ex) { throw new KryoException("Error constructing instance of class: " + className(type), ex); } } }; } catch (Exception ignored) { } } } // Reflection. try { Constructor ctor; try { ctor = type.getConstructor((Class[])null); } catch (Exception ex) { ctor = type.getDeclaredConstructor((Class[])null); ctor.setAccessible(true); } final Constructor constructor = ctor; return new ObjectInstantiator() { public Object newInstance () { try { return constructor.newInstance(); } catch (Exception ex) { throw new KryoException("Error constructing instance of class: " + className(type), ex); } } }; } catch (Exception ignored) { } if (strategy == null) { if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers())) throw new KryoException("Class cannot be created (non-static member class): " + className(type)); else throw new KryoException("Class cannot be created (missing no-arg constructor): " + className(type)); } // InstantiatorStrategy. return strategy.newInstantiatorOf(type); } /** Creates a new instance of a class using {@link Registration#getInstantiator()}. If the registration's instantiator is null, * a new one is set using {@link #newInstantiator(Class)}. */ public <T> T newInstance (Class<T> type) { Registration registration = getRegistration(type); ObjectInstantiator instantiator = registration.getInstantiator(); if (instantiator == null) { instantiator = newInstantiator(type); registration.setInstantiator(instantiator); } return (T)instantiator.newInstance(); } /** Name/value pairs that are available to all serializers. */ public ObjectMap getContext () { if (context == null) context = new ObjectMap(); return context; } /** Name/value pairs that are available to all serializers and are cleared after each object graph is serialized or * deserialized. */ public ObjectMap getGraphContext () { if (graphContext == null) graphContext = new ObjectMap(); return graphContext; } /** Returns the number of child objects away from the object graph root. */ public int getDepth () { return depth; } /** If true (the default), {@link #reset()} is called automatically after an entire object graph has been read or written. If * false, {@link #reset()} must be called manually, which allows unregistered class names, references, and other information to * span multiple object graphs. */ public void setAutoReset (boolean autoReset) { this.autoReset = autoReset; } /** Sets the maxiumum depth of an object graph. This can be used to prevent malicious data from causing a stack overflow. * Default is {@link Integer#MAX_VALUE}. */ public void setMaxDepth (int maxDepth) { if (maxDepth <= 0) throw new IllegalArgumentException("maxDepth must be > 0."); this.maxDepth = maxDepth; } /** Returns true if the specified type is final. Final types can be serialized more efficiently because they are * non-polymorphic. * <p> * This can be overridden to force non-final classes to be treated as final. Eg, if an application uses ArrayList extensively * but never uses an ArrayList subclass, treating ArrayList as final could allow FieldSerializer to save 1-2 bytes per * ArrayList field. */ public boolean isFinal (Class type) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (type.isArray()) return Modifier.isFinal(Util.getElementClass(type).getModifiers()); return Modifier.isFinal(type.getModifiers()); } /** Returns the first level of classes or interfaces for a generic type. * @return null if the specified type is not generic or its generic types are not classes. */ public Class[] getGenerics (Type genericType) { if (genericType instanceof GenericArrayType) { Type componentType = ((GenericArrayType)genericType).getGenericComponentType(); if(componentType instanceof Class) return new Class[] {(Class)componentType}; else return getGenerics(componentType); } if (!(genericType instanceof ParameterizedType)) return null; if (TRACE) trace("kryo", "Processing generic type " + genericType); Type[] actualTypes = ((ParameterizedType)genericType).getActualTypeArguments(); Class[] generics = new Class[actualTypes.length]; int count = 0; for (int i = 0, n = actualTypes.length; i < n; i++) { Type actualType = actualTypes[i]; if (TRACE) trace("kryo", "Processing actual type " + actualType + " (" + actualType.getClass().getName() + ")"); generics[i] = Object.class; if (actualType instanceof Class) generics[i] = (Class)actualType; else if (actualType instanceof ParameterizedType) generics[i] = (Class)((ParameterizedType)actualType).getRawType(); else if (actualType instanceof TypeVariable) { Generics scope = getGenericsScope(); if (scope != null) { Class clazz = scope.getConcreteClass(((TypeVariable)actualType).getName()); if (clazz != null) { generics[i] = clazz; } else continue; } else continue; } else continue; count++; } if (count == 0) return null; return generics; } static final class DefaultSerializerEntry { Class type; Serializer serializer; Class<? extends Serializer> serializerClass; } public void pushGenericsScope (Class type, Generics generics) { if (TRACE) trace("kryo", "Settting a new generics scope for class " + type.getName() + ": " + generics); Generics currentScope = genericsScope; genericsScope = generics; genericsScope.setParentScope(currentScope); } public void popGenericsScope () { Generics oldScope = genericsScope; if (genericsScope != null) genericsScope = genericsScope.getParentScope(); if (oldScope != null) oldScope.resetParentScope(); } public Generics getGenericsScope () { return genericsScope; } public StreamFactory getStreamFactory () { return streamFactory; } public void setStreamFactory (FastestStreamFactory streamFactory) { this.streamFactory = streamFactory; } /** Tells Kryo, if ASM-based backend should be used by new serializer instances created using this Kryo instance. Already * existing serializer instances are not affected by this setting. * * <p> * By default, Kryo uses ASM-based backend. * </p> * * @param flag if true, ASM-based backend will be used. Otherwise Unsafe-based backend could be used by some serializers, e.g. * FieldSerializer */ public void setAsmEnabled (boolean flag) { this.asmEnabled = flag; } public boolean getAsmEnabled () { return asmEnabled; } }
package com.jme.input.action; import com.jme.input.Mouse; import com.jme.input.RelativeMouse; import com.jme.math.Vector3f; import com.jme.renderer.Camera; /** * <code>MouseLook</code> defines a mouse action that detects mouse movement * and converts it into camera rotations and camera tilts. * @author Mark Powell * @version $Id: MouseLook.java,v 1.9 2004-07-30 21:33:40 cep21 Exp $ */ public class MouseLook implements MouseInputAction { private RelativeMouse mouse; private KeyLookDownAction lookDown; private KeyLookUpAction lookUp; private KeyRotateLeftAction rotateLeft; private KeyRotateRightAction rotateRight; private Vector3f lockAxis; private float speed; // private Camera camera; /** * Constructor creates a new <code>MouseLook</code> object. It takes the * mouse, camera and speed of the looking. * @param mouse the mouse to calculate view changes. * @param camera the camera to move. * @param speed the speed at which to alter the camera. */ public MouseLook(Mouse mouse, Camera camera, float speed) { this.mouse = (RelativeMouse)mouse; this.speed = speed; // this.camera = camera; lookDown = new KeyLookDownAction(camera, speed); lookUp = new KeyLookUpAction(camera, speed); rotateLeft = new KeyRotateLeftAction(camera, speed); rotateRight = new KeyRotateRightAction(camera, speed); } /** * * <code>setLockAxis</code> sets the axis that should be locked down. This * prevents "rolling" about a particular axis. Typically, this is set to * the mouse's up vector. Note this is only a shallow copy. * @param lockAxis the axis that should be locked down to prevent rolling. */ public void setLockAxis(Vector3f lockAxis) { this.lockAxis = lockAxis; rotateLeft.setLockAxis(lockAxis); rotateRight.setLockAxis(lockAxis); } /** * Returns the axis that is currently locked. * @return The currently locked axis * @see #setLockAxis(com.jme.math.Vector3f) */ public Vector3f getLockAxis(){ return lockAxis; } /** * * <code>setSpeed</code> sets the speed of the mouse look. * @param speed the speed of the mouse look. */ public void setSpeed(float speed) { this.speed = speed; lookDown.setSpeed(speed); lookUp.setSpeed(speed); rotateRight.setSpeed(speed); rotateLeft.setSpeed(speed); } /** * * <code>getSpeed</code> retrieves the speed of the mouse look. * @return the speed of the mouse look. */ public float getSpeed() { return speed; } /** * <code>performAction</code> checks for any movement of the mouse, and * calls the appropriate method to alter the camera's orientation when * applicable. * @see com.jme.input.action.MouseInputAction#performAction(float) */ public void performAction(float time) { time *= speed; if (mouse.getLocalTranslation().x > 0) { rotateRight.performAction( time * mouse.getLocalTranslation().x); } else if (mouse.getLocalTranslation().x < 0) { rotateLeft.performAction( time * mouse.getLocalTranslation().x * -1); } if (mouse.getLocalTranslation().y > 0) { lookUp.performAction( time * mouse.getLocalTranslation().y); } else if (mouse.getLocalTranslation().y < 0) { lookDown.performAction( time * mouse.getLocalTranslation().y * -1); } } /** * <code>setMouse</code> sets the mouse used to check for movement. * @see com.jme.input.action.MouseInputAction#setMouse(com.jme.input.Mouse) */ public void setMouse(Mouse mouse) { this.mouse = (RelativeMouse)mouse; } }
package com.legit2.Demigods; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @SuppressWarnings("unused") public class DScheduler { // Define commands private static Demigods plugin = DUtil.getPlugin(); private static int savePlayers; /* * startThreads() : Starts the scheduler threads. */ @SuppressWarnings("deprecation") public static void startThreads() { // Setup threads for saving, health, and favor int start_delay = (int)(DConfig.getSettingDouble("start_delay_seconds")*20); int favor_frequency = (int)(DConfig.getSettingDouble("favor_regen_seconds")*20); int save_frequency = DConfig.getSettingInt("save_interval_seconds")*20; if (favor_frequency < 0) favor_frequency = 600; if (start_delay <= 0) start_delay = 1; if (save_frequency <= 0) save_frequency = 300; plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { @Override public void run() { DDatabase.saveAllData(); } }, start_delay, save_frequency); plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { @Override public void run() { DUtil.regenerateAllFavor(); } }, 0, favor_frequency); // Expiring Hashmaps plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { @Override public void run() { for(Player player : Bukkit.getOnlinePlayers()) { if(DSave.hasPlayerData(player.getName(), "was_PVP_temp")) { if(DUtil.toInteger(DSave.getPlayerData(player.getName(), "was_PVP_temp")) > (int) System.currentTimeMillis() - (int) (DConfig.getSettingDouble("pvp_area_delay_seconds") * 20)) continue; DSave.removePlayerData(player.getName(), "was_PVP_temp"); player.sendMessage(ChatColor.YELLOW + "You are now safe from PVP."); } } } }, 0, 15); } /* * stopThreads() : Stops all scheduler threads. */ public static void stopThreads() { plugin.getServer().getScheduler().cancelAllTasks(); } }
package com.sproutlife.panel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JSplitPane; public class GameFrame extends JFrame { private static final Dimension DEFAULT_WINDOW_SIZE = new Dimension(1000, 600); private static final Dimension MINIMUM_WINDOW_SIZE = new Dimension(300, 300); PanelController panelController; JSplitPane splitPane = new JSplitPane(); public GameFrame(PanelController panelController) { this.panelController = panelController; initFrame(); setLayout(new BorderLayout(0, 0)); splitPane = new JSplitPane(); splitPane.setResizeWeight(1); splitPane.setOneTouchExpandable(true); add(splitPane); } public JSplitPane getSplitPane() { return splitPane; } private void initFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Sprout Life - Evolving Game of Life"); // game.setIconImage(new // ImageIcon(ConwaysGameOfLife.class.getResource("/images/logo.png")).getImage()); setSize(DEFAULT_WINDOW_SIZE); setMinimumSize(MINIMUM_WINDOW_SIZE); setLocation( (Toolkit.getDefaultToolkit().getScreenSize().width - getWidth()) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getHeight()) / 2); } }
package com.uid.DroidDoesMusic.UI; import android.app.TabActivity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.res.Resources; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TabHost; import com.uid.DroidDoesMusic.R; import com.uid.DroidDoesMusic.player.Player; public class Main extends TabActivity { protected static final String TAG = "DroidDoesMusic"; protected Player mPlayer; @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, getClass().getSimpleName() + ": onCreate"); bind(); super.onCreate(savedInstanceState); setContentView(R.layout.main); setupTabs(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Inflates menu items from resources MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Switch over options selected switch (item.getItemId()) { case R.id.settings: startActivity(new Intent(this, Preferences.class)); return true; } return false; } private void bind() { Log.d(TAG, "Attempting to bind to Player" ); bindService(new Intent(this, Player.class), mConnection, Context.BIND_AUTO_CREATE); } public boolean isPlayerBound=false; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName classname, IBinder service){ Log.d(TAG, "Player Service Connected" +classname.toShortString()); Player player = ((Player.DataBinder)service).getService(); mPlayer = player; isPlayerBound=true; } public void onServiceDisconnected(ComponentName classname){ Log.d(TAG, "Player Service Disconnected"); isPlayerBound = false; } }; public void setupTabs() { // Resource object for drawables Resources res = getResources(); // TabHost from TabActivity TabHost tabHost = getTabHost(); // TabSpec for reuse (object creation is expensive) TabHost.TabSpec spec; // Intent for reuse Intent intent; // Tab titles from resources String[] tabs = res.getStringArray(R.array.tabs); // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, Playlist.class); // Initialize a TabSpec for each tab and add it to the TabHost // Playlist spec = tabHost.newTabSpec("playlist") .setIndicator(tabs[0], res.getDrawable(R.drawable.ic_tab_playlist)) .setContent(intent); tabHost.addTab(spec); // Library // Artists intent = new Intent().setClass(this, Library.class); intent.putExtra("view", Library.ARTIST_VIEW); spec = tabHost.newTabSpec("library_artists") .setIndicator(tabs[1], res.getDrawable(R.drawable.ic_tab_playlist)) .setContent(intent); tabHost.addTab(spec); // Albums intent = new Intent().setClass(this, Library.class); intent.putExtra("view", Library.ALBUM_VIEW); spec = tabHost.newTabSpec("library_albums") .setIndicator(tabs[2], res.getDrawable(R.drawable.ic_tab_playlist)) .setContent(intent); tabHost.addTab(spec); // Songs intent = new Intent().setClass(this, Library.class); intent.putExtra("view", Library.SONG_VIEW); spec = tabHost.newTabSpec("library_songs") .setIndicator(tabs[3], res.getDrawable(R.drawable.ic_tab_playlist)) .setContent(intent); tabHost.addTab(spec); /*// Now Playing intent = new Intent().setClass(this, NowPlaying.class); spec = tabHost.newTabSpec("now_playing") .setIndicator(tabs[4], res.getDrawable(R.drawable.ic_tab_playlist)) .setContent(intent); tabHost.addTab(spec);*/ // Set current tab to Library tabHost.setCurrentTab(1); } }
package com.vmware.vim.rest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class RestClient { final private static String NONCE = "vmware-session-nonce"; final private static String NONCE_VAL_START = "value=\""; private String baseUrl = null; static { try { trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier ( new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } } ); } catch (Exception e) {} } public RestClient(String serverUrl, String username, String password) { if(serverUrl.endsWith("/")) { serverUrl = serverUrl.substring(0, serverUrl.length()-1); } else if (serverUrl.endsWith("/mob")) { serverUrl = serverUrl.substring(0, serverUrl.length()-4); } else if (serverUrl.endsWith("/mob/")) { serverUrl = serverUrl.substring(0, serverUrl.length()-5); } this.baseUrl = serverUrl; setLogin(username, password); } public String get(String urlStr) throws IOException { urlStr = preProcessUrl(urlStr); StringBuffer sb = getRawPage(urlStr); int start = sb.indexOf("<xml id=\"objData\">"); int objPos = sb.indexOf("<object>", start); sb.replace(objPos, objPos+8 , "<object xmlns:xsi='http: int end = sb.indexOf("</textarea>", objPos); return sb.substring(start, end); } private String preProcessUrl(String url) { if(url==null || url.equals("/")) { url = baseUrl + "/mob"; } else if(!(url.startsWith("http") || url.startsWith("https"))) { if(url.startsWith("/mob/?moid=")) { url = baseUrl + url; } else if(url.startsWith("moid=")) { url = baseUrl + "/mob/?" + url; } else if(url.startsWith("?moid=")) { url = baseUrl + "/mob/" + url; } } return url; } private StringBuffer getRawPage(String urlStr) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection(); conn.connect(); return readStream(conn.getInputStream()); } public String post(String urlStr) throws Exception { return post(urlStr, new Hashtable<String, String>()); } public String post(String urlStr, Map<String, String> para) throws Exception { urlStr = preProcessUrl(urlStr); HttpURLConnection getCon = (HttpURLConnection) new URL( urlStr).openConnection(); getCon.connect(); String cookie = getCon.getHeaderField("Set-Cookie"); cookie = cookie.substring(0, cookie.indexOf(";")); //As of 4.1u1, a hidden input is added into form, shown as follows //<input name="vmware-session-nonce" type="hidden" value="52f3d5cc-5664-6d09-cd3a-73869a2de488"> String nonceStr = findVMwareSessionNonce(getCon.getInputStream()); HttpURLConnection postCon = (HttpURLConnection) new URL(urlStr).openConnection(); postCon.setRequestMethod("POST"); postCon.setDoOutput(true); postCon.setDoInput(true); postCon.setRequestProperty("Cookie", cookie); OutputStream os = postCon.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os); if(nonceStr!=null) { out.write(NONCE + "=" + nonceStr); } Iterator<String> keys = para.keySet().iterator(); while(keys.hasNext()) { String key = keys.next(); String value = para.get(key); key = URLEncoder.encode(key, "UTF-8"); value = URLEncoder.encode(value, "UTF-8"); out.write(key + "=" + value); } out.close(); InputStream is = postCon.getInputStream(); StringBuffer sb = readStream(is); String resultFlag = "Method Invocation Result:"; int start = sb.indexOf(resultFlag); String result = sb.substring(start + resultFlag.length()); return ResultConverter.convert2Xml(result); } public String getUrlStr() { return this.baseUrl; } private String findVMwareSessionNonce(InputStream is) throws IOException { StringBuffer sb = readStream(is); int pos = sb.indexOf(NONCE); if(pos == -1) { return null; } int start = sb.indexOf(NONCE_VAL_START, pos + NONCE.length()) + NONCE_VAL_START.length(); int end = sb.indexOf("\"", start); return sb.substring(start, end); } private StringBuffer readStream(InputStream is) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String lineStr; while ((lineStr = in.readLine()) != null) { sb.append(lineStr); } in.close(); return sb; } private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[1]; trustAllCerts[0] = new TrustAllManager(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory()); } private static class TrustAllManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { } } private void setLogin(String username, String password) { final String user = username; final String pass = password; Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication (user, pass.toCharArray()); } } ); } }
package net.time4j.i18n; import net.time4j.CalendarUnit; import net.time4j.ClockUnit; import net.time4j.Duration; import net.time4j.IsoUnit; import net.time4j.PlainDate; import net.time4j.PlainTimestamp; import net.time4j.PrettyTime; import net.time4j.base.TimeSource; import net.time4j.engine.BasicUnit; import net.time4j.engine.ChronoEntity; import net.time4j.engine.Chronology; import net.time4j.engine.UnitRule; import net.time4j.format.TextWidth; import net.time4j.format.expert.ChronoFormatter; import net.time4j.format.expert.PatternType; import net.time4j.tz.Timezone; import net.time4j.tz.ZonalOffset; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.IOException; import java.util.Locale; import java.util.concurrent.TimeUnit; import static net.time4j.CalendarUnit.*; import static net.time4j.ClockUnit.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(JUnit4.class) public class PrettyTimeTest { @Test public void printRelativePT() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 4, 14, 40, 10).atUTC(); assertThat( PrettyTime.of(new Locale("pt", "PT")) .withReferenceClock(clock) .withShortStyle() .printRelative( PlainTimestamp.of(2014, 9, 4, 14, 40, 5).atUTC(), ZonalOffset.UTC ), is("há 5 s")); // from pt_PT-resource assertThat( PrettyTime.of(new Locale("pt")) .withReferenceClock(clock) .withShortStyle() .printRelative( PlainTimestamp.of(2014, 9, 4, 14, 40, 5).atUTC(), ZonalOffset.UTC ), is("há 5 seg.")); // Brazilian assertThat( PrettyTime.of(new Locale("pt", "PT")) .withReferenceClock(clock) .withShortStyle() .printRelative( PlainTimestamp.of(2014, 9, 4, 12, 40, 5).atUTC(), ZonalOffset.UTC ), is("há 2 h")); // inherited from Brazilian, does not exist in pt_PT-resource } @Test public void printDurationPT() { assertThat( PrettyTime.of(new Locale("pt", "PT")).withShortStyle().print(Duration.of(5, ClockUnit.SECONDS)), is("5 s")); // from pt_PT-resource assertThat( PrettyTime.of(new Locale("pt")).withShortStyle().print(Duration.of(5, ClockUnit.SECONDS)), is("5 seg")); // Brazilian assertThat( PrettyTime.of(new Locale("pt", "PT")).withShortStyle().print(Duration.of(2, ClockUnit.HOURS)), is("2 h")); // inherited from Brazilian, does not exist in pt_PT-resource } @Test public void printRelativeOrDate() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 4, 14, 40).atUTC(); assertThat( PrettyTime.of(Locale.GERMAN) .withReferenceClock(clock) .withWeeksToDays() .printRelativeOrDate( PlainDate.of(2014, 10, 3), ZonalOffset.UTC, CalendarUnit.DAYS, ChronoFormatter.ofDatePattern( "d. MMMM uuuu", PatternType.CLDR, Locale.GERMAN) ), is("in 29 Tagen")); assertThat( PrettyTime.of(Locale.GERMAN) .withReferenceClock(clock) .withWeeksToDays() .printRelativeOrDate( PlainDate.of(2014, 10, 4), ZonalOffset.UTC, CalendarUnit.DAYS, ChronoFormatter.ofDatePattern( "d. MMMM uuuu", PatternType.CLDR, Locale.GERMAN) ), is("4. Oktober 2014")); assertThat( PrettyTime.of(Locale.GERMAN) .withReferenceClock(clock) .withWeeksToDays() .printRelativeOrDate( PlainDate.of(2014, 9, 3), ZonalOffset.UTC, CalendarUnit.DAYS, ChronoFormatter.ofDatePattern( "d. MMMM uuuu", PatternType.CLDR, Locale.GERMAN) ), is("gestern")); } @Test public void printRelativeOrDateTime() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 40).atUTC(); assertThat( PrettyTime.of(Locale.GERMAN) .withReferenceClock(clock) .printRelativeOrDateTime( PlainTimestamp.of(2014, 10, 3, 14, 30).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.MINUTES, 86400L * 30, // 30 days ChronoFormatter.ofMomentPattern( "d. MMMM uuuu", PatternType.CLDR, Locale.GERMAN, Timezone.of("Europe/Berlin").getID()) ), is("3. Oktober 2014")); assertThat( PrettyTime.of(Locale.GERMAN) .withReferenceClock(clock) .withWeeksToDays() .printRelativeOrDateTime( PlainTimestamp.of(2014, 9, 30, 14, 40).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.MINUTES, 86400L * 29, // 29 days ChronoFormatter.ofMomentPattern( "d. MMMM uuuu", PatternType.CLDR, Locale.GERMAN, Timezone.of("Europe/Berlin").getID()) ), is("in 29 Tagen")); assertThat( PrettyTime.of(Locale.GERMAN) .withReferenceClock(clock) .withWeeksToDays() .printRelativeOrDateTime( PlainTimestamp.of(2014, 9, 30, 14, 40).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.MINUTES, CalendarUnit.DAYS, ChronoFormatter.ofMomentPattern( "d. MMMM uuuu", PatternType.CLDR, Locale.GERMAN, Timezone.of("Europe/Berlin").getID()) ), is("in 29 Tagen")); assertThat( PrettyTime.of(Locale.GERMAN) .withReferenceClock(clock) .withWeeksToDays() .printRelativeOrDateTime( PlainTimestamp.of(2014, 10, 1, 14, 40).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.MINUTES, CalendarUnit.DAYS, ChronoFormatter.ofMomentPattern( "d. MMMM uuuu", PatternType.CLDR, Locale.GERMAN, Timezone.of("Europe/Berlin").getID()) ), is("1. Oktober 2014")); } @Test public void getLocale() { assertThat( PrettyTime.of(Locale.ROOT).getLocale(), is(Locale.ROOT)); } @Test public void withMinusSign() { String minus = "_"; assertThat( PrettyTime.of(new Locale("ar", "DZ")) .withMinusSign(minus) .print(-3, MONTHS, TextWidth.SHORT), is(minus + "3 أشهر")); } @Test public void withEmptyDayUnit() { assertThat( PrettyTime.of(Locale.ROOT).withEmptyUnit(DAYS) .print(Duration.ofZero(), TextWidth.WIDE), is("0 d")); } @Test public void withEmptyMinuteUnit() { assertThat( PrettyTime.of(Locale.ROOT).withEmptyUnit(MINUTES) .print(Duration.ofZero(), TextWidth.WIDE), is("0 min")); } @Test(expected=NullPointerException.class) public void withEmptyNullUnit() { CalendarUnit unit = null; PrettyTime.of(Locale.ROOT).withEmptyUnit(unit); } @Test(expected=NullPointerException.class) public void withNullReferenceClock() { PrettyTime.of(Locale.ROOT).withReferenceClock(null); } @Test public void print0DaysEnglish() { assertThat( PrettyTime.of(Locale.ENGLISH).print(0, DAYS, TextWidth.WIDE), is("0 days")); } @Test public void print1DayEnglish() { assertThat( PrettyTime.of(Locale.ENGLISH).print(1, DAYS, TextWidth.WIDE), is("1 day")); } @Test public void print3DaysEnglish() { assertThat( PrettyTime.of(Locale.ENGLISH).print(3, DAYS, TextWidth.WIDE), is("3 days")); } @Test public void print0DaysFrench() { assertThat( PrettyTime.of(Locale.FRANCE).print(0, DAYS, TextWidth.WIDE), is("0 jour")); } @Test public void print1DayFrench() { assertThat( PrettyTime.of(Locale.FRANCE).print(1, DAYS, TextWidth.WIDE), is("1 jour")); } @Test public void print3DaysFrench() { assertThat( PrettyTime.of(Locale.FRANCE).print(3, DAYS, TextWidth.WIDE), is("3 jours")); } @Test public void print0DaysLatvian() { assertThat( PrettyTime.of(new Locale("lv")).print(0, DAYS, TextWidth.WIDE), is("0 dienas")); } @Test public void print1DayLatvian() { assertThat( PrettyTime.of(new Locale("lv")).print(1, DAYS, TextWidth.WIDE), is("1 diena")); } @Test public void print67DaysLatvian() { assertThat( PrettyTime.of(new Locale("lv")).print(67, DAYS, TextWidth.WIDE), is("67 dienas")); } @Test public void print3WeeksDanish() { assertThat( PrettyTime.of(new Locale("da")).print(3, WEEKS, TextWidth.WIDE), is("3 uger")); } @Test public void print3WeeksDanishAndWeeksToDays() { assertThat( PrettyTime.of(new Locale("da")) .withWeeksToDays() .print(3, WEEKS, TextWidth.WIDE), is("21 dage")); } @Test public void printNowGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(), ZonalOffset.UTC), is("jetzt")); } @Test public void printRelativeInStdTimezone() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelativeInStdTimezone(PlainTimestamp.of(2014, 9, 5, 14, 0).atUTC()), is(PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative(PlainTimestamp.of(2014, 9, 5, 14, 0).atUTC(), Timezone.ofSystem().getID()))); } @Test public void printLastLeapsecondGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2012, 7, 1, 0, 0, 5).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2012, 6, 30, 23, 59, 59).atUTC(), ZonalOffset.UTC), is("vor 7 Sekunden")); } @Test public void printNextLeapsecondEnglish() { TimeSource<?> clock = () -> PlainTimestamp.of(2012, 6, 30, 23, 59, 54).atUTC(); assertThat( PrettyTime.of(Locale.ENGLISH) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2012, 7, 1, 0, 0, 0).atUTC(), ZonalOffset.UTC), is("in 7 seconds")); } @Test public void printYesterdayGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 4, 14, 40).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 3, 14, 30).atUTC(), ZonalOffset.UTC), is("gestern")); } @Test public void printTodayGerman1() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 3, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 3, 1, 0).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.DAYS), is("heute")); } @Test public void printTodayGerman2() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 3, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 3, 14, 0).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.HOURS), is("jetzt")); } @Test public void printTodayGerman3() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 3, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 3, 14, 0).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.MINUTES), is("vor 30 Minuten")); } @Test public void printTodayGerman4() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 3, 15, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 3, 14, 0).atUTC(), Timezone.of(ZonalOffset.UTC), TimeUnit.HOURS), is("vor 1 Stunde")); } @Test public void printTomorrowGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 2, 14, 45).atUTC(), ZonalOffset.UTC), is("morgen")); } @Test public void print3DaysLaterGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 5, 14, 0).atUTC(), ZonalOffset.UTC), is("in 3 Tagen")); } @Test public void print4MonthsEarlierGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 4, 5, 14, 0).atUTC(), ZonalOffset.UTC), is("vor 4 Monaten")); } @Test public void print4HoursEarlierGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 3, 30, 5, 0) .in(Timezone.of("Europe/Berlin")); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 3, 30, 0, 0) .in(Timezone.of("Europe/Berlin")), "Europe/Berlin"), is("vor 4 Stunden")); } @Test public void print4HoursEarlierGermanShort() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 3, 30, 5, 0) .in(Timezone.of("Europe/Berlin")); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .withShortStyle() .printRelative( PlainTimestamp.of(2014, 3, 30, 0, 0) .in(Timezone.of("Europe/Berlin")), "Europe/Berlin"), is("vor 4 Std.")); } @Test public void print3DaysRussian() { assertThat( PrettyTime.of(new Locale("ru")).print(3, DAYS, TextWidth.WIDE), is("3 дня")); } @Test public void print12DaysRussian() { assertThat( PrettyTime.of(new Locale("ru")).print(12, DAYS, TextWidth.WIDE), is("12 дней")); } @Test public void print0MonthsArabic1() { assertThat( PrettyTime.of(new Locale("ar", "DZ")).print( 0, MONTHS, TextWidth.SHORT), is("0 شهر")); } @Test public void print0MonthsArabic2() { assertThat( PrettyTime.of(new Locale("ar", "DZ")) .withEmptyUnit(MONTHS) .print(Duration.of(0, MONTHS), TextWidth.SHORT), is("0 شهر")); } @Test public void print2MonthsArabic() { assertThat( PrettyTime.of(new Locale("ar", "DZ")).print( 2, MONTHS, TextWidth.SHORT), is("شهران")); } @Test public void print3MonthsArabic() { assertThat( PrettyTime.of(new Locale("ar", "DZ")).print( 3, MONTHS, TextWidth.SHORT), is("3 أشهر")); } @Test public void print3MonthsArabicU0660() { assertThat( PrettyTime.of(new Locale("ar", "DZ")) .withZeroDigit('\u0660') .print(3, MONTHS, TextWidth.SHORT), is('\u0663' + " أشهر")); } @Test public void printMillisWideGerman() { assertThat( PrettyTime.of(Locale.GERMANY) .print(Duration.of(123, MILLIS), TextWidth.WIDE), is("123 Millisekunden")); } @Test public void printMicrosWideGerman() { assertThat( PrettyTime.of(Locale.GERMANY) .print(Duration.of(123456, MICROS), TextWidth.WIDE), is("123456 Mikrosekunden")); } @Test public void printNanosWideGerman() { assertThat( PrettyTime.of(Locale.GERMANY) .print( Duration.of(123456789, NANOS), TextWidth.WIDE), is("123456789 Nanosekunden")); } @Test public void printMillisShortGerman() { assertThat( PrettyTime.of(Locale.GERMANY) .print(Duration.of(123, MILLIS), TextWidth.SHORT), is("123 ms")); } @Test public void printMicrosShortGerman() { assertThat( PrettyTime.of(Locale.GERMANY) .print(Duration.of(123456, MICROS), TextWidth.SHORT), is("123456 μs")); } @Test public void printNanosShortGerman() { assertThat( PrettyTime.of(Locale.GERMANY) .print( Duration.of(123456789, NANOS), TextWidth.SHORT), is("123456789 ns")); } @Test public void printMillisWideEnglish() { Duration<ClockUnit> dur = Duration.of(123, MILLIS).plus(1000, MICROS); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE), is("124 milliseconds")); } @Test public void printMicrosWideEnglish() { Duration<ClockUnit> dur = Duration.of(123, MILLIS).plus(1001, MICROS); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE), is("124001 microseconds")); } @Test public void print15Years3Months1Week2DaysUS() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS); assertThat( PrettyTime.of(Locale.US).print(duration), is("15 years, 3 months, 1 week, and 2 days")); } @Test public void print15Years3Months1Week2DaysBritish() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS); assertThat( PrettyTime.of(Locale.UK).print(duration, TextWidth.WIDE), is("15 years, 3 months, 1 week and 2 days")); } @Test public void print15Years3Months1Week2DaysFrench() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS); assertThat( PrettyTime.of(Locale.FRANCE).print(duration, TextWidth.WIDE), is("15 ans, 3 mois, 1 semaine et 2 jours")); } @Test public void print15Years3Months1Week2DaysMinusGerman() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2) .plus(1, WEEKS) .inverse(); assertThat( PrettyTime.of(Locale.GERMANY).print(duration, TextWidth.WIDE), is("-15 Jahre, -3 Monate, -1 Woche und -2 Tage")); } @Test public void print15Years3Months1Week2DaysArabic() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS); assertThat( PrettyTime.of(new Locale("ar")) .withZeroDigit('0') .print(duration, TextWidth.WIDE), is("15 سنة، 3 أشهر، أسبوع، ويومان")); } @Test public void print15Years3Months1Week2DaysArabicU0660() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS); assertThat( PrettyTime.of(new Locale("ar")) .print(duration, TextWidth.WIDE), is("١٥ سنة، ٣ أشهر، أسبوع، ويومان")); } @Test public void print15Years3Months1Week2DaysArabicMinus() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS) .inverse(); assertThat( PrettyTime.of(new Locale("ar", "DZ")) .print(duration, TextWidth.WIDE), is("\u200E-15 سنة، \u200E-3 أشهر، أسبوع، ويومان")); } @Test public void print15Years3Months1Week2DaysArabicU0660Minus() { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS) .inverse(); assertThat( PrettyTime.of(new Locale("ar")) .print(duration, TextWidth.WIDE), is("\u200F-١٥ سنة، \u200F-٣ أشهر، أسبوع، ويومان")); } @Test public void print15Years3Months1Week2DaysFarsiMinus() throws IOException { Duration<?> duration = Duration.ofCalendarUnits(15, 3, 2).plus(1, WEEKS) .inverse(); String s = PrettyTime.of(new Locale("fa")).print(duration, TextWidth.WIDE); String expected = "‎−۱۵ سال،‏ ‎−۳ ماه،‏ ‎−۱ هفته، و ‎−۲ روز"; assertThat(s, is(expected)); } @Test public void printMillisWideMax1English() { Duration<ClockUnit> dur = Duration.of(123, MILLIS).plus(1000, MICROS); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE, false, 1), is("124 milliseconds")); } @Test public void printHoursMillisWideMax1English() { Duration<ClockUnit> dur = Duration.of(123, MILLIS).plus(4, HOURS); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE, false, 1), is("4 hours")); } @Test public void printMinutesMillisWideZeroMax1English() { Duration<ClockUnit> dur = Duration.of(123, MILLIS).plus(4, MINUTES); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE, true, 1), is("4 minutes")); } @Test public void printMinutesMillisWideZeroMax2English() { Duration<ClockUnit> dur = Duration.of(123, MILLIS).plus(4, MINUTES); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE, true, 2), is("4 minutes and 0 seconds")); } @Test public void printMinutesMicrosWideZeroMax3English() { Duration<ClockUnit> dur = Duration.of(123, MICROS).plus(4, MINUTES); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE, true, 3), is("4 minutes, 0 seconds, and 123 microseconds")); } @Test public void printDaysMinutesMicrosWideZeroMax3English() { Duration<?> dur = Duration.ofZero() .plus(1, DAYS) .plus(123, MICROS).plus(4, MINUTES); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE, true, 3), is("1 day, 0 hours, and 4 minutes")); } @Test public void printDaysMinutesMicrosWideZeroMax3French() { Duration<?> dur = Duration.ofZero() .plus(1, DAYS) .plus(123, MICROS).plus(4, MINUTES); assertThat( PrettyTime.of(Locale.FRANCE).print(dur, TextWidth.WIDE, true, 3), is("1 jour, 0 heure et 4 minutes")); } @Test public void printDaysMinutesMicrosWideZeroMax8French() { Duration<?> dur = Duration.ofZero() .plus(1, DAYS) .plus(123, MICROS).plus(4, MINUTES); assertThat( PrettyTime.of(Locale.FRANCE).print(dur, TextWidth.WIDE, true, 8), is("1 jour, 0 heure, 4 minutes, 0 seconde et 123 microsecondes")); } @Test public void printYearsDaysMinutesMicrosWideZeroMax6English() { Duration<?> dur = Duration.ofZero() .plus(3, YEARS) .plus(1, DAYS) .plus(123, MICROS).plus(4, MINUTES); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE, true, 6), is("3 years, 0 months, 0 weeks, 1 day, 0 hours, and 4 minutes")); } @Test public void withWeeksToDaysPrintDuration() { Duration<?> dur = Duration.ofZero() .plus(3, YEARS) .plus(2, WEEKS) .plus(1, DAYS) .plus(4, MINUTES); assertThat( PrettyTime.of(Locale.GERMANY).withWeeksToDays() .print(dur, TextWidth.WIDE), is("3 Jahre, 15 Tage und 4 Minuten")); } @Test public void withWeeksToDaysPrintDurationZeroMax4() { Duration<?> dur = Duration.ofZero() .plus(3, YEARS) .plus(2, WEEKS) .plus(1, DAYS) .plus(4, MINUTES); assertThat( PrettyTime.of(Locale.GERMANY).withWeeksToDays() .print(dur, TextWidth.WIDE, true, 4), is("3 Jahre, 0 Monate, 15 Tage und 0 Stunden")); } @Test public void print3WeeksLaterGerman() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 25, 12, 0).atUTC(), ZonalOffset.UTC), is("in 3 Wochen")); } @Test public void print3WeeksLaterGermanAndWeeksToDays() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(Locale.GERMANY) .withReferenceClock(clock) .withWeeksToDays() .printRelative( PlainTimestamp.of(2014, 9, 25, 12, 0).atUTC(), ZonalOffset.UTC), is("in 23 Tagen")); } @Test public void print3WeeksLaterNorsk() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 9, 1, 14, 30).atUTC(); assertThat( PrettyTime.of(new Locale("no")) // language match no => nb .withReferenceClock(clock) .printRelative( PlainTimestamp.of(2014, 9, 25, 12, 0).atUTC(), ZonalOffset.UTC), is("om 3 uker")); } @Test public void printCenturiesAndWeekBasedYearsEnglish() { Duration<?> dur = Duration.ofZero() .plus(1, CENTURIES) .plus(2, CalendarUnit.weekBasedYears()); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE), is("102 years")); } @Test public void printOverflowUnitsEnglish() { Duration<?> dur = Duration.ofZero() .plus(1, QUARTERS) .plus(2, MONTHS.withCarryOver()); assertThat( PrettyTime.of(Locale.US).print(dur, TextWidth.WIDE), is("5 months")); } @Test public void printSpecialUnitsEnglish() { TimeSource<?> clock = () -> PlainTimestamp.of(2014, 10, 1, 14, 30).atUTC(); Duration<?> dur = Duration.ofZero() .plus(8, DAYS) .plus(2, new FortnightPlusOneDay()); assertThat( PrettyTime.of(Locale.US) .withReferenceClock(clock) .print(dur, TextWidth.WIDE), is("4 weeks and 10 days")); } @Test public void printFrenchDemoExample() { Duration<?> dur = Duration.of(337540, ClockUnit.SECONDS).with(Duration.STD_CLOCK_PERIOD); String formattedDuration = PrettyTime.of(Locale.FRANCE).print(dur, TextWidth.WIDE); assertThat( formattedDuration, is("93 heures, 45 minutes et 40 secondes")); } private static class FortnightPlusOneDay extends BasicUnit implements IsoUnit { @Override public char getSymbol() { return 'F'; } @Override public double getLength() { return 86400.0 * 15; } @Override @SuppressWarnings("unchecked") public <T extends ChronoEntity<T>> UnitRule<T> derive(Chronology<T> c) { if (c.equals(PlainTimestamp.axis())) { Object rule = new UnitRule<PlainTimestamp>() { @Override public PlainTimestamp addTo( PlainTimestamp timepoint, long amount ) { return timepoint.plus(amount * 15, DAYS); } @Override public long between( PlainTimestamp start, PlainTimestamp end ) { long days = DAYS.between(start, end); return days / 15; } }; return (UnitRule<T>) rule; } throw new UnsupportedOperationException( c.getChronoType().getName()); } } }
package org.apache.cordova.firebase; import com.google.firebase.messaging.RemoteMessage; import java.util.ArrayList; import java.util.List; public class FirebasePluginMessageReceiverManager { private static List<FirebasePluginMessageReceiver> receivers = new ArrayList<FirebasePluginMessageReceiver>(); public static void register(FirebasePluginMessageReceiver receiver){ receivers.add(receiver); } public static boolean onMessageReceived(RemoteMessage remoteMessage){ boolean handled = false; for(FirebasePluginMessageReceiver receiver : receivers){ boolean wasHandled = receiver.onMessageReceived(remoteMessage); if(wasHandled){ handled = true; } } return handled; } }
package authoring.actionslogic; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; /** * Controller for Action Logic Chart in Authoring Environment * */ public class ActionLogicController implements Initializable { @FXML private ListView<String> actionsListView; @FXML private ChoiceBox<String> actorsChoiceBox; @FXML private VBox myReceiversVBox; @FXML private Button saveButton; private List<String> myPieceTypes = new ArrayList<String>(); private Map<String, Map<String,List<String>>> myLogicMap = new HashMap<String, Map<String,List<String>>>(); private List<CheckBox> myCBList = new ArrayList<CheckBox>(); @Override // TODO: [IMPORTANT] This constructor will need a List<String> or Set<String> that contains // names of Pieces as its argument // also, need a list of existing actions(or names of actions) public void initialize (URL location, ResourceBundle resources) { // for testing actionsListView.getItems().addAll("Attack"); actionsListView.getItems().addAll("Heal"); actionsListView.getItems().addAll("Run"); myPieceTypes.add("Piece A"); myPieceTypes.add("Piece B"); myPieceTypes.add("Piece C"); actorsChoiceBox.getItems().addAll(myPieceTypes); actorsChoiceBox .getSelectionModel() .selectedItemProperty() .addListener( (observable, oldValue, selectedActor) -> updatePossibleReceivers(selectedActor)); } private void updatePossibleReceivers (String selectedActor) { List<String> myPosReceivers = getReceivers(myPieceTypes, selectedActor); for (String p : myPosReceivers) { CheckBox receiverCB = new CheckBox(p); myCBList.add(receiverCB); myReceiversVBox.getChildren().add(receiverCB); } } private List<String> getReceivers (List<String> myPieceTypes, String actor) { List<String> receivers = new ArrayList<String>(); for (String p : myPieceTypes) { if (!p.equals(actor)) { receivers.add(p); } } return receivers; } @FXML private void saveLogic () { String currAction = actionsListView.getSelectionModel().getSelectedItem(); String currActor = actorsChoiceBox.getSelectionModel().getSelectedItem(); Map<String,List<String>> actionReceiver = myLogicMap.get(currActor); List<String> receiverList = new ArrayList<String>(); for (CheckBox cb : myCBList) { if(cb.isSelected()){ receiverList.add(cb.getText()); } } if(actionReceiver == null){ actionReceiver = new HashMap<String,List<String>>(); } actionReceiver.put(currAction, receiverList); myLogicMap.put(currActor, actionReceiver); System.out.println(myLogicMap); } }
package be.kuleuven.cs.distrinet.jnome.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.io.File; import org.aikodi.chameleon.core.Config; import org.aikodi.chameleon.oo.type.Type; import org.aikodi.chameleon.support.test.ExpressionTest; import org.aikodi.chameleon.test.CompositeTest; import org.aikodi.chameleon.test.CrossReferenceTest; import org.aikodi.chameleon.test.provider.BasicDescendantProvider; import org.aikodi.chameleon.test.provider.ElementProvider; import org.aikodi.chameleon.workspace.XMLProjectLoader; import org.aikodi.chameleon.workspace.ConfigException; import org.aikodi.chameleon.workspace.LanguageRepository; import org.aikodi.chameleon.workspace.Project; import org.aikodi.chameleon.workspace.ProjectConfigurator; import org.aikodi.chameleon.workspace.Workspace; import org.junit.Before; import org.junit.Test; import be.kuleuven.cs.distrinet.jnome.core.language.Java7; import be.kuleuven.cs.distrinet.jnome.core.language.Java7LanguageFactory; import be.kuleuven.cs.distrinet.jnome.workspace.JavaProjectConfigurator; public abstract class JavaTest extends CompositeTest { public final static File TEST_DATA = new File("testdata"); protected abstract File projectFile(); /** * Set the log levels of Log4j. By default, nothing is changed. */ @Before public void setLogLevels() { // Logger.getRootLogger().setLevel(Level.FATAL); // Logger.getLogger("chameleon.test.expression").setLevel(Level.FATAL); } @Before public void setMultiThreading() { Config.setSingleThreaded(false); } private static ExecutorService threadPool = Executors.newCachedThreadPool(); @Override protected ExecutorService threadPool() { return threadPool; } @Override @Test public void testCrossReferences() throws Exception { // ElementImpl.elementsCreated = 0; // ElementImpl.elementsOnWhichParentInvoked = 0; // LexicalLookupContext.CREATED = 0; // LocalLookupContext.CREATED = 0; // Block.LINEAR.reset(); // LocalVariableDeclarator.LINEAR.reset(); // LookupContextFactory.LEXICAL_ALLOCATORS.clear(); // LookupContextFactory.LEXICAL_DONE.clear(); // LocalLookupContext.ALLOCATORS.clear(); // LocalLookupContext.DONE.clear(); // Timer.INFIX_OPERATOR_INVOCATION.reset(); // Timer.PREFIX_OPERATOR_INVOCATION.reset(); // Timer.POSTFIX_OPERATOR_INVOCATION.reset(); // Lists.LIST_CREATION.reset(); Project project = project(); // ElementProvider<Type> typeProvider = typeProvider(); new ExpressionTest(project, namespaceProvider(),threadPool).testExpressionTypes(); new CrossReferenceTest(project, namespaceProvider(),threadPool).testCrossReferences(); // new CrossReferenceTest(project, new BasicDescendantProvider<CrossReference>(typeProvider(), CrossReference.class),threadPool).testCrossReferences(); // System.out.println("Created "+SimpleNameSignature.COUNT+" SimpleNameSignature objects."); // System.out.println("Created "+LexicalLookupContext.CREATED+" lexical lookup contexts."); // System.out.println("Created "+LocalLookupContext.CREATED+" local lookup contexts."); // System.out.println("Block linear context: "+Block.LINEAR.elapsedMillis()+"ms"); // System.out.println("Local variable declarator linear context: "+LocalVariableDeclarator.LINEAR.elapsedMillis()+"ms"); // System.out.println("Local context allocations per class:"); // for(Map.Entry<Class, Integer> entry: LocalLookupContext.ALLOCATORS.entrySet()) { // System.out.println(entry.getKey().getName()+" : "+entry.getValue()); // System.out.println("infix operator invocations: "+Timer.INFIX_OPERATOR_INVOCATION.elapsedMillis()+"ms"); // System.out.println("prefix operator invocations: "+Timer.PREFIX_OPERATOR_INVOCATION.elapsedMillis()+"ms"); // System.out.println("postfix operator invocations: "+Timer.POSTFIX_OPERATOR_INVOCATION.elapsedMillis()+"ms"); // System.out.println("list creation: "+Lists.LIST_CREATION.elapsedMillis()+"ms"); // System.out.println("Elements created: "+ElementImpl.elementsCreated); // System.out.println("Elements on which parent was invoked: "+ElementImpl.elementsOnWhichParentInvoked); // System.out.println("Elements ratio: "+(double)ElementImpl.elementsOnWhichParentInvoked/(double)ElementImpl.elementsCreated); } public ElementProvider<Type> typeProvider() { return new BasicDescendantProvider<Type>(namespaceProvider(), Type.class); } /** * Test the verification by invoking verify() for all namespace parts, and checking if the result is valid. */ @Test @Override public void testVerification() throws Exception { } protected final Project makeProject() throws ConfigException { Project project; LanguageRepository repo = new LanguageRepository(); Workspace workspace = new Workspace(repo); Java7 java = new Java7LanguageFactory().create(); repo.add(java); java.setPlugin(ProjectConfigurator.class, new JavaProjectConfigurator(Java7LanguageFactory.javaBaseJar())); XMLProjectLoader config = new XMLProjectLoader(workspace); project = config.project(projectFile(),null); return project; } }
package org.reactfx.value; import java.time.Duration; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import javafx.animation.Interpolatable; import javafx.beans.InvalidationListener; import javafx.beans.property.Property; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.Scene; import javafx.stage.Window; import org.reactfx.Change; import org.reactfx.EventStream; import org.reactfx.EventStreamBase; import org.reactfx.EventStreams; import org.reactfx.Observable; import org.reactfx.Subscription; import org.reactfx.collection.LiveList; import org.reactfx.util.HexaFunction; import org.reactfx.util.Interpolator; import org.reactfx.util.PentaFunction; import org.reactfx.util.TetraFunction; import org.reactfx.util.TriFunction; import org.reactfx.util.WrapperBase; /** * Adds more operations to {@link ObservableValue}. * * <p>Canonical observer of {@code Val<T>} is an <em>invalidation observer</em> * of type {@code Consumer<? super T>}, which accepts the _invalidated_ value. * This is different from {@linkplain InvalidationListener}, which does not * accept the invalidated value. */ public interface Val<T> extends ObservableValue<T>, Observable<Consumer<? super T>> { default void addInvalidationObserver(Consumer<? super T> observer) { addObserver(observer); } default void removeInvalidationObserver(Consumer<? super T> observer) { removeObserver(observer); } default Subscription observeInvalidations( Consumer<? super T> oldValueObserver) { return observe(oldValueObserver); } default Subscription pin() { return observeInvalidations(oldVal -> {}); } @Override default void addListener(InvalidationListener listener) { addInvalidationObserver(new InvalidationListenerWrapper<>(this, listener)); } @Override default void removeListener(InvalidationListener listener) { removeInvalidationObserver(new InvalidationListenerWrapper<>(this, listener)); } @Override default void addListener(ChangeListener<? super T> listener) { addInvalidationObserver(new ChangeListenerWrapper<>(this, listener)); } @Override default void removeListener(ChangeListener<? super T> listener) { removeInvalidationObserver(new ChangeListenerWrapper<>(this, listener)); } /** * Adds a change listener and returns a Subscription that can be * used to remove that listener. */ default Subscription observeChanges(ChangeListener<? super T> listener) { return observeInvalidations(new ChangeListenerWrapper<>(this, listener)); } /** * Returns a stream of invalidated values, which emits the invalidated value * (i.e. the old value) on each invalidation of this observable value. */ default EventStream<T> invalidations() { return new EventStreamBase<T>() { @Override protected Subscription observeInputs() { return observeInvalidations(this::emit); } }; } /** * Returns a stream of changed values, which emits the changed value * (i.e. the old and the new value) on each change of this observable value. */ default EventStream<Change<T>> changes() { return EventStreams.changesOf(this); } /** * Returns a stream of values of this {@linkplain Val}. The returned stream * emits the current value of this {@linkplain Val} for each new subscriber * and then the new value whenever the value changes. */ default EventStream<T> values() { return EventStreams.valuesOf(this); } /** * Checks whether this {@linkplain Val} holds a (non-null) value. * @return {@code true} if this {@linkplain Val} holds a (non-null) value, * {@code false} otherwise. */ default boolean isPresent() { return getValue() != null; } /** * Inverse of {@link #isPresent()}. */ default boolean isEmpty() { return getValue() == null; } /** * Invokes the given function if this {@linkplain Val} holds a (non-null) * value. * @param f function to invoke on the value currently held by this * {@linkplain Val}. */ default void ifPresent(Consumer<? super T> f) { T val = getValue(); if(val != null) { f.accept(val); } } /** * Returns the value currently held by this {@linkplain Val}. * @throws NoSuchElementException if there is no value present. */ default T getOrThrow() { T res = getValue(); if(res != null) { return res; } else { throw new NoSuchElementException(); } } /** * Returns the value currently held by this {@linkplain Val}. If this * {@linkplain Val} is empty, {@code defaultValue} is returned instead. * @param defaultValue value to return if there is no value present in * this {@linkplain Val}. */ default T getOrElse(T defaultValue) { T res = getValue(); if(res != null) { return res; } else { return defaultValue; } } /** * Like {@link #getOrElse(Object)}, except the default value is computed * by {@code defaultSupplier} only when necessary. * @param defaultSupplier computation to produce default value, if this * {@linkplain Val} is empty. */ default T getOrSupply(Supplier<? extends T> defaultSupplier) { T res = getValue(); if(res != null) { return res; } else { return defaultSupplier.get(); } } /** * Returns an {@code Optional} describing the value currently held by this * {@linkplain Val}, or and empty {@code Optional} if this {@linkplain Val} * is empty. */ default Optional<T> getOpt() { return Optional.ofNullable(getValue()); } /** * Returns a new {@linkplain Val} that holds the value held by this * {@linkplain Val}, or {@code other} when this {@linkplain Val} is empty. */ default Val<T> orElseConst(T other) { return orElseConst(this, other); } /** * Returns a new {@linkplain Val} that holds the value held by this * {@linkplain Val}, or the value held by {@code other} when this * {@linkplain Val} is empty. */ default Val<T> orElse(ObservableValue<T> other) { return orElse(this, other); } /** * Returns a new {@linkplain Val} that holds the same value * as this {@linkplain Val} when the value satisfies the predicate * and is empty when this {@linkplain Val} is empty or its value * does not satisfy the given predicate. */ default Val<T> filter(Predicate<? super T> p) { return filter(this, p); } /** * Returns a new {@linkplain Val} that holds a mapping of the value held by * this {@linkplain Val}, and is empty when this {@linkplain Val} is empty. * @param f function to map the value held by this {@linkplain Val}. */ default <U> Val<U> map(Function<? super T, ? extends U> f) { return map(this, f); } /** * Like {@link #map(Function)}, but also allows dynamically changing * map function. */ default <U> Val<U> mapDynamic( ObservableValue<? extends Function<? super T, ? extends U>> f) { return mapDynamic(this, f); } /** * Returns a new {@linkplain Val} that, when this {@linkplain Val} holds * value {@code x}, holds the value held by {@code f(x)}, and is empty * when this {@linkplain Val} is empty. */ default <U> Val<U> flatMap( Function<? super T, ? extends ObservableValue<U>> f) { return flatMap(this, f); } /** * Similar to {@link #flatMap(Function)}, except the returned Val is also * a Var. This means you can call {@code setValue()} and {@code bind()} * methods on the returned value, which delegate to the currently selected * Property. * * <p>As the value of this {@linkplain Val} changes, so does the selected * Property. When the Var returned from this method is bound, as the * selected Property changes, the previously selected Property is unbound * and the newly selected Property is bound. * * <p>Note that if the currently selected Property is {@code null}, then * calling {@code getValue()} on the returned value will return {@code null} * regardless of any prior call to {@code setValue()} or {@code bind()}. */ default <U> Var<U> selectVar( Function<? super T, ? extends Property<U>> f) { return selectVar(this, f); } default <U> Var<U> selectVar( Function<? super T, ? extends Property<U>> f, U resetToOnUnbind) { return selectVar(this, f, resetToOnUnbind); } /** * Returns a new {@linkplain Val} that only observes this {@linkplain Val} * when {@code condition} is {@code true}. More precisely, the returned * {@linkplain Val} observes {@code condition} whenever it itself has at * least one observer and observes {@code this} {@linkplain Val} whenever * it itself has at least one observer <em>and</em> the value of * {@code condition} is {@code true}. When {@code condition} is * {@code true}, the returned {@linkplain Val} has the same value as this * {@linkplain Val}. When {@code condition} is {@code false}, the returned * {@linkplain Val} has the value that was held by this {@linkplain Val} at * the time when {@code condition} changed to {@code false}. */ default Val<T> conditionOn(ObservableValue<Boolean> condition) { return conditionOn(this, condition); } /** * Equivalent to {@link #conditionOn(ObservableValue)} where the condition * is that {@code node} is <em>showing</em>: it is part of a scene graph * ({@link Node#sceneProperty()} is not {@code null}), its scene is part of * a window ({@link Scene#windowProperty()} is not {@code null}) and the * window is showing ({@link Window#showingProperty()} is {@code true}). */ default Val<T> conditionOnShowing(Node node) { return conditionOnShowing(this, node); } default SuspendableVal<T> suspendable() { return suspendable(this); } /** * Returns a new {@linkplain Val} that gradually transitions to the value * of this {@linkplain Val} every time this {@linkplain Val} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of this {@linkplain Val}), instead of any * intermediate interpolated value. * * @param duration function that calculates the desired duration of the * transition for two boundary values. * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ default Val<T> animate( BiFunction<? super T, ? super T, Duration> duration, Interpolator<T> interpolator) { return animate(this, duration, interpolator); } /** * Returns a new {@linkplain Val} that gradually transitions to the value * of this {@linkplain Val} every time this {@linkplain Val} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of this {@linkplain Val}), instead of any * intermediate interpolated value. * * @param duration the desired duration of the transition * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ default Val<T> animate( Duration duration, Interpolator<T> interpolator) { return animate(this, duration, interpolator); } /** * Let's this {@linkplain Val} be viewed as a {@linkplain Var}, with the * given {@code setValue} function serving the purpose of * {@link Var#setValue(Object)}. * @see Var#fromVal(ObservableValue, Consumer) */ default Var<T> asVar(Consumer<T> setValue) { return new VarFromVal<>(this, setValue); } /** * Returns a {@linkplain LiveList} view of this {@linkplain Val}. The * returned list will have size 1 when this {@linkplain Val} is present * (i.e. not {@code null}) and size 0 otherwise. */ default LiveList<T> asList() { return LiveList.wrapVal(this); } /** * Returns a {@linkplain Val} wrapper around {@linkplain ObservableValue}. * If the argument is already a {@code Val<T>}, no wrapping occurs and the * argument is returned as is. * Note that one rarely needs to use this method, because most of the time * one can use the appropriate static method directly to get the desired * result. For example, instead of * * <pre> * {@code * Val.wrap(obs).orElse(other) * } * </pre> * * one can write * * <pre> * {@code * Val.orElse(obs, other) * } * </pre> * * However, an explicit wrapper is necessary if access to * {@link #observeInvalidations(Consumer)}, or {@link #invalidations()} * is needed, since there is no direct static method equivalent for them. */ static <T> Val<T> wrap(ObservableValue<T> obs) { return obs instanceof Val ? (Val<T>) obs : new ValWrapper<>(obs); } static <T> Subscription observeChanges( ObservableValue<? extends T> obs, ChangeListener<? super T> listener) { if(obs instanceof Val) { return ((Val<? extends T>) obs).observeChanges(listener); } else { obs.addListener(listener); return () -> obs.removeListener(listener); } } static Subscription observeInvalidations( ObservableValue<?> obs, InvalidationListener listener) { obs.addListener(listener); return () -> obs.removeListener(listener); } static <T> Val<T> orElseConst(ObservableValue<? extends T> src, T other) { return new OrElseConst<>(src, other); } static <T> Val<T> orElse( ObservableValue<? extends T> src, ObservableValue<? extends T> other) { return new OrElse<>(src, other); } static <T> Val<T> filter( ObservableValue<T> src, Predicate<? super T> p) { return map(src, t -> p.test(t) ? t : null); } static <T, U> Val<U> map( ObservableValue<T> src, Function<? super T, ? extends U> f) { return new MappedVal<>(src, f); } static <T, U> Val<U> mapDynamic( ObservableValue<T> src, ObservableValue<? extends Function<? super T, ? extends U>> f) { return combine( src, f, (t, fn) -> t == null || fn == null ? null : fn.apply(t)); } static <T, U> Val<U> flatMap( ObservableValue<T> src, Function<? super T, ? extends ObservableValue<U>> f) { return new FlatMappedVal<>(src, f); } static <T, U> Var<U> selectVar( ObservableValue<T> src, Function<? super T, ? extends Property<U>> f) { return new FlatMappedVar<>(src, f); } static <T, U> Var<U> selectVar( ObservableValue<T> src, Function<? super T, ? extends Property<U>> f, U resetToOnUnbind) { return new FlatMappedVar<>(src, f, resetToOnUnbind); } static <T> Val<T> conditionOn( ObservableValue<T> obs, ObservableValue<Boolean> condition) { return flatMap(condition, con -> con ? obs : constant(obs.getValue())); } static <T> Val<T> conditionOnShowing(ObservableValue<T> obs, Node node) { return conditionOn(obs, showingProperty(node)); } static <T> SuspendableVal<T> suspendable(ObservableValue<T> obs) { if(obs instanceof SuspendableVal) { return (SuspendableVal<T>) obs; } else { Val<T> val = obs instanceof Val ? (Val<T>) obs : new ValWrapper<>(obs); return new SuspendableValWrapper<>(val); } } /** * Creates a new {@linkplain Val} that gradually transitions to the value * of the given {@linkplain ObservableValue} {@code obs} every time * {@code obs} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of {@code obs}), instead of any intermediate * interpolated value. * * @param obs observable value to animate * @param duration function that calculates the desired duration of the * transition for two boundary values. * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ static <T> Val<T> animate( ObservableValue<T> obs, BiFunction<? super T, ? super T, Duration> duration, Interpolator<T> interpolator) { return new AnimatedVal<>(obs, duration, interpolator); } /** * Creates a new {@linkplain Val} that gradually transitions to the value * of the given {@linkplain ObservableValue} {@code obs} every time * {@code obs} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of {@code obs}), instead of any intermediate * interpolated value. * * @param obs observable value to animate * @param duration the desired duration of the transition * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ static <T> Val<T> animate( ObservableValue<T> obs, Duration duration, Interpolator<T> interpolator) { return animate(obs, (a, b) -> duration, interpolator); } /** * Like {@link #animate(ObservableValue, BiFunction, Interpolator)}, but * uses the interpolation defined by the {@linkplain Interpolatable} type * {@code T}. */ static <T extends Interpolatable<T>> Val<T> animate( ObservableValue<T> obs, BiFunction<? super T, ? super T, Duration> duration) { return animate(obs, duration, Interpolator.get()); } /** * Like {@link #animate(ObservableValue, Duration, Interpolator)}, but * uses the interpolation defined by the {@linkplain Interpolatable} type * {@code T}. */ static <T extends Interpolatable<T>> Val<T> animate( ObservableValue<T> obs, Duration duration) { return animate(obs, duration, Interpolator.get()); } static <A, B, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, BiFunction<? super A, ? super B, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null) { return f.apply(src1.getValue(), src2.getValue()); } else { return null; } }, src1, src2); } static <A, B, C, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, TriFunction<? super A, ? super B, ? super C, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue()); } else { return null; } }, src1, src2, src3); } static <A, B, C, D, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, ObservableValue<D> src4, TetraFunction<? super A, ? super B, ? super C, ? super D, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null && src4.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue(), src4.getValue()); } else { return null; } }, src1, src2, src3, src4); } static <A, B, C, D, E, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, ObservableValue<D> src4, ObservableValue<E> src5, PentaFunction<? super A, ? super B, ? super C, ? super D, ? super E, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null && src4.getValue() != null && src5.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue(), src4.getValue(), src5.getValue()); } else { return null; } }, src1, src2, src3, src4, src5); } static <A, B, C, D, E, F, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, ObservableValue<D> src4, ObservableValue<E> src5, ObservableValue<F> src6, HexaFunction<? super A, ? super B, ? super C, ? super D, ? super E, ? super F, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null && src4.getValue() != null && src5.getValue() != null && src6.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue(), src4.getValue(), src5.getValue(), src6.getValue()); } else { return null; } }, src1, src2, src3, src4, src5, src6); } static <T> Val<T> create( Supplier<? extends T> computeValue, javafx.beans.Observable... dependencies) { return new ValBase<T>() { @Override protected Subscription connect() { InvalidationListener listener = obs -> invalidate(); for(javafx.beans.Observable dep: dependencies) { dep.addListener(listener); } return () -> { for(javafx.beans.Observable dep: dependencies) { dep.removeListener(listener); } }; } @Override protected T computeValue() { return computeValue.get(); } }; } static <T> Val<T> create( Supplier<? extends T> computeValue, EventStream<?> invalidations) { return new ValBase<T>() { @Override protected Subscription connect() { return invalidations.subscribe(x -> invalidate()); } @Override protected T computeValue() { return computeValue.get(); } }; } /** * Returns a constant {@linkplain Val} that holds the given value. * The value never changes and no notifications are ever produced. */ static <T> Val<T> constant(T value) { return new ConstVal<>(value); } /** * Returns a {@linkplain Val} whose value is {@code true} when {@code node} * is <em>showing</em>: it is part of a scene graph * ({@link Node#sceneProperty()} is not {@code null}), its scene is part of * a window ({@link Scene#windowProperty()} is not {@code null}) and the * window is showing ({@link Window#showingProperty()} is {@code true}). */ static Val<Boolean> showingProperty(Node node) { return Val .flatMap(node.sceneProperty(), Scene::windowProperty) .flatMap(Window::showingProperty) .orElseConst(false); } } class InvalidationListenerWrapper<T> extends WrapperBase<InvalidationListener> implements Consumer<T> { private final ObservableValue<T> obs; public InvalidationListenerWrapper( ObservableValue<T> obs, InvalidationListener listener) { super(listener); this.obs = obs; } @Override public void accept(T oldValue) { getWrappedValue().invalidated(obs); } } class ChangeListenerWrapper<T> extends WrapperBase<ChangeListener<? super T>> implements Consumer<T> { private final ObservableValue<T> obs; public ChangeListenerWrapper( ObservableValue<T> obs, ChangeListener<? super T> listener) { super(listener); this.obs = obs; } @Override public void accept(T oldValue) { T newValue = obs.getValue(); if(!Objects.equals(oldValue, newValue)) { getWrappedValue().changed(obs, oldValue, newValue); } } }
// modification, are permitted provided that the following conditions are met: // and/or other materials provided with the distribution. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. package br.com.carlosrafaelgn.fplay; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.text.InputType; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import java.io.File; import java.util.ArrayList; import java.util.Locale; import br.com.carlosrafaelgn.fplay.activity.ClientActivity; import br.com.carlosrafaelgn.fplay.list.AlbumArtFetcher; import br.com.carlosrafaelgn.fplay.list.FileFetcher; import br.com.carlosrafaelgn.fplay.list.FileList; import br.com.carlosrafaelgn.fplay.list.FileSt; import br.com.carlosrafaelgn.fplay.list.Song; import br.com.carlosrafaelgn.fplay.playback.Player; import br.com.carlosrafaelgn.fplay.ui.BgButton; import br.com.carlosrafaelgn.fplay.ui.BgListView; import br.com.carlosrafaelgn.fplay.ui.CustomContextMenu; import br.com.carlosrafaelgn.fplay.ui.FileView; import br.com.carlosrafaelgn.fplay.ui.SongAddingMonitor; import br.com.carlosrafaelgn.fplay.ui.UI; import br.com.carlosrafaelgn.fplay.ui.drawable.ColorDrawable; import br.com.carlosrafaelgn.fplay.ui.drawable.TextIconDrawable; public final class ActivityBrowser2 extends ActivityBrowserView implements View.OnClickListener, DialogInterface.OnClickListener, DialogInterface.OnCancelListener, BgListView.OnBgListViewKeyDownObserver { private static final int MNU_REMOVEFAVORITE = 100; private FileSt lastClickedFavorite; private TextView lblPath, sep, sep2; private BgListView list; private FileList fileList; private RelativeLayout panelSecondary, panelLoading; private EditText txtURL, txtTitle; private BgButton btnGoBack, btnRadio, btnURL, chkFavorite, chkAlbumArt, btnHome, chkAll, btnGoBackToPlayer, btnAdd, btnPlay; private AlbumArtFetcher albumArtFetcher; private int checkedCount; private boolean loading, isAtHome, verifyAlbumWhenChecking, albumArtArea; @Override public CharSequence getTitle() { return getText(R.string.add_songs); } private void updateOverallLayout() { RelativeLayout.LayoutParams rp; if (isAtHome) { lblPath.setPadding(0, 0, 0, 0); rp = (RelativeLayout.LayoutParams)lblPath.getLayoutParams(); rp.height = 0; lblPath.setLayoutParams(rp); panelSecondary.setPadding(0, 0, 0, 0); btnGoBackToPlayer.setVisibility(View.GONE); sep.setVisibility(View.GONE); chkAll.setVisibility(View.GONE); rp = new RelativeLayout.LayoutParams(UI.defaultControlSize, UI.defaultControlSize); rp.leftMargin = UI._8dp; rp.rightMargin = UI._8dp; rp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); chkFavorite.setNextFocusUpId(R.id.list); btnHome.setLayoutParams(rp); btnHome.setNextFocusUpId(R.id.list); btnHome.setNextFocusRightId(R.id.list); UI.setNextFocusForwardId(btnHome, R.id.list); chkAll.setNextFocusUpId(R.id.list); btnGoBack.setNextFocusUpId(R.id.list); btnGoBack.setNextFocusLeftId(R.id.list); UI.setNextFocusForwardId(list, R.id.btnGoBack); } else { rp = (RelativeLayout.LayoutParams)lblPath.getLayoutParams(); rp.height = RelativeLayout.LayoutParams.WRAP_CONTENT; lblPath.setLayoutParams(rp); if (UI.isLargeScreen) lblPath.setPadding(UI._4dp, UI._4dp - UI.thickDividerSize, UI._4dp, UI._4dp); else lblPath.setPadding(UI._2dp, UI._2dp - UI.thickDividerSize, UI._2dp, UI._2dp); UI.prepareControlContainerPaddingOnly(panelSecondary, true, false); btnGoBackToPlayer.setVisibility(View.VISIBLE); sep.setVisibility(View.VISIBLE); chkAll.setVisibility(View.VISIBLE); rp = new RelativeLayout.LayoutParams(UI.defaultControlSize, UI.defaultControlSize); rp.leftMargin = UI._8dp; rp.rightMargin = UI._8dp; rp.addRule(RelativeLayout.LEFT_OF, R.id.sep); chkFavorite.setNextFocusUpId(R.id.btnGoBackToPlayer); btnHome.setLayoutParams(rp); btnHome.setNextFocusUpId((checkedCount != 0) ? R.id.btnAdd : R.id.btnGoBackToPlayer); btnHome.setNextFocusRightId(R.id.chkAll); UI.setNextFocusForwardId(btnHome, R.id.chkAll); chkAll.setNextFocusUpId((checkedCount != 0) ? R.id.btnPlay : R.id.btnGoBackToPlayer); btnGoBack.setNextFocusUpId(R.id.btnGoBackToPlayer); btnGoBack.setNextFocusLeftId((checkedCount != 0) ? R.id.btnPlay : R.id.btnGoBackToPlayer); UI.setNextFocusForwardId(list, R.id.btnGoBackToPlayer); btnGoBackToPlayer.setNextFocusRightId((checkedCount != 0) ? R.id.btnAdd : R.id.btnGoBack); UI.setNextFocusForwardId(btnGoBackToPlayer, (checkedCount != 0) ? R.id.btnAdd : R.id.btnGoBack); } } private void updateButtons() { if (!isAtHome != (chkAll.getVisibility() == View.VISIBLE)) updateOverallLayout(); if ((checkedCount != 0) != (btnAdd.getVisibility() == View.VISIBLE)) { if (checkedCount != 0) { btnAdd.setVisibility(View.VISIBLE); sep2.setVisibility(View.VISIBLE); btnPlay.setVisibility(View.VISIBLE); btnGoBack.setNextFocusLeftId(R.id.btnPlay); btnHome.setNextFocusUpId(R.id.btnAdd); chkAll.setNextFocusUpId(R.id.btnPlay); btnGoBackToPlayer.setNextFocusRightId(R.id.btnAdd); UI.setNextFocusForwardId(btnGoBackToPlayer, R.id.btnAdd); } else { btnAdd.setVisibility(View.GONE); sep2.setVisibility(View.GONE); btnPlay.setVisibility(View.GONE); btnGoBack.setNextFocusLeftId(R.id.btnGoBackToPlayer); btnHome.setNextFocusUpId(R.id.btnGoBackToPlayer); chkAll.setNextFocusUpId(R.id.btnGoBackToPlayer); btnGoBackToPlayer.setNextFocusRightId(R.id.btnGoBack); UI.setNextFocusForwardId(btnGoBackToPlayer, R.id.btnGoBack); } } } private void selectAlbumSongs(int position) { final boolean check = fileList.getItemT(position).isChecked; FileSt file; position++; while (position < fileList.getCount() && (file = fileList.getItemT(position)).specialType == 0) { file.isChecked = check; position++; } checkedCount = 0; for (int i = fileList.getCount() - 1; i >= 0; i if (fileList.getItemT(i).isChecked) checkedCount++; } chkAll.setChecked(checkedCount == fileList.getCount()); fileList.notifyCheckedChanged(); updateButtons(); } private void addPlayCheckedItems(final boolean play) { if (checkedCount <= 0) return; try { boolean addingFolder = false; int c = 0; final FileSt[] fs = new FileSt[checkedCount]; for (int i = fileList.getCount() - 1, j = checkedCount - 1; i >= 0 && j >= 0; i final FileSt file = fileList.getItemT(i); if (file.isChecked && file.specialType != FileSt.TYPE_ALBUM_ITEM) { if (!addingFolder) { c++; if (c > 1 || file.specialType != 0 || file.isDirectory) addingFolder = true; } fs[j] = file; j } } Player.songs.addingStarted(); SongAddingMonitor.start(getHostActivity()); (new Thread("Checked File Adder Thread") { @Override public void run() { boolean addingFolder = false; try { Throwable firstException = null; final ArrayList<FileSt> filesToAdd = new ArrayList<FileSt>(256); for (int i = 0; i < fs.length; i++) { if (Player.getState() == Player.STATE_TERMINATED || Player.getState() == Player.STATE_TERMINATING) { Player.songs.addingEnded(); return; } final FileSt file = fs[i]; if (file == null) continue; if (!file.isDirectory) { filesToAdd.add(file); if (!addingFolder && filesToAdd.size() > 1) addingFolder = true; } else { addingFolder = true; final FileFetcher ff = FileFetcher.fetchFilesInThisThread(file.path, null, false, true, true, false, false); if (ff.getThrowedException() == null) { if (ff.count <= 0) continue; filesToAdd.ensureCapacity(filesToAdd.size() + ff.count); for (int j = 0; j < ff.count; j++) filesToAdd.add(ff.files[j]); } else { if (firstException == null) firstException = ff.getThrowedException(); } } } if (filesToAdd.size() <= 0) { if (firstException != null) Player.songs.onFilesFetched(null, firstException); else Player.songs.addingEnded(); } else { Player.songs.addFiles(null, filesToAdd.iterator(), filesToAdd.size(), play, addingFolder, false); } } catch (Throwable ex) { Player.songs.addingEnded(); } } }).start(); if (play && addingFolder && Player.goBackWhenPlayingFolders) finish(0, null, true); } catch (Throwable ex) { Player.songs.addingEnded(); UI.toast(getApplication(), ex.getMessage()); } } @Override public void loadingProcessChanged(boolean started) { if (UI.browserActivity != this) return; loading = started; if (panelLoading != null) panelLoading.setVisibility(started ? View.VISIBLE : View.GONE); if (fileList != null) { verifyAlbumWhenChecking = ((fileList.getCount() > 0) && (fileList.getItemT(0).specialType == FileSt.TYPE_ALBUM_ITEM)); if (list != null && !list.isInTouchMode()) list.centerItem(fileList.getSelection(), false); } if (list != null) list.setCustomEmptyText(started ? "" : null); if (!started) updateButtons(); } @Override public View createView() { return new FileView(Player.getService(), albumArtFetcher, true, true); } @Override public void processItemButtonClick(int position, boolean add) { //somehow, Google Play indicates a NullPointerException, either here or //in processItemClick, in a LG Optimus L3 (2.3.3) :/ if (list == null || fileList == null) return; if (!add && !list.isInTouchMode()) fileList.setSelection(position, true); final FileSt file = fileList.getItemT(position); if (file == null) //same as above return; if (file.specialType == FileSt.TYPE_ALBUM_ITEM) { selectAlbumSongs(position); } else { if (file.isChecked) { if (verifyAlbumWhenChecking) { //check the album if all of its songs are checked while (--position >= 0) { final FileSt album = fileList.getItemT(position); if (album.specialType == FileSt.TYPE_ALBUM_ITEM) { boolean checkAlbum = true; while (++position < fileList.getCount()) { final FileSt song = fileList.getItemT(position); if (song.specialType != 0) break; if (!song.isChecked) { checkAlbum = false; break; } } if (checkAlbum && !album.isChecked) { album.isChecked = true; checkedCount++; fileList.notifyCheckedChanged(); } break; } } } checkedCount++; if (checkedCount >= fileList.getCount()) { checkedCount = fileList.getCount(); chkAll.setChecked(true); } } else { if (verifyAlbumWhenChecking) { //uncheck the album while (--position >= 0) { final FileSt album = fileList.getItemT(position); if (album.specialType == FileSt.TYPE_ALBUM_ITEM) { if (album.isChecked) { album.isChecked = false; checkedCount fileList.notifyCheckedChanged(); } break; } } } checkedCount chkAll.setChecked(false); if (checkedCount < 0) checkedCount = 0; } updateButtons(); } } @Override public void processItemClick(int position) { //somehow, Google Play indicates a NullPointerException, either here or //in processItemButtonClick, in a LG Optimus L3 (2.3.3) :/ if (list == null || fileList == null) return; if (!UI.doubleClickMode || fileList.getSelection() == position) { final FileSt file = fileList.getItemT(position); if (file == null) //same as above return; if (file.isDirectory && file.specialType != FileSt.TYPE_ALBUM_ITEM) { navigateTo(file.path, null); } else { file.isChecked = !file.isChecked; if (file.specialType != FileSt.TYPE_ALBUM_ITEM) fileList.notifyCheckedChanged(); processItemButtonClick(position, true); } } else { fileList.setSelection(position, true); } } @Override public void processItemLongClick(int position) { lastClickedFavorite = fileList.getItemT(position); if (lastClickedFavorite.specialType == FileSt.TYPE_FAVORITE) CustomContextMenu.openContextMenu(chkAll, this); else lastClickedFavorite = null; } private void processMenuItemClick(int id) { switch (id) { case MNU_REMOVEFAVORITE: if (lastClickedFavorite != null) { Player.removeFavoriteFolder(lastClickedFavorite.path); fileList.setSelection(fileList.indexOf(lastClickedFavorite), false); fileList.removeSelection(); fileList.setSelection(-1, false); } else { UI.toast(getApplication(), R.string.msg_select_favorite_remove); } lastClickedFavorite = null; break; } } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { UI.prepare(menu); menu.add(0, MNU_REMOVEFAVORITE, 0, R.string.remove_favorite) .setOnMenuItemClickListener(this) .setIcon(new TextIconDrawable(UI.ICON_FAVORITE_OFF)); } @Override public boolean onMenuItemClick(MenuItem item) { processMenuItemClick(item.getItemId()); return true; } private void navigateTo(String to, String from) { if (isAtHome) Player.originalPath = to; isAtHome = (to.length() == 0); final boolean fav = ((to.length() > 1) && (to.charAt(0) == File.separatorChar)); final boolean others = !isAtHome; albumArtArea = false; if (fav) { btnRadio.setVisibility(View.GONE); btnURL.setVisibility(View.GONE); btnGoBack.setNextFocusRightId(R.id.chkFavorite); UI.setNextFocusForwardId(btnGoBack, R.id.chkFavorite); btnHome.setNextFocusLeftId(R.id.chkFavorite); chkFavorite.setChecked(Player.isFavoriteFolder(to)); chkFavorite.setVisibility(View.VISIBLE); chkAlbumArt.setVisibility(View.GONE); btnHome.setVisibility(View.VISIBLE); } else if (others) { albumArtArea = ((to.length() > 0) && ((to.charAt(0) == FileSt.ALBUM_ROOT_CHAR) || (to.charAt(0) == FileSt.ARTIST_ROOT_CHAR)));// (to.startsWith(FileSt.ALBUM_PREFIX) || to.startsWith(FileSt.ARTIST_ALBUM_PREFIX)); btnRadio.setVisibility(View.GONE); btnURL.setVisibility(View.GONE); if (albumArtArea) { btnGoBack.setNextFocusRightId(R.id.chkAlbumArt); UI.setNextFocusForwardId(btnGoBack, R.id.chkAlbumArt); btnHome.setNextFocusLeftId(R.id.chkAlbumArt); } else { btnGoBack.setNextFocusRightId(R.id.btnHome); UI.setNextFocusForwardId(btnGoBack, R.id.btnHome); btnHome.setNextFocusLeftId(R.id.btnGoBack); } chkFavorite.setVisibility(View.GONE); chkAlbumArt.setVisibility(albumArtArea ? View.VISIBLE : View.GONE); btnHome.setVisibility(View.VISIBLE); } else { btnRadio.setVisibility(View.VISIBLE); btnURL.setVisibility(View.VISIBLE); btnGoBack.setNextFocusRightId(R.id.btnRadio); UI.setNextFocusForwardId(btnGoBack, R.id.btnRadio); chkFavorite.setVisibility(View.GONE); chkAlbumArt.setVisibility(View.GONE); btnHome.setVisibility(View.GONE); } checkedCount = 0; chkAll.setChecked(false); updateButtons(); Player.path = to; lblPath.setText(((to.length() > 0) && (to.charAt(0) != File.separatorChar)) ? to.substring(to.indexOf(FileSt.FAKE_PATH_ROOT_CHAR) + 1).replace(FileSt.FAKE_PATH_SEPARATOR_CHAR, File.separatorChar) : to); final boolean sectionsEnabled = ((to.length() > 0) && (to.startsWith(FileSt.ARTIST_PREFIX) || to.startsWith(FileSt.ALBUM_PREFIX))); list.setScrollBarType(((UI.browserScrollBarType == BgListView.SCROLLBAR_INDEXED) && !sectionsEnabled) ? BgListView.SCROLLBAR_LARGE : UI.browserScrollBarType); fileList.setPath(to, from, list.isInTouchMode(), (UI.browserScrollBarType == BgListView.SCROLLBAR_INDEXED) && sectionsEnabled); } @Override public boolean onBgListViewKeyDown(BgListView bgListView, int keyCode, KeyEvent event) { int p; switch (keyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: if (btnURL.getVisibility() == View.VISIBLE) btnURL.requestFocus(); else if (chkAll.getVisibility() == View.VISIBLE) chkAll.requestFocus(); else btnGoBack.requestFocus(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (btnGoBackToPlayer.getVisibility() == View.VISIBLE) btnGoBackToPlayer.requestFocus(); else btnGoBack.requestFocus(); return true; case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: p = fileList.getSelection(); if (p >= 0) processItemClick(p); return true; case KeyEvent.KEYCODE_0: case KeyEvent.KEYCODE_SPACE: p = fileList.getSelection(); if (p >= 0) { final FileSt file = fileList.getItemT(p); file.isChecked = !file.isChecked; processItemButtonClick(p, false); } return true; } return false; } @Override public void onClick(View view) { if (view == btnGoBack) { if (Player.path.length() > 1) { if (Player.path.equals(Player.originalPath)) { navigateTo("", Player.path); return; } if (Player.path.charAt(0) != File.separatorChar) { final int fakePathIdx = Player.path.indexOf(FileSt.FAKE_PATH_ROOT_CHAR); final String realPath = Player.path.substring(0, fakePathIdx); final String fakePath = Player.path.substring(fakePathIdx + 1); int i = realPath.lastIndexOf(File.separatorChar, realPath.length() - 1); if (i < 0) navigateTo("", Player.path); else navigateTo(realPath.substring(0, i) + FileSt.FAKE_PATH_ROOT + fakePath.substring(0, fakePath.lastIndexOf(FileSt.FAKE_PATH_SEPARATOR_CHAR)), realPath + FileSt.FAKE_PATH_ROOT); } else { final int i = Player.path.lastIndexOf(File.separatorChar, Player.path.length() - 1); final String originalPath = Player.path; navigateTo((i <= 0) ? File.separator : Player.path.substring(0, i), ((i >= 0) && (i < originalPath.length())) ? originalPath.substring(i + 1) : null); } } else if (Player.path.length() == 1) { navigateTo("", Player.path); } else { finish(0, view, true); } } else if (view == btnRadio) { startActivity(new ActivityBrowserRadio(), 1, view, true); } else if (view == btnURL) { final Context ctx = getHostActivity(); final LinearLayout l = (LinearLayout)UI.createDialogView(ctx, null); TextView lbl = new TextView(ctx); lbl.setText(R.string.url); lbl.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp); l.addView(lbl); txtURL = new EditText(ctx); txtURL.setContentDescription(ctx.getText(R.string.url)); txtURL.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp); txtURL.setInputType(InputType.TYPE_TEXT_VARIATION_URI); LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); p.topMargin = UI._DLGsppad; p.bottomMargin = UI._DLGsppad << 1; txtURL.setLayoutParams(p); l.addView(txtURL); lbl = new TextView(ctx); lbl.setText(R.string.description); lbl.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp); l.addView(lbl); txtTitle = new EditText(ctx); txtTitle.setContentDescription(ctx.getText(R.string.description)); txtTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp); txtTitle.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); txtTitle.setSingleLine(); p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); p.topMargin = UI._DLGsppad; txtTitle.setLayoutParams(p); l.addView(txtTitle); UI.prepareDialogAndShow((new AlertDialog.Builder(ctx)) .setTitle(getText(R.string.add_url_title)) .setView(l) .setPositiveButton(R.string.add, this) .setNegativeButton(R.string.cancel, this) .create()); } else if (view == chkFavorite) { if (Player.path.length() <= 1) return; if (chkFavorite.isChecked()) Player.addFavoriteFolder(Player.path); else Player.removeFavoriteFolder(Player.path); } else if (view == chkAlbumArt) { UI.albumArt = chkAlbumArt.isChecked(); for (int i = list.getChildCount() - 1; i >= 0; i final View v = list.getChildAt(i); if (v instanceof FileView) ((FileView)v).refreshItem(); } } if (view == btnHome) { if (Player.path.length() > 0) navigateTo("", Player.path); } else if (view == chkAll) { if (loading) return; final boolean ck = chkAll.isChecked(); int i = fileList.getCount() - 1; checkedCount = (ck ? (i + 1) : 0); for (; i >= 0; i fileList.getItemT(i).isChecked = ck; fileList.notifyCheckedChanged(); updateButtons(); } else if (view == btnGoBackToPlayer) { finish(0, view, true); } else if (view == btnAdd) { addPlayCheckedItems(false); } else if (view == btnPlay) { addPlayCheckedItems(true); } } @Override public void onClick(DialogInterface dialog, int which) { if (which == AlertDialog.BUTTON_POSITIVE) { String url = txtURL.getText().toString().trim(); if (url.length() >= 4) { int s = 7; final String urlLC = url.toLowerCase(Locale.US); if (urlLC.startsWith("http: url = "http://" + url.substring(7); } else if (urlLC.startsWith("https: url = "https://" + url.substring(8); s = 8; } else { url = "http://" + url; } String title = txtTitle.getText().toString().trim(); if (title.length() == 0) title = url.substring(s); final int p = Player.songs.getCount(); Player.songs.add(new Song(url, title), -1); Player.setSelectionAfterAdding(p); } } txtURL = null; txtTitle = null; } @Override public void onCancel(DialogInterface dialog) { onClick(dialog, AlertDialog.BUTTON_NEGATIVE); } public void activityFinished(ClientActivity activity, int requestCode, int code) { if (requestCode == 1 && code == -1) finish(0, null, true); } @Override protected boolean onBackPressed() { if (UI.backKeyAlwaysReturnsToPlayerWhenBrowsing || isAtHome) return false; if (chkAll != null && checkedCount != 0) { chkAll.setChecked(false); checkedCount = 0; for (int i = fileList.getCount() - 1; i >= 0; i fileList.getItemT(i).isChecked = false; fileList.notifyCheckedChanged(); updateButtons(); return true; } onClick(btnGoBack); return true; } @Override protected void onCreate() { if (Player.path == null) Player.path = ""; if (Player.originalPath == null) Player.originalPath = ""; isAtHome = (Player.path.length() == 0); UI.browserActivity = this; fileList = new FileList(); //We cannot use getDrawable() here, as sometimes the bitmap used by the drawable //is internally cached, therefore, causing an exception when we try to use it //after being recycled... //final Resources res = getResources(); //try { // ic_closed_folder = new ReleasableBitmapWrapper(BitmapFactory.decodeResource(res, R.drawable.ic_closed_folder)); //} catch (Throwable ex) { albumArtFetcher = new AlbumArtFetcher(); } @SuppressWarnings("deprecation") @Override protected void onCreateLayout(boolean firstCreation) { setContentView(R.layout.activity_browser2); final TextView lblLoading = (TextView)findViewById(R.id.lblLoading); UI.largeText(lblLoading); lblLoading.setTextColor(UI.colorState_text_listitem_static); lblPath = (TextView)findViewById(R.id.lblPath); lblPath.setTextColor(UI.colorState_text_highlight_static); UI.mediumText(lblPath); lblPath.setBackgroundDrawable(new ColorDrawable(UI.color_highlight)); list = (BgListView)findViewById(R.id.list); list.setOnKeyDownObserver(this); fileList.setObserver(list); panelLoading = (RelativeLayout)findViewById(R.id.panelLoading); btnGoBack = (BgButton)findViewById(R.id.btnGoBack); btnGoBack.setOnClickListener(this); btnGoBack.setIcon(UI.ICON_GOBACK); btnRadio = (BgButton)findViewById(R.id.btnRadio); btnRadio.setOnClickListener(this); btnRadio.setDefaultHeight(); btnRadio.setCompoundDrawables(new TextIconDrawable(UI.ICON_RADIO, UI.color_text, UI.defaultControlContentsSize), null, null, null); btnURL = (BgButton)findViewById(R.id.btnURL); btnURL.setOnClickListener(this); btnURL.setDefaultHeight(); btnURL.setCompoundDrawables(new TextIconDrawable(UI.ICON_LINK, UI.color_text, UI.defaultControlContentsSize), null, null, null); chkFavorite = (BgButton)findViewById(R.id.chkFavorite); chkFavorite.setOnClickListener(this); chkFavorite.setIcon(UI.ICON_FAVORITE_ON, UI.ICON_FAVORITE_OFF, false, false, true, true); chkFavorite.setContentDescription(getText(R.string.remove_from_favorites), getText(R.string.add_to_favorites)); chkAlbumArt = (BgButton)findViewById(R.id.chkAlbumArt); chkAlbumArt.setOnClickListener(this); chkAlbumArt.setIcon(UI.ICON_ALBUMART, UI.ICON_ALBUMART_OFF, UI.albumArt, false, true, true); btnHome = (BgButton)findViewById(R.id.btnHome); btnHome.setOnClickListener(this); btnHome.setIcon(UI.ICON_HOME); panelSecondary = (RelativeLayout)findViewById(R.id.panelSecondary); sep = (TextView)findViewById(R.id.sep); RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(UI.strokeSize, UI.defaultControlContentsSize); rp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); rp.addRule(RelativeLayout.LEFT_OF, R.id.chkAll); rp.leftMargin = UI._8dp; rp.rightMargin = UI._8dp; sep.setLayoutParams(rp); sep.setBackgroundDrawable(new ColorDrawable(UI.color_highlight)); chkAll = (BgButton)findViewById(R.id.chkAll); chkAll.setOnClickListener(this); chkAll.setIcon(UI.ICON_OPTCHK, UI.ICON_OPTUNCHK, false, true, true, true); chkAll.setContentDescription(getText(R.string.unselect_everything), getText(R.string.select_everything)); btnGoBackToPlayer = (BgButton)findViewById(R.id.btnGoBackToPlayer); btnGoBackToPlayer.setTextColor(UI.colorState_text_reactive); btnGoBackToPlayer.setOnClickListener(this); btnGoBackToPlayer.setCompoundDrawables(new TextIconDrawable(UI.ICON_RIGHT, UI.color_text, UI.defaultControlContentsSize), null, null, null); btnGoBackToPlayer.setDefaultHeight(); btnAdd = (BgButton)findViewById(R.id.btnAdd); btnAdd.setTextColor(UI.colorState_text_reactive); btnAdd.setOnClickListener(this); btnAdd.setIcon(UI.ICON_ADD, true, false); sep2 = (TextView)findViewById(R.id.sep2); rp = new RelativeLayout.LayoutParams(UI.strokeSize, UI.defaultControlContentsSize); rp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); rp.addRule(RelativeLayout.LEFT_OF, R.id.btnPlay); rp.leftMargin = UI._8dp; rp.rightMargin = UI._8dp; sep2.setLayoutParams(rp); sep2.setBackgroundDrawable(new ColorDrawable(UI.color_highlight)); btnPlay = (BgButton)findViewById(R.id.btnPlay); btnPlay.setTextColor(UI.colorState_text_reactive); btnPlay.setOnClickListener(this); btnPlay.setIcon(UI.ICON_PLAY, true, false); if (UI.isLargeScreen) { lblPath.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._22sp); } else if (UI.isLowDpiScreen) { btnRadio.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._18sp); btnURL.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._18sp); } if (UI.browserScrollBarType == BgListView.SCROLLBAR_INDEXED || UI.browserScrollBarType == BgListView.SCROLLBAR_LARGE) { UI.prepareControlContainer(findViewById(R.id.panelControls), false, true); } else { if (UI.extraSpacing) { final RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, UI.defaultControlSize); lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); lp.rightMargin = UI._8dp; btnURL.setLayoutParams(lp); } UI.prepareControlContainerWithoutRightPadding(findViewById(R.id.panelControls), false, true); } UI.prepareControlContainer(panelSecondary, true, false); if (UI.isLargeScreen) UI.prepareViewPaddingForLargeScreen(list, 0, 0); UI.prepareEdgeEffectColor(getApplication()); //this is the opposite as in updateButtons(), to force updateOverallLayout() //to be called at least once if (!isAtHome == (chkAll.getVisibility() == View.VISIBLE)) updateOverallLayout(); navigateTo(Player.path, null); } @Override protected void onPause() { SongAddingMonitor.stop(); fileList.setObserver(null); } @Override protected void onResume() { UI.browserActivity = this; fileList.setObserver(list); SongAddingMonitor.start(getHostActivity()); if (loading != fileList.isLoading()) loadingProcessChanged(fileList.isLoading()); } @Override protected void onOrientationChanged() { if (UI.isLargeScreen && list != null) UI.prepareViewPaddingForLargeScreen(list, 0, 0); } @Override protected void onCleanupLayout() { lastClickedFavorite = null; lblPath = null; list = null; panelLoading = null; panelSecondary = null; btnGoBack = null; btnRadio = null; btnURL = null; chkFavorite = null; chkAlbumArt = null; btnHome = null; sep = null; chkAll = null; btnGoBackToPlayer = null; btnAdd = null; sep2 = null; btnPlay = null; } @Override protected void onDestroy() { UI.browserActivity = null; fileList.cancel(); fileList = null; if (albumArtFetcher != null) { albumArtFetcher.stopAndCleanup(); albumArtFetcher = null; } } }
package ch.ntb.inf.deep.eclipse.ui.view; import java.io.IOException; import java.io.OutputStream; import ch.ntb.mcdp.blackbox.uart.Uart0; public class USBLogWriter extends Thread { private OutputStream out; private boolean isRunning = true; public USBLogWriter(String name, OutputStream out){ super(name); this.out = out; } @Override public void run(){ byte[] readed = null; try { while(isRunning){ readed = Uart0.read(); if(readed != null){ out.write(readed); } Thread.sleep(50); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public void setRunning(boolean run){ isRunning = run; } }
package ch.unizh.ini.caviar.chip; import ch.unizh.ini.caviar.aemonitor.*; import ch.unizh.ini.caviar.event.*; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.event.BasicEvent; import ch.unizh.ini.caviar.event.OutputEventIterator; import java.util.logging.Logger; /** * An abstract 2D event extractor for 16 bit raw addresses. It is called with addresses and timestamps and extracts * these to {X, Y, type} arrays based on methods that you define by subclassing and overriding the abstract methods. * * xMask, * yMask, typeMask mask for x, y address and cell type, and xShift, yShift, typeShift say how many bits to shift after * masking, xFlip,yFlip,typeFlip use the chip size to flip the x,y, and type to invert the addresses. * * @author tobi */ abstract public class TypedEventExtractor<T extends BasicEvent> implements EventExtractor2D, java.io.Serializable { static Logger log=Logger.getLogger("ch.unizh.ini.caviar.chip"); // protected AEChip chip; protected int xmask,ymask; protected byte xshift,yshift; protected int typemask; protected byte typeshift; protected AEChip chip=null; protected boolean flipx=false, flipy=false, rotate=false; protected boolean fliptype=false; protected boolean hexArrangement=false; // the reused output eventpacket protected EventPacket out=null; // AEPacket2D outReused=new AEPacket2D(); Class eventClass=TypedEvent.class; /** determines subSampling of rendered events (for speed) */ private boolean subsamplingEnabled=false; private int subsampleThresholdEventCount=50000; private short sizex,sizey; // these are size-1 (e.g. if 128 pixels, sizex=127). used for flipping below. private byte sizetype; // /** Creates a new instance of RetinaEventExtractor */ // public TypedEventExtractor() { /** Creates a new instance of RetinaEventExtractor * @param aechip the chip this extractor extracts */ public TypedEventExtractor(AEChip aechip) { chip=aechip; setchipsizes(); } private void setchipsizes(){ sizex=(short)(chip.getSizeX()-1); sizey=(short)(chip.getSizeY()-1); sizetype=(byte)(chip.getNumCellTypes()-1); } /** * Gets X from raw address. declared final for speed, cannot be overridden in subclass. It expects addr to be from a certain * format like ???? XXX? X?X? ????. The mask 0000 1110 1010 0000 will get those Xs. So, what's left is 0000 XXX0 X0X0 0000. * Then it is shifted (the triple means zero-padding regardless of sign, necessary because addr is not defined as unsigned!) * with the xshift parameter. So, in this case e.g. 5, what will make the result 0000 0000 0XXX 0X0X (0-64). If the incoming * addr is big-endian versus small-endian the entire bit sequence has to be reversed of course. This is not what is done by * flipx! That is just a boolean that results in the chip size minus the result otherwise. So, in the above example the * place for X is still expected in the same spots (the mask is not inverted). Last remark: the masks are normally continuous, * no weird blanks within them. :-) Ultimate remark: a mask of size 1 will invert the value if the flip parameter is set. * Super-last remark: the parameter sizex should be 7 (not 8) for a mask of size 3 (000 - 111), like mentioned before. So, * the sizex and sizey parameters in this TypedEventExtractor class are decremented with one compared to the same parameters * in the class AEChip. * *@param addr the raw address. *@return physical address */ public short getXFromAddress(int addr){ if(!flipx) return ((short)((addr&xmask)>>>xshift)); else return (short)(sizex - ((int)((addr&xmask)>>>xshift))); // e.g. chip.sizex=32, sizex=31, addr=0, getX=31, addr=31, getX=0 } /** gets Y from raw address. declared final for speed, cannot be overridden in subclass. *@param addr the raw address. *@return physical address */ public short getYFromAddress(int addr){ if(!flipy) return ((short)((addr&ymask)>>>yshift)); else return (short)(sizey-((int)((addr&ymask)>>>yshift))); } /** gets type from raw address. declared final for speed, cannot be overridden in subclass. *@param addr the raw address. *@return physical address */ public byte getTypeFromAddress(int addr){ if(!fliptype) return (byte)((addr&typemask)>>>typeshift); else return (byte)(sizetype-(byte)((addr&typemask)>>>typeshift)); } /** extracts the meaning of the raw events. *@param in the raw events, can be null *@return out the processed events. these are partially processed in-place. empty packet is returned if null is supplied as in. */ synchronized public EventPacket extractPacket(AEPacketRaw in) { if(out==null){ out=new EventPacket<T>(chip.getEventClass()); }else{ out.clear(); } if(in==null) return out; extractPacket(in,out); return out; } /** * Extracts the meaning of the raw events. This form is used to supply an output packet. This method is used for real time * event filtering using a buffer of output events local to data acquisition. An AEPacketRaw may contain multiple events, * not all of them have to sent out as EventPackets. An AEPacketRaw is a set(!) of addresses and corresponding timing moments. * * A first filter (independent from the other ones) is implemented by subSamplingEnabled and getSubsampleThresholdEventCount. * The latter may limit the amount of samples in one package to say 50,000. If there are 160,000 events and there is a sub sample * threshold of 50,000, a "skip parameter" set to 3. Every so now and then the routine skips with 4, so we end up with 50,000. * It's an approximation, the amount of events may be less than 50,000. The events are extracted uniform from the input. * * @param in the raw events, can be null * @param out the processed events. these are partially processed in-place. empty packet is returned if null is * supplied as input. */ synchronized public void extractPacket(AEPacketRaw in, EventPacket out) { out.clear(); if(in==null) return; int n=in.getNumEvents(); //addresses.length; int skipBy=1, incEach = 0, j = 0; if(subsamplingEnabled){ skipBy = n/getSubsampleThresholdEventCount(); incEach = getSubsampleThresholdEventCount() / (n % getSubsampleThresholdEventCount()); } if (skipBy==0) {incEach = 0; skipBy = 1; } int[] a=in.getAddresses(); int[] timestamps=in.getTimestamps(); boolean hasTypes=false; if(chip!=null) hasTypes=chip.getNumCellTypes()>1; OutputEventIterator<?> outItr=out.outputIterator(); for(int i=0; i<n; i+=skipBy){ int addr=a[i]; BasicEvent e=(BasicEvent)outItr.nextOutput(); e.timestamp=(timestamps[i]); e.x=getXFromAddress(addr); e.y=getYFromAddress(addr); if(hasTypes){ ((TypedEvent)e).type=getTypeFromAddress(addr); } j++; if (j==incEach) {j=0; i++;} // System.out.println("a="+a[i]+" t="+e.timestamp+" x,y="+e.x+","+e.y); } } /* synchronized public void extractPacket(AEPacketRaw in, EventPacket out) { out.clear(); if(in==null) return; int n=in.getNumEvents(); //addresses.length; int skipBy=1; if(subsamplingEnabled){ while(n/skipBy>getSubsampleThresholdEventCount()){ skipBy++; } } int[] a=in.getAddresses(); int[] timestamps=in.getTimestamps(); boolean hasTypes=false; if(chip!=null) hasTypes=chip.getNumCellTypes()>1; OutputEventIterator outItr=out.outputIterator(); for(int i=0; i<n; i+=skipBy){ // bug here? no, bug is before :-) int addr=a[i]; BasicEvent e=(BasicEvent)outItr.nextOutput(); e.timestamp=(timestamps[i]); e.x=getXFromAddress(addr); e.y=getYFromAddress(addr); if(hasTypes){ ((TypedEvent)e).type=getTypeFromAddress(addr); } // System.out.println("a="+a[i]+" t="+e.timestamp+" x,y="+e.x+","+e.y); } } */ public int getTypemask() { return this.typemask; } public void setTypemask(final int typemask) { this.typemask = typemask; } public byte getTypeshift() { return this.typeshift; } public void setTypeshift(final byte typeshift) { this.typeshift = typeshift; } public int getXmask() { return this.xmask; } /** bit mask for x address, before shift */ public void setXmask(final int xmask) { this.xmask = xmask; } public byte getXshift() { return this.xshift; } /** @param xshift the number of bits to right shift raw address after masking with {@link #setXmask} */ public void setXshift(final byte xshift) { this.xshift = xshift; } public int getYmask() { return this.ymask; } /** @param ymask the bit mask for y address, before shift */ public void setYmask(final int ymask) { this.ymask = ymask; } public byte getYshift() { return this.yshift; } /** @param yshift the number of bits to right shift raw address after masking with {@link #setYmask} */ public void setYshift(final byte yshift) { this.yshift = yshift; } // short clipx(short v){ short c=(short) (v>(chip.sizeX-1)? chip.sizeX-1: v); c=c<0?0:c; return c;} // short clipy(short v){ short c= (short)(v>(chip.sizeY-1)? chip.sizeY-1: v); c=c<0?0:c; return c;} public boolean isFlipx() { return this.flipx; } public void setFlipx(final boolean flipx) { if(chip.getSizeX()==1){ log.warning("setFlipx for chip"+chip+": chip sizeX=1, flipping doesn't make sense, disabling"); this.flipx=false; return; } this.flipx = flipx; } public boolean isFlipy() { return this.flipy; } public void setFlipy(final boolean flipy) { if(chip.getSizeY()==1){ log.warning("setFlipy for chip"+chip+": chip sizeY=1, flipping doesn't make sense, disabling"); this.flipy=false; return; } this.flipy = flipy; } public boolean isFliptype() { return this.fliptype; } public void setFliptype(final boolean fliptype) { if(chip.getNumCellTypes()==1){ log.warning("setFliptype for chip"+chip+": chip numTypes=1, flipping doesn't usually make sense, will treat it to make type=1 instead of default 0"); // this.fliptype=false; // return; } this.fliptype = fliptype; } public int getUsedBits() { return (int)((xmask<<xshift+ymask<<yshift+typemask<<typeshift)); } public boolean matchesAddress(int addr1, int addr2){ return (addr1&getUsedBits())==(addr2&getUsedBits()); } /** computes the raw address from an x,y, and type. Useful for searching for events in e.g. matlab, given the raw addresses. *This function does include flipped addresses - it uses flip booleans to pre-adjust x,y,type for chip. *@param x the x address *@param y the y address *@param type the cell type *@return the raw address */ public int getAddressFromCell(int x, int y, int type) { if(flipx) x=sizex-x; if(flipy) y=sizey-y; if(fliptype) type=sizetype-type; return (int)( (x<<xshift) +(y<<yshift) +(type<<typeshift) ); } public boolean isSubsamplingEnabled() { return subsamplingEnabled; } public void setSubsamplingEnabled(boolean subsamplingEnabled) { this.subsamplingEnabled = subsamplingEnabled; } public int getSubsampleThresholdEventCount() { return subsampleThresholdEventCount; } public void setSubsampleThresholdEventCount(int subsampleThresholdEventCount) { this.subsampleThresholdEventCount = subsampleThresholdEventCount; } AEPacketRaw raw=null; /** * Reconstructs a raw packet suitable for logging to a data file, from an EventPacket that could be the result of filtering * operations * @param packet the EventPacket * @return a raw packet holding the device events */ public AEPacketRaw reconstructRawPacket(EventPacket packet) { if(raw==null) raw=new AEPacketRaw(); raw.setNumEvents(0); EventRaw r=new EventRaw(); for(Object o:packet){ TypedEvent e=(TypedEvent)o; r.timestamp=e.timestamp; r.address=getAddressFromCell(e.x,e.y,e.type); raw.addEvent(r); } return raw; } }
package org.lockss.plugin; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.*; import java.lang.reflect.*; import java.util.zip.*; import org.apache.commons.io.IOUtils; import org.lockss.test.*; import org.lockss.daemon.*; import org.lockss.plugin.simulated.*; import org.lockss.util.*; import org.lockss.app.*; import org.lockss.config.*; /** * Utilities for manipulating plugins and their components in tests */ public class PluginTestUtil { static Logger log = Logger.getLogger("PluginTestUtil"); static List aulist = new LinkedList(); static final Pattern COMPRESSED_PATTERN = Pattern.compile( "\\.(zip|tar\\.gz|tgz)$", Pattern.CASE_INSENSITIVE ); public static void registerArchivalUnit(Plugin plug, ArchivalUnit au) { PluginManager mgr = getPluginManager(); log.debug3(mgr.toString()); String plugid = au.getPluginId(); log.debug("registerArchivalUnit plugin = " + plug + "au = " + au); if (plug != mgr.getPlugin(plugid)) { try { PrivilegedAccessor.invokeMethod(mgr, "setPlugin", ListUtil.list(plugid, plug).toArray()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } } PluginTestable tp = (PluginTestable)plug; tp.registerArchivalUnit(au); try { PrivilegedAccessor.invokeMethod(mgr, "putAuInMap", ListUtil.list(au).toArray()); } catch (InvocationTargetException e) { log.error("Couldn't register AU", e); log.error("Nested", e.getTargetException()); throw new RuntimeException(e.toString()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } aulist.add(au); } public static void registerArchivalUnit(ArchivalUnit au) { PluginManager mgr = getPluginManager(); String plugid = au.getPluginId(); Plugin plug = mgr.getPlugin(plugid); log.debug("registerArchivalUnit id = " + au.getAuId() + ", pluginid = " + plugid + ", plugin = " + plug); if (plug == null) { MockPlugin mp = new MockPlugin(); mp.setPluginId(plugid); plug = mp; } registerArchivalUnit(plug, au); } /* public static void registerArchivalUnit(ArchivalUnit au) { PluginManager mgr = getPluginManager(); log.debug(mgr.toString()); String plugid = au.getPluginId(); Plugin plug = mgr.getPlugin(plugid); log.debug("registerArchivalUnit id = " + au.getAuId() + ", pluginid = " + plugid + ", plugin = " + plug); if (plug == null) { MockPlugin mp = new MockPlugin(); mp.setPluginId(plugid); plug = mp; try { PrivilegedAccessor.invokeMethod(mgr, "setPlugin", ListUtil.list(plugid, mp).toArray()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } } PluginTestable tp = (PluginTestable)plug; tp.registerArchivalUnit(au); try { PrivilegedAccessor.invokeMethod(mgr, "putAuMap", ListUtil.list(plug, au).toArray()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } aulist.add(au); } */ public static void unregisterArchivalUnit(ArchivalUnit au) { PluginManager mgr = getPluginManager(); String plugid = au.getPluginId(); Plugin plug = mgr.getPlugin(plugid); if (plug != null) { PluginTestable tp = (PluginTestable)plug; tp.unregisterArchivalUnit(au); aulist.remove(au); } mgr.stopAu(au, new AuEvent(AuEvent.Type.Delete, false)); } public static void unregisterAllArchivalUnits() { log.debug("unregisterAllArchivalUnits()"); List aus = new ArrayList(aulist); for (Iterator iter = aus.iterator(); iter.hasNext(); ) { unregisterArchivalUnit((ArchivalUnit)iter.next()); } } public static Plugin findPlugin(String pluginName) { PluginManager pluginMgr = getPluginManager(); String key = pluginMgr.pluginKeyFromName(pluginName); pluginMgr.ensurePluginLoaded(key); return pluginMgr.getPlugin(key); } public static Plugin findPlugin(Class pluginClass) { return findPlugin(pluginClass.getName()); } public static ArchivalUnit createAu(Plugin plugin, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return getPluginManager().createAu(plugin, auConfig, new AuEvent(AuEvent.Type.Create, false)); } public static ArchivalUnit createAndStartAu(Plugin plugin, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return startAu(createAu(plugin, auConfig)); } static ArchivalUnit startAu(ArchivalUnit au) { LockssDaemon daemon = au.getPlugin().getDaemon(); daemon.getHistoryRepository(au).startService(); daemon.getLockssRepository(au).startService(); daemon.getNodeManager(au).startService(); return au; } public static ArchivalUnit createAu(String pluginName, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAu(findPlugin(pluginName), auConfig); } public static ArchivalUnit createAndStartAu(String pluginName, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAndStartAu(findPlugin(pluginName), auConfig); } public static ArchivalUnit createAu(Class pluginClass, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAu(findPlugin(pluginClass.getName()), auConfig); } public static ArchivalUnit createAndStartAu(Class pluginClass, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAndStartAu(findPlugin(pluginClass.getName()), auConfig); } public static SimulatedArchivalUnit createSimAu(Configuration auConfig) throws ArchivalUnit.ConfigurationException { return (SimulatedArchivalUnit)createAu(findPlugin(SimulatedPlugin.class), auConfig); } static Configuration getAuConfig(TdbAu tau) { PluginManager mgr = getPluginManager(); Plugin plugin = tau.getPlugin(mgr); TitleConfig tc = new TitleConfig(tau, plugin); return tc.getConfig(); } public static ArchivalUnit createAu(TdbAu tau) throws ArchivalUnit.ConfigurationException { PluginManager mgr = getPluginManager(); Plugin plugin = findPlugin(tau.getPluginId()); return createAu(plugin, getAuConfig(tau)); } public static ArchivalUnit createAu(Plugin plugin, TdbAu tau) throws ArchivalUnit.ConfigurationException { return createAu(plugin, getAuConfig(tau)); } public static ArchivalUnit createAndStartAu(TdbAu tau) throws ArchivalUnit.ConfigurationException { return startAu(createAu(tau)); } public static ArchivalUnit createAndStartAu(Plugin plugin, TdbAu tau) throws ArchivalUnit.ConfigurationException { return startAu(createAu(plugin, tau)); } public static SimulatedArchivalUnit createAndStartSimAu(Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAndStartSimAu(SimulatedPlugin.class, auConfig); } public static SimulatedArchivalUnit createAndStartSimAu(Class pluginClass, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return (SimulatedArchivalUnit)createAndStartAu(pluginClass, auConfig); } public static void crawlSimAu(SimulatedArchivalUnit sau) { if (!sau.hasContentTree()) { // log.debug("Creating simulated content tree: " + sau.getParamMap()); sau.generateContentTree(); } log.debug("Crawling simulated content"); NoCrawlEndActionsFollowLinkCrawler crawler = new NoCrawlEndActionsFollowLinkCrawler(sau, new MockAuState()); //crawler.setCrawlManager(crawlMgr); crawler.doCrawl(); } public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu) { return copyAu(fromAu, toAu, null, null, null); } public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu, String ifMatch) { return copyAu(fromAu, toAu, ifMatch, null, null); } public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu, String ifMatch, String pat, String rep) { return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, pat, rep); } public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu) { return copyCus(fromCus, toAu, null, null, null); } public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu, String ifMatch, String pat, String rep) { boolean res = true; ArchivalUnit fromAu = fromCus.getArchivalUnit(); Pattern pattern = null; if (pat != null) { pattern = Pattern.compile(pat); } Pattern ifMatchPat = null; if (ifMatch != null) { ifMatchPat = Pattern.compile(ifMatch); } for (CachedUrl cu : fromCus.getCuIterable()) { try { String fromUrl = cu.getUrl(); String toUrl = fromUrl; Matcher compMat = COMPRESSED_PATTERN.matcher(fromUrl); if (compMat.find()) { log.debug("encountered a compressed file, skipping"); continue; } if (ifMatchPat != null) { Matcher mat = ifMatchPat.matcher(fromUrl); if (!mat.find()) { log.debug3("no match: " + fromUrl + ", " + ifMatchPat); continue; } } if (pattern != null) { Matcher mat = pattern.matcher(fromUrl); toUrl = mat.replaceAll(rep); } CIProperties props = cu.getProperties(); if (props == null) { log.debug3("in copyCus() props was null for url: " + fromUrl); } UrlCacher uc = toAu.makeUrlCacher( new UrlData(cu.getUnfilteredInputStream(), props, toUrl)); uc.storeContent(); if (!toUrl.equals(fromUrl)) { log.info("Copied " + fromUrl + " to " + toUrl); } else { log.debug2("Copied " + fromUrl); } } catch (Exception e) { log.error("Couldn't copy " + cu.getUrl(), e); res = false; } finally { cu.release(); } } return res; } /** * Overloaded method of copyCus which takes pattern-replacement set */ public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu, String ifMatch, PatternReplacements prps) { return false; } /** * TODO: Take the plugin as param and check it for which types of files to see as archives * e.g. toAu.getArchiveFileTypes().getFromCu(cu) * if null * copy cu as normal * elsif in map: * switch : * zip - use the copyzip * tar - either figure it out or Throw an error * com.ice.tar.TarInputStream * tgz - ibid * double wrap - unwrap gzip, then TarInputStream * else: * Throw error */ /** * Copies all zips in from one crawl into another without modification. * * @see PluginTestUtil#copyZip(CachedUrl, ArchivalUnit, PatternReplacements) */ public static boolean copyAuZip(ArchivalUnit fromAu, ArchivalUnit toAu) { return copyZipCus(fromAu.getAuCachedUrlSet(), toAu, null); } /** * Works just like {@link PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List, List)}. * Just gets the cachedUrlSet in fromAU and Makes lists from pat & rep. * * @see PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List, List) */ public static boolean copyAuZip(ArchivalUnit fromAu, ArchivalUnit toAu, String pat, String rep) throws Exception { return copyZipCus(fromAu.getAuCachedUrlSet(), toAu, pat, rep); } /** * Works just like {@link PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List, List)}. * Just gets the cachedUrlSet in fromAu. * * @see PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List, List) */ public static boolean copyAuZip(ArchivalUnit fromAu, ArchivalUnit toAu, List<String> pats, List<String> reps) throws Exception { return copyZipCus(fromAu.getAuCachedUrlSet(), toAu, pats, reps); } /** * Works just like {@link PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List, List)}. * Just makes lists and adds pat and rep to them. * * @see PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List, List) */ public static boolean copyZipCus(CachedUrlSet fromCus, ArchivalUnit toAu, String pat, String rep) throws Exception { List<String> pats = Collections.singletonList(pat); List<String> reps = Collections.singletonList(rep); return copyZipCus(fromCus, toAu, pats, reps); } /** * Utility to copy zip files from a simulated crawl to a mock archival unit. * if only fromAu and toAu are provided, all zips encountered are copied without modification. * * @param fromCus the CachedUrlSet which has been crawled * @param toAu the Archival Unit to copy content to * @param pats List of regexes to search in the zipped contents * @param reps List of replacements for each pattern * @return true, if all copies attempted succeeded, false otherwise */ public static boolean copyZipCus(CachedUrlSet fromCus, ArchivalUnit toAu, List<String> pats, List<String> reps) throws Exception { return copyZipCus(fromCus, toAu, new PatternReplacements(pats, reps)); } /** * Iterates over all CachedUrls in a simulated crawl and copies them to a mock Au if patterns and replacements * are identified in the simulated crawl from the Pattern-Replacements given. * * @see PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List, List) */ private static boolean copyZipCus(CachedUrlSet fromCus, ArchivalUnit toAu, PatternReplacements patReps) { boolean res = true; for (CachedUrl cu : fromCus.getCuIterable()) { try { String fromUrl = cu.getUrl(); // only copy the file if it is a zip. Matcher mat = COMPRESSED_PATTERN.matcher(fromUrl); if (mat.find()) { if (patReps!=null) { log.debug("entering zip file to copy contents"); copyZip(cu, toAu, patReps); } else { log.debug("copying unmodified zip"); CIProperties props = cu.getProperties(); UrlCacher uc = toAu.makeUrlCacher( new UrlData(cu.getUnfilteredInputStream(), props, fromUrl)); uc.storeContent(); } } } catch (Exception e) { log.error("Couldn't copy " + cu.getUrl(), e); res = false; } finally { cu.release(); } } return res; } /** * Opens a single CachedUrl zip file, iterates over its contents and copies the contents if they pass * given pattern(s) and replacements. * @param cu A CachedUrl of compressed content. * @param toAu The ArchivalUnit to copy the cu into. * @param patReps Pattern-Replacement pairs to selectively copy zipped content and rename it in the new zip. * @throws IOException When I/O zip files encounter any number of problems. */ private static void copyZip(CachedUrl cu, ArchivalUnit toAu, PatternReplacements patReps) throws IOException { boolean doCache = false; String zipUrl = cu.getUrl() + "!/"; String toUrl; String toFile; String zippedFile; String fromFile; ZipInputStream zis = null; ZipOutputStream zos; String outZip = null; try { InputStream cuis = new ReaderInputStream(cu.openForReading()); zis = new ZipInputStream(cuis); zos = new ZipOutputStream(Files.newOutputStream( Paths.get(cu.getArchivalUnit().getProperties().getString("root") + "temp.zip"))); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(Deflater.BEST_COMPRESSION); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { continue; } else if (entry.getName().endsWith(".zip") ) { // TODO recurse through nested // zipCopy(cu, toAu, zipUrl + ); } fromFile = entry.getName(); zippedFile = zipUrl + fromFile; for (PatternReplacementPair prp : patReps.pairs) { Matcher mat = prp.pat.matcher(zippedFile); if (mat.find()) { toUrl = mat.replaceAll(prp.rep); if (!toUrl.equals(zippedFile)) { log.debug("Found a zipped file match: " + zippedFile + " -> " + toUrl); doCache = true; outZip = toUrl.split("!/")[0]; toFile = toUrl.split("!/")[1]; ZipEntry outEntry = new ZipEntry(toFile); zos.putNextEntry(outEntry); StreamUtil.copy(zis, zos); zos.closeEntry(); } break; } } } zos.close(); // any copied file triggers saving the new zip stream if (doCache) { FileInputStream is = new FileInputStream(new File( cu.getArchivalUnit().getProperties().getString("root"), "temp.zip")); // save all the copied zip entries to a new zip on the toAu CIProperties props = cu.getProperties(); if (props == null) { log.debug3("in copyCus() props was null for url: " + cu.getUrl()); } log.debug("Storing new cu: " + outZip); UrlCacher uc = toAu.makeUrlCacher( new UrlData(is, props, outZip)); uc.storeContent(); is.close(); } } finally { IOUtil.safeClose(zis); } } public static List<String> urlsOf(final Iterable<CachedUrl> cus) { return new ArrayList<String>() {{ for (CachedUrl cu : cus) { add(cu.getUrl()); } }}; } private static PluginManager getPluginManager() { return (PluginManager)LockssDaemon.getManager(LockssDaemon.PLUGIN_MANAGER); } public static PatternReplacementPair makePatRepPair(String pat, String rep) { return new PatternReplacementPair(pat , rep); } public static class PatternReplacementPair { public Pattern pat; public String rep; /** * Simple Container class for Regex pattern -> Replacement pairs. * @param pat String regex, gets compiled to a Pattern * @param rep Replacement string */ PatternReplacementPair(String pat, String rep) { this.pat = Pattern.compile(pat, Pattern.CASE_INSENSITIVE); this.rep = rep; } } // TODO Remove this class private static class PatternReplacements { public PatternReplacementPair[] pairs; /** * Simple array class which stores Pattern-Replacement pairs. * * @param pats List of regex patterns in string format * @param reps List of corresponding replacement patterns. * @throws Exception if the inputs are not compliant */ PatternReplacements(List<String> pats, List<String> reps) throws Exception { if (pats == null || reps == null) { throw new Exception("Patterns and Replacements cannot be null"); } if (pats.size() != reps.size()) { throw new Exception("Patterns and Replacements do not match up. Must contain the same number of elements."); } if (pats.size() < 1) { throw new Exception("No patterns/replacements given. Must provide at least one pair."); } pairs = new PatternReplacementPair[pats.size()]; for (int i=0; i<pats.size(); i++) { pairs[i] = new PatternReplacementPair(pats.get(i), reps.get(i)); } } } }
/* * $Id: TestCXSerializer.java,v 1.11 2008-02-15 09:17:36 tlipkis Exp $ */ package org.lockss.util; import java.io.*; /** * <p>Tests the Castor/XStream hybrid serializer.</p> * @author Thib Guicherd-Callin */ public class TestCXSerializer extends ObjectSerializerTester { /** * <p>Tests that the deserializer in XStreamOverWrite mode behaves * appropriately with Castor input.</p> * @throws Exception if an unexpected or unhandled problem arises. */ public void testXStreamOverwriteMode() throws Exception { // Make a sample object ExtMapBean original = makeSample_ExtMapBean(); // Define variant actions RememberFile[] actions = new RememberFile[] { // Wit a File new RememberFile() { public void doSomething(ObjectSerializer serializer) throws Exception { serializer.deserialize(file); } }, // With a String new RememberFile() { public void doSomething(ObjectSerializer serializer) throws Exception { serializer.deserialize(file.toString()); } }, }; // For each variant action... for (int action = 0 ; action < actions.length ; ++action) { logger.debug("Begin with action " + action); // For each type of deserializer... ObjectSerializer[] deserializers = getObjectSerializers_ExtMapBean(); for (int deserializer = 0 ; deserializer < deserializers.length ; ++deserializer) { if (((CXSerializer)deserializers[deserializer]).getCompatibilityMode() == CXSerializer.XSTREAM_OVERWRITE_MODE) { logger.debug("Begin with deserializer " + deserializer); // Assign a file to the action actions[action].file = File.createTempFile("testfile", ".xml"); actions[action].file.deleteOnExit(); // Serialize in Castor format CastorSerializer serializer = new CastorSerializer(ExternalizableMap.MAPPING_FILE_NAME, ExtMapBean.class); // Read back serializer.serialize(actions[action].file, original); ExtMapBean clone1 = (ExtMapBean)deserializers[deserializer].deserialize(actions[action].file); assertEquals(original.getMap(), clone1.getMap()); // Verify that the conversion has been made XStreamSerializer verify = new XStreamSerializer(); ExtMapBean clone2 = (ExtMapBean)verify.deserialize(actions[action].file); assertEquals(original.getMap(), clone2.getMap()); } else { // Skip if not in XStreamOverwriteMode logger.debug("Skipping deserializer " + deserializer); } } } } /** * <p>Checks that the serializer writes output in a format that is * appropriate for its mode, by re-reading it through a * corresponding single-mode deserializer.</p> * @throws Exception if an error condition arises. */ public void testOutputFormat() throws Exception { ObjectSerializer[] serializers = getObjectSerializers_ExtMapBean(); for (int serializer = 0 ; serializer < serializers.length ; ++serializer) { ObjectSerializer deserializer = null; switch (((CXSerializer)serializers[serializer]).getCompatibilityMode()) { case CXSerializer.CASTOR_MODE: deserializer = new CastorSerializer(ExternalizableMap.MAPPING_FILE_NAME, ExtMapBean.class); break; case CXSerializer.XSTREAM_MODE: case CXSerializer.XSTREAM_OVERWRITE_MODE: deserializer = new XStreamSerializer(); break; default: // shouldn't happen fail("Unexpected compatibility mode (#" + serializer + ")"); } performRoundTrip(serializers[serializer], deserializer); } } /** * <p>Checks that the deserializer can read input in Castor * format.</p> * @throws Exception if an error condition arises. */ public void testReadCastorInput() throws Exception { ObjectSerializer[] deserializers = getObjectSerializers_ExtMapBean(); for (int deserializer = 0 ; deserializer < deserializers.length ; ++deserializer) { CastorSerializer serializer = new CastorSerializer(ExternalizableMap.MAPPING_FILE_NAME, ExtMapBean.class); performRoundTrip(serializer, deserializers[deserializer]); } } /** * <p>Checks that the deserializer can read input in XStream * format.</p> * @throws Exception if an error condition arises. */ public void testReadXStreamInput() throws Exception { ObjectSerializer[] deserializers = getObjectSerializers_ExtMapBean(); for (int deserializer = 0 ; deserializer < deserializers.length ; ++deserializer) { XStreamSerializer serializer = new XStreamSerializer(); performRoundTrip(serializer, deserializers[deserializer]); } } /** * <p>A specialized version of * {@link ObjectSerializerTester#getObjectSerializers_ExtMapBean} * that produces on series of serializers for each compatibility * mode.</p> * @see ObjectSerializerTester#getObjectSerializers_ExtMapBean */ protected ObjectSerializer[] getObjectSerializers_ExtMapBean() { // Compatibility modes int[] compatModes = new int[] { // CXSerializer.CASTOR_MODE, CXSerializer.XSTREAM_MODE, CXSerializer.XSTREAM_OVERWRITE_MODE, }; int parentLength = getMinimalObjectSerializers_ExtMapBean().length; CXSerializer[] result = new CXSerializer[parentLength * compatModes.length]; // For each compatibility mode... int current = 0; for (int compatMode = 0 ; compatMode < compatModes.length ; ++compatMode) { // ...get a full stack of serializers (produced by this class) ObjectSerializer[] parent = getMinimalObjectSerializers_ExtMapBean(); // and set their compatibility mode for (int serializer = 0 ; serializer < parentLength ; ++serializer) { result[current] = (CXSerializer)parent[serializer]; result[current++].setCompatibilityMode(compatModes[compatMode]); } } return result; } /* Inherit documentation */ protected ObjectSerializer makeObjectSerializer_ExtMapBean(boolean saveTempFiles, int failedDeserializationMode) { return new CXSerializer(ExternalizableMap.MAPPING_FILE_NAME, ExtMapBean.class, saveTempFiles, failedDeserializationMode); } /** * <p>Performs a quick round trip into the serializer and back from * the deserializer, expecting the operation to succeed.</p> * @param serializer Any ObjectSerializer. * @param deserializer Any ObjectSerializer. * @throws Exception if an unexpected or unhandled problem arises. */ private void performRoundTrip(ObjectSerializer serializer, ObjectSerializer deserializer) throws Exception { // Set up needed objects ExtMapBean original = makeSample_ExtMapBean(); ExtMapBean clone; ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in; try { serializer.serialize(out, original); in = new ByteArrayInputStream(out.toByteArray()); clone = (ExtMapBean)deserializer.deserialize(in); } catch (SerializationException se) { StringBuffer buffer = new StringBuffer(); buffer.append("SerializationException thrown while in correct mode. "); buffer.append("Nested message: "); buffer.append(se.getMessage()); fail(buffer.toString()); } } }
package it.unimi.dsi.sux4j.test; import it.unimi.dsi.fastutil.io.FastBufferedOutputStream; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.util.XorShift1024StarRandomGenerator; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import org.apache.commons.math3.random.RandomGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.UnflaggedOption; public class GenerateRandom64BitStrings { public static final Logger LOGGER = LoggerFactory.getLogger( GenerateRandom64BitStrings.class ); public static void main( final String[] arg ) throws JSAPException, IOException { final SimpleJSAP jsap = new SimpleJSAP( GenerateRandom64BitStrings.class.getName(), "Generates a list of sorted 64-bit random strings using only characters in the ISO-8859-1 printable range [32..256).", new Parameter[] { new FlaggedOption( "repeat", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'r', "repeat", "Repeat each byte this number of times" ), new UnflaggedOption( "n", JSAP.LONG_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The number of strings." ), new UnflaggedOption( "output", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The output file." ) }); JSAPResult jsapResult = jsap.parse( arg ); if ( jsap.messagePrinted() ) return; final long n = jsapResult.getLong( "n" ); final int repeat = jsapResult.getInt( "repeat" ); final String output = jsapResult.getString( "output" ); RandomGenerator r = new XorShift1024StarRandomGenerator(); ProgressLogger pl = new ProgressLogger( LOGGER ); pl.expectedUpdates = n; pl.start( "Generating... " ); BigInteger l = BigInteger.ZERO, t; BigInteger limit = BigInteger.valueOf( 224 ).pow( 8 ); long incr = (long)Math.floor( 1.99 * ( limit.divide( BigInteger.valueOf( n ) ).longValue() ) ) - 1; @SuppressWarnings("resource") final FastBufferedOutputStream fbs = new FastBufferedOutputStream( new FileOutputStream( output ) ); final BigInteger divisor = BigInteger.valueOf( 224 ); LOGGER.info( "Increment: " + incr ); BigInteger a[]; int[] b = new int[ 8 ]; for( long i = 0; i < n; i++ ) { l = l.add( BigInteger.valueOf( ( r.nextLong() & 0x7FFFFFFFFFFFFFFFL ) % incr + 1 ) ); t = l; if ( l.compareTo( limit ) >= 0 ) throw new AssertionError( Long.toString( i ) ); for( int j = 8; j a = t.divideAndRemainder( divisor ); b[ j ] = a[ 1 ].intValue() + 32; assert b[ j ] < 256; assert b[ j ] >= 32; t = a[ 0 ]; } for( int j = 0; j < 8; j++ ) for( int k = repeat; k fbs.write( b[ j ] ); fbs.write( 10 ); pl.lightUpdate(); } pl.done(); fbs.close(); LOGGER.info( "Last/limit: " + ( l.doubleValue() / limit.doubleValue() ) ); } }
package it.unitn.vanguard.reminiscence; import it.unitn.vanguard.reminiscence.QuestionPopUpHandler.QuestionPopUp; import it.unitn.vanguard.reminiscence.asynctasks.GetPublicStoriesTask; import it.unitn.vanguard.reminiscence.asynctasks.GetStoriesTask; import it.unitn.vanguard.reminiscence.asynctasks.LogoutTask; import it.unitn.vanguard.reminiscence.frags.StoryFragment; import it.unitn.vanguard.reminiscence.interfaces.OnGetStoryTask; import it.unitn.vanguard.reminiscence.interfaces.OnTaskFinished; import it.unitn.vanguard.reminiscence.utils.Constants; import it.unitn.vanguard.reminiscence.utils.FinalFunctionsUtilities; import it.unitn.vanguard.reminiscence.utils.Story; import java.util.Locale; import org.json.JSONException; import org.json.JSONObject; import android.app.ActionBar; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import eu.giovannidefrancesco.DroidTimeline.view.TimeLineView; import eu.giovannidefrancesco.DroidTimeline.view.YearView; public class ViewStoriesActivity extends BaseActivity implements OnTaskFinished, QuestionPopUp, OnGetStoryTask { private static final String SAVE_INDEX = "saved_index"; private Context context; // private ViewPager mViewPager; private GridView mCards; private TimeLineView mTimeLine; private ProgressDialog dialog; private ActionBar actionBar; private TextView mQuestionTv; private ImageView mCloseQuestionImgV; private StoriesAdapter mStoriesAdapter; private int selectedIndex; // private YearView selected; private int startYear; private int requestYear; private YearView lastSelected; @Override public void onCreate(Bundle arg0) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(arg0); setContentView(R.layout.activity_viewstories); context = ViewStoriesActivity.this; String language = FinalFunctionsUtilities.getSharedPreferences( "language", context); FinalFunctionsUtilities.switchLanguage(new Locale(language), context); mCards = (GridView) findViewById(R.id.viewstroies_cards_gw); mTimeLine = (TimeLineView) findViewById(R.id.viewstories_tlv); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( getApplicationContext(), R.array.stories_dropdown, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { switch (itemPosition) { case 0: if (FinalFunctionsUtilities.isDeviceConnected(context)) { FinalFunctionsUtilities.stories.clear(); new GetStoriesTask(ViewStoriesActivity.this, requestYear).execute(); } else { Toast.makeText(context, R.string.connection_fail, Toast.LENGTH_LONG) .show(); } break; case 1: if (FinalFunctionsUtilities.isDeviceConnected(context)) { FinalFunctionsUtilities.stories.clear(); new GetPublicStoriesTask(ViewStoriesActivity.this, requestYear).execute(); } else { Toast.makeText(context, R.string.connection_fail, Toast.LENGTH_LONG) .show(); } break; } return true; } }); mStoriesAdapter = new StoriesAdapter(); mCards.setAdapter(mStoriesAdapter); // e' per avere lo 0 alla fine degli anni.(per avere l'intera decade, // praticmanete) String year = FinalFunctionsUtilities.getSharedPreferences( Constants.YEAR_KEY, this); year = year.substring(0, year.length() - 1); requestYear = Integer.parseInt(year + '0'); startYear = requestYear; mTimeLine.setStartYear(startYear); if (arg0 != null) { selectedIndex = arg0.getInt(SAVE_INDEX); FinalFunctionsUtilities.stories.clear(); mStoriesAdapter.notifyDataSetChanged(); } else { selectedIndex = 0; } YearView selected = (YearView) mTimeLine.getAdapter().getView( selectedIndex, null, null); requestYear = selected.getYear(); lastSelected = selected; setListeners(); initializePopUps(); initializeStoryList(); } private void initializeStoryList() { /*doppie storie perch doppia richiesta, richiesta che avviene gi con l'inizializzazione della * barra privato/pubblico // Comincia a chiedere al server le storie if (FinalFunctionsUtilities.isDeviceConnected(context)) { new GetStoriesTask(this, requestYear).execute(); } else { Toast.makeText(context, R.string.connection_fail, Toast.LENGTH_LONG) .show(); }*/ } private void initializePopUps() { Bundle b = new Bundle(); b.putString(QuestionPopUpHandler.QUESTION_PASSED_KEY, "Sei mai andato in crociera?"); Message msg = new Message(); msg.setData(b); new QuestionPopUpHandler(this).sendMessageDelayed(msg, Constants.QUESTION_INTERVAL); } private void setListeners() { mTimeLine.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { ((YearView)arg1).setBackgroundColor(getResources().getColor( R.color.pomegranate)); lastSelected.setBackgroundColor(getResources().getColor( R.color.red_background_dark)); lastSelected =(YearView) arg1; /* vecchio codice di giovanni // Cambio il background della vecchia selezione updateSelected(false); */ // aggiorno gli indici selectedIndex = arg2; requestYear = ((YearView)arg1).getYear(); // tolgo le vecchie e chiedo le nuove FinalFunctionsUtilities.stories.clear(); mStoriesAdapter.notifyDataSetChanged(); new GetStoriesTask(ViewStoriesActivity.this, requestYear) .execute(); } }); mQuestionTv = (TextView) findViewById(R.id.viewtories_addstory_hint); mQuestionTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OnHide(); } }); mCloseQuestionImgV = (ImageView) findViewById(R.id.viewstories_addstory_hint_close); mCloseQuestionImgV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OnHide(); } }); mLogout = (TextView) findViewById(R.id.hiddebmenu_logout_tv); mLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder( ViewStoriesActivity.this); builder.setMessage(R.string.exit_message) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialogInterface, int id) { if(FinalFunctionsUtilities.isDeviceConnected(context)) { dialog = new ProgressDialog( ViewStoriesActivity.this); dialog.setTitle(getResources() .getString(R.string.please)); dialog.setMessage(getResources() .getString(R.string.wait)); dialog.setCancelable(false); dialog.show(); String email = FinalFunctionsUtilities .getSharedPreferences( Constants.MAIL_KEY, ViewStoriesActivity.this); String password = FinalFunctionsUtilities .getSharedPreferences( Constants.PASSWORD_KEY, ViewStoriesActivity.this); new LogoutTask( ViewStoriesActivity.this) .execute(email, password); } else { Toast.makeText(context, getResources().getString(R.string.connection_fail), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); ((TextView) alert.findViewById(android.R.id.message)) .setGravity(Gravity.CENTER); ((Button) alert.getButton(AlertDialog.BUTTON_POSITIVE)) .setBackgroundResource(R.drawable.bottone_logout); ((Button) alert.getButton(AlertDialog.BUTTON_POSITIVE)) .setTextColor(Color.WHITE); } }); } private class StoriesAdapter extends BaseAdapter { @Override public int getCount() { return FinalFunctionsUtilities.stories.size(); } @Override public Object getItem(int arg0) { return FinalFunctionsUtilities.stories.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(final int arg0, View arg1, ViewGroup arg2) { View v = getLayoutInflater().inflate(R.layout.card_story, arg2, false); Story story = FinalFunctionsUtilities.stories.get(arg0); ImageView back = (ImageView) v.findViewById(R.id.cardstory_img); TextView title = (TextView) v.findViewById(R.id.cardstory_title); TextView desc = (TextView) v.findViewById(R.id.cardstory_desc); if (story != null) { if (story.getBackground() != null) back.setImageBitmap(FinalFunctionsUtilities.stories.get( arg0).getBackground()); title.setText(story.getTitle()); desc.setText(story.getDesc()); } v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View clicked) { Story story = FinalFunctionsUtilities.stories.get(arg0); StoryFragment sf = StoryFragment.newIstance( story.getTitle(), story.getDesc(), "" + story.getAnno()); sf.show(getSupportFragmentManager(), "visualized"); } }); return v; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.timeline, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add_story: Intent i = new Intent(this, EmptyStoryActivity.class); i.putExtra(EmptyStoryActivity.YEAR_PASSED_KEY, requestYear); startActivity(i); break; } return super.onOptionsItemSelected(item); } @Override public void onTaskFinished(JSONObject res) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } try { if (res.getString("success").equals("true")) { Toast.makeText(context, getResources().getString(R.string.logout_success), Toast.LENGTH_LONG).show(); FinalFunctionsUtilities.clearSharedPreferences(context); startActivity(new Intent(ViewStoriesActivity.this, LoginActivity.class)); this.finish(); } else { Toast.makeText(this, getResources().getString(R.string.logout_failed), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Log.e(LoginActivity.class.getName(), e.toString()); } } @Override public void OnShow(String question) { togglePopup(true); mQuestionTv.setText(question); } @Override public void OnHide() { togglePopup(false); } private void togglePopup(boolean visibility) { if (!visibility) { mQuestionTv.setVisibility(View.GONE); mCloseQuestionImgV.setVisibility(View.GONE); } else { mQuestionTv.setVisibility(View.VISIBLE); mCloseQuestionImgV.setVisibility(View.VISIBLE); } } @Override public void OnStart() { setProgressBarIndeterminateVisibility(true); } @Override public void OnProgress() { mStoriesAdapter.notifyDataSetChanged(); } @Override public void OnFinish(Boolean result) { // TODO display a toast in case of error setProgressBarIndeterminateVisibility(false); if (requestYear == startYear) { addBornStory(); } View no_res = findViewById(R.id.no_result_tv); if (FinalFunctionsUtilities.stories.isEmpty()) { no_res.setVisibility(View.VISIBLE); mCards.setVisibility(View.INVISIBLE); } else { no_res.setVisibility(View.INVISIBLE); mCards.setVisibility(View.VISIBLE); } //updateSelected(true); OnProgress(); } private void addBornStory() { String title = getString(R.string.born_title); String desc = String.format(getString(R.string.born), FinalFunctionsUtilities.getSharedPreferences( Constants.LOUGO_DI_NASCITA_PREFERENCES_KEY, ViewStoriesActivity.this)); Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.baby); Story s = new Story(startYear, title, desc); s.setBackground(img); FinalFunctionsUtilities.stories.addFirst(s); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(SAVE_INDEX, selectedIndex); } private void updateSelected(boolean selected){ YearView v=(YearView) mTimeLine.getChildAt(selectedIndex); if(v==null) v= (YearView) mTimeLine.getAdapter().getView( selectedIndex, null, null); if(selected) v.setBackgroundColor(getResources() .getColor(R.color.pomegranate)); else v.setBackgroundColor(getResources().getColor( R.color.red_background_dark)); } }