answer
stringlengths
17
10.2M
package com.andela.notelib.note; import com.andela.notelib.util.SortById; import junit.framework.TestCase; import java.util.Collections; public class NoteListTest extends TestCase { NoteList<Note> notes; PaperNote paperNote; PaperNote paperNote1; PaperNote paperNote2; PaperNote paperNote3; PaperNote paperNote4; PaperNote paperNote5; PaperNote paperNote6; PaperNote paperNote7; PaperNote paperNote8; PaperNote paperNote9; PaperNote paperNote10; PaperNote paperNote11; PaperNote paperNote12; PaperNote paperNote13; PaperNote paperNote14; NoteList<Note> noteList; public void setUp() throws Exception { notes = new NoteList<>(); paperNote = new PaperNote("REAL", "Husbands of hollywood", "Corsiva", 40, 1); paperNote.setId(0); paperNote.setFolderId(0); paperNote1 = new PaperNote("STRONG", "MEN of hollywood", "Corsiva", 40, 1); paperNote1.setId(1); paperNote1.setFolderId(0); paperNote2 = new PaperNote("DANGEROUS", "DUDES of hollywood", "Corsiva", 40, 1); paperNote2.setId(2); paperNote2.setFolderId(0); paperNote3 = new PaperNote("MEAN", "GIRLS of hollywood", "Corsiva", 40, 1); paperNote3.setId(3); paperNote3.setFolderId(0); paperNote4 = new PaperNote("COOL", "GUYZ of hollywood", "Corsiva", 40, 1); paperNote4.setId(4); paperNote4.setFolderId(0); paperNote5 = new PaperNote("VUN", "HELLO of hollywood", "Corsiva", 40, 1); paperNote5.setId(5); paperNote5.setFolderId(0); paperNote6 = new PaperNote("SIX", "HELLO of hollywood", "Corsiva", 40, 1); paperNote6.setId(6); paperNote6.setFolderId(0); paperNote7 = new PaperNote("SEVEN", "YES of hollywood", "Corsiva", 40, 1); paperNote7.setId(7); paperNote7.setFolderId(0); paperNote8 = new PaperNote("EIGHT", "LOVE of hollywood", "Corsiva", 40, 1); paperNote8.setId(8); paperNote8.setFolderId(0); paperNote9 = new PaperNote("NINE", "CAN of hollywood", "Corsiva", 40, 1); paperNote9.setId(9); paperNote9.setFolderId(0); paperNote10 = new PaperNote("TEN", "DRINK of hollywood", "Corsiva", 40, 1); paperNote10.setId(10); paperNote10.setFolderId(0); paperNote11 = new PaperNote("ELEVEN", "MALT of hollywood", "Corsiva", 40, 1); paperNote11.setId(11); paperNote11.setFolderId(0); paperNote12 = new PaperNote("TWELVE", "COKE of hollywood", "Corsiva", 40, 1); paperNote12.setId(12); paperNote12.setFolderId(0); paperNote13 = new PaperNote("THIRTEEN", "MELLON of hollywood", "Corsiva", 40, 1); paperNote13.setId(13); paperNote13.setFolderId(0); paperNote14 = new PaperNote("FOURTEEN", "ORANGES of hollywood", "Corsiva", 40, 1); paperNote14.setId(14); paperNote14.setFolderId(0); noteList = new NoteList<>(); noteList.addNote(paperNote1); noteList.addNote(paperNote); noteList.addNote(paperNote2); super.setUp(); } private void addNote(){ notes.addNote(paperNote); notes.addNote(paperNote1); notes.addNote(paperNote2); } private void addOrderedNote(){ notes.addNote(paperNote2); notes.addNote(paperNote1); notes.addNote(paperNote); notes.addNote(paperNote3); notes.addNote(paperNote5); notes.addNote(paperNote4); notes.addNote(paperNote7); notes.addNote(paperNote6); notes.addNote(paperNote9); notes.addNote(paperNote8); notes.addNote(paperNote10); notes.addNote(paperNote13); notes.addNote(paperNote14); notes.addNote(paperNote12); notes.addNote(paperNote11); } public void tearDown() throws Exception { } public void testGetNote() throws Exception { addNote(); PaperNote note = (PaperNote) notes.get(0); assertEquals(note.getNote(), paperNote.getNote()); } public void testGetFolderNotes() throws Exception { addNote(); NoteList<Note> noteList = notes.getFolderNotes(0); assertEquals(noteList, notes); } public void testUpdateNote() throws Exception { addNote(); paperNote.setTitle("GET READY!"); notes.updateNote(paperNote); assertEquals(((PaperNote) notes.getNote(0)).getTitle(), paperNote.getTitle()); } public void testContainsNote() throws Exception { addNote(); assertTrue(notes.containsNote(paperNote)); notes.removeNote(paperNote); assertFalse(notes.containsNote(paperNote)); } public void testAddNote() throws Exception { addNote(); assertEquals(notes.size(), 3); } public void testAddOrderedNote() throws Exception { addOrderedNote(); Collections.sort(notes, new SortById()); assertEquals(((PaperNote) notes.get(0)).getTitle(), paperNote14.getTitle()); } public void testRemoveNote() throws Exception { assertEquals(notes.size(), 0); addNote(); assertEquals(notes.size(), 3); notes.removeNote(paperNote); assertEquals(notes.size(), 2); } public void testContainsAllNote() throws Exception { assertEquals(notes.size(), 0); addOrderedNote(); assertEquals(notes.size(), 15); assertTrue(notes.containsAllNote(noteList)); } public void testAddAllNote() throws Exception { assertEquals(notes.size(), 0); notes.addAllNote(noteList); assertEquals(notes.size(), 3); } public void testAddAllOrderedNote() throws Exception { assertEquals(notes.size(), 0); notes.addAllOrderedNote(noteList); assertEquals(((PaperNote)notes.get(0)).getTitle(), paperNote2.getTitle()); } public void testRemoveAllNote() throws Exception { assertEquals(notes.size(), 0); notes.addAllOrderedNote(noteList); assertEquals(((PaperNote) notes.get(0)).getTitle(), paperNote2.getTitle()); notes.removeAllNote(noteList); assertEquals(notes.size(), 0); } }
package com.imcode.imcms.mapping; import com.imcode.imcms.api.DocumentLanguage; import com.imcode.imcms.api.DocumentVersion; import com.imcode.imcms.mapping.container.DocRef; import imcode.server.Imcms; import imcode.server.document.DocumentDomainObject; import imcode.server.user.UserDomainObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * Parametrized callback for DocumentMapper#getDocument method. * A callback is updated on each request and (re)assigned to a user. * <p> * Default doc callback always returns default version of any doc if it is present and the user has at least 'view' rights on it. * <p> * Working and Custom doc callback return working and custom version of a document with particular id; * for other doc ids they behave exactly as default doc callback. * * @see imcode.server.Imcms * @see com.imcode.imcms.servlet.ImcmsSetupFilter * @see com.imcode.imcms.mapping.DocumentGetter#getDocument(int) */ public class DocGetterCallback { private interface Callback { DocumentDomainObject getDoc(int docId, DocumentMapper docMapper); } private static final Logger logger = LoggerFactory.getLogger(DocGetterCallback.class); private volatile DocumentLanguage language; private volatile boolean isDefaultLanguage; private UserDomainObject user; private Map<Integer, Callback> callbacks = new ConcurrentHashMap<>(); private Callback workingDocCallback = (docId, docMapper) -> { logger.trace("Working doc requested - user: {}, docId: {}, language: {}.", user, docId, language); return docMapper.getWorkingDocument(docId, language); }; private Callback uncheckedDefaultDocCallback = (docId, docMapper) -> { logger.trace("Default doc (unchecked) requested - user: {}, docId: {}, language: {}.", user, docId, language); return docMapper.getDefaultDocument(docId, language); }; private Callback defaultDocCallback = (docId, docMapper) -> { logger.trace("Default doc requested - user: {}, docId: {}, language: {}.", docId, language); DocumentDomainObject doc = docMapper.getDefaultDocument(docId, language); if (doc != null) { List<DocumentLanguage> docLanguages = Imcms.getServices() .getDocumentMapper() .getCommonContents(doc.getId()) .entrySet() .stream() .filter(langToContent -> langToContent.getValue().getEnabled()) .map(Map.Entry::getKey) .collect(Collectors.toCollection(ArrayList::new)); if (!docLanguages.contains(language)) { // current language is disabled for current document doc = shouldDocBeShownWithDefaultLang(doc, docLanguages) ? docMapper.getDefaultDocument(docId) : null; } } return doc; }; private boolean shouldDocBeShownWithDefaultLang(DocumentDomainObject doc, List<DocumentLanguage> docLanguages) { return (doc.getDisabledLanguageShowMode() == DocumentMeta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE && docLanguages.contains(Imcms.getServices().getDocumentLanguages().getDefault())); } public DocGetterCallback(UserDomainObject user) { this.user = user; } @SuppressWarnings("unchecked") public <T extends DocumentDomainObject> T getDoc(int docId, DocumentMapper docMapper) { Callback callback = user.isDefaultUser() ? defaultDocCallback : callbacks.getOrDefault(docId, uncheckedDefaultDocCallback); return (T) callback.getDoc(docId, docMapper); } public void setDefault(int docId) { callbacks.remove(docId); } public void setWorking(int docId) { if (!user.isDefaultUser()) { callbacks.put(docId, workingDocCallback); } } public void setCustom(int docId, int versionNo) { if (!user.isDefaultUser()) { callbacks.put(docId, versionNo == DocumentVersion.WORKING_VERSION_NO ? workingDocCallback : createCustomDocCallback(versionNo)); } } private Callback createCustomDocCallback(int versionNo) { return (docId, docMapper) -> { logger.trace("Custom doc requested - user: {}, docId: {}, versionNo: {}, language: {}.", user, docId, versionNo, language); return docMapper.getCustomDocument(DocRef.of(docId, versionNo, language.getCode())); }; } public DocumentLanguage getLanguage() { return language; } public void setLanguage(DocumentLanguage language, boolean isDefaultLanguage) { this.language = language; this.isDefaultLanguage = isDefaultLanguage; } public void setLanguage(DocumentLanguage language) { this.language = language; } }
package br.com.jq.syncthia; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import br.com.jq.syncthia.bdcreator.schema.SchemaCollection; import br.com.jq.syncthia.bdcreator.schema.SchemaCreator; import br.com.jq.syncthia.bdcreator.table.Table; import br.com.jq.syncthia.bdcreator.table.migration.MigrationStrategy; import br.com.jq.syncthia.sample.Sample1MigrationSchema; import br.com.jq.syncthia.sample.Sample2MigrationsSchema; /** * Unit test for simple App. */ public class SchemaMigrationTest extends TestCase { SchemaCollection collection; /** * Create the test case * * @param testName * name of the test case */ public SchemaMigrationTest(String testName) { super(testName); collection = new SchemaCollection(); collection.registerSchema(new Sample1MigrationSchema()); collection.registerSchema(new Sample2MigrationsSchema()); collection.createOrMigrateSchema(); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(SchemaMigrationTest.class); } public void testCreateSchema() { List<SchemaCreator> schemaList = collection.getRegisteredSchemas(); assertEquals(3, schemaList.size()); } public void testTableSchemaVersion() { SchemaCreator schema1Migration = collection.getSchema("Sample 1 migration schema"); SchemaCreator schema2Migrations = collection.getSchema("Sample 2 migrations schema"); for (Table t: schema1Migration.getTables()) { assertEquals("v1", t.getRegisteredVersion()); } for (Table t: schema2Migrations.getTables()) { assertEquals("v1", t.getRegisteredVersion()); } } public void testTableDesiredVersion() { SchemaCreator schema1Migration = collection.getSchema("Sample 1 migration schema"); SchemaCreator schema2Migrations = collection.getSchema("Sample 2 migrations schema"); for (Table t: schema1Migration.getTables()) { assertEquals("v2", t.getDesiredVersion()); } for (Table t: schema2Migrations.getTables()) { assertEquals("v3", t.getDesiredVersion()); } } public void testTableMigrations() { SchemaCreator schema1Migration = collection.getSchema("Sample 1 migration schema"); SchemaCreator schema2Migrations = collection.getSchema("Sample 2 migrations schema"); for (Table t: schema1Migration.getTables()) { List<MigrationStrategy> migrations = t.getDesiredMigrations(); assertEquals(1, migrations.size()); assertEquals("v1", migrations.get(0).getOldVersion()); assertEquals("v2", migrations.get(0).getNewVersion()); } for (Table t: schema2Migrations.getTables()) { List<MigrationStrategy> migrations = t.getDesiredMigrations(); assertEquals(2, migrations.size()); assertEquals("v1", migrations.get(0).getOldVersion()); assertEquals("v2", migrations.get(0).getNewVersion()); assertEquals(migrations.get(0).getNewVersion(), migrations.get(1).getOldVersion()); assertEquals("v2", migrations.get(1).getOldVersion()); assertEquals("v3", migrations.get(1).getNewVersion()); } } }
package com.impossibl.postgres.jdbc; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.Iterator; import java.util.List; import com.impossibl.postgres.protocol.Notice; /** * Utilities for creating SQLException and SQLWarnings from PostgreSQL's * "Notice" and "Error" message data * * @author kdubb * */ public class PSQLErrorUtils { /** * Converts the given list of notices into a chained list of SQLWarnings * * @param notices List of notices to convert * @return Root of converted list or null is no notices were given */ public static SQLWarning makeSQLWarningChain(List<Notice> notices) { Iterator<Notice> noticeIter = notices.iterator(); SQLWarning root = null; if(noticeIter.hasNext()) { root = makeSQLWarning(noticeIter.next()); SQLWarning current = root; while(noticeIter.hasNext()) { Notice notice = noticeIter.next(); // Only include warnings... if(!notice.isWarning()) continue; SQLWarning nextWarning = makeSQLWarning(notice); current.setNextWarning(nextWarning); current = nextWarning; } } return root; } /** * Converts the given list of notices into a chained list of SQLExceptions * * @param notices List of notices to convert * @return Root of converted list or null is no notices were given */ public static SQLException makeSQLExceptionChain(List<Notice> notices) { Iterator<Notice> noticeIter = notices.iterator(); SQLException root = null; if(noticeIter.hasNext()) { root = makeSQLException(noticeIter.next()); SQLException current = root; while(noticeIter.hasNext()) { SQLException nextException = makeSQLException(noticeIter.next()); current.setNextException(nextException); current = nextException; } } return root; } /** * Converts a single warning notice to a single SQLWarning * * @param notice Notice to convert * @return SQLWarning */ public static SQLWarning makeSQLWarning(Notice notice) { if(notice.isWarning()) { throw new IllegalArgumentException("notice not an error"); } return new SQLWarning(notice.message, notice.code); } /** * Converts a single error notice to a single SQLException * * @param notice Notice to convert * @return SQLException */ public static SQLException makeSQLException(Notice notice) { return new SQLException(notice.message, notice.code); } }
package GUI; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; 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.JTextArea; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import ProgramControl.MainController; @SuppressWarnings({"serial", "rawtypes", "unchecked"}) public class OrganizationStyleSelectionWindow extends JFrame implements ActionListener { private JMenuBar MenuBar; private JMenu File, Edit, View, Help; private JTextArea CurrentDirectory; private JLabel CurDir; private JButton Browse, Add, Remove, Up, Down, Return; private JList Order, Exclude; private String OrderSelectedItem, ExcludeSelectedItem; public OrganizationStyleSelectionWindow() { this.setLayout(null); //Declares each element needed for the Main Menu this.MenuBar = new JMenuBar(); this.File = new JMenu("File"); this.Edit = new JMenu("Edit"); this.View = new JMenu("View"); this.Help = new JMenu("Help"); this.CurrentDirectory = new JTextArea(MainController.CurrentDirectory.toString()); this.Browse = new JButton("Change..."); this.CurDir = new JLabel("Current Directory:"); this.Add = new JButton("Add"); this.Remove = new JButton("Remove"); this.Up = new JButton("Move Up"); this.Down = new JButton("Move Down"); this.Return = new JButton("<html><center>Return To Main Menu</center></html>"); //TODO Add options String[] Options = {/*TODO Tester*/"Album", "Artist", "Genre", "Year"}; this.Order = new JList(); this.Exclude = new JList(Options); //Adds the Action Listener to each element that requires one this.Browse.addActionListener(this); this.Add.addActionListener(this); this.Remove.addActionListener(this); this.Up.addActionListener(this); this.Down.addActionListener(this); this.Return.addActionListener(this); //Adds the List Listener to each list this.Order.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if(!e.getValueIsAdjusting()) { OrderSelectedItem = (String)Order.getSelectedValue(); } } }); this.Exclude.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if(!e.getValueIsAdjusting()) { ExcludeSelectedItem = (String)Order.getSelectedValue(); } } }); //Sets the location for each element this.CurrentDirectory.setBounds(15, 25, 520, 25); this.Browse.setBounds(550, 25, 90, 25); this.CurDir.setBounds(15, 5, 325, 15); this.Order.setBounds(15, 65, 250, 225); this.Exclude.setBounds(385, 65, 250, 225); this.Add.setBounds(275, 65, 100, 40); this.Remove.setBounds(275, 115, 100, 40); this.Up.setBounds(275, 165, 100, 40); this.Down.setBounds(275, 215, 100, 40); this.Return.setBounds(275, 295, 100, 65); //Adds each Menu Bar element to the Menu Bar this.MenuBar.add(this.File); this.MenuBar.add(this.Edit); this.MenuBar.add(this.View); this.MenuBar.add(this.Help); //Adds each element to the Window this.add(MenuBar); this.add(CurrentDirectory); this.add(Browse); this.add(CurDir); this.add(Order); this.add(Exclude); this.add(Add); this.add(Remove); this.add(Up); this.add(Down); this.add(Return); //Sets the window title, size, default for closing & sets it to open in the middle of the screen this.setTitle("Organization Style Selection"); this.setSize(665, 400); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == Browse) { int Location = MainController.FileChooser.showOpenDialog(MainController.ReferenceFrame); if(Location == JFileChooser.APPROVE_OPTION) { MainController.CurrentDirectory = MainController.FileChooser.getSelectedFile(); } this.CurDir.setText(MainController.CurrentDirectory.toString()); } else if(e.getSource() == Add) { //TODO } else if(e.getSource() == Remove) { //TODO } else if(e.getSource() == Up) { //TODO } else if(e.getSource() == Down) { //TODO } else if(e.getSource() == Return) { MainController.OSSW.setVisible(false); MainController.MainMenu.setEnabled(true); } } public ArrayList<String> getOrganizationOrder() { ArrayList<String> ItemsInOrder = new ArrayList<String>(); int i = 0; while(((String.valueOf(Order.getComponent(i)) != null) || ((String.valueOf(Order.getComponent(i)) != "")))) { ItemsInOrder.add(String.valueOf(Order.getComponent(i))); i++; } return ItemsInOrder; } }
package data.little; public class Little { static int foo; int[] a = new int[3]; /** * @param args */ public void testFloats(float x, float y, float z) { assert !(x > y && y > z); } public void testFloats2(float x, float y, float z) { assert !(x == y + 1.1f || y == z + 1.1f || x == z + 2.2f); } public void testFloatsRound(float x, float y, float z) { assert x + y + z == z + y + x; } public void testIntsRound(int x, int y, int z) { assert x + y + z == z + y + x; } public void testFloatsNot(float x, float y, float z) { assert !(x > y && y > z && z > x); } public void testFloatBox() { FloatCell fb = new FloatCell(4.0f); float f = fb.value; assert 5.0f == f - 1.0; } public void testFloatBoxNot() { FloatCell fb = new FloatCell(4.0f); float f = fb.value; assert 5.0f == f + 1.0f; } public void testFields() { List l = new List(1); l.next = new List(2); assert (l.value == 1); } public void testArrayWrite1(){ int[] arr = new int[3]; arr[1] = 1; //assert (arr.length == 1) && (arr[1]==1); assert (arr[1] == 1); //assert (arr.length ==3); } public void testArrayWrite2(){ int[] arr = new int[3]; arr[1] = 1; //assert (arr.length == 1) && (arr[1]==1); assert (arr[1] == 2); //assert (arr.length ==3); } public void testArrayWrite3(){ int[] arr = new int[3]; arr[1] = 1; assert (arr.length ==3); } public void testArrayWrite4(){ int[] arr = new int[3]; arr[1] = 1; assert (arr.length == 7); } public void testArrayWrite5(){ int[] arr = new int[3]; arr[1] = 1; assert (arr.length == 1) && (arr[1]==1); } public void testArrayWrite6(){ int[] arr = new int[5]; arr[1] = 1; arr[2] = arr[1]; arr[3] = 2; assert (arr[1] == 1 && arr[2] == 1 && arr[3] == 2); } public void testArrayWrite7(){ int[] arr = new int[5]; arr[1] = 1; arr[2] = arr[1]; arr[3] = 2; assert (arr[1] == 10 && arr[2] == 2 && arr[3] == 2); } public void testArrayWrite8(){ int[] arr = new int[5]; arr[0] = 1; assert (arr[0] == 1); } public void testArrayWrite9(){ int[] arr = new int[5]; arr[0] = 1; assert arr[0] == 2; } public void testArrayWrite10(){ int[] arr = new int[3]; arr[0] = 1; assert arr[1] == 1; } public void testArrayWrite11(){ int[] arr1 = new int[3]; int[] arr2 = new int[3]; arr1[0] = 1; arr2[0] = 2; assert arr2[0] == 2 && arr1[0] == 2; } public void testNestedIfs(){ int i = 3; int j = 4; int k = foo(i,j); assert k == 10; } int foo(int i, int j){ int k = 0; if (i == 3){ k = 9; if (j != 4){ k = k+1; } k = 8; } return k; } public void testStatic() { foo = 7; assert (foo != 7); } public void testStaticBoolean(){ Value.myResult = true; assert Value.myResult; } public void testStaticInt(){ Value.myInt = 1; assert Value.myInt == 1; } public void testStaticInt0(){ Value.myInt = 0; assert Value.myInt == 0; } public void testStaticObject(){ Object o = new Object(); Value.myObject = o; assert Value.myObject == o; } public void testStaticInt1(){ Value.myInt = 2; assert Value.myInt == 3; } public void testArray() { Little l = new Little(); assert (l.a[0] != 1); } public void testArray1(int[] b){ assert (b[0] != 1); } public void testInts(int x, int y, int z){ assert !(x > y && y > z); } public void testLoop(){ for(int i = 0; i < 3; i++){ assert i < 3; } } public void testLoop1(){ int j = 0; while (j < 3){ j++; } assert j == 5; } public static class IntCell { static final Object NULL_KEY = new Object(); int value; IntCell() { value = 1; } IntCell(int value){ this.value = value; } public boolean equals(Object o){ return (o instanceof IntCell && value == ((IntCell) o).value); } public int hashCode(){ return super.hashCode() + value; } } public static class FloatCell { static final Object NULL_KEY = new Object(); private float value; FloatCell(float value){ this.value = value; } public boolean equals(Object o){ return (o instanceof FloatCell && value == ((FloatCell) o).value); } public int hashCode(){ return super.hashCode() + (int)(1031*value); } } private static class SubCell extends IntCell { int myVal; SubCell() { myVal = 1; } } private static class Value { public static boolean myResult; public static int myInt; public static Object myObject; final int myVal; final int herVal; public Value(int myVal, int herVal){ this.myVal = myVal; this.herVal = herVal; } public boolean equals(Object o){ return (o instanceof Value) && myVal == ((Value)o).myVal && herVal == ((Value)o).herVal; } public int hashCode(){ return myVal + (5*herVal); } } private static class BValue extends Value { int hisVal; public BValue(int myVal, int herVal, int hisVal){ super(myVal, herVal); this.hisVal = hisVal; } public boolean equals(Object o){ return super.equals(o) && (o instanceof BValue) && hisVal == ((BValue)o).hisVal; } public int hashCode(){ return super.hashCode() + hisVal<<12; } } private static class List { int value; List next; List last; List(int value) { this.value = value; last = this; //next = null; } void add(int value){ List list = new List(value); last.next = list; last = list; } List remove(int value){ List temp = this; List prev = null; while(temp != null){ if (temp.value == value){ if (prev != null) { prev.next = temp.next; if (temp == last){ last = prev; List temp1 = this; while(temp1 != null){ temp1.last = prev; temp1 = temp1.next; } } return this; } else { temp.next.last = last; return temp.next; } } prev = temp; temp = temp.next; } return this; } } public void testCell(){ IntCell l = new IntCell(1); assert l.value == 1; } public void testList(){ List l = new List(1); l.add(2); l.add(3); assert l.next.last.value == 2; } public void testListRemoveOther(){ List l = new List(1); l.add(2); l.add(3); assert (l.remove(2).last.value == 3); } public void testListRemoveFirst(){ List l = new List(1); l.add(2); l.add(3); assert (l.remove(1).last.value == 3); } public void testSimpleFields(){ List l = new List(1); l.add(2); List l2 = l.next; l.next = l2.next; assert l.next == null; } public void testListRemoveCounter(){ List l = new List(1); l.add(2); l.add(3); assert (l.last.value == 13); } static class MyArrayList { int[] arr; int last; MyArrayList(int capacity){ arr = new int[capacity]; //last = 0; } void add(int v){ arr[last++] = v; } int get(int i){ return arr[i]; } } static class MyArrayListObj { Object[] arr; int last; MyArrayListObj(int capacity){ arr = new Object[capacity]; last = 0; } void add(Object o) { arr[last++] = o;} boolean contains(Object o){ return indexOf(o) >= 0; } int indexOf(Object o){ if (o == null) { for (int i = 0; i < last; i++) if (arr[i]==null) return i; } else { for (int i = 0; i< last; i++){ if (arr[i].equals(o)) return i; } } return -1; } boolean ensureCapacity(int minCapacity){ int oldCapacity = arr.length; if (minCapacity > oldCapacity) { return true; } return false; } } public void testMyArrayList1(){ MyArrayList arr = new MyArrayList(3); arr.add(1); assert arr.last == 1 && arr.arr[0] == 1; } public void testMyArrayList2(){ MyArrayListObj arr = new MyArrayListObj(3); arr.add(new IntCell(1)); assert (!arr.contains(new IntCell(1))); } public void testMyArrayList3(){ MyArrayListObj arr = new MyArrayListObj(3); arr.add(new IntCell(1)); arr.add(new IntCell(2)); boolean res = arr.contains(new IntCell(1)); assert res; } public void testMyArrayList4(){ MyArrayListObj arr = new MyArrayListObj(3); arr.add(new IntCell(1)); assert !arr.contains(new IntCell(2)); } public void testMyArrayList5(){ MyArrayListObj arr = new MyArrayListObj(3); arr.add(new IntCell(1)); assert arr.indexOf(new IntCell(1)) == 0; } public void testMyArrayList6(){ MyArrayListObj arr = new MyArrayListObj(3); arr.add(new IntCell(1)); assert arr.indexOf(new IntCell(2)) == -1; } public void testMyArrayList7(){ MyArrayListObj arr = new MyArrayListObj(2); Value v1 = new Value(1,2); Value v2 = new Value(3,4); Value v3 = new Value(1,2); arr.add(v1); arr.add(v2); assert arr.contains(v3); } public void testIntFields0(){ IntCell c = new IntCell(0); assert (c.value == 0); } public void testIntFields1(){ IntCell c = new IntCell(1); IntCell c1 = new IntCell(2); assert (c.value == 1 && c1.value == 2); } public void testIntFields2(){ IntCell c = new IntCell(1); IntCell c1 = new IntCell(2); assert c.value == 2 || c1.value == 1; } public void testCell1(){ IntCell c1 = new IntCell(1); IntCell c2 = new IntCell(2); assert (!c1.equals(c2)); } public void testCell2(){ IntCell c1 = new IntCell(3); IntCell c2 = new IntCell(3); assert (!c1.equals(c2)); } public void testArrayCopy1(){ int[] arr1 = new int[3]; arr1[0] = 1; arr1[1] = 2; int[] arr2 = new int[3]; for(int i = 0; i < arr1.length; i++){ arr2[i] = arr1[i]; } assert arr2[0] == 1 && arr2[1] == 2; } public void testArrayCopy2(){ IntCell[] arr1 = new IntCell[3]; arr1[0] = new IntCell(1); arr1[1] = new IntCell(2); IntCell[] arr2 = new IntCell[3]; for(int i = 0; i < arr1.length; i++){ arr2[i] = arr1[i]; } assert arr2[0].equals(new IntCell(1)) && arr2[1].equals(new IntCell(2)); } public void testArrayAssign(){ int[] arr = new int[3]; arr[1 + 0] = 3; assert arr[1] == 3; } public void testArrayParam(){ int[] arr1 = new int[3]; int[] arr2 = new int[3]; arr1[0] = 1; arr1[1] = 2; arr1[2] = 3; foo(arr1, arr2); assert arr2[0] == 1 && arr2[1] == 2 && arr2[2] == 3 && arr1[0] == 1 && arr1[1] == 2 && arr1[2] == 3 ; } public void testArrayParam4(){ int[] arr1 = new int[3]; int[] arr2 = new int[3]; arr1[0] = 1; arr1[1] = 2; arr1[2] = 3; foo(arr1, arr2); assert arr2[0] == 1 && arr2[1] == 2 && arr2[2] == 4 && arr1[0] == 1 && arr1[1] == 2 && arr1[2] == 3 ; } private void foo(int[] arr1, int[] arr2){ for(int i = 0; i< arr1.length; i++){ arr2[i] = arr1[i]; } } public void testArrayParam1(){ int[] arr = new int[3]; bar1(arr); assert arr[0] == 1 && arr[1] != 1; } private void bar1(int[] arr){ arr[0] = 1; arr[1] = 1; } public void testArrayParam2(){ int[] arr1 = new int[2]; int[] arr2 = new int[2]; foo1(arr2, arr1); assert arr2[0] == 1 && arr1[1] == 2; } private void foo1(int[] arr2, int[] arr1){ arr2[0] = 1; arr1[1] = 2; } public void testArrayParam3(){ int[] arr1 = new int[2]; int[] arr2 = new int[2]; foo2(arr2, arr1); assert arr2[0] == 1 && arr1[1] == 2; } private void foo2(int[] arr2, int[] arr1){ arr1[1] = 2; arr2[0] = 1; } public void testFieldParam(){ IntCell c = new IntCell(0); bar(c); assert c.value == 1; } private void bar(IntCell c){ c.value = 1; } public void testConstructorSubclass(){ SubCell c = new SubCell(); assert c.myVal == 1; } public void testObjectHashCodeCall(){ IntCell c = new IntCell(1); assert c.hashCode() == 0; } public void testObjectHashCodeCall1(){ Object o = new IntCell(); int k = hash(o); assert k == 1; } public void testObjectHashCodeCall2(){ Object k = maskNull(new IntCell()); int hash = hash(k); assert hash == 2; } static Object maskNull(Object key) { return (key == null ? IntCell.NULL_KEY : key); } private static int hash(Object o){ return o.hashCode(); } public void testIrrelevant(){ Value v = new Value(1,2); assert true; } public void testEquals(){ Value v = new Value(1,2); Value v1 = new Value(1,2); assert v.equals(v1); } public void testEquals1(){ BValue v = new BValue(1,2,3); BValue v1 = new BValue(1,2,3); assert v.equals(v1); } public void testEquals2(){ BadValue v = new BadValue(1,2,3); BadValue v1 = new BadValue(1,2,3); assert v.equals(v1); } private static class MyEntry { Object element; MyEntry next; MyEntry previous; MyEntry(Object element, MyEntry next, MyEntry previous) { this.element = element; this.next = next; this.previous = previous; } } private static class MyLinkedList { private MyEntry header; private int size = 0; public MyLinkedList() { header = new MyEntry(null, null, null); header.next = header; header.previous = header; return; } public boolean add(Object o) { //addBefore(o, header); //MyEntry newEntry = new MyEntry(o, null, null); //newEntry.previous.next = newEntry; //newEntry.next.previous = newEntry; return true; } private MyEntry addBefore(Object o, MyEntry e) { MyEntry newEntry = new MyEntry(o, e, e.previous); newEntry.previous.next = newEntry; newEntry.next.previous = newEntry; size++; return newEntry; } } public void testMyLinkedList1(){ MyLinkedList l = new MyLinkedList(); assert l.header.next == l.header.previous; } public void testMyLinkedList2(){ MyLinkedList l = new MyLinkedList(); assert l.header.next != l.header.previous; } public void testMyLinkedList3(){ MyLinkedList l = new MyLinkedList(); assert l.header == null; } public void testFieldAccess(){ MyEntry e1 = new MyEntry(new Value(1,2), null, null); MyEntry e2 = new MyEntry(new Value(3,4), null, null); e1.next = e2; e2.previous = e1; assert e2.next == e1; } }
package jkind.analysis.evaluation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import jkind.lustre.ArrayAccessExpr; import jkind.lustre.ArrayExpr; import jkind.lustre.ArrayUpdateExpr; import jkind.lustre.BinaryExpr; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.CondactExpr; import jkind.lustre.Constant; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.NodeCallExpr; import jkind.lustre.RealExpr; import jkind.lustre.RecordAccessExpr; import jkind.lustre.RecordExpr; import jkind.lustre.RecordUpdateExpr; import jkind.lustre.TupleExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.values.ArrayValue; import jkind.lustre.values.BooleanValue; import jkind.lustre.values.IntegerValue; import jkind.lustre.values.RealValue; import jkind.lustre.values.RecordValue; import jkind.lustre.values.TupleValue; import jkind.lustre.values.Value; import jkind.lustre.visitors.ExprVisitor; import jkind.util.BigFraction; public class ConstantEvaluator implements ExprVisitor<Value> { private final Map<String, Value> constants = new HashMap<>();; public ConstantEvaluator() { } public ConstantEvaluator(List<Constant> constants) { for (Constant c : constants) { addConstant(c); } } public Value addConstant(Constant c) { return constants.put(c.id, c.expr.accept(this)); } @Override public Value visit(ArrayAccessExpr e) { ArrayValue array = (ArrayValue) e.array.accept(this); IntegerValue index = (IntegerValue) e.index.accept(this); if (array == null || index == null) { return null; } return array.elements.get(index.value.intValue()); } @Override public Value visit(ArrayExpr e) { List<Value> elements = visitExprs(e.elements); if (elements == null) { return null; } return new ArrayValue(elements); } @Override public Value visit(ArrayUpdateExpr e) { ArrayValue array = (ArrayValue) e.array.accept(this); IntegerValue index = (IntegerValue) e.index.accept(this); Value value = e.value.accept(this); if (array == null || index == null || value == null) { return null; } return array.update(index.value.intValue(), value); } @Override public Value visit(BinaryExpr e) { Value left = e.left.accept(this); Value right = e.right.accept(this); if (left == null || right == null) { return null; } return left.applyBinaryOp(e.op, right); } @Override public Value visit(BoolExpr e) { return BooleanValue.fromBoolean(e.value); } @Override public Value visit(CastExpr e) { Value value = e.expr.accept(this); if (value == null) { return null; } if (e.type == NamedType.REAL && value instanceof IntegerValue) { IntegerValue iv = (IntegerValue) value; return new RealValue(new BigFraction(iv.value)); } else if (e.type == NamedType.INT && value instanceof RealValue) { RealValue rv = (RealValue) value; return new IntegerValue(rv.value.floor()); } else { throw new IllegalArgumentException(); } } @Override public Value visit(CondactExpr e) { return null; } @Override public Value visit(IdExpr e) { return constants.get(e.id); } @Override public Value visit(IfThenElseExpr e) { BooleanValue cond = (BooleanValue) e.accept(this); if (cond == null) { return null; } if (cond.value) { return e.thenExpr.accept(this); } else { return e.elseExpr.accept(this); } } @Override public Value visit(IntExpr e) { return new IntegerValue(e.value); } @Override public Value visit(NodeCallExpr e) { return null; } @Override public Value visit(RealExpr e) { return new RealValue(new BigFraction(e.value)); } @Override public Value visit(RecordAccessExpr e) { RecordValue record = (RecordValue) e.record.accept(this); if (record == null) { return null; } return record.fields.get(e.field); } @Override public Value visit(RecordExpr e) { Map<String, Value> fields = new HashMap<>(); for (Entry<String, Expr> entry : e.fields.entrySet()) { Value value = entry.getValue().accept(this); if (value == null) { return null; } fields.put(entry.getKey(), value); } return new RecordValue(fields); } @Override public Value visit(RecordUpdateExpr e) { RecordValue record = (RecordValue) e.record.accept(this); Value value = e.value.accept(this); if (record == null || value == null) { return null; } return record.update(e.field, value); } @Override public Value visit(TupleExpr e) { List<Value> elements = visitExprs(e.elements); if (elements == null) { return null; } return new TupleValue(elements); } @Override public Value visit(UnaryExpr e) { Value value = e.expr.accept(this); if (value == null) { return null; } else if (e.op == UnaryOp.PRE) { return value; } else { return value.applyUnaryOp(e.op); } } private List<Value> visitExprs(List<Expr> es) { List<Value> values = new ArrayList<>(); for (Expr e : es) { Value value = e.accept(this); if (value == null) { return null; } values.add(value); } return values; } }
package com.intalio.bpmn2.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.eclipse.bpmn2.BaseElement; import org.eclipse.bpmn2.BoundaryEvent; import org.eclipse.bpmn2.BusinessRuleTask; import org.eclipse.bpmn2.CallActivity; import org.eclipse.bpmn2.CallableElement; import org.eclipse.bpmn2.CatchEvent; import org.eclipse.bpmn2.Choreography; import org.eclipse.bpmn2.CompensateEventDefinition; import org.eclipse.bpmn2.ComplexGateway; import org.eclipse.bpmn2.ConditionalEventDefinition; import org.eclipse.bpmn2.Conversation; import org.eclipse.bpmn2.DataInput; import org.eclipse.bpmn2.DataInputAssociation; import org.eclipse.bpmn2.DataObject; import org.eclipse.bpmn2.DataOutput; import org.eclipse.bpmn2.DataOutputAssociation; import org.eclipse.bpmn2.Definitions; import org.eclipse.bpmn2.EndEvent; import org.eclipse.bpmn2.Error; import org.eclipse.bpmn2.ErrorEventDefinition; import org.eclipse.bpmn2.EscalationEventDefinition; import org.eclipse.bpmn2.Event; import org.eclipse.bpmn2.EventBasedGateway; import org.eclipse.bpmn2.EventDefinition; import org.eclipse.bpmn2.ExclusiveGateway; import org.eclipse.bpmn2.Expression; import org.eclipse.bpmn2.FlowElement; import org.eclipse.bpmn2.FlowNode; import org.eclipse.bpmn2.FormalExpression; import org.eclipse.bpmn2.Gateway; import org.eclipse.bpmn2.GlobalBusinessRuleTask; import org.eclipse.bpmn2.GlobalChoreographyTask; import org.eclipse.bpmn2.GlobalManualTask; import org.eclipse.bpmn2.GlobalScriptTask; import org.eclipse.bpmn2.GlobalTask; import org.eclipse.bpmn2.GlobalUserTask; import org.eclipse.bpmn2.InclusiveGateway; import org.eclipse.bpmn2.InputSet; import org.eclipse.bpmn2.Interface; import org.eclipse.bpmn2.IntermediateCatchEvent; import org.eclipse.bpmn2.IntermediateThrowEvent; import org.eclipse.bpmn2.ItemDefinition; import org.eclipse.bpmn2.ManualTask; import org.eclipse.bpmn2.Message; import org.eclipse.bpmn2.MessageEventDefinition; import org.eclipse.bpmn2.OutputSet; import org.eclipse.bpmn2.ParallelGateway; import org.eclipse.bpmn2.PotentialOwner; import org.eclipse.bpmn2.Process; import org.eclipse.bpmn2.Property; import org.eclipse.bpmn2.ReceiveTask; import org.eclipse.bpmn2.Resource; import org.eclipse.bpmn2.ResourceRole; import org.eclipse.bpmn2.RootElement; import org.eclipse.bpmn2.ScriptTask; import org.eclipse.bpmn2.SendTask; import org.eclipse.bpmn2.SequenceFlow; import org.eclipse.bpmn2.ServiceTask; import org.eclipse.bpmn2.Signal; import org.eclipse.bpmn2.SignalEventDefinition; import org.eclipse.bpmn2.StartEvent; import org.eclipse.bpmn2.SubProcess; import org.eclipse.bpmn2.Task; import org.eclipse.bpmn2.TerminateEventDefinition; import org.eclipse.bpmn2.ThrowEvent; import org.eclipse.bpmn2.TimerEventDefinition; import org.eclipse.bpmn2.UserTask; import org.eclipse.bpmn2.di.BPMNDiagram; import org.eclipse.bpmn2.di.BPMNEdge; import org.eclipse.bpmn2.di.BPMNPlane; import org.eclipse.bpmn2.di.BPMNShape; import org.eclipse.dd.dc.Bounds; import org.eclipse.dd.dc.Point; import org.eclipse.dd.di.DiagramElement; import org.eclipse.emf.ecore.util.FeatureMap; import com.intalio.web.profile.IDiagramProfile; /** * @author Antoine Toulme * * a marshaller to transform BPMN 2.0 elements into JSON format. * */ public class Bpmn2JsonMarshaller { private Map<String, DiagramElement> _diagramElements = new HashMap<String, DiagramElement>(); private IDiagramProfile profile; public void setProfile(IDiagramProfile profile) { this.profile = profile; } public String marshall(Definitions def) throws IOException { //StringWriter writer = new StringWriter(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonFactory f = new JsonFactory(); JsonGenerator generator = f.createJsonGenerator(baos, JsonEncoding.UTF8); marshallDefinitions(def, generator); generator.close(); return baos.toString("UTF-8"); } private void linkSequenceFlows(List<FlowElement> flowElements) { Map<String, FlowNode> nodes = new HashMap<String, FlowNode>(); for (FlowElement flowElement: flowElements) { if (flowElement instanceof FlowNode) { nodes.put(flowElement.getId(), (FlowNode) flowElement); if (flowElement instanceof SubProcess) { linkSequenceFlows(((SubProcess) flowElement).getFlowElements()); } } } for (FlowElement flowElement: flowElements) { if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; if (sequenceFlow.getSourceRef() == null && sequenceFlow.getTargetRef() == null) { String id = sequenceFlow.getId(); try { String[] subids = id.split("-_"); String id1 = subids[0]; String id2 = "_" + subids[1]; FlowNode source = nodes.get(id1); if (source != null) { sequenceFlow.setSourceRef(source); } FlowNode target = nodes.get(id2); if (target != null) { sequenceFlow.setTargetRef(target); } } catch (Throwable t) { // Do nothing } } } } } private void marshallDefinitions(Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { try{ generator.writeStartObject(); generator.writeObjectField("resourceId", def.getId()); /** * "properties":{"name":"", * "documentation":"", * "auditing":"", * "monitoring":"", * "executable":"true", * "package":"com.sample", * "vardefs":"a,b,c,d", * "id":"", * "version":"", * "author":"", * "language":"", * "namespaces":"", * "targetnamespace":"", * "expressionlanguage":"", * "typelanguage":"", * "creationdate":"", * "modificationdate":"" * } */ Map<String, Object> props = new LinkedHashMap<String, Object>(); props.put("namespaces", ""); props.put("targetnamespace", def.getTargetNamespace()); props.put("typelanguage", def.getTypeLanguage()); props.put("name",def.getName()); props.put("id", def.getId()); props.put("expressionlanguage", def.getExpressionLanguage()); if( def.getDocumentation() != null && def.getDocumentation().size() > 0 ) { props.put("documentation", def.getDocumentation().get(0).getText()); } for (RootElement rootElement : def.getRootElements()) { if (rootElement instanceof Process) { // have to wait for process node to finish properties and stencil marshalling props.put("executable", ((Process) rootElement).isIsExecutable() + ""); props.put("id", ((Process) rootElement).getId()); List<Property> processProperties = ((Process) rootElement).getProperties(); if(processProperties != null && processProperties.size() > 0) { String propVal = ""; for(int i=0; i<processProperties.size(); i++) { Property p = processProperties.get(i); propVal += p.getId(); if(i != processProperties.size()-1) { propVal += ","; } } props.put("vardefs", propVal); } // packageName and version are jbpm-specific extension attribute Iterator<FeatureMap.Entry> iter = ((Process) rootElement).getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("packageName")) { props.put("package", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("version")) { props.put("version", entry.getValue()); } } marshallProperties(props, generator); marshallStencil("BPMNDiagram", generator); linkSequenceFlows(((Process) rootElement).getFlowElements()); marshallProcess((Process) rootElement, def, generator); } else if (rootElement instanceof Interface) { // TODO } else if (rootElement instanceof ItemDefinition) { // TODO } else if (rootElement instanceof Resource) { // TODO } else if (rootElement instanceof Error) { // TODO } else if (rootElement instanceof Message) { // TODO } else if (rootElement instanceof Signal) { // TODO } else { throw new UnsupportedOperationException("Unknown root element " + rootElement); //TODO! } } generator.writeObjectFieldStart("stencilset"); generator.writeObjectField("url", this.profile.getStencilSetURL()); generator.writeObjectField("namespace", this.profile.getStencilSetNamespaceURL()); generator.writeEndObject(); generator.writeArrayFieldStart("ssextensions"); generator.writeObject(this.profile.getStencilSetExtensionURL()); generator.writeEndArray(); generator.writeEndObject(); } finally { _diagramElements.clear(); } } /** private void marshallMessage(Message message, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); generator.writeStartObject(); generator.writeObjectField("resourceId", message.getId()); properties.put("name", message.getName()); if(message.getDocumentation() != null && message.getDocumentation().size() > 0) { properties.put("documentation", message.getDocumentation().get(0).getText()); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Message"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeEndArray(); generator.writeEndObject(); } **/ private void marshallCallableElement(CallableElement callableElement, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", callableElement.getId()); if (callableElement instanceof Choreography) { marshallChoreography((Choreography) callableElement, generator); } else if (callableElement instanceof Conversation) { marshallConversation((Conversation) callableElement, generator); } else if (callableElement instanceof GlobalChoreographyTask) { marshallGlobalChoreographyTask((GlobalChoreographyTask) callableElement, generator); } else if (callableElement instanceof GlobalTask) { marshallGlobalTask((GlobalTask) callableElement, generator); } else if (callableElement instanceof Process) { marshallProcess((Process) callableElement, def, generator); } else { throw new UnsupportedOperationException("TODO"); //TODO! } generator.writeEndObject(); } private void marshallProcess(Process process, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { BPMNPlane plane = null; for (BPMNDiagram d: def.getDiagrams()) { if (d != null) { BPMNPlane p = d.getPlane(); if (p != null) { if (p.getBpmnElement() == process) { plane = p; break; } } } } if (plane == null) { throw new IllegalArgumentException("Could not find BPMNDI information"); } generator.writeArrayFieldStart("childShapes"); for (FlowElement flowElement: process.getFlowElements()) { marshallFlowElement(flowElement, plane, generator, 0, 0); } generator.writeEndArray(); } private void setCatchEventProperties(CatchEvent event, Map<String, Object> properties) { if(event.getOutputSet() != null) { List<DataOutput> dataOutputs = event.getOutputSet().getDataOutputRefs(); StringBuffer doutbuff = new StringBuffer(); for(DataOutput dout : dataOutputs) { doutbuff.append(dout.getName()); doutbuff.append(","); } if(doutbuff.length() > 0) { doutbuff.setLength(doutbuff.length() - 1); } properties.put("dataoutput", doutbuff.toString()); List<DataOutputAssociation> outputAssociations = event.getDataOutputAssociation(); StringBuffer doutassociationbuff = new StringBuffer(); for(DataOutputAssociation doa : outputAssociations) { doutassociationbuff.append(((DataOutput)doa.getSourceRef().get(0)).getName()); doutassociationbuff.append("->"); doutassociationbuff.append(doa.getTargetRef().getId()); doutassociationbuff.append(","); } if(doutassociationbuff.length() > 0) { doutassociationbuff.setLength(doutassociationbuff.length() - 1); } properties.put("dataoutputassociations", doutassociationbuff.toString()); } // event definitions List<EventDefinition> eventdefs = event.getEventDefinitions(); for(EventDefinition ed : eventdefs) { if(ed instanceof TimerEventDefinition) { TimerEventDefinition ted = (TimerEventDefinition) ed; if(ted.getTimeDate() != null) { properties.put("timedate", ((FormalExpression) ted.getTimeDate()).getBody()); } if(ted.getTimeDuration() != null) { properties.put("timeduration", ((FormalExpression) ted.getTimeDuration()).getBody()); } if(ted.getTimeCycle() != null) { properties.put("timecycle", ((FormalExpression) ted.getTimeCycle()).getBody()); } } else if( ed instanceof SignalEventDefinition) { if(((SignalEventDefinition) ed).getSignalRef() != null) { properties.put("signalref", ((SignalEventDefinition) ed).getSignalRef().getName()); } } } } private void setThrowEventProperties(ThrowEvent event, Map<String, Object> properties) { if(event.getInputSet() != null) { List<DataInput> dataInputs = event.getInputSet().getDataInputRefs(); StringBuffer dinbuff = new StringBuffer(); for(DataInput din : dataInputs) { dinbuff.append(din.getName()); dinbuff.append(","); } if(dinbuff.length() > 0) { dinbuff.setLength(dinbuff.length() - 1); } properties.put("datainput", dinbuff.toString()); List<DataInputAssociation> inputAssociations = event.getDataInputAssociation(); StringBuffer dinassociationbuff = new StringBuffer(); for(DataInputAssociation din : inputAssociations) { dinassociationbuff.append(din.getSourceRef().get(0).getId()); dinassociationbuff.append("->"); dinassociationbuff.append( ((DataInput)din.getTargetRef()).getName()); dinassociationbuff.append(","); } if(dinassociationbuff.length() > 0) { dinassociationbuff.setLength(dinassociationbuff.length() - 1); } properties.put("datainputassociations", dinassociationbuff.toString()); } // event definitions // TODO } private void marshallFlowElement(FlowElement flowElement, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", flowElement.getId()); Map<String, Object> catchEventProperties = new LinkedHashMap<String, Object>(); Map<String, Object> throwEventProperties = new LinkedHashMap<String, Object>(); if(flowElement instanceof CatchEvent) { setCatchEventProperties((CatchEvent) flowElement, catchEventProperties); } if(flowElement instanceof ThrowEvent) { setThrowEventProperties((ThrowEvent) flowElement, throwEventProperties); } if (flowElement instanceof StartEvent) { marshallStartEvent((StartEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof EndEvent) { marshallEndEvent((EndEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties); } else if (flowElement instanceof IntermediateThrowEvent) { marshallIntermediateThrowEvent((IntermediateThrowEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties); } else if (flowElement instanceof IntermediateCatchEvent) { marshallIntermediateCatchEvent((IntermediateCatchEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof BoundaryEvent) { marshallBoundaryEvent((BoundaryEvent) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof Task) { marshallTask((Task) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof SequenceFlow) { marshallSequenceFlow((SequenceFlow) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof ParallelGateway) { marshallParallelGateway((ParallelGateway) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof ExclusiveGateway) { marshallExclusiveGateway((ExclusiveGateway) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof InclusiveGateway) { marshallInclusiveGateway((InclusiveGateway) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof EventBasedGateway) { marshallEventBasedGateway((EventBasedGateway) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof ComplexGateway) { marshallComplexGateway((ComplexGateway) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof CallActivity) { marshallCallActivity((CallActivity) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof SubProcess) { marshallSubProcess((SubProcess) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof DataObject) { marshallDataObject((DataObject) flowElement, plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Unknown flow element " + flowElement); } generator.writeEndObject(); } private void marshallStartEvent(StartEvent startEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = startEvent.getEventDefinitions(); if (eventDefinitions == null || eventDefinitions.size() == 0) { marshallNode(startEvent, properties, "StartNoneEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof ConditionalEventDefinition) { marshallNode(startEvent, properties, "StartConditionalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof SignalEventDefinition) { marshallNode(startEvent, properties, "StartSignalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(startEvent, properties, "StartMessageEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(startEvent, properties, "StartTimerEvent", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Multiple event definitions not supported for start event"); } } private void marshallEndEvent(EndEvent endEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = endEvent.getEventDefinitions(); if (eventDefinitions == null || eventDefinitions.size() == 0) { marshallNode(endEvent, properties, "EndNoneEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof TerminateEventDefinition) { marshallNode(endEvent, properties, "EndTerminateEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof SignalEventDefinition) { marshallNode(endEvent, properties, "EndSignalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(endEvent, properties, "EndMessageEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(endEvent, properties, "EndErrorEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(endEvent, properties, "EndEscalationEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(endEvent, properties, "EndCompensationEvent", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Multiple event definitions not supported for end event"); } } private void marshallIntermediateCatchEvent(IntermediateCatchEvent catchEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = catchEvent.getEventDefinitions(); if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(catchEvent, properties, "IntermediateSignalEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(catchEvent, properties, "IntermediateMessageEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(catchEvent, properties, "IntermediateTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ConditionalEventDefinition) { marshallNode(catchEvent, properties, "IntermediateConditionalEvent", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("None or multiple event definitions not supported for intermediate catch event"); } } private void marshallBoundaryEvent(BoundaryEvent boundaryEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = boundaryEvent.getEventDefinitions(); if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(boundaryEvent, "IntermediateEscalationEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(boundaryEvent, "IntermediateErrorEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(boundaryEvent, "IntermediateTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(boundaryEvent, "IntermediateCompensationEventCatching", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("None or multiple event definitions not supported for boundary event"); } } private void marshallIntermediateThrowEvent(IntermediateThrowEvent throwEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = throwEvent.getEventDefinitions(); if (eventDefinitions.size() == 0) { marshallNode(throwEvent, properties, "IntermediateEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(throwEvent, "IntermediateSignalEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(throwEvent, "IntermediateMessageEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(throwEvent, "IntermediateEscalationEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(throwEvent, "IntermediateCompensationEventThrowing", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("None or multiple event definitions not supported for intermediate throw event"); } } private void marshallTask(Task task, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); String taskType = "None"; if (task instanceof BusinessRuleTask) { taskType = "Business Rule"; Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("ruleFlowGroup")) { properties.put("ruleflowgroup", entry.getValue()); } } } else if (task instanceof ScriptTask) { ScriptTask scriptTask = (ScriptTask) task; properties.put("script", scriptTask.getScript()); properties.put("script_language", scriptTask.getScriptFormat()); taskType = "Script"; } else if (task instanceof ServiceTask) { taskType = "Service"; } else if (task instanceof ManualTask) { taskType = "Manual"; } else if (task instanceof UserTask) { taskType = "User"; // get the user task actors List<ResourceRole> roles = task.getResources(); StringBuilder sb = new StringBuilder(); for(ResourceRole role : roles) { if(role instanceof PotentialOwner) { FormalExpression fe = (FormalExpression) ( (PotentialOwner)role).getResourceAssignmentExpression().getExpression(); sb.append(fe.getBody()); sb.append(","); } } if(sb.length() > 0) { //get rid of annoying last comma sb.setLength(sb.length() - 1); } properties.put("actors", sb.toString()); } else if (task instanceof SendTask) { taskType = "Send"; } else if (task instanceof ReceiveTask) { taskType = "Receive"; } properties.put("tasktype", taskType); // get out the droolsjbpm-specific attributes "ruleflowGroup" and "taskName" Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("taskName")) { properties.put("taskname", entry.getValue()); } } // data inputs if(task.getIoSpecification() != null) { List<InputSet> inputSetList = task.getIoSpecification().getInputSets(); StringBuilder dataInBuffer = new StringBuilder(); for(InputSet inset : inputSetList) { List<DataInput> dataInputList = inset.getDataInputRefs(); for(DataInput dataIn : dataInputList) { // dont add "TaskName" as that is added manually if(dataIn.getName() != null && !dataIn.getName().equals("TaskName")) { dataInBuffer.append(dataIn.getName()); dataInBuffer.append(","); } } } if(dataInBuffer.length() > 0) { dataInBuffer.setLength(dataInBuffer.length() - 1); } properties.put("datainputset", dataInBuffer.toString()); } // data outputs if(task.getIoSpecification() != null) { List<OutputSet> outputSetList = task.getIoSpecification().getOutputSets(); StringBuilder dataOutBuffer = new StringBuilder(); for(OutputSet outset : outputSetList) { List<DataOutput> dataOutputList = outset.getDataOutputRefs(); for(DataOutput dataOut : dataOutputList) { dataOutBuffer.append(dataOut.getName()); dataOutBuffer.append(","); } } if(dataOutBuffer.length() > 0) { dataOutBuffer.setLength(dataOutBuffer.length() - 1); } properties.put("dataoutputset", dataOutBuffer.toString()); } // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = task.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = task.getDataOutputAssociations(); List<String> uniDirectionalAssociations = new ArrayList<String>(); List<String> biDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : inputAssociations) { if(datain.getSourceRef().size() > 0) { String lhsAssociation = datain.getSourceRef().get(0).getId(); String rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); boolean isBiDirectional = false; // check if this is a bi-directional association for(DataOutputAssociation dataout : outputAssociations) { if(dataout.getTargetRef().getId().equals(lhsAssociation) && ((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) { isBiDirectional = true; break; } } if(isBiDirectional) { associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation); associationBuff.append(","); biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } else { associationBuff.append(lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } } } for(DataOutputAssociation dataout : outputAssociations) { if(dataout.getSourceRef().size() > 0) { String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName(); String rhsAssociation = dataout.getTargetRef().getId(); boolean wasBiDirectional = false; // check if we already addressed this association as bidirectional for(String bda : biDirectionalAssociations) { String[] dbaparts = bda.split( ",\\s*" ); if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) { wasBiDirectional = true; break; } } if(!wasBiDirectional) { associationBuff.append(lhsAssociation).append("->").append(rhsAssociation); } } } if(associationBuff.length() > 0) { //get rid of annoying last comma associationBuff.setLength(associationBuff.length() - 1); } properties.put("assignments", associationBuff.toString()); // marshall the node out marshallNode(task, properties, "Task", plane, generator, xOffset, yOffset); } private void marshallParallelGateway(ParallelGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { marshallNode(gateway, "ParallelGateway", plane, generator, xOffset, yOffset); } private void marshallExclusiveGateway(ExclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { marshallNode(gateway, "Exclusive_Databased_Gateway", plane, generator, xOffset, yOffset); } private void marshallInclusiveGateway(InclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { marshallNode(gateway, "InclusiveGateway", plane, generator, xOffset, yOffset); } private void marshallEventBasedGateway(EventBasedGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { marshallNode(gateway, "EventbasedGateway", plane, generator, xOffset, yOffset); } private void marshallComplexGateway(ComplexGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { marshallNode(gateway, "ComplexGateway", plane, generator, xOffset, yOffset); } private void marshallCallActivity(CallActivity callActivity, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { marshallNode(callActivity, "CollapsedSubprocess", plane, generator, xOffset, yOffset); } private void marshallNode(FlowNode node, String stencil, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { marshallNode(node, null, stencil, plane, generator, xOffset, yOffset); } private void marshallNode(FlowNode node, Map<String, Object> properties, String stencil, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { if (properties == null) { properties = new LinkedHashMap<String, Object>(); } if(node.getDocumentation() != null && node.getDocumentation().size() > 0) { properties.put("documentation", node.getDocumentation().get(0).getText()); } properties.put("name", node.getName()); marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", stencil); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (SequenceFlow outgoing: node.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } generator.writeEndArray(); BPMNShape shape = (BPMNShape) findDiagramElement(plane, node); Bounds bounds = shape.getBounds(); correctEventNodeSize(shape); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } private void correctEventNodeSize(BPMNShape shape) { BaseElement element = shape.getBpmnElement(); if (element instanceof Event) { Bounds bounds = shape.getBounds(); float width = bounds.getWidth(); float height = bounds.getHeight(); if (width != 30 || height != 30) { bounds.setWidth(30); bounds.setHeight(30); float x = bounds.getX(); float y = bounds.getY(); x = x - ((30 - width)/2); y = y - ((30 - height)/2); bounds.setX(x); bounds.setY(y); } } else if (element instanceof Gateway) { Bounds bounds = shape.getBounds(); float width = bounds.getWidth(); float height = bounds.getHeight(); if (width != 40 || height != 40) { bounds.setWidth(40); bounds.setHeight(40); float x = bounds.getX(); float y = bounds.getY(); x = x - ((40 - width)/2); y = y - ((40 - height)/2); bounds.setX(x); bounds.setY(y); } } } private void marshallDataObject(DataObject dataObject, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("name", dataObject.getName()); marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "DataObject"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, dataObject)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } private void marshallSubProcess(SubProcess subProcess, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("name", subProcess.getName()); marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Subprocess"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); Bounds bounds = ((BPMNShape) findDiagramElement(plane, subProcess)).getBounds(); for (FlowElement flowElement: subProcess.getFlowElements()) { marshallFlowElement(flowElement, plane, generator, (int) (xOffset + bounds.getX()), (int) (yOffset + bounds.getY())); } generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (BoundaryEvent boundaryEvent: subProcess.getBoundaryEventRefs()) { generator.writeStartObject(); generator.writeObjectField("resourceId", boundaryEvent.getId()); generator.writeEndObject(); } for (SequenceFlow outgoing: subProcess.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } generator.writeEndArray(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } private void marshallSequenceFlow(SequenceFlow sequenceFlow, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("name", sequenceFlow.getName()); Expression conditionExpression = sequenceFlow.getConditionExpression(); if (conditionExpression instanceof FormalExpression) { properties.put("conditionexpression", ((FormalExpression) conditionExpression).getBody()); properties.put("conditionexpression_language", ((FormalExpression) conditionExpression).getLanguage()); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "SequenceFlow"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeStartObject(); generator.writeObjectField("resourceId", sequenceFlow.getTargetRef().getId()); generator.writeEndObject(); generator.writeEndArray(); Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getSourceRef())).getBounds(); Bounds targetBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getTargetRef())).getBounds(); generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", sourceBounds.getWidth() / 2); generator.writeObjectField("y", sourceBounds.getHeight() / 2); generator.writeEndObject(); List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, sequenceFlow)).getWaypoint(); for (int i = 1; i < waypoints.size() - 1; i++) { Point waypoint = waypoints.get(i); generator.writeStartObject(); generator.writeObjectField("x", waypoint.getX()); generator.writeObjectField("y", waypoint.getY()); generator.writeEndObject(); } generator.writeStartObject(); generator.writeObjectField("x", targetBounds.getWidth() / 2); generator.writeObjectField("y", targetBounds.getHeight() / 2); generator.writeEndObject(); generator.writeEndArray(); } private DiagramElement findDiagramElement(BPMNPlane plane, FlowElement flowElement) { DiagramElement result = _diagramElements.get(flowElement.getId()); if (result != null) { return result; } for (DiagramElement element: plane.getPlaneElement()) { if ((element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == flowElement) || (element instanceof BPMNShape && ((BPMNShape) element).getBpmnElement() == flowElement)) { _diagramElements.put(flowElement.getId(), element); return element; } } throw new IllegalArgumentException( "Could not find BPMNDI information for " + flowElement.getId()); } private void marshallGlobalTask(GlobalTask globalTask, JsonGenerator generator) { if (globalTask instanceof GlobalBusinessRuleTask) { } else if (globalTask instanceof GlobalManualTask) { } else if (globalTask instanceof GlobalScriptTask) { } else if (globalTask instanceof GlobalUserTask) { } else { } } private void marshallGlobalChoreographyTask(GlobalChoreographyTask callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } private void marshallConversation(Conversation callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } private void marshallChoreography(Choreography callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } private void marshallProperties(Map<String, Object> properties, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeObjectFieldStart("properties"); for (Entry<String, Object> entry : properties.entrySet()) { generator.writeObjectField(entry.getKey(), String.valueOf(entry.getValue())); } generator.writeEndObject(); } private void marshallStencil(String stencilId, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", stencilId); generator.writeEndObject(); } }
package com.dbpm.repository; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FileRepositoryTest{ static String TESTPACKAGE = "Testpackage-1.0.0-oracle.dbpgk"; String repoName = "testrepo.xml"; String storeName = "store"; FileRepository repo; @Before public void setup() { repo = new FileRepository(repoName, storeName); } @Test public void test_createRepo() { assertTrue(repo.createRepo()); } @Test public void test_checkRepo() { assertTrue(repo.checkRepo()); } @Test public void test_writeEntry() { repo.createRepo(); assertTrue(repo.writeEntry("testDB", "TestSchema", new Package(TESTPACKAGE))); } @Test public void test_isPackageInstalledPositive() throws Exception{ repo.createRepo(); assertTrue(repo.writeEntry("testDB", "TestSchema", new Package(TESTPACKAGE))); assertTrue(repo.isPackageInstalled("testDB", "TestSchema", new Package(TESTPACKAGE))); } @Test public void test_isPackageInstalledNegative() throws Exception { repo.createRepo(); // No database or schema exist assertFalse(repo.isPackageInstalled("testDB", "TestSchema", new Package(TESTPACKAGE))); // No schema exists but database does already exist assertTrue(repo.writeEntry("testDB", "TestSchema", new Package(TESTPACKAGE))); assertFalse(repo.isPackageInstalled("testDB", "OtherTestSchema", new Package(TESTPACKAGE))); // Schema and DB exist but package does not exist assertFalse(repo.isPackageInstalled("testDB", "TestSchema", new Package("dummy-9.9.9-mysql.dbpgk"))); } @Test public void test_savePackage() throws IOException { repo.createRepo(); byte[] content = Files.readAllBytes(Paths.get(repoName)); repo.savePackage(new Package(TESTPACKAGE), content); } @After public void tearDown() { new File(repoName).delete(); new File(storeName).delete(); } }
package com.martiansoftware.io; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.nio.channels.FileLock; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; /** * This class is similar to the standard java.io.FileOutputStream, except that * the destination file is not touched until the stream is closed. The destination * file is then atomically updated (replaced if necessary) with the freshly-written contents. * * The strategy is to: * <ol> * <li>write to a temporary file in the same directory as the destination file.</li> * <li>create a backup of the original file (if it exists) in the same directory</li> * <li>atomically copy the temporary file to the destination file</li> * <li>delete the backup file</li> * </ol> * * If anything goes wrong, the temporary file will be deleted. If anything goes * wrong between backing up and replacing the original, a backup file may * remain on disk (and can be obtained via getBackup()). If all goes well, * no temporary or backup files will remain on disk after closing the stream. * * @author Marty Lamb */ public class AtomicFileOutputStream extends OutputStream { private final Path _dest; private final Path _tmp; private final Path _bak; private final FileLock _fileLock; private final FileOutputStream _out; /** * Creates a new AtomicFileOutputStream to write to or replace the specified File * @param file the File to write to or replace * @throws IOException */ public AtomicFileOutputStream(File file) throws IOException { this (file.toPath()); } /** * Creates a new AtomicFileOutputStream to write to or replace the File at the specified Path * @param path the path of the File to write to or replace * @throws IOException */ public AtomicFileOutputStream(Path path) throws IOException { _dest = path; _fileLock = new RandomAccessFile(_dest.toFile(), "rw").getChannel().tryLock(); try { _tmp = Files.createTempFile(_dest.getParent(), _dest.getName(_dest.getNameCount() - 1).toString() + ".", ".tmp"); _bak = _tmp.resolveSibling(_tmp.getFileName().toString().replaceAll("\\.tmp$", ".bak")); _out = new FileOutputStream(_tmp.toFile()); } catch (IOException e) { cleanup(); throw e; } } /** * Returns the Path of a possibly nonexistent backup copy of the original File that is being replaced (if any) * @return the Path of a possibly nonexistent backup copy of the original File that is being replaced (if any) */ public Path getBackup() { return _bak; } @Override public void close() throws IOException { io(() -> _out.close()); io(() -> finish(true)); } public void cancel() throws IOException { io(() -> _out.close()); io(() -> finish(false)); } @Override public void flush() throws IOException { io(() -> _out.flush()); } @Override public void write(byte[] b) throws IOException { io(() -> _out.write(b)); } @Override public void write(byte[] b, int off, int len) throws IOException { io(() -> _out.write(b, off, len)); } @Override public void write(int b) throws IOException { io(() -> _out.write(b)); } // wraps around an IO operation to clean up any temporary files if an exception occurs private void io(DelegatedIo d) throws IOException { check(); try { d.io(); } catch (IOException e) { cleanup(); throw e; } } // perform the final operations to move the temporary file to its final destination private void finish(boolean success) throws IOException { check(); if (success) { try { // copy original to .bak Files.copy(_dest, _bak, StandardCopyOption.REPLACE_EXISTING); // atomically move tmp over original Files.move(_tmp, _dest, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { cleanup(); throw(e); } } cleanup(); Files.deleteIfExists(_bak); // only delete backup if everything works } private void check() throws IOException { if (!_fileLock.isValid()) throw new IOException("Stream is closed or invalid."); } private void cleanup() { synchronized(_fileLock) { if (_fileLock.isValid()) { try { _fileLock.release(); } catch (IOException ignored) {} try { Files.deleteIfExists(_tmp); } catch (IOException ignored) {} } } } private interface DelegatedIo { public void io() throws IOException; } }
package com.jme3.material; import com.jme3.export.*; import com.jme3.scene.Mesh; import java.io.IOException; /** * <code>RenderState</code> specifies material rendering properties that cannot * be controlled by a shader on a {@link Material}. The properties * allow manipulation of rendering features such as depth testing, alpha blending, * face culling, stencil operations, and much more. * * @author Kirill Vainer */ public class RenderState implements Cloneable, Savable { /** * The <code>DEFAULT</code> render state is the one used by default * on all materials unless changed otherwise by the user. * * <p> * It has the following properties: * <ul> * <li>Back Face Culling</li> * <li>Depth Testing Enabled</li> * <li>Depth Writing Enabled</li> * </ul> */ public static final RenderState DEFAULT = new RenderState(); /** * The <code>NULL</code> render state is identical to the {@link RenderState#DEFAULT} * render state except that depth testing and face culling are disabled. */ public static final RenderState NULL = new RenderState(); /** * The <code>ADDITIONAL</code> render state is identical to the * {@link RenderState#DEFAULT} render state except that all apply * values are set to false. This allows the <code>ADDITIONAL</code> render * state to be combined with other state but only influencing values * that were changed from the original. */ public static final RenderState ADDITIONAL = new RenderState(); /** * <code>TestFunction</code> specifies the testing function for stencil test * function. * * <p> * The reference value given in the stencil command is the input value while * the reference is the value already in the stencil buffer. */ public enum TestFunction { /** * The test always fails */ Never, /** * The test succeeds if the input value is equal to the reference value. */ Equal, /** * The test succeeds if the input value is less than the reference value. */ Less, /** * The test succeeds if the input value is less than or equal to * the reference value. */ LessOrEqual, /** * The test succeeds if the input value is greater than the reference value. */ Greater, /** * The test succeeds if the input value is greater than or equal to * the reference value. */ GreaterOrEqual, /** * The test succeeds if the input value does not equal the * reference value. */ NotEqual, /** * The test always passes */ Always } /** * <code>BlendEquation</code> specifies the blending equation to combine * pixels. */ public enum BlendEquation { /** * Sets the blend equation so that the source and destination data are * added. (Default) Clamps to [0,1] Useful for things like antialiasing * and transparency. */ Add, /** * Sets the blend equation so that the source and destination data are * subtracted (Src - Dest). Clamps to [0,1] Falls back to Add if * supportsSubtract is false. */ Subtract, /** * Same as Subtract, but the order is reversed (Dst - Src). Clamps to * [0,1] Falls back to Add if supportsSubtract is false. */ ReverseSubtract, /** * Sets the blend equation so that each component of the result color is * the minimum of the corresponding components of the source and * destination colors. This and Max are useful for applications that * analyze image data (image thresholding against a constant color, for * example). Falls back to Add if supportsMinMax is false. */ Min, /** * Sets the blend equation so that each component of the result color is * the maximum of the corresponding components of the source and * destination colors. This and Min are useful for applications that * analyze image data (image thresholding against a constant color, for * example). Falls back to Add if supportsMinMax is false. */ Max } /** * <code>BlendEquationAlpha</code> specifies the blending equation to * combine pixels for the alpha component. */ public enum BlendEquationAlpha { /** * Sets the blend equation to be the same as the one defined by * {@link #blendEquation}. * */ InheritColor, /** * Sets the blend equation so that the source and destination data are * added. (Default) Clamps to [0,1] Useful for things like antialiasing * and transparency. */ Add, /** * Sets the blend equation so that the source and destination data are * subtracted (Src - Dest). Clamps to [0,1] Falls back to Add if * supportsSubtract is false. */ Subtract, /** * Same as Subtract, but the order is reversed (Dst - Src). Clamps to * [0,1] Falls back to Add if supportsSubtract is false. */ ReverseSubtract, /** * Sets the blend equation so that the result alpha is the minimum of * the source alpha and destination alpha. This and Max are useful for * applications that analyze image data (image thresholding against a * constant color, for example). Falls back to Add if supportsMinMax is * false. */ Min, /** * sSets the blend equation so that the result alpha is the maximum of * the source alpha and destination alpha. This and Min are useful for * applications that analyze image data (image thresholding against a * constant color, for example). Falls back to Add if supportsMinMax is * false. */ Max } /** * <code>BlendFunc</code> defines the blending functions for use with * <code>BlendMode.Custom</code>. * Source color components are referred to as (R_s0, G_s0, B_s0, A_s0). * Destination color components are referred to as (R_d, G_d, B_d, A_d). */ public enum BlendFunc { /** * RGB Factor (0, 0, 0), Alpha Factor (0) */ Zero, /** * RGB Factor (1, 1, 1), Alpha Factor (1) */ One, /** * RGB Factor (R_s0, G_s0, B_s0), Alpha Factor (A_s0) */ Src_Color, /** * RGB Factor (1-R_s0, 1-G_s0, 1-B_s0), Alpha Factor (1-A_s0) */ One_Minus_Src_Color, /** * RGB Factor (R_d, G_d, B_d), Alpha Factor (A_d) */ Dst_Color, /** * RGB Factor (1-R_d, 1-G_d, 1-B_d), Alpha Factor (1-A_d) */ One_Minus_Dst_Color, /** * RGB Factor (A_s0, A_s0, A_s0), Alpha Factor (A_s0) */ Src_Alpha, /** * RGB Factor (1-A_s0, 1-A_s0, 1-A_s0), Alpha Factor (1-A_s0) */ One_Minus_Src_Alpha, /** * RGB Factor (A_d, A_d, A_d), Alpha Factor (A_d) */ Dst_Alpha, /** * RGB Factor (1-A_d, 1-A_d, 1-A_d), Alpha Factor (1-A_d) */ One_Minus_Dst_Alpha, /** * RGB Factor (i, i, i), Alpha Factor (1) */ Src_Alpha_Saturate; } /** * <code>BlendMode</code> specifies the blending operation to use. * * @see RenderState#setBlendMode(com.jme3.material.RenderState.BlendMode) */ public enum BlendMode { /** * No blending mode is used. */ Off, /** * Additive blending. For use with glows and particle emitters. * <p> * Result = Source Color + Destination Color -&gt; (GL_ONE, GL_ONE) */ Additive, /** * Premultiplied alpha blending, for use with premult alpha textures. * <p> * Result = Source Color + (Dest Color * (1 - Source Alpha) ) -&gt; (GL_ONE, GL_ONE_MINUS_SRC_ALPHA) */ PremultAlpha, /** * Additive blending that is multiplied with source alpha. * For use with glows and particle emitters. * <p> * Result = (Source Alpha * Source Color) + Dest Color -&gt; (GL_SRC_ALPHA, GL_ONE) */ AlphaAdditive, /** * Color blending, blends in color from dest color * using source color. * <p> * Result = Source Color + (1 - Source Color) * Dest Color -&gt; (GL_ONE, GL_ONE_MINUS_SRC_COLOR) */ Color, /** * Alpha blending, interpolates to source color from dest color * using source alpha. * <p> * Result = Source Alpha * Source Color + * (1 - Source Alpha) * Dest Color -&gt; (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) */ Alpha, /** * Alpha blending, interpolates to source color from dest color * using source alpha. * The resulting alpha is the sum between the source alpha and the destination alpha. * <p> * Result.rgb = Source Alpha * Source Color + * (1 - Source Alpha) * Dest Color -&gt; (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) * Result.a = 1 * Source Alpha + 1 * Dest Alpha -&gt; (GL_ONE, GL_ONE) * */ AlphaSumA, /** * Multiplies the source and dest colors. * <p> * Result = Source Color * Dest Color -&gt; (GL_DST_COLOR, GL_ZERO) */ Modulate, /** * Multiplies the source and dest colors then doubles the result. * <p> * Result = 2 * Source Color * Dest Color -&gt; (GL_DST_COLOR, GL_SRC_COLOR) */ ModulateX2, /** * Opposite effect of Modulate/Multiply. Invert both colors, multiply and * then invert the result. * <p> * Result = 1 - (1 - Source Color) * (1 - Dest Color) -&gt; (GL_ONE, GL_ONE_MINUS_SRC_COLOR) */ Screen, /** * Mixes the destination and source colors similar to a color-based XOR * operation. This is directly equivalent to Photoshop's "Exclusion" blend. * <p> * Result = (Source Color * (1 - Dest Color)) + (Dest Color * (1 - Source Color)) * -&gt; (GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR) */ Exclusion, /** * Uses the blend equations and blend factors defined by the render state. * <p> * These attributes can be set by using the following methods: * <ul> * <li>{@link RenderState#setBlendEquation(BlendEquation)} * <li>{@link RenderState#setBlendEquationAlpha(BlendEquationAlpha)} * <li>{@link RenderState#setCustomBlendFactors(BlendFunc, BlendFunc, BlendFunc, BlendFunc)} * </ul> * <p> * Result.RGB = BlendEquation( sfactorRGB * Source.RGB , dfactorRGB * Destination.RGB )<br> * Result.A = BlendEquationAlpha( sfactorAlpha * Source.A , dfactorAlpha * Destination.A ) */ Custom } /** * <code>FaceCullMode</code> specifies the criteria for faces to be culled. * * @see RenderState#setFaceCullMode(com.jme3.material.RenderState.FaceCullMode) */ public enum FaceCullMode { /** * Face culling is disabled. */ Off, /** * Cull front faces */ Front, /** * Cull back faces */ Back, /** * Cull both front and back faces. */ FrontAndBack } /** * <code>StencilOperation</code> specifies the stencil operation to use * in a certain scenario as specified in {@link RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) } */ public enum StencilOperation { /** * Keep the current value. */ Keep, /** * Set the value to 0 */ Zero, /** * Replace the value in the stencil buffer with the reference value. */ Replace, /** * Increment the value in the stencil buffer, clamp once reaching * the maximum value. */ Increment, /** * Increment the value in the stencil buffer and wrap to 0 when * reaching the maximum value. */ IncrementWrap, /** * Decrement the value in the stencil buffer and clamp once reaching 0. */ Decrement, /** * Decrement the value in the stencil buffer and wrap to the maximum * value when reaching 0. */ DecrementWrap, /** * Does a bitwise invert of the value in the stencil buffer. */ Invert } static { NULL.cullMode = FaceCullMode.Off; NULL.depthTest = false; } static { ADDITIONAL.applyWireFrame = false; ADDITIONAL.applyCullMode = false; ADDITIONAL.applyDepthWrite = false; ADDITIONAL.applyDepthTest = false; ADDITIONAL.applyColorWrite = false; ADDITIONAL.applyBlendMode = false; ADDITIONAL.applyPolyOffset = false; } boolean wireframe = false; boolean applyWireFrame = true; FaceCullMode cullMode = FaceCullMode.Back; boolean applyCullMode = true; boolean depthWrite = true; boolean applyDepthWrite = true; boolean depthTest = true; boolean applyDepthTest = true; boolean colorWrite = true; boolean applyColorWrite = true; BlendEquation blendEquation = BlendEquation.Add; BlendEquationAlpha blendEquationAlpha = BlendEquationAlpha.InheritColor; BlendMode blendMode = BlendMode.Off; boolean applyBlendMode = true; float offsetFactor = 0; float offsetUnits = 0; boolean offsetEnabled = false; boolean applyPolyOffset = true; boolean stencilTest = false; boolean applyStencilTest = false; float lineWidth = 1; boolean applyLineWidth = false; TestFunction depthFunc = TestFunction.LessOrEqual; //by default depth func will be applied anyway if depth test is applied boolean applyDepthFunc = false; StencilOperation frontStencilStencilFailOperation = StencilOperation.Keep; StencilOperation frontStencilDepthFailOperation = StencilOperation.Keep; StencilOperation frontStencilDepthPassOperation = StencilOperation.Keep; StencilOperation backStencilStencilFailOperation = StencilOperation.Keep; StencilOperation backStencilDepthFailOperation = StencilOperation.Keep; StencilOperation backStencilDepthPassOperation = StencilOperation.Keep; TestFunction frontStencilFunction = TestFunction.Always; TestFunction backStencilFunction = TestFunction.Always; int cachedHashCode = -1; BlendFunc sfactorRGB = BlendFunc.One; BlendFunc dfactorRGB = BlendFunc.One; BlendFunc sfactorAlpha = BlendFunc.One; BlendFunc dfactorAlpha = BlendFunc.One; @Override public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(true, "pointSprite", false); oc.write(wireframe, "wireframe", false); oc.write(cullMode, "cullMode", FaceCullMode.Back); oc.write(depthWrite, "depthWrite", true); oc.write(depthTest, "depthTest", true); oc.write(colorWrite, "colorWrite", true); oc.write(blendMode, "blendMode", BlendMode.Off); oc.write(offsetEnabled, "offsetEnabled", false); oc.write(offsetFactor, "offsetFactor", 0); oc.write(offsetUnits, "offsetUnits", 0); oc.write(stencilTest, "stencilTest", false); oc.write(frontStencilStencilFailOperation, "frontStencilStencilFailOperation", StencilOperation.Keep); oc.write(frontStencilDepthFailOperation, "frontStencilDepthFailOperation", StencilOperation.Keep); oc.write(frontStencilDepthPassOperation, "frontStencilDepthPassOperation", StencilOperation.Keep); oc.write(backStencilStencilFailOperation, "backStencilStencilFailOperation", StencilOperation.Keep); oc.write(backStencilDepthFailOperation, "backStencilDepthFailOperation", StencilOperation.Keep); oc.write(backStencilDepthPassOperation, "backStencilDepthPassOperation", StencilOperation.Keep); oc.write(frontStencilFunction, "frontStencilFunction", TestFunction.Always); oc.write(backStencilFunction, "backStencilFunction", TestFunction.Always); oc.write(blendEquation, "blendEquation", BlendEquation.Add); oc.write(blendEquationAlpha, "blendEquationAlpha", BlendEquationAlpha.InheritColor); oc.write(depthFunc, "depthFunc", TestFunction.LessOrEqual); oc.write(lineWidth, "lineWidth", 1); oc.write(sfactorRGB, "sfactorRGB", sfactorRGB); oc.write(dfactorRGB, "dfactorRGB", dfactorRGB); oc.write(sfactorAlpha, "sfactorAlpha", sfactorAlpha); oc.write(dfactorAlpha, "dfactorAlpha", dfactorAlpha); // Only "additional render state" has them set to false by default oc.write(applyWireFrame, "applyWireFrame", true); oc.write(applyCullMode, "applyCullMode", true); oc.write(applyDepthWrite, "applyDepthWrite", true); oc.write(applyDepthTest, "applyDepthTest", true); oc.write(applyColorWrite, "applyColorWrite", true); oc.write(applyBlendMode, "applyBlendMode", true); oc.write(applyPolyOffset, "applyPolyOffset", true); oc.write(applyDepthFunc, "applyDepthFunc", true); oc.write(applyLineWidth, "applyLineWidth", true); } @Override public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); wireframe = ic.readBoolean("wireframe", false); cullMode = ic.readEnum("cullMode", FaceCullMode.class, FaceCullMode.Back); depthWrite = ic.readBoolean("depthWrite", true); depthTest = ic.readBoolean("depthTest", true); colorWrite = ic.readBoolean("colorWrite", true); blendMode = ic.readEnum("blendMode", BlendMode.class, BlendMode.Off); offsetEnabled = ic.readBoolean("offsetEnabled", false); offsetFactor = ic.readFloat("offsetFactor", 0); offsetUnits = ic.readFloat("offsetUnits", 0); stencilTest = ic.readBoolean("stencilTest", false); frontStencilStencilFailOperation = ic.readEnum("frontStencilStencilFailOperation", StencilOperation.class, StencilOperation.Keep); frontStencilDepthFailOperation = ic.readEnum("frontStencilDepthFailOperation", StencilOperation.class, StencilOperation.Keep); frontStencilDepthPassOperation = ic.readEnum("frontStencilDepthPassOperation", StencilOperation.class, StencilOperation.Keep); backStencilStencilFailOperation = ic.readEnum("backStencilStencilFailOperation", StencilOperation.class, StencilOperation.Keep); backStencilDepthFailOperation = ic.readEnum("backStencilDepthFailOperation", StencilOperation.class, StencilOperation.Keep); backStencilDepthPassOperation = ic.readEnum("backStencilDepthPassOperation", StencilOperation.class, StencilOperation.Keep); frontStencilFunction = ic.readEnum("frontStencilFunction", TestFunction.class, TestFunction.Always); backStencilFunction = ic.readEnum("backStencilFunction", TestFunction.class, TestFunction.Always); blendEquation = ic.readEnum("blendEquation", BlendEquation.class, BlendEquation.Add); blendEquationAlpha = ic.readEnum("blendEquationAlpha", BlendEquationAlpha.class, BlendEquationAlpha.InheritColor); depthFunc = ic.readEnum("depthFunc", TestFunction.class, TestFunction.LessOrEqual); lineWidth = ic.readFloat("lineWidth", 1); sfactorRGB = ic.readEnum("sfactorRGB", BlendFunc.class, BlendFunc.One); dfactorAlpha = ic.readEnum("dfactorRGB", BlendFunc.class, BlendFunc.One); sfactorRGB = ic.readEnum("sfactorAlpha", BlendFunc.class, BlendFunc.One); dfactorAlpha = ic.readEnum("dfactorAlpha", BlendFunc.class, BlendFunc.One); applyWireFrame = ic.readBoolean("applyWireFrame", true); applyCullMode = ic.readBoolean("applyCullMode", true); applyDepthWrite = ic.readBoolean("applyDepthWrite", true); applyDepthTest = ic.readBoolean("applyDepthTest", true); applyColorWrite = ic.readBoolean("applyColorWrite", true); applyBlendMode = ic.readBoolean("applyBlendMode", true); applyPolyOffset = ic.readBoolean("applyPolyOffset", true); applyDepthFunc = ic.readBoolean("applyDepthFunc", true); applyLineWidth = ic.readBoolean("applyLineWidth", true); } /** * Create a clone of this <code>RenderState</code> * * @return Clone of this render state. */ @Override public RenderState clone() { try { return (RenderState) super.clone(); } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } /** * returns true if the given renderState is equal to this one * @param o the renderState to compare to * @return true if the renderStates are equal */ @Override public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof RenderState)) { return false; } RenderState rs = (RenderState) o; if (wireframe != rs.wireframe) { return false; } if (cullMode != rs.cullMode) { return false; } if (depthWrite != rs.depthWrite) { return false; } if (depthTest != rs.depthTest) { return false; } if (depthTest) { if (depthFunc != rs.depthFunc) { return false; } } if (colorWrite != rs.colorWrite) { return false; } if (blendMode != rs.blendMode) { return false; } if (blendMode == BlendMode.Custom) { if (blendEquation != rs.blendEquation) { return false; } if (blendEquationAlpha != rs.blendEquationAlpha) { return false; } if (sfactorRGB != rs.sfactorRGB) { return false; } if (dfactorRGB != rs.dfactorRGB) { return false; } if (sfactorAlpha != rs.sfactorAlpha) { return false; } if (dfactorAlpha != rs.dfactorAlpha) { return false; } } if (offsetEnabled != rs.offsetEnabled) { return false; } if (offsetFactor != rs.offsetFactor) { return false; } if (offsetUnits != rs.offsetUnits) { return false; } if (stencilTest != rs.stencilTest) { return false; } if (stencilTest) { if (frontStencilStencilFailOperation != rs.frontStencilStencilFailOperation) { return false; } if (frontStencilDepthFailOperation != rs.frontStencilDepthFailOperation) { return false; } if (frontStencilDepthPassOperation != rs.frontStencilDepthPassOperation) { return false; } if (backStencilStencilFailOperation != rs.backStencilStencilFailOperation) { return false; } if (backStencilDepthFailOperation != rs.backStencilDepthFailOperation) { return false; } if (backStencilDepthPassOperation != rs.backStencilDepthPassOperation) { return false; } if (frontStencilFunction != rs.frontStencilFunction) { return false; } if (backStencilFunction != rs.backStencilFunction) { return false; } } if(lineWidth != rs.lineWidth){ return false; } return true; } /** * Enable writing color. * * <p>When color write is enabled, the result of a fragment shader, the * <code>gl_FragColor</code>, will be rendered into the color buffer * (including alpha). * * @param colorWrite Set to true to enable color writing. */ public void setColorWrite(boolean colorWrite) { applyColorWrite = true; this.colorWrite = colorWrite; cachedHashCode = -1; } /** * Set the face culling mode. * * <p>See the {@link FaceCullMode} enum on what each value does. * Face culling will project the triangle's points onto the screen * and determine if the triangle is in counter-clockwise order or * clockwise order. If a triangle is in counter-clockwise order, then * it is considered a front-facing triangle, otherwise, it is considered * a back-facing triangle. * * @param cullMode the face culling mode. */ public void setFaceCullMode(FaceCullMode cullMode) { applyCullMode = true; this.cullMode = cullMode; cachedHashCode = -1; } /** * Set the blending mode. * * <p>When blending is enabled, (<code>blendMode</code> is not {@link BlendMode#Off}) * the input pixel will be blended with the pixel * already in the color buffer. The blending operation is determined * by the {@link BlendMode}. For example, the {@link BlendMode#Additive} * will add the input pixel's color to the color already in the color buffer: * <br> * <code>Result = Source Color + Destination Color</code> * * @param blendMode The blend mode to use. Set to {@link BlendMode#Off} * to disable blending. */ public void setBlendMode(BlendMode blendMode) { applyBlendMode = true; this.blendMode = blendMode; cachedHashCode = -1; } /** * Set the blending equation for the color component (RGB). * <p> * The blending equation determines, how the RGB values of the input pixel * will be blended with the RGB values of the pixel already in the color buffer.<br> * For example, {@link BlendEquation#Add} will add the input pixel's color * to the color already in the color buffer: * <br> * <code>Result = Source Color + Destination Color</code> * <p> * <b>Note:</b> This gets only used in {@link BlendMode#Custom} mode. * All other blend modes will ignore this setting. * * @param blendEquation The {@link BlendEquation} to use. */ public void setBlendEquation(BlendEquation blendEquation) { this.blendEquation = blendEquation; cachedHashCode = -1; } /** * Set the blending equation for the alpha component. * <p> * The alpha blending equation determines, how the alpha values of the input pixel * will be blended with the alpha values of the pixel already in the color buffer.<br> * For example, {@link BlendEquationAlpha#Add} will add the input pixel's color * to the color already in the color buffer: * <br> * <code>Result = Source Color + Destination Color</code> * <p> * <b>Note:</b> This gets only used in {@link BlendMode#Custom} mode. * All other blend modes will ignore this setting. * * @param blendEquationAlpha The {@link BlendEquationAlpha} to use. */ public void setBlendEquationAlpha(BlendEquationAlpha blendEquationAlpha) { this.blendEquationAlpha = blendEquationAlpha; cachedHashCode = -1; } /** * Sets the blend factors used for the source and destination color. * <p> * These factors will be multiplied with the color values of the input pixel * and the pixel already in the color buffer, before both colors gets combined by the {@link BlendEquation}. * <p> * <b>Note:</b> This gets only used in {@link BlendMode#Custom} mode. * All other blend modes will ignore this setting. * * @param sfactorRGB The source blend factor for RGB components. * @param dfactorRGB The destination blend factor for RGB components. * @param sfactorAlpha The source blend factor for the alpha component. * @param dfactorAlpha The destination blend factor for the alpha component. */ public void setCustomBlendFactors(BlendFunc sfactorRGB, BlendFunc dfactorRGB, BlendFunc sfactorAlpha, BlendFunc dfactorAlpha) { this.sfactorRGB = sfactorRGB; this.dfactorRGB = dfactorRGB; this.sfactorAlpha = sfactorAlpha; this.dfactorAlpha = dfactorAlpha; cachedHashCode = -1; } /** * Enable depth testing. * * <p>When depth testing is enabled, a pixel must pass the depth test * before it is written to the color buffer. * The input pixel's depth value must be less than or equal than * the value already in the depth buffer to pass the depth test. * * @param depthTest Enable or disable depth testing. */ public void setDepthTest(boolean depthTest) { applyDepthTest = true; this.depthTest = depthTest; cachedHashCode = -1; } /** * Enable depth writing. * * <p>After passing the {@link RenderState#setDepthTest(boolean) depth test}, * a pixel's depth value will be written into the depth buffer if * depth writing is enabled. * * @param depthWrite True to enable writing to the depth buffer. */ public void setDepthWrite(boolean depthWrite) { applyDepthWrite = true; this.depthWrite = depthWrite; cachedHashCode = -1; } /** * Enables wireframe rendering mode. * * <p>When in wireframe mode, {@link Mesh meshes} rendered in triangle mode * will not be solid, but instead, only the edges of the triangles * will be rendered. * * @param wireframe True to enable wireframe mode. */ public void setWireframe(boolean wireframe) { applyWireFrame = true; this.wireframe = wireframe; cachedHashCode = -1; } public void setPolyOffset(float factor, float units) { applyPolyOffset = true; if (factor == 0 && units == 0) { offsetEnabled = false; } else { offsetEnabled = true; offsetFactor = factor; offsetUnits = units; } cachedHashCode = -1; } /** * Enable stencil testing. * * <p>Stencil testing can be used to filter pixels according to the stencil * buffer. Objects can be rendered with some stencil operation to manipulate * the values in the stencil buffer, then, other objects can be rendered * to test against the values written previously. * * @param enabled Set to true to enable stencil functionality. If false * all other parameters are ignored. * * @param _frontStencilStencilFailOperation Sets the operation to occur when * a front-facing triangle fails the front stencil function. * @param _frontStencilDepthFailOperation Sets the operation to occur when * a front-facing triangle fails the depth test. * @param _frontStencilDepthPassOperation Set the operation to occur when * a front-facing triangle passes the depth test. * @param _backStencilStencilFailOperation Set the operation to occur when * a back-facing triangle fails the back stencil function. * @param _backStencilDepthFailOperation Set the operation to occur when * a back-facing triangle fails the depth test. * @param _backStencilDepthPassOperation Set the operation to occur when * a back-facing triangle passes the depth test. * @param _frontStencilFunction Set the test function for front-facing triangles. * @param _backStencilFunction Set the test function for back-facing triangles. */ public void setStencil(boolean enabled, StencilOperation _frontStencilStencilFailOperation, StencilOperation _frontStencilDepthFailOperation, StencilOperation _frontStencilDepthPassOperation, StencilOperation _backStencilStencilFailOperation, StencilOperation _backStencilDepthFailOperation, StencilOperation _backStencilDepthPassOperation, TestFunction _frontStencilFunction, TestFunction _backStencilFunction) { stencilTest = enabled; applyStencilTest = true; this.frontStencilStencilFailOperation = _frontStencilStencilFailOperation; this.frontStencilDepthFailOperation = _frontStencilDepthFailOperation; this.frontStencilDepthPassOperation = _frontStencilDepthPassOperation; this.backStencilStencilFailOperation = _backStencilStencilFailOperation; this.backStencilDepthFailOperation = _backStencilDepthFailOperation; this.backStencilDepthPassOperation = _backStencilDepthPassOperation; this.frontStencilFunction = _frontStencilFunction; this.backStencilFunction = _backStencilFunction; cachedHashCode = -1; } /** * Set the depth comparison function to the given TestFunction * default is LessOrEqual (GL_LEQUAL) * @see TestFunction * @see RenderState#setDepthTest(boolean) * @param depthFunc the depth comparison function */ public void setDepthFunc(TestFunction depthFunc) { applyDepthFunc = true; this.depthFunc = depthFunc; cachedHashCode = -1; } /** * Sets the mesh line width. * Use this in conjunction with {@link #setWireframe(boolean)} or with a mesh in * {@link com.jme3.scene.Mesh.Mode#Lines} mode. * @param lineWidth the line width. */ public void setLineWidth(float lineWidth) { if (lineWidth < 1f) { throw new IllegalArgumentException("lineWidth must be greater than or equal to 1.0"); } this.lineWidth = lineWidth; this.applyLineWidth = true; cachedHashCode = -1; } /** * Check if stencil test is enabled. * * @return True if stencil test is enabled. */ public boolean isStencilTest() { return stencilTest; } /** * Retrieve the front stencil fail operation. * * @return the front stencil fail operation. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public StencilOperation getFrontStencilStencilFailOperation() { return frontStencilStencilFailOperation; } /** * Retrieve the front depth test fail operation. * * @return the front depth test fail operation. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public StencilOperation getFrontStencilDepthFailOperation() { return frontStencilDepthFailOperation; } /** * Retrieve the front depth test pass operation. * * @return the front depth test pass operation. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public StencilOperation getFrontStencilDepthPassOperation() { return frontStencilDepthPassOperation; } /** * Retrieve the back stencil fail operation. * * @return the back stencil fail operation. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public StencilOperation getBackStencilStencilFailOperation() { return backStencilStencilFailOperation; } /** * Retrieve the back depth test fail operation. * * @return the back depth test fail operation. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public StencilOperation getBackStencilDepthFailOperation() { return backStencilDepthFailOperation; } /** * Retrieve the back depth test pass operation. * * @return the back depth test pass operation. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public StencilOperation getBackStencilDepthPassOperation() { return backStencilDepthPassOperation; } /** * Retrieve the front stencil function. * * @return the front stencil function. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public TestFunction getFrontStencilFunction() { return frontStencilFunction; } /** * Retrieve the back stencil function. * * @return the back stencil function. * * @see RenderState#setStencil(boolean, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.StencilOperation, * com.jme3.material.RenderState.TestFunction, * com.jme3.material.RenderState.TestFunction) */ public TestFunction getBackStencilFunction() { return backStencilFunction; } /** * Retrieve the blend equation. * * @return the blend equation. */ public BlendEquation getBlendEquation() { return blendEquation; } /** * Retrieve the blend equation used for the alpha component. * * @return the blend equation for the alpha component. */ public BlendEquationAlpha getBlendEquationAlpha() { return blendEquationAlpha; } /** * Retrieve the blend mode. * * @return the blend mode. */ public BlendMode getBlendMode() { return blendMode; } /** * Provides the source factor for the RGB components in * <code>BlendMode.Custom</code>. * * @return the custom source factor for RGB components. */ public BlendFunc getCustomSfactorRGB() { return sfactorRGB; } /** * Provides the destination factor for the RGB components in * <code>BlendMode.Custom</code>. * * @return the custom destination factor for RGB components. */ public BlendFunc getCustomDfactorRGB() { return dfactorRGB; } /** * Provides the source factor for the alpha component in * <code>BlendMode.Custom</code>. * * @return the custom destination factor for alpha component. */ public BlendFunc getCustomSfactorAlpha() { return sfactorAlpha; } /** * Provides the destination factor for the alpha component in * <code>BlendMode.Custom</code>. * * @return the custom destination factor for alpha component. */ public BlendFunc getCustomDfactorAlpha() { return dfactorAlpha; } /** * @return true * @deprecated Always returns true since point sprite is always enabled. */ @Deprecated public boolean isPointSprite() { return true; } /** * @deprecated To use alpha test, set the <code>AlphaDiscardThreshold</code> * material parameter. * @return false */ @Deprecated public boolean isAlphaTest() { return false; } /** * Retrieve the face cull mode. * * @return the face cull mode. * * @see RenderState#setFaceCullMode(com.jme3.material.RenderState.FaceCullMode) */ public FaceCullMode getFaceCullMode() { return cullMode; } /** * Check if depth test is enabled. * * @return True if depth test is enabled. * * @see RenderState#setDepthTest(boolean) */ public boolean isDepthTest() { return depthTest; } /** * Check if depth write is enabled. * * @return True if depth write is enabled. * * @see RenderState#setDepthWrite(boolean) */ public boolean isDepthWrite() { return depthWrite; } /** * Check if wireframe mode is enabled. * * @return True if wireframe mode is enabled. * * @see RenderState#setWireframe(boolean) */ public boolean isWireframe() { return wireframe; } /** * Check if color writing is enabled. * * @return True if color writing is enabled. * * @see RenderState#setColorWrite(boolean) */ public boolean isColorWrite() { return colorWrite; } /** * Retrieve the poly offset factor value. * * @return the poly offset factor value. * * @see RenderState#setPolyOffset(float, float) */ public float getPolyOffsetFactor() { return offsetFactor; } /** * Retrieve the poly offset units value. * * @return the poly offset units value. * * @see RenderState#setPolyOffset(float, float) */ public float getPolyOffsetUnits() { return offsetUnits; } /** * Check if polygon offset is enabled. * * @return True if polygon offset is enabled. * * @see RenderState#setPolyOffset(float, float) */ public boolean isPolyOffset() { return offsetEnabled; } /** * @return 0 * @deprecated */ @Deprecated public float getAlphaFallOff() { return 0f; } /** * Retrieve the depth comparison function * * @return the depth comparison function * * @see RenderState#setDepthFunc(com.jme3.material.RenderState.TestFunction) */ public TestFunction getDepthFunc() { return depthFunc; } /** * @return {@link TestFunction#Greater}. * @deprecated */ @Deprecated public TestFunction getAlphaFunc() { return TestFunction.Greater; } /** * returns the wireframe line width * * @return the line width */ public float getLineWidth() { return lineWidth; } public boolean isApplyBlendMode() { return applyBlendMode; } public boolean isApplyColorWrite() { return applyColorWrite; } public boolean isApplyCullMode() { return applyCullMode; } public boolean isApplyDepthTest() { return applyDepthTest; } public boolean isApplyDepthWrite() { return applyDepthWrite; } public boolean isApplyPolyOffset() { return applyPolyOffset; } public boolean isApplyWireFrame() { return applyWireFrame; } public boolean isApplyDepthFunc() { return applyDepthFunc; } public boolean isApplyLineWidth() { return applyLineWidth; } /** * @return value for use in hashing */ public int contentHashCode() { if (cachedHashCode == -1){ int hash = 7; hash = 79 * hash + (this.wireframe ? 1 : 0); hash = 79 * hash + (this.cullMode != null ? this.cullMode.hashCode() : 0); hash = 79 * hash + (this.depthWrite ? 1 : 0); hash = 79 * hash + (this.depthTest ? 1 : 0); hash = 79 * hash + (this.depthFunc != null ? this.depthFunc.hashCode() : 0); hash = 79 * hash + (this.colorWrite ? 1 : 0); hash = 79 * hash + (this.blendMode != null ? this.blendMode.hashCode() : 0); hash = 79 * hash + (this.blendEquation != null ? this.blendEquation.hashCode() : 0); hash = 79 * hash + (this.blendEquationAlpha != null ? this.blendEquationAlpha.hashCode() : 0); hash = 79 * hash + Float.floatToIntBits(this.offsetFactor); hash = 79 * hash + Float.floatToIntBits(this.offsetUnits); hash = 79 * hash + (this.offsetEnabled ? 1 : 0); hash = 79 * hash + (this.stencilTest ? 1 : 0); hash = 79 * hash + (this.frontStencilStencilFailOperation != null ? this.frontStencilStencilFailOperation.hashCode() : 0); hash = 79 * hash + (this.frontStencilDepthFailOperation != null ? this.frontStencilDepthFailOperation.hashCode() : 0); hash = 79 * hash + (this.frontStencilDepthPassOperation != null ? this.frontStencilDepthPassOperation.hashCode() : 0); hash = 79 * hash + (this.backStencilStencilFailOperation != null ? this.backStencilStencilFailOperation.hashCode() : 0); hash = 79 * hash + (this.backStencilDepthFailOperation != null ? this.backStencilDepthFailOperation.hashCode() : 0); hash = 79 * hash + (this.backStencilDepthPassOperation != null ? this.backStencilDepthPassOperation.hashCode() : 0); hash = 79 * hash + (this.frontStencilFunction != null ? this.frontStencilFunction.hashCode() : 0); hash = 79 * hash + (this.backStencilFunction != null ? this.backStencilFunction.hashCode() : 0); hash = 79 * hash + Float.floatToIntBits(this.lineWidth); hash = 79 * hash + this.sfactorRGB.hashCode(); hash = 79 * hash + this.dfactorRGB.hashCode(); hash = 79 * hash + this.sfactorAlpha.hashCode(); hash = 79 * hash + this.dfactorAlpha.hashCode(); cachedHashCode = hash; } return cachedHashCode; } public RenderState copyMergedTo(RenderState additionalState, RenderState state) { if (additionalState == null) { return this; } if (additionalState.applyWireFrame) { state.wireframe = additionalState.wireframe; } else { state.wireframe = wireframe; } if (additionalState.applyCullMode) { state.cullMode = additionalState.cullMode; } else { state.cullMode = cullMode; } if (additionalState.applyDepthWrite) { state.depthWrite = additionalState.depthWrite; } else { state.depthWrite = depthWrite; } if (additionalState.applyDepthTest) { state.depthTest = additionalState.depthTest; } else { state.depthTest = depthTest; } if (additionalState.applyDepthFunc) { state.depthFunc = additionalState.depthFunc; } else { state.depthFunc = depthFunc; } if (additionalState.applyColorWrite) { state.colorWrite = additionalState.colorWrite; } else { state.colorWrite = colorWrite; } if (additionalState.applyBlendMode) { state.blendMode = additionalState.blendMode; if (additionalState.blendMode == BlendMode.Custom) { state.blendEquation = additionalState.blendEquation; state.blendEquationAlpha = additionalState.blendEquationAlpha; state.sfactorRGB = additionalState.sfactorRGB; state.dfactorRGB = additionalState.dfactorRGB; state.sfactorAlpha = additionalState.sfactorAlpha; state.dfactorAlpha = additionalState.dfactorAlpha; } } else { state.blendMode = blendMode; if (blendMode == BlendMode.Custom) { state.blendEquation = blendEquation; state.blendEquationAlpha = blendEquationAlpha; state.sfactorRGB = sfactorRGB; state.dfactorRGB = dfactorRGB; state.sfactorAlpha = sfactorAlpha; state.dfactorAlpha = dfactorAlpha; } } if (additionalState.applyPolyOffset) { state.offsetEnabled = additionalState.offsetEnabled; state.offsetFactor = additionalState.offsetFactor; state.offsetUnits = additionalState.offsetUnits; } else { state.offsetEnabled = offsetEnabled; state.offsetFactor = offsetFactor; state.offsetUnits = offsetUnits; } if (additionalState.applyStencilTest) { state.stencilTest = additionalState.stencilTest; state.frontStencilStencilFailOperation = additionalState.frontStencilStencilFailOperation; state.frontStencilDepthFailOperation = additionalState.frontStencilDepthFailOperation; state.frontStencilDepthPassOperation = additionalState.frontStencilDepthPassOperation; state.backStencilStencilFailOperation = additionalState.backStencilStencilFailOperation; state.backStencilDepthFailOperation = additionalState.backStencilDepthFailOperation; state.backStencilDepthPassOperation = additionalState.backStencilDepthPassOperation; state.frontStencilFunction = additionalState.frontStencilFunction; state.backStencilFunction = additionalState.backStencilFunction; } else { state.stencilTest = stencilTest; state.frontStencilStencilFailOperation = frontStencilStencilFailOperation; state.frontStencilDepthFailOperation = frontStencilDepthFailOperation; state.frontStencilDepthPassOperation = frontStencilDepthPassOperation; state.backStencilStencilFailOperation = backStencilStencilFailOperation; state.backStencilDepthFailOperation = backStencilDepthFailOperation; state.backStencilDepthPassOperation = backStencilDepthPassOperation; state.frontStencilFunction = frontStencilFunction; state.backStencilFunction = backStencilFunction; } if (additionalState.applyLineWidth) { state.lineWidth = additionalState.lineWidth; } else { state.lineWidth = lineWidth; } state.cachedHashCode = -1; return state; } public void set(RenderState state) { wireframe = state.wireframe; cullMode = state.cullMode; depthWrite = state.depthWrite; depthTest = state.depthTest; colorWrite = state.colorWrite; blendMode = state.blendMode; offsetEnabled = state.offsetEnabled; offsetFactor = state.offsetFactor; offsetUnits = state.offsetUnits; stencilTest = state.stencilTest; frontStencilStencilFailOperation = state.frontStencilStencilFailOperation; frontStencilDepthFailOperation = state.frontStencilDepthFailOperation; frontStencilDepthPassOperation = state.frontStencilDepthPassOperation; backStencilStencilFailOperation = state.backStencilStencilFailOperation; backStencilDepthFailOperation = state.backStencilDepthFailOperation; backStencilDepthPassOperation = state.backStencilDepthPassOperation; frontStencilFunction = state.frontStencilFunction; backStencilFunction = state.backStencilFunction; blendEquationAlpha = state.blendEquationAlpha; blendEquation = state.blendEquation; depthFunc = state.depthFunc; lineWidth = state.lineWidth; applyWireFrame = true; applyCullMode = true; applyDepthWrite = true; applyDepthTest = true; applyColorWrite = true; applyBlendMode = true; applyPolyOffset = true; applyDepthFunc = true; applyLineWidth = true; sfactorRGB = state.sfactorRGB; dfactorRGB = state.dfactorRGB; sfactorAlpha = state.sfactorAlpha; dfactorAlpha = state.dfactorAlpha; } @Override public String toString() { return "RenderState[\n" + "\nwireframe=" + wireframe + "\napplyWireFrame=" + applyWireFrame + "\ncullMode=" + cullMode + "\napplyCullMode=" + applyCullMode + "\ndepthWrite=" + depthWrite + "\napplyDepthWrite=" + applyDepthWrite + "\ndepthTest=" + depthTest + "\ndepthFunc=" + depthFunc + "\napplyDepthTest=" + applyDepthTest + "\ncolorWrite=" + colorWrite + "\napplyColorWrite=" + applyColorWrite + "\nblendEquation=" + blendEquation + "\nblendMode=" + blendMode + "\napplyBlendMode=" + applyBlendMode + "\noffsetEnabled=" + offsetEnabled + "\napplyPolyOffset=" + applyPolyOffset + "\noffsetFactor=" + offsetFactor + "\noffsetUnits=" + offsetUnits + "\nlineWidth=" + lineWidth + (blendMode.equals(BlendMode.Custom)? "\ncustomBlendFactors=("+sfactorRGB+", "+dfactorRGB+", "+sfactorAlpha+", "+dfactorAlpha+")":"") +"\n]"; } }
package com.rangarok.jparserutil.test; import com.ragnarok.jparseutil.JavaSourceReader; import com.ragnarok.jparseutil.util.Log; import com.ragnarok.jparseutil.visitor.SourceTreeVisitor; import com.sun.source.tree.CompilationUnitTree; public class TestMain { private static final String TAG = "JParserUtil.TestMain"; public static void main(String[] args) { String filePath = "test/User.java"; // this should be the path to User.java JavaSourceReader sourceReader = new JavaSourceReader(filePath); Iterable<? extends CompilationUnitTree> parseResult = sourceReader.readSource(); Log.d(TAG, "currentDir: %s", System.getProperty("user.dir")); SourceTreeVisitor sourceTreeVisitor = new SourceTreeVisitor(); for (CompilationUnitTree compilationUnitTree : parseResult) { compilationUnitTree.accept(sourceTreeVisitor, null); } } }
package com.microsoft.sqlserver.jdbc; import java.security.SecureRandom; import java.text.MessageFormat; import java.util.Arrays; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * * This is an utility class to encrypt/decrypt strings. This is used to obfuscate passwords so they won't be visible as * plaintext. */ final class SecureStringUtil { /* cipher transformation in the form of algorithm/mode/padding */ static final String CIPHER_TRANSFORMATION = "AES/GCM/NoPadding"; /* key generator algorithm */ static final String KEYGEN_ALGORITHEM = "AES"; /* length of initialization vector buffer */ static final int IV_LENGTH = 12; /* key size */ static final int KEY_SIZE = 256; /* authentication tag length in bits */ static final int TAG_LENGTH = 16; /** secret key for encryption/decryption */ SecretKeySpec secretKey; /* cryptographic cipher for encryption */ private Cipher encryptCipher; /* cryptographic cipher for decryption */ private Cipher decryptCipher; /* singleton instance */ private static volatile SecureStringUtil instance; private static final Lock INSTANCE_LOCK = new ReentrantLock(); private static final Lock ENCRYPT_LOCK = new ReentrantLock(); private static final Lock DECRYPT_LOCK = new ReentrantLock(); /** * Get reference to SecureStringUtil instance * * @return the SecureStringUtil instance * * @throws SQLServerException * if error */ static SecureStringUtil getInstance() throws SQLServerException { if (instance == null) { INSTANCE_LOCK.lock(); try { if (instance == null) { instance = new SecureStringUtil(); } } finally { INSTANCE_LOCK.unlock(); } } return instance; } /** * Creates an instance of the SecureStringUtil object and initialize values to encrypt/decrypt strings * * @throws SQLServerException * if error */ private SecureStringUtil() throws SQLServerException { try { // generate key */ KeyGenerator keygen = KeyGenerator.getInstance(KEYGEN_ALGORITHEM); keygen.init(KEY_SIZE); secretKey = new SecretKeySpec(keygen.generateKey().getEncoded(), "AES"); // get ciphers for encryption/decryption encryptCipher = Cipher.getInstance(CIPHER_TRANSFORMATION); decryptCipher = Cipher.getInstance(CIPHER_TRANSFORMATION); } catch (Exception e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_SecureStringInitFailed")); Object[] msgArgs = {e.getMessage()}; throw new SQLServerException(this, form.format(msgArgs), null, 0, false); } } /** * Get encrypted value of given string * * @param chars * string to encrypt * * @return encrypted string * * @throws SQLServerException * Throws an exception if the method fails to encrypt the character array */ byte[] getEncryptedBytes(char[] chars) throws SQLServerException { ENCRYPT_LOCK.lock(); try { if (chars == null) { return null; } byte[] iv = new byte[IV_LENGTH]; SecureRandom random = new SecureRandom(); random.nextBytes(iv); GCMParameterSpec ivParamSpec = new GCMParameterSpec(TAG_LENGTH * 8, iv); encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParamSpec); byte[] cipherText = encryptCipher.doFinal(Util.charsToBytes(chars)); byte[] bytes = new byte[iv.length + cipherText.length]; System.arraycopy(iv, 0, bytes, 0, iv.length); System.arraycopy(cipherText, 0, bytes, iv.length, cipherText.length); return bytes; } catch (Exception e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_EncryptionFailed")); Object[] msgArgs = {e.getMessage()}; throw new SQLServerException(this, form.format(msgArgs), null, 0, false); } finally { ENCRYPT_LOCK.unlock(); } } /** * Get decrypted value of an encrypted string * * @param bytes * The byte array to decrypt into a character array * * @return decrypted string * * @throws SQLServerException * Throws an exception if the method fails to decrypt the byte array */ char[] getDecryptedChars(byte[] bytes) throws SQLServerException { DECRYPT_LOCK.lock(); byte[] plainText = null; try { if (bytes == null) { return null; } byte[] iv = new byte[IV_LENGTH]; System.arraycopy(bytes, 0, iv, 0, IV_LENGTH); GCMParameterSpec ivParamSpec = new GCMParameterSpec(TAG_LENGTH * 8, iv); decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, ivParamSpec); plainText = decryptCipher.doFinal(bytes, IV_LENGTH, bytes.length - IV_LENGTH); return Util.bytesToChars(plainText); } catch (Exception e) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_DecryptionFailed")); Object[] msgArgs = {e.getMessage()}; throw new SQLServerException(this, form.format(msgArgs), null, 0, false); } finally { if (plainText != null) { Arrays.fill(plainText, (byte) 0); } DECRYPT_LOCK.unlock(); } } }
package org.codehaus.jparsec; import static org.codehaus.jparsec.Asserts.assertFailure; import static org.codehaus.jparsec.Asserts.assertParser; import static org.codehaus.jparsec.Parsers.constant; import static org.codehaus.jparsec.Scanners.string; import static org.codehaus.jparsec.TestParsers.areChars; import static org.codehaus.jparsec.TestParsers.isChar; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.StringReader; import java.util.Arrays; import java.util.List; import org.codehaus.jparsec.easymock.BaseMockTest; import org.codehaus.jparsec.error.ParserException; import org.codehaus.jparsec.functors.Map; import org.codehaus.jparsec.functors.Map2; import org.codehaus.jparsec.functors.Maps; import org.junit.Test; /** * Unit test for {@link Parser}. * * @author Ben Yu */ public class ParserTest extends BaseMockTest { private static final Parser<Integer> INTEGER = Scanners.INTEGER.source().map(Maps.TO_INTEGER); private static final Parser<String> FOO = constant("foo"); private static final Parser<String> FAILURE = Parsers.fail("failure"); private static final Parser<Void> COMMA = Scanners.isChar(','); @SuppressWarnings("deprecation") @Test public void testParse() throws Exception { assertEquals("foo", FOO.parse("")); assertFailure(FOO, "a", 1, 1, "EOF expected, a encountered."); assertFailure(FOO, "a", 1, 1, "test module", "EOF expected, a encountered."); assertEquals(new Integer(123), INTEGER.parse(new StringReader("123"))); try { INTEGER.parse(new StringReader("x"), "test module"); fail(); } catch (ParserException e) { assertEquals(1, e.getLocation().line); assertEquals(1, e.getLocation().column); assertTrue(e.getMessage(), e.getMessage().contains("test module")); assertTrue(e.getMessage(), e.getMessage().contains("integer expected, x encountered.")); } } @Test public void testSource() { assertEquals("source", FOO.source().toString()); assertParser(FOO.source(), "", ""); assertParser(COMMA.source(), ", ", ",", " "); assertParser(Terminals.IntegerLiteral.TOKENIZER.label("INTEGER").source(), "123 ", "123", " "); assertParser( Parsers.tokenType(Integer.class, "int").from(INTEGER, Scanners.WHITESPACES).source(), "123", "123"); } @Test public void testToken() { assertEquals("foo", FOO.token().toString()); assertParser(FOO.token(), "", new Token(0, 0, "foo")); assertParser(INTEGER.token(), "123", new Token(0, 3, 123)); assertFailure(INTEGER.token(), "a", 1, 1); } @Test public void testWithSource() { assertEquals("foo", FOO.withSource().toString()); assertParser(FOO.withSource(), "", new WithSource<String>("foo", "")); assertParser(INTEGER.withSource(), "123", new WithSource<Integer>(123, "123")); assertFailure(INTEGER.withSource(), "a", 1, 1); } @Mock Map<Object, Parser<String>> next; @Test public void testNext_withMap() { expect(next.map(1)).andReturn(FOO); replay(); assertParser(INTEGER.next(next), "1", "foo"); assertEquals(next.toString(), INTEGER.next(next).toString()); } @Test public void testNext_firstParserFails() { replay(); assertFailure(FAILURE.next(next), "", 1, 1, "failure"); } @Test public void testNext_nextParserFails() { expect(next.map(123)).andReturn(FAILURE); replay(); assertFailure(INTEGER.next(next), "123", 1, 4, "failure"); } @Test public void testNext() { assertEquals("sequence", COMMA.next(INTEGER).toString()); assertParser(COMMA.next(INTEGER), ",123", 123); assertFailure(FAILURE.next(FOO), "", 1, 1, "failure"); assertFailure(INTEGER.next(COMMA), "123", 1, 4); } @Test public void testRetn() { assertParser(COMMA.retn(1), ",", 1); assertFailure(FAILURE.retn(1), "", 1, 1, "failure"); } @Test public void testUntil() { Parser<String> comma = Scanners.isChar(',').source(); Parser<?> dot = Scanners.isChar('.'); Parser<List<Object>> parser = INTEGER.cast().or(comma).until(dot); assertParser(parser, "123,456.", Arrays.<Object>asList(123, ",", 456), "."); assertFailure(parser, "", 1, 1); assertParser(parser, ".", Arrays.asList(), "."); } @Test public void testFollowedBy() { assertParser(INTEGER.followedBy(COMMA), "123,", 123); assertFailure(FAILURE.followedBy(FOO), "", 1, 1, "failure"); assertFailure(INTEGER.followedBy(COMMA), "123", 1, 4, ", expected, EOF encountered."); } @Test public void testNotFollowedBy() { assertParser(INTEGER.notFollowedBy(COMMA), "123", 123); assertParser(INTEGER.notFollowedBy(COMMA.times(2)).followedBy(COMMA), "123,", 123); assertFailure(FAILURE.notFollowedBy(FOO), "", 1, 1, "failure"); assertFailure(INTEGER.notFollowedBy(COMMA), "123,", 1, 4, "unexpected ,."); } @Test public void testSkipTimes() { assertParser(isChar('a').skipTimes(3), "aaa", null); assertFailure(isChar('a').skipTimes(3), "aa", 1, 3); assertParser(areChars("ab").skipTimes(3), "ababab", null); assertParser(FOO.skipTimes(3), "", null); assertFailure(areChars("ab").skipTimes(3), "aba", 1, 4); assertEquals("skipTimes", INTEGER.skipTimes(1).toString()); } @Test public void testTimes() { assertListParser(isChar('a').times(3), "aaa", 'a', 'a', 'a'); assertFailure(isChar('a').times(3), "aa", 1, 3); assertListParser(areChars("ab").times(3), "ababab", 'b', 'b', 'b'); assertListParser(FOO.times(2), "", "foo", "foo"); assertFailure(areChars("ab").times(3), "aba", 1, 4); assertEquals("times", INTEGER.times(1).toString()); } @Test public void skipTimes_range() { assertParser(isChar('a').skipTimes(0, 1), "", null); assertFailure(isChar('a').skipTimes(1, 2), "", 1, 1); assertFailure(areChars("ab").skipTimes(1, 2), "aba", 1, 4); assertFailure(areChars("ab").skipTimes(1, 2), "aba", 1, 4); assertParser(FOO.skipTimes(0, 1), "", null); assertParser(FOO.skipTimes(1, 2), "", null); assertParser(isChar('a').step(0).next(isChar('b')).skipTimes(1, 2), "aba", null, "a"); assertEquals("skipTimes", isChar('a').skipTimes(1, 2).toString()); } @Test public void testTimes_range() { assertListParser(isChar('a').times(0, 1), ""); assertFailure(isChar('a').times(1, 2), "", 1, 1); assertFailure(areChars("ab").times(1, 2), "aba", 1, 4); assertFailure(areChars("ab").times(1, 2), "aba", 1, 4); assertListParser(FOO.times(0, 1), "", "foo"); assertListParser(FOO.times(2, 3), "", "foo", "foo", "foo"); assertListParser(isChar('a').step(0).next(isChar('b')).times(1, 2).followedBy(isChar('a')), "aba", 'b'); assertEquals("times", isChar('a').times(1, 2).toString()); } @Test public void testSkipMany() { assertParser(isChar('a').skipMany(), "", null); assertParser(isChar('a').skipMany(), "a", null); assertParser(isChar('a').skipMany(), "aaa", null); assertFailure(areChars("ab").skipMany(), "aba", 1, 4); assertParser(FOO.skipMany(), "", null); assertParser(isChar('a').skipAtLeast(0), "", null); assertFailure(isChar('a').skipAtLeast(1), "", 1, 1); assertFailure(areChars("ab").skipAtLeast(1), "aba", 1, 4); assertFailure(areChars("ab").skipAtLeast(2), "aba", 1, 4); assertParser(FOO.skipAtLeast(0), "", null); assertParser(FOO.skipAtLeast(2), "", null); assertParser(isChar('a').step(0).next(isChar('b')).skipMany(), "a", null, "a"); assertEquals("skipAtLeast", isChar('a').skipMany().toString()); assertEquals("skipAtLeast", isChar('a').skipAtLeast(2).toString()); } @Test public void testSkipMany1() { assertFailure(isChar('a').skipMany1(), "", 1, 1); assertParser(isChar('a').skipMany1(), "a", null); assertParser(isChar('a').skipMany1(), "aaa", null); assertFailure(areChars("ab").skipMany1(), "aba", 1, 4); assertParser(FOO.skipMany1(), "", null); assertParser(isChar('a').step(0).next(isChar('b')).skipMany1(), "aba", null, "a"); assertEquals("skipAtLeast", isChar('a').skipMany1().toString()); } @Test public void testMany1() { assertFailure(isChar('a').many1(), "", 1, 1); assertListParser(isChar('a').many1(), "a", 'a'); assertListParser(isChar('a').many1(), "aaa", 'a', 'a', 'a'); assertFailure(areChars("ab").many1(), "aba", 1, 4); assertListParser(FOO.many1(), "", "foo"); assertListParser(isChar('a').step(0).next(isChar('b')).many1().followedBy(isChar('a')), "aba", 'b'); assertEquals("atLeast", isChar('a').many1().toString()); } @Test public void testMany() { assertListParser(isChar('a').many(), ""); assertListParser(isChar('a').many(), "a", 'a'); assertListParser(isChar('a').many(), "aaa", 'a', 'a', 'a'); assertFailure(areChars("ab").many(), "aba", 1, 4); assertListParser(FOO.many(), ""); assertListParser(isChar('a').atLeast(0), ""); assertFailure(isChar('a').atLeast(1), "", 1, 1); assertFailure(areChars("ab").atLeast(1), "aba", 1, 4); assertFailure(areChars("ab").atLeast(2), "aba", 1, 4); assertListParser(FOO.atLeast(0), ""); assertListParser(FOO.atLeast(2), "", "foo", "foo"); assertListParser(isChar('a').step(0).next(isChar('b')).many().followedBy(isChar('a')), "a"); assertEquals("atLeast", isChar('a').many().toString()); assertEquals("atLeast", isChar('a').atLeast(1).toString()); } @Test public void testOr() { assertEquals("or", INTEGER.or(INTEGER).toString()); assertParser(INTEGER.or(constant(456)), "123", 123); assertParser(isChar('a').or(constant('b')), "", 'b'); assertParser(areChars("ab").or(isChar('a')), "a", 'a'); assertListParser(areChars("ab").or(isChar('a')).many(), "a", 'a'); assertFailure(areChars("ab").or(isChar('a')), "x", 1, 1); } @Test public void testOptional() { assertParser(INTEGER.optional(), "12", 12); assertParser(INTEGER.optional(), "", null); assertFailure(areChars("ab").optional(), "a", 1, 2); } @Test public void testOptional_withDefaultValue() { assertParser(INTEGER.optional(0), "12", 12); assertParser(INTEGER.optional(0), "", 0); assertFailure(areChars("ab").optional('x'), "a", 1, 2); } @Test public void testNot() { assertParser(INTEGER.not(), "", null); assertFailure(INTEGER.not(), "12", 1, 1); assertParser(areChars("ab").not(), "a", null, "a"); assertParser(INTEGER.not("num"), "", null); assertFailure(INTEGER.not("num"), "12", 1, 1, "unexpected num"); } @Test public void testPeek() { assertParser(INTEGER.peek(), "12", 12, "12"); assertFailure(INTEGER.peek(), "a", 1, 1); assertFailure(areChars("ab").peek(), "a", 1, 2); assertFailure(Parsers.plus(areChars("ab").peek(), isChar('a')), "a", 1, 2); assertEquals("peek", INTEGER.peek().toString()); } @Test public void testAtomic() { assertEquals("integer", INTEGER.atomic().toString()); assertParser(areChars("ab").atomic(), "ab", 'b'); assertParser(Parsers.plus(areChars("ab").atomic(), isChar('a')), "a", 'a'); assertFailure(areChars("ab").atomic(), "a", 1, 2); } @Test public void testStep() { assertEquals(INTEGER.toString(), INTEGER.step(0).toString()); assertParser(Parsers.plus(areChars("ab").step(0).next(isChar('c')), areChars("ab")), "ab", 'b'); } @Test public void testStep_negativeStep() { try { INTEGER.step(-1); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "step < 0", e.getMessage()); } } @Test public void testSucceeds() { assertParser(isChar('a').succeeds(), "ab", true, "b"); assertParser(isChar('a').succeeds(), "xb", false, "xb"); assertParser(areChars("ab").succeeds(), "ax", false, "ax"); } @Test public void testFails() { assertParser(isChar('a').fails(), "ab", false, "b"); assertParser(isChar('a').fails(), "xb", true, "xb"); assertParser(areChars("ab").fails(), "ax", true, "ax"); } @Test public void testIfElse() { Parser<Integer> parser = areChars("ab").ifelse(INTEGER, constant(0)); assertEquals("ifelse", parser.toString()); assertParser(parser, "ab12", 12); assertParser(parser, "", 0); assertParser(parser, "a", 0, "a"); } @Test public void testIfElse_withNext() { expect(next.map('b')).andReturn(FOO); replay(); assertParser(areChars("ab").ifelse(next, constant("bar")), "ab", "foo"); } @Test public void testLabel() { assertParser(FOO.label("the foo"), "", "foo"); assertFailure(INTEGER.label("number"), "", 1, 1, "number"); } @Test public void testCast() { Parser<String> parser = Parsers.<CharSequence>constant("chars").<String>cast(); assertEquals("chars", parser.toString()); assertParser(parser, "", "chars"); } @Test public void testBetween() { assertParser(INTEGER.between(isChar('('), isChar(')')), "(123)", 123); } @Mock Map<Integer, String> map; @Test public void testMap() { expect(map.map(12)).andReturn("foo"); replay(); assertParser(INTEGER.map(map), "12", "foo"); assertEquals(map.toString(), INTEGER.map(map).toString()); } @Test public void testMap_fails() { replay(); assertFailure(INTEGER.map(map), "", 1, 1, "integer expected, EOF encountered."); } @Test public void testSepBy1() { Parser<List<Integer>> parser = INTEGER.sepBy1(isChar(',')); assertListParser(parser, "1", 1); assertListParser(parser, "123,45", 123, 45); assertListParser(parser.followedBy(Scanners.isChar(' ')), "1 ", 1); assertListParser(parser.followedBy(isChar(',')), "1,", 1); assertFailure(parser, "", 1, 1); assertFailure(areChars("ab").sepBy1(isChar(',')), "ab,a", 1, 5); } @Test public void testSepBy() { Parser<List<Integer>> parser = INTEGER.sepBy(isChar(',')); assertListParser(parser, "1", 1); assertListParser(parser, "123,45", 123, 45); assertListParser(parser.followedBy(isChar(' ')), "1 ", 1); assertListParser(parser, ""); assertListParser(parser.followedBy(isChar(',')), "1,", 1); assertFailure(areChars("ab").sepBy(isChar(',')), "ab,a", 1, 5); } @Test public void testEndBy() { Parser<List<Integer>> parser = INTEGER.endBy(isChar(';')); assertListParser(parser, ""); assertListParser(parser, "1;", 1); assertListParser(parser, "12;3;", 12, 3); assertListParser(parser.followedBy(isChar(';')), ";"); assertFailure(parser, "1", 1, 2); assertFailure(areChars("ab").endBy(isChar(';')), "ab;a", 1, 5); } @Test public void testEndBy1() { Parser<List<Integer>> parser = INTEGER.endBy1(isChar(';')); assertListParser(parser, "1;", 1); assertListParser(parser, "12;3;", 12, 3); assertFailure(parser, "", 1, 1); assertFailure(parser, ";", 1, 1); assertFailure(parser, "1", 1, 2); assertFailure(areChars("ab").endBy1(isChar(';')), "ab;a", 1, 5); } @Test public void testSepEndBy1() { Parser<List<Integer>> parser = INTEGER.sepEndBy1(COMMA); assertListParser(parser, "1,2", 1, 2); assertListParser(parser, "1", 1); assertListParser(parser, "1,", 1); assertFailure(parser, ",", 1, 1); assertFailure(parser, "", 1, 1); assertFailure(parser.next(Parsers.EOF), "1,,", 1, 3); assertFailure(areChars("ab").sepEndBy1(isChar(';')), "ab;a", 1, 5); // atomize on delimiter assertListParser(INTEGER.sepEndBy1(COMMA.next(COMMA).atomic()).followedBy(COMMA), "1,", 1); // 0 step partial delimiter consumption assertListParser(INTEGER.sepEndBy1(COMMA.step(0).next(COMMA)).followedBy(COMMA), "1,", 1); // partial delimiter consumption assertFailure(INTEGER.sepEndBy1(COMMA.next(COMMA)), "1,", 1, 3, ", expected, EOF encountered."); // infinite loop. assertListParser(Parsers.always().sepEndBy1(Parsers.always()), "", (Integer) null); // partial consumption on delimited. assertFailure(INTEGER.followedBy(COMMA).sepEndBy1(COMMA), "1,,1", 1, 5, ", expected, EOF encountered."); // 0 step partial delimited consumption assertListParser(INTEGER.step(0).followedBy(COMMA).sepEndBy1(COMMA).followedBy(string("1")) , "1,,1", 1); } @Test public void testSepEndBy() { Parser<List<Integer>> parser = INTEGER.sepEndBy(COMMA); assertListParser(parser, "1,2", 1, 2); assertListParser(parser, "1", 1); assertListParser(parser, "1,", 1); assertListParser(parser.followedBy(isChar(',')), ","); assertListParser(parser, ""); assertFailure(parser.next(Parsers.EOF), "1,,", 1, 3); assertFailure(areChars("ab").sepEndBy(isChar(';')), "ab;a", 1, 5); // atomize on delimiter assertListParser(INTEGER.sepEndBy(COMMA.next(COMMA).atomic()).followedBy(COMMA), "1,", 1); // 0 step partial delimiter consumption assertListParser(INTEGER.sepEndBy(COMMA.step(0).next(COMMA)).followedBy(COMMA), "1,", 1); // partial delimiter consumption assertFailure(INTEGER.sepEndBy(COMMA.next(COMMA)), "1,", 1, 3, ", expected, EOF encountered."); // infinite loop. assertListParser(Parsers.always().sepEndBy(Parsers.always()), "", (Integer) null); // partial consumption on delimited. assertFailure(INTEGER.followedBy(COMMA).sepEndBy(COMMA), "1,,1", 1, 5, ", expected, EOF encountered."); // 0 step partial delimited consumption assertListParser(INTEGER.step(0).followedBy(COMMA).sepEndBy(COMMA).followedBy(string("1")) , "1,,1", 1); } @Test public void testEmptyListParser_toString() { assertEquals("[]", EmptyListParser.instance().toString()); } @Mock Map<Integer, Integer> unaryOp; @Test public void testPrefix_noOperator() { replay(); Parser<Integer> parser = INTEGER.prefix(isChar('-').retn(unaryOp)); assertEquals("prefix", parser.toString()); assertParser(parser, "123", 123); } @Test public void testPrefix() { expect(unaryOp.map(1)).andReturn(-1); expect(unaryOp.map(-1)).andReturn(1); expect(unaryOp.map(1)).andReturn(-1); replay(); Parser<Integer> parser = INTEGER.prefix(isChar('-').retn(unaryOp)); assertEquals("prefix", parser.toString()); assertParser(parser, "---1", -1); } @Test public void testPostfix_noOperator() { replay(); Parser<Integer> parser = INTEGER.postfix(isChar('^').retn(unaryOp)); assertEquals("postfix", parser.toString()); assertParser(parser, "123", 123); } @Test public void testPostfix() { expect(unaryOp.map(2)).andReturn(4); expect(unaryOp.map(4)).andReturn(256); replay(); Parser<Integer> parser = INTEGER.postfix(isChar('^').retn(unaryOp)); assertEquals("postfix", parser.toString()); assertParser(parser, "2^^", 256); } @Mock Map2<Integer, Integer, Integer> binaryOp; @Test public void testInfixn_noOperator() { replay(); Parser<Integer> parser = INTEGER.infixn(isChar('+').retn(binaryOp)); assertEquals("infixn", parser.toString()); assertParser(parser, "1", 1); } @Test public void testInfixn() { expect(binaryOp.map(1, 2)).andReturn(3); replay(); Parser<Integer> parser = INTEGER.infixn(isChar('+').retn(binaryOp)); assertEquals("infixn", parser.toString()); assertParser(parser, "1+2+3", 3, "+3"); } @Test public void testInfixl_noOperator() { replay(); Parser<Integer> parser = INTEGER.infixl(isChar('+').retn(binaryOp)); assertEquals("infixl", parser.toString()); assertParser(parser, "1", 1); } @Test public void testInfixl() { expect(binaryOp.map(4, 1)).andReturn(3); expect(binaryOp.map(3, 2)).andReturn(1); replay(); Parser<Integer> parser = INTEGER.infixl(isChar('-').retn(binaryOp)); assertEquals("infixl", parser.toString()); assertParser(parser, "4-1-2", 1); } @Test public void testInfixl_fails() { replay(); assertFailure(INTEGER.infixl(isChar('-').retn(binaryOp)), "4-1-", 1, 5); } @Test public void testInfixr_noOperator() { replay(); Parser<Integer> parser = INTEGER.infixr(isChar('+').retn(binaryOp)); assertEquals("infixr", parser.toString()); assertParser(parser, "1", 1); } @Test public void testInfixr() { expect(binaryOp.map(1, 2)).andReturn(12); expect(binaryOp.map(4, 12)).andReturn(412); replay(); Parser<Integer> parser = INTEGER.infixr(string("->").retn(binaryOp)); assertEquals("infixr", parser.toString()); assertParser(parser, "4->1->2", 412); } @Test public void testInfixr_fails() { replay(); assertFailure(INTEGER.infixr(isChar('-').retn(binaryOp)), "4-1-", 1, 5); } @Test public void testFrom() { List<Token> tokenList = Arrays.asList(new Token(0, 2, 'a'), new Token(2, 3, 4L)); Parser<Long> parser = Terminals.CharLiteral.PARSER.next(Terminals.LongLiteral.PARSER); Parser<List<Token>> lexeme = constant(tokenList); assertParser(parser.from(lexeme), "", 4L); assertFailure(Terminals.CharLiteral.PARSER.from(constant(Arrays.<Token>asList())), "", 1, 1, "character literal expected, EOF encountered."); assertListParser(Parsers.ANY_TOKEN.many().from(lexeme), "", 'a', 4L); assertFailure(Parsers.ANY_TOKEN.from(lexeme), "abcde", 1, 3); assertFailure(Parsers.always().from(Parsers.<List<Token>>fail("foo")), "", 1, 1); Parser<String> badParser = Terminals.CharLiteral.PARSER.next(Terminals.Identifier.PARSER); assertFailure(badParser.from(lexeme), "aabbb", 1, 3); } @Test public void testFrom_throwsOnScanners() { assertFailure(string("foo").from(constant(Arrays.asList(new Token(0, 3, "foo")))), "foo", 1, 1, "Cannot scan characters on tokens."); assertFailure(isChar('f').from(constant(Arrays.asList(new Token(0, 1, 'f')))), "f", 1, 1, "Cannot scan characters on tokens."); } @Test public void testFrom_withDelimiter() { Parser<List<String>> integers = Terminals.IntegerLiteral.PARSER.many(); Parser<List<String>> parser = integers.from(Terminals.IntegerLiteral.TOKENIZER, Scanners.WHITESPACES); assertEquals("followedBy", parser.toString()); assertListParser(parser, "12 34 5 ", "12", "34", "5"); } @Test public void testLexer() { Parser<List<Token>> parser = Terminals.LongLiteral.DEC_TOKENIZER.lexer(Scanners.WHITESPACES); assertParser(parser, "", Arrays.<Token>asList()); assertParser(parser, " ", Arrays.<Token>asList()); assertParser(parser, " 12 ", Arrays.<Token>asList(new Token(1, 2, 12L))); assertParser(parser, "12 3 ", Arrays.<Token>asList(new Token(0, 2, 12L), new Token(3, 1, 3L))); } @Test public void testCopy() throws Exception { String content = "foo bar and baz"; StringBuilder to = Parser.read(new StringReader(content)); assertEquals(content, to.toString()); } @Test public void emptyParseTreeInParserException() { try { Scanners.string("begin").parse("", Parser.Mode.DEBUG); fail(); } catch (ParserException e) { ParseTree tree = e.getParseTree(); assertEquals("root", tree.getName()); assertEquals(0, tree.getBeginIndex()); assertEquals(0, tree.getEndIndex()); assertEquals(null, tree.getValue()); assertEquals(tree.toString(), 0, tree.getChildren().size()); } } @Test public void populatedParseTreeInParserException() { try { Scanners.string("begin").parse("beginx", Parser.Mode.DEBUG); fail(); } catch (ParserException e) { ParseTree tree = e.getParseTree(); assertEquals("root", tree.getName()); assertEquals(0, tree.getBeginIndex()); assertEquals(0, tree.getEndIndex()); assertEquals(null, tree.getValue()); assertEquals(tree.toString(), 1, tree.getChildren().size()); ParseTree child = tree.getChildren().get(0); assertEquals("begin", child.getName()); assertEquals(0, child.getBeginIndex()); assertEquals("begin".length(), child.getEndIndex()); assertEquals(null, tree.getValue()); assertEquals(child.toString(), 0, child.getChildren().size()); } } @Test public void populatedParseTreeWithExplicitLabelInParserException() { // try { Scanners.string("begin").label("begin").parse("begi", Parser.Mode.DEBUG); // fail(); // } catch (ParserException e) { // ParseTree tree = e.getParseTree(); // assertEquals("root", tree.getName()); // assertEquals(0, tree.getBeginIndex()); // assertEquals(0, tree.getEndIndex()); // assertEquals(null, tree.getValue()); // assertEquals(tree.toString(), 1, tree.getChildren().size()); // ParseTree child = tree.getChildren().get(0); // assertEquals("hello", child.getName()); // assertEquals(0, child.getBeginIndex()); // assertEquals("begin".length(), child.getEndIndex()); // assertEquals(null, tree.getValue()); // assertEquals(child.toString(), 0, child.getChildren().size()); } private static void assertListParser( Parser<? extends List<?>> parser, String source, Object... expected) { assertList(parser.parse(source), expected); } private static void assertList(Object actual, Object... expected) { assertEquals(Arrays.asList(expected), actual); } }
package com.mixpanel.android.viewcrawler; import android.graphics.BitmapFactory; import android.util.Base64; import android.util.Log; import android.view.accessibility.AccessibilityEvent; import android.widget.RelativeLayout; import com.mixpanel.android.mpmetrics.ResourceIds; import com.mixpanel.android.util.JSONUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* package */ class EditProtocol { public static class BadInstructionsException extends Exception { private static final long serialVersionUID = -4062004792184145311L; public BadInstructionsException(String message) { super(message); } public BadInstructionsException(String message, Exception e) { super(message, e); } } public static class InapplicableInstructionsException extends BadInstructionsException { private static final long serialVersionUID = 3977056710817909104L; public InapplicableInstructionsException(String message) { super(message); } } public EditProtocol(ResourceIds resourceIds) { mResourceIds = resourceIds; } public ViewVisitor readEventBinding(JSONObject source, ViewVisitor.OnEventListener listener) throws BadInstructionsException { try { final String eventName = source.getString("event_name"); final String eventType = source.getString("event_type"); final JSONArray pathDesc = source.getJSONArray("path"); final List<Pathfinder.PathElement> path = readPath(pathDesc, mResourceIds); if (path.size() == 0) { throw new InapplicableInstructionsException("event '" + eventName + "' will not be bound to any element in the UI."); } if ("click".equals(eventType)) { return new ViewVisitor.AddAccessibilityEventVisitor( path, AccessibilityEvent.TYPE_VIEW_CLICKED, eventName, listener ); } else if ("selected".equals(eventType)) { return new ViewVisitor.AddAccessibilityEventVisitor( path, AccessibilityEvent.TYPE_VIEW_SELECTED, eventName, listener ); } else if ("text_changed".equals(eventType)) { return new ViewVisitor.AddTextChangeListener(path, eventName, listener); } else if ("detected".equals(eventType)) { return new ViewVisitor.ViewDetectorVisitor(path, eventName, listener); } else { throw new BadInstructionsException("Mixpanel can't track event type \"" + eventType + "\""); } } catch (final JSONException e) { throw new BadInstructionsException("Can't interpret instructions due to JSONException", e); } } public ViewVisitor readEdit(JSONObject source) throws BadInstructionsException { try { final JSONArray pathDesc = source.getJSONArray("path"); final List<Pathfinder.PathElement> path = readPath(pathDesc, mResourceIds); if (path.size() == 0) { throw new InapplicableInstructionsException("Edit will not be bound to any element in the UI."); } if (source.getString("change_type").equals("property")) { final JSONObject propertyDesc = source.getJSONObject("property"); final String targetClassName = propertyDesc.getString("classname"); if (null == targetClassName) { throw new BadInstructionsException("Can't bind an edit property without a target class"); } final Class<?> targetClass; try { targetClass = Class.forName(targetClassName); } catch (final ClassNotFoundException e) { throw new BadInstructionsException("Can't find class for visit path: " + targetClassName, e); } final PropertyDescription prop = readPropertyDescription(targetClass, source.getJSONObject("property")); final JSONArray argsAndTypes = source.getJSONArray("args"); final Object[] methodArgs = new Object[argsAndTypes.length()]; for (int i = 0; i < argsAndTypes.length(); i++) { final JSONArray argPlusType = argsAndTypes.getJSONArray(i); final Object jsonArg = argPlusType.get(0); final String argType = argPlusType.getString(1); methodArgs[i] = convertArgument(jsonArg, argType); } final Caller mutator = prop.makeMutator(methodArgs); if (null == mutator) { throw new BadInstructionsException("Can't update a read-only property " + prop.name + " (add a mutator to make this work)"); } return new ViewVisitor.PropertySetVisitor(path, mutator, prop.accessor); } else if (source.getString("change_type").equals("layout")) { final JSONArray args = source.getJSONArray("args"); JSONObject layout_info = args.optJSONObject(0); ViewVisitor.LayoutRule params; int verb = layout_info.getInt("verb"); if (layout_info.getString("operation").equals("remove")) { params = new ViewVisitor.LayoutRule(verb, 0); } else if (layout_info.has("anchor_id")) { params = new ViewVisitor.LayoutRule(verb, layout_info.getInt("anchor_id")); } else { params = new ViewVisitor.LayoutRule(verb, RelativeLayout.TRUE); } return new ViewVisitor.LayoutSetVisitor(path, params); } else { throw new BadInstructionsException("Can't figure out the edit type"); } } catch (final NoSuchMethodException e) { throw new BadInstructionsException("Can't create property mutator", e); } catch (final JSONException e) { throw new BadInstructionsException("Can't interpret instructions due to JSONException", e); } } public ViewSnapshot readSnapshotConfig(JSONObject source) throws BadInstructionsException { final List<PropertyDescription> properties = new ArrayList<PropertyDescription>(); try { final JSONObject config = source.getJSONObject("config"); final JSONArray classes = config.getJSONArray("classes"); for (int classIx = 0; classIx < classes.length(); classIx++) { final JSONObject classDesc = classes.getJSONObject(classIx); final String targetClassName = classDesc.getString("name"); final Class<?> targetClass = Class.forName(targetClassName); final JSONArray propertyDescs = classDesc.getJSONArray("properties"); for (int i = 0; i < propertyDescs.length(); i++) { final JSONObject propertyDesc = propertyDescs.getJSONObject(i); final PropertyDescription desc = readPropertyDescription(targetClass, propertyDesc); properties.add(desc); } } return new ViewSnapshot(properties, mResourceIds); } catch (JSONException e) { throw new BadInstructionsException("Can't read snapshot configuration", e); } catch (final ClassNotFoundException e) { throw new BadInstructionsException("Can't resolve types for snapshot configuration", e); } } // Package access FOR TESTING ONLY /* package */ List<Pathfinder.PathElement> readPath(JSONArray pathDesc, ResourceIds idNameToId) throws JSONException { final List<Pathfinder.PathElement> path = new ArrayList<Pathfinder.PathElement>(); for (int i = 0; i < pathDesc.length(); i++) { final JSONObject targetView = pathDesc.getJSONObject(i); final String prefixCode = JSONUtils.optionalStringKey(targetView, "prefix"); final String targetViewClass = JSONUtils.optionalStringKey(targetView, "view_class"); final int targetIndex = targetView.optInt("index", -1); final String targetDescription = JSONUtils.optionalStringKey(targetView, "contentDescription"); final int targetExplicitId = targetView.optInt("id", -1); final String targetIdName = JSONUtils.optionalStringKey(targetView, "mp_id_name"); final String targetTag = JSONUtils.optionalStringKey(targetView, "tag"); final int prefix; if ("shortest".equals(prefixCode)) { prefix = Pathfinder.PathElement.SHORTEST_PREFIX; } else if (null == prefixCode) { prefix = Pathfinder.PathElement.ZERO_LENGTH_PREFIX; } else { Log.w(LOGTAG, "Unrecognized prefix type \"" + prefixCode + "\". No views will be matched"); return NEVER_MATCH_PATH; } final int targetId; final Integer targetIdOrNull = reconcileIdsInPath(targetExplicitId, targetIdName, idNameToId); if (null == targetIdOrNull) { return NEVER_MATCH_PATH; } else { targetId = targetIdOrNull.intValue(); } path.add(new Pathfinder.PathElement(prefix, targetViewClass, targetIndex, targetId, targetDescription, targetTag)); } return path; } // May return null (and log a warning) if arguments cannot be reconciled private Integer reconcileIdsInPath(int explicitId, String idName, ResourceIds idNameToId) { final int idFromName; if (null != idName) { if (idNameToId.knownIdName(idName)) { idFromName = idNameToId.idFromName(idName); } else { Log.w(LOGTAG, "Path element contains an id name not known to the system. No views will be matched.\n" + "Make sure that you're not stripping your packages R class out with proguard.\n" + "id name was \"" + idName + "\"" ); return null; } } else { idFromName = -1; } if (-1 != idFromName && -1 != explicitId && idFromName != explicitId) { Log.e(LOGTAG, "Path contains both a named and an explicit id, and they don't match. No views will be matched."); return null; } if (-1 != idFromName) { return idFromName; } return explicitId; } private PropertyDescription readPropertyDescription(Class<?> targetClass, JSONObject propertyDesc) throws BadInstructionsException { try { final String propName = propertyDesc.getString("name"); Caller accessor = null; if (propertyDesc.has("get")) { final JSONObject accessorConfig = propertyDesc.getJSONObject("get"); final String accessorName = accessorConfig.getString("selector"); final String accessorResultTypeName = accessorConfig.getJSONObject("result").getString("type"); final Class<?> accessorResultType = Class.forName(accessorResultTypeName); accessor = new Caller(targetClass, accessorName, NO_PARAMS, accessorResultType); } final String mutatorName; if (propertyDesc.has("set")) { final JSONObject mutatorConfig = propertyDesc.getJSONObject("set"); mutatorName = mutatorConfig.getString("selector"); } else { mutatorName = null; } return new PropertyDescription(propName, targetClass, accessor, mutatorName); } catch (final NoSuchMethodException e) { throw new BadInstructionsException("Can't create property reader", e); } catch (final JSONException e) { throw new BadInstructionsException("Can't read property JSON", e); } catch (final ClassNotFoundException e) { throw new BadInstructionsException("Can't read property JSON, relevant arg/return class not found", e); } } private Object convertArgument(Object jsonArgument, String type) throws BadInstructionsException { // Object is a Boolean, JSONArray, JSONObject, Number, String, or JSONObject.NULL try { if ("java.lang.CharSequence".equals(type)) { // Because we're assignable return jsonArgument; } else if ("boolean".equals(type) || "java.lang.Boolean".equals(type)) { return jsonArgument; } else if ("int".equals(type) || "java.lang.Integer".equals(type)) { return ((Number) jsonArgument).intValue(); } else if ("float".equals(type) || "java.lang.Float".equals(type)) { return ((Number) jsonArgument).floatValue(); } else if ("android.graphics.Bitmap".equals(type)) { final byte[] bytes = Base64.decode((String) jsonArgument, 0); return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } else { throw new BadInstructionsException("Don't know how to interpret type " + type + " (arg was " + jsonArgument + ")"); } } catch (final ClassCastException e) { throw new BadInstructionsException("Couldn't interpret <" + jsonArgument + "> as " + type); } } private final ResourceIds mResourceIds; private static final Class<?>[] NO_PARAMS = new Class[0]; private static final List<Pathfinder.PathElement> NEVER_MATCH_PATH = Collections.<Pathfinder.PathElement>emptyList(); @SuppressWarnings("unused") private static final String LOGTAG = "MixpanelAPI.EProtocol"; } // EditProtocol
package de.bmoth.parser.ast.nodes; import de.bmoth.TestParser; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertTrue; public class EqualAstTest extends TestParser { @Test public void testEqualAstIfSubstitution() { MachineNode machine = new MachineBuilder() .setName("IfSubstitutionMachine") .setVariables("a") .setInvariant("a : INTEGER") .setInitialization("a := 0") .addOperation("op1 = IF a = 3 THEN a:=2 ELSE a:=1 END") .addOperation("op2 = IF a = 3 THEN a:=2 ELSE a:=1 END") .addOperation("op_changed1 = IF a = 2 THEN a:=2 ELSE a:=1 END") .addOperation("op_changed2 = IF a = 3 THEN a:=5 ELSE a:=1 END") .addOperation("op_changed3 = IF a = 3 THEN a:=2 ELSE a:=3 END") .addOperation("op_not_if = SELECT a = 3 THEN a:=2 END") .build(); List<SubstitutionNode> substitutions = machine.getOperations().stream().map(OperationNode::getSubstitution).collect(Collectors.toList()); assertTrue(substitutions.get(0).equalAst(substitutions.get(1))); assertFalse(substitutions.get(0).equalAst(substitutions.get(2))); assertFalse(substitutions.get(0).equalAst(substitutions.get(3))); assertFalse(substitutions.get(0).equalAst(substitutions.get(4))); assertFalse(substitutions.get(0).equalAst(substitutions.get(5))); } @Test public void testEqualAstSelectSubstitution() { MachineNode machine = new MachineBuilder() .setName("IfSubstitutionMachine") .setVariables("a") .setInvariant("a : INTEGER") .setInitialization("a := 0") .addOperation("op1 = SELECT a : {2+1} THEN a:=2 END") .addOperation("op2 = SELECT a : {2+1} THEN a:=2 END") .addOperation("op_changed1 = SELECT a = 3 THEN a:=2 END") .addOperation("op_changed2 = SELECT a : {2+1} THEN a:=1+1 END") .addOperation("op_not_select = IF a = 3 THEN a:=2 ELSE a:=3 END") .build(); List<SubstitutionNode> substitutions = machine.getOperations().stream().map(OperationNode::getSubstitution).collect(Collectors.toList()); assertTrue(substitutions.get(0).equalAst(substitutions.get(1))); assertFalse(substitutions.get(0).equalAst(substitutions.get(2))); assertFalse(substitutions.get(0).equalAst(substitutions.get(3))); assertFalse(substitutions.get(0).equalAst(substitutions.get(4))); } }
package com.rarchives.ripme.ripper; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.jsoup.HttpStatusException; import com.rarchives.ripme.ui.RipStatusMessage.STATUS; import com.rarchives.ripme.utils.Utils; /** * Thread for downloading files. * Includes retry logic, observer notifications, and other goodies. */ public class DownloadFileThread extends Thread { private static final Logger logger = Logger.getLogger(DownloadFileThread.class); private String referrer = ""; private Map<String,String> cookies = new HashMap<String,String>(); private URL url; private File saveAs; private String prettySaveAs; private AbstractRipper observer; private int retries; private final int TIMEOUT; public DownloadFileThread(URL url, File saveAs, AbstractRipper observer) { super(); this.url = url; this.saveAs = saveAs; this.prettySaveAs = Utils.removeCWD(saveAs); this.observer = observer; this.retries = Utils.getConfigInteger("download.retries", 1); this.TIMEOUT = Utils.getConfigInteger("download.timeout", 60000); } public void setReferrer(String referrer) { this.referrer = referrer; } public void setCookies(Map<String,String> cookies) { this.cookies = cookies; } /** * Attempts to download the file. Retries as needed. * Notifies observers upon completion/error/warn. */ public void run() { try { observer.stopCheck(); } catch (IOException e) { observer.downloadErrored(url, "Download interrupted"); return; } if (saveAs.exists()) { if (Utils.getConfigBoolean("file.overwrite", false)) { logger.info("[!] Deleting existing file" + prettySaveAs); saveAs.delete(); } else { logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs); observer.downloadProblem(url, "File already exists: " + prettySaveAs); return; } } URL urlToDownload = this.url; boolean redirected = false; int tries = 0; // Number of attempts to download do { tries += 1; InputStream bis = null; OutputStream fos = null; try { logger.info(" Downloading file: " + urlToDownload + (tries > 0 ? " Retry #" + tries : "")); observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm()); // Setup HTTP request HttpURLConnection huc; if (this.url.toString().startsWith("https")) { huc = (HttpsURLConnection) urlToDownload.openConnection(); } else { huc = (HttpURLConnection) urlToDownload.openConnection(); } huc.setInstanceFollowRedirects(true); huc.setConnectTimeout(TIMEOUT); huc.setRequestProperty("accept", "*/*"); huc.setRequestProperty("Referer", referrer); // Sic huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT); String cookie = ""; for (String key : cookies.keySet()) { if (!cookie.equals("")) { cookie += "; "; } cookie += key + "=" + cookies.get(key); } huc.setRequestProperty("Cookie", cookie); huc.connect(); int statusCode = huc.getResponseCode(); if (statusCode / 100 == 3) { // 3xx Redirect if (!redirected) { // Don't increment retries on the first redirect tries redirected = true; } String location = huc.getHeaderField("Location"); urlToDownload = new URL(location); // Throw exception so download can be retried throw new IOException("Redirect status code " + statusCode + " - redirect to " + location); } if (statusCode / 100 == 4) { // 4xx errors logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url); observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm()); return; // Not retriable, drop out. } if (statusCode / 100 == 5) { // 5xx errors observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm()); // Throw exception so download can be retried throw new IOException("Retriable status code " + statusCode); } if (huc.getContentLength() == 503 && urlToDownload.getHost().endsWith("imgur.com")) { // Imgur image with 503 bytes is "404" logger.error("[!] Imgur image is 404 (503 bytes long): " + url); observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm()); return; } // Save file bis = new BufferedInputStream(huc.getInputStream()); fos = new FileOutputStream(saveAs); IOUtils.copy(bis, fos); break; // Download successful: break out of infinite loop } catch (HttpStatusException hse) { logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + urlToDownload); if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) { observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm()); return; } } catch (IOException e) { logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage()); } finally { // Close any open streams try { if (bis != null) { bis.close(); } } catch (IOException e) { } try { if (fos != null) { fos.close(); } } catch (IOException e) { } } if (tries > this.retries) { logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url); observer.downloadErrored(url, "Failed to download " + url.toExternalForm()); return; } } while (true); observer.downloadCompleted(url, saveAs); logger.info("[+] Saved " + url + " as " + this.prettySaveAs); } }
package com.matthewhatcher.vpnguard.Utils; import com.matthewhatcher.vpnguard.VPNGuard; public class WebUtils { private VPNGuard plugin; String apiUrl; String fallbackApiUrl; public WebUtils(VPNGuard plugin) { this.plugin = plugin; if(plugin.config.hasEmail()) { apiUrl = "http://check.getipintel.net/check.php?ip=%ip%&contact=" + plugin.config.adminEmail; fallbackApiUrl = "http://legacy.iphub.info/api.php?ip=%ip%&showtype=4&email=" + plugin.config.adminEmail; } else { apiUrl = null; fallbackApiUrl = "http://legacy.iphub.info/api.php?ip=%ip%&showtype=4"; } } public boolean apiIsOnline() { return true; } public boolean fallbackIsOnline() { return true; } }
package com.rwtema.funkylocomotion.blocks; import com.rwtema.funkylocomotion.fakes.FakeWorldClient; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import java.util.List; import java.util.Random; public class BlockMoving extends Block { public static BlockMoving instance; public static IIcon crate; public static IIcon crate_error; @Override public boolean canRenderInPass(int pass) { return false; } public BlockMoving() { super(Material.rock); this.setBlockUnbreakable(); this.setBlockName("funkylocomotion:moving"); this.setBlockTextureName("funkylocomotion:crate"); instance = this; } public static boolean _Immoveable() { return true; } @Override @SuppressWarnings("unchecked") public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB axis, List list, Entity entity) { TileEntity tile = world.getTileEntity(x, y, z); if (!(tile instanceof TileMovingBase)) return; for (AxisAlignedBB bb : ((TileMovingBase) tile).getTransformedColisions()) if (axis.intersectsWith(bb)) list.add(bb); ForgeDirection d = ((TileMovingBase) tile).dir; TileEntity tile2 = world.getTileEntity(x + d.offsetX, y + d.offsetY, z + d.offsetZ); if (!(tile2 instanceof TileMovingBase)) return; for (AxisAlignedBB bb : ((TileMovingBase) tile2).getTransformedColisions()) if (axis.intersectsWith(bb)) list.add(bb); } @Override public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z) { this.setBlockBounds(0, 0, 0, 1, 1, 1); TileEntity tile = world.getTileEntity(x, y, z); if (tile instanceof TileMovingBase) { if (((TileMovingBase) tile).isAir) this.setBlockBounds(0, 0, 0, 0, 0, 0); } // if (world instanceof World) { // TileEntity tile = world.getTileEntity(x, y, z); // if (tile instanceof TileMovingBase) { // AxisAlignedBB bb = ((TileMovingBase) tile).getCombinedCollisions(); // if (bb != null) { // bb = bb; // this.setBlockBounds((float) bb.minX, (float) bb.minY, (float) bb.minZ, // (float) bb.maxX, (float) bb.maxY, (float) bb.maxZ); } @Override public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { return super.getCollisionBoundingBoxFromPool(world, x, y, z); // TileEntity tile = world.getTileEntity(x, y, z); // return tile instanceof TileMovingBase ? ((TileMovingBase) tile).getCombinedCollisions().offset(x, y, z) : null; } @Override public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) { return super.getSelectedBoundingBoxFromPool(world, x, y, z); } @Override public void registerBlockIcons(IIconRegister p_149651_1_) { crate = this.blockIcon = p_149651_1_.registerIcon(this.getTextureName()); crate_error = p_149651_1_.registerIcon("funkylocomotion:crate_error"); } @Override public void onEntityCollidedWithBlock(World p_149670_1_, int p_149670_2_, int p_149670_3_, int p_149670_4_, Entity p_149670_5_) { super.onEntityCollidedWithBlock(p_149670_1_, p_149670_2_, p_149670_3_, p_149670_4_, p_149670_5_); } @Override public boolean hasTileEntity(int metadata) { return true; } @Override public TileEntity createTileEntity(World world, int metadata) { if (world.isRemote || FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) return new TileMovingClient(); else return new TileMovingServer(); } @Override public int getRenderType() { return -1; } @Override public boolean isOpaqueCube() { return false; } @SuppressWarnings("deprecation") @Override public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { return null; } @Override public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player) { return null; } @Override public int getLightValue(IBlockAccess world, int x, int y, int z) { TileEntity tile = world.getTileEntity(x, y, z); return tile instanceof TileMovingBase ? ((TileMovingBase) tile).lightLevel : super.getLightValue(world, x, y, z); } @Override public boolean isBlockSolid(IBlockAccess p_149747_1_, int p_149747_2_, int p_149747_3_, int p_149747_4_, int p_149747_5_) { return false; } @Override public boolean renderAsNormalBlock() { return false; } @Override public int getLightOpacity(IBlockAccess world, int x, int y, int z) { TileEntity tile = world.getTileEntity(x, y, z); return tile instanceof TileMovingBase ? ((TileMovingBase) tile).lightOpacity : super.getLightOpacity(world, x, y, z); } @Override public int getLightOpacity() { return super.getLightOpacity(); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { if (world.isRemote) return true; TileEntity tile = world.getTileEntity(x, y, z); if (tile instanceof TileMovingServer) { ((TileMovingServer) tile).cacheActivate(player, side, hitX, hitY, hitZ); } return true; } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(World world, int x, int y, int z, Random rand) { TileEntity tile = world.getTileEntity(x, y, z); if (tile instanceof TileMovingClient) { TileMovingClient mover = (TileMovingClient) tile; FakeWorldClient fakeWorld = FakeWorldClient.getFakeWorldWrapper(world); fakeWorld.offset = mover.offset(true); fakeWorld.dir = mover.dir; mover.block.randomDisplayTick(fakeWorld, mover.xCoord, mover.yCoord, mover.zCoord, rand); fakeWorld.offset = 0; } } @Override public boolean isNormalCube(IBlockAccess world, int x, int y, int z) { return false; } }
package hudson.plugins.git; import hudson.EnvVars; import hudson.model.TaskListener; import hudson.tools.AbstractCommandInstaller; import hudson.tools.BatchCommandInstaller; import hudson.tools.CommandInstaller; import hudson.tools.InstallSourceProperty; import java.io.File; import java.io.IOException; import java.util.Collections; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; public class GitToolResolverTest { @Rule public JenkinsRule j = new JenkinsRule(); private GitTool gitTool; @Before public void setUp() throws IOException { GitTool.onLoaded(); gitTool = GitTool.getDefaultInstallation(); } @Test public void shouldResolveToolsOnMaster() throws Exception { final String label = "master"; final String command = "echo Hello"; final String toolHome = "TOOL_HOME"; AbstractCommandInstaller installer; String expectedSubstring; if (isWindows()) { installer = new BatchCommandInstaller(label, command, toolHome); expectedSubstring = System.getProperty("java.io.tmpdir", "C:\\Temp"); } else { installer = new CommandInstaller(label, command, toolHome); expectedSubstring = toolHome; } GitTool t = new GitTool("myGit", null, Collections.singletonList( new InstallSourceProperty(Collections.singletonList(installer)))); t.getDescriptor().setInstallations(t); GitTool defaultTool = GitTool.getDefaultInstallation(); GitTool resolved = (GitTool) defaultTool.translate(j.jenkins, new EnvVars(), TaskListener.NULL); assertThat(resolved.getGitExe(), org.hamcrest.CoreMatchers.containsString(expectedSubstring)); } private boolean isWindows() { return File.pathSeparatorChar == ';'; } }
package com.mlibrary.patch.framework; import android.app.Application; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.text.TextUtils; import com.mlibrary.patch.MDynamicLib; import com.mlibrary.patch.hack.AndroidHack; import com.mlibrary.patch.hack.SysHacks; import com.mlibrary.patch.hotpatch.HotPatchManager; import com.mlibrary.patch.runtime.InstrumentationHook; import com.mlibrary.patch.runtime.ResourcesHook; import com.mlibrary.patch.runtime.RuntimeArgs; import com.mlibrary.patch.util.FileUtil; import com.mlibrary.patch.util.LogUtil; import com.mlibrary.patch.util.PreferencesUtil; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @SuppressWarnings("ResultOfMethodCallIgnored") public class BundleManager { private static final String TAG = MDynamicLib.TAG + ":BundleManager"; private static final String BUNDLE_LIB_PATH = "assets/baseres/"; private static final String BUNDLE_SUFFIX = ".so"; private final Map<String, Bundle> bundles = new ConcurrentHashMap<>(); private String storageLocation; private long nextBundleID = 1; private static BundleManager instance = null; private BundleManager() { } public static BundleManager getInstance() { if (instance == null) { synchronized (BundleManager.class) { if (instance == null) instance = new BundleManager(); } } return instance; } public void init(Application application, boolean isOpenLog) { long startTime = System.currentTimeMillis(); LogUtil.setDebugAble(isOpenLog); LogUtil.w(TAG, "======================================================================"); LogUtil.w(TAG, "******** mdynamiclib init start **************************************"); LogUtil.w(TAG, "======================================================================"); try { SysHacks.defineAndVerify(); RuntimeArgs.androidApplication = application; RuntimeArgs.delegateResources = application.getResources(); AndroidHack.injectInstrumentationHook(new InstrumentationHook(AndroidHack.getInstrumentation(), application.getBaseContext())); //init storageLocation start String baseDir = null; //String baseDir = RuntimeArgs.androidApplication.getFilesDir().getAbsolutePath(); //SDCard File externalFile = RuntimeArgs.androidApplication.getExternalFilesDir(null); if (externalFile != null) baseDir = externalFile.getAbsolutePath(); if (baseDir == null) baseDir = RuntimeArgs.androidApplication.getFilesDir().getAbsolutePath(); storageLocation = baseDir + File.separatorChar + "storage" + File.separatorChar; LogUtil.w(TAG, "bundle location:" + storageLocation); //init storageLocation end checkStatus(application); } catch (Exception e) { e.printStackTrace(); } finally { LogUtil.w(TAG, "======================================================================"); LogUtil.w(TAG, "******** mdynamiclib init end [: " + (System.currentTimeMillis() - startTime) + "ms]"); LogUtil.w(TAG, "======================================================================"); } } private void checkStatus(final Application application) { LogUtil.e(TAG, "checkStatus: start :check is need reCopyInstall bundles"); LogUtil.e(TAG, ">>>> final long startTime = System.currentTimeMillis(); boolean isLocalBundlesValid = isLocalBundlesValid(); if (!TextUtils.equals(getCurrentBundleKey(application), getLastBundleKey(application)) || !isLocalBundlesValid) { LogUtil.d(TAG, "checkStatus: currentBundleKey != lastBundleKey , clean local and reCopyInstall bundles, isLocalBundlesValid==" + isLocalBundlesValid); new Thread(new Runnable() { @Override public void run() { LogUtil.w(TAG, "checkStatus: start new thread to reCopyInstall bundles"); HotPatchManager.getInstance().clean(); cleanLocal(); copyBundles(application); installBundleDexs(); LogUtil.e(TAG, "checkStatus: end : : " + (System.currentTimeMillis() - startTime) + "ms"); LogUtil.e(TAG, "<<<< } }).start(); } else { LogUtil.d(TAG, "checkStatus: currentBundleKey == lastBundleKey , restore from local hotfix and bundles, isLocalBundlesValid==true"); restoreFromProfile(); HotPatchManager.getInstance().installHotFixDexs(); installBundleDexs(); LogUtil.e(TAG, "checkStatus: end : : " + (System.currentTimeMillis() - startTime) + "ms"); LogUtil.e(TAG, "<<<< } } private boolean isLocalBundlesValid() { //local cleanLocal copyToLocal //meta //bundles md5md5bundle.zipbundle.dex, return isLocalMetaFileExists(); } public void cleanLocal() { LogUtil.w(TAG, "cleanLocal start:" + storageLocation); File file = new File(storageLocation); if (file.exists()) FileUtil.deleteDirectory(file); file.mkdirs(); saveToProfile(); LogUtil.w(TAG, "cleanLocal end"); } public void installBundleDexs() { LogUtil.w(TAG, "installBundleDexsstart"); long startTime = System.currentTimeMillis(); for (Bundle bundle : getBundles()) { try { bundle.installBundleDexs(); } catch (Exception e) { LogUtil.e(TAG, "installBundleDex exception", e); } } try { ResourcesHook.newResourcesHook(RuntimeArgs.androidApplication, RuntimeArgs.delegateResources); } catch (Exception e) { LogUtil.e(TAG, "DelegateResources.newResourcesHook exception", e); } LogUtil.w(TAG, "installBundleDexsend : " + String.valueOf(System.currentTimeMillis() - startTime) + "ms"); } public List<String> getBundleList(ZipFile zipFile, String prefix, String suffix) { List<String> arrayList = new ArrayList<>(); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { String name = ((ZipEntry) entries.nextElement()).getName(); if (!TextUtils.isEmpty(name) && name.startsWith(prefix) && name.endsWith(suffix)) arrayList.add(name); } return arrayList; } public void copyBundles(Application application) { LogUtil.w(TAG, "copyBundles:start:allBundles:\n" + getInstance().getBundles().toString()); long startTime = System.currentTimeMillis(); ZipFile zipFile = null; try { zipFile = new ZipFile(application.getApplicationInfo().sourceDir); List<String> bundleList = getBundleList(zipFile, BUNDLE_LIB_PATH, BUNDLE_SUFFIX); if (bundleList.size() > 0) { for (String bundleItem : bundleList) { String packageNameFromEntryName = bundleItem.substring(bundleItem.indexOf(BUNDLE_LIB_PATH) + BUNDLE_LIB_PATH.length(), bundleItem.indexOf(".so")).replace("_", "."); if (!isLocalBundleExists(packageNameFromEntryName)) copyToLocal(packageNameFromEntryName, zipFile.getInputStream(zipFile.getEntry(bundleItem))); } saveBundleKey(application, getCurrentBundleKey(application)); } else { LogUtil.w(TAG, "find no bundles at " + BUNDLE_LIB_PATH); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (zipFile != null) zipFile.close(); } catch (Exception e) { e.printStackTrace(); } } LogUtil.w(TAG, "copyBundles:end:allBundles:: " + (System.currentTimeMillis() - startTime) + "ms \n" + getInstance().getBundles().toString()); } private boolean isLocalBundleExists(String packageName) { boolean isLocalBundleExists = getBundle(packageName) != null; LogUtil.d(TAG, packageName + " isLocalBundleExists == " + isLocalBundleExists); return isLocalBundleExists; } public Bundle copyToLocal(String location, InputStream inputStream) { LogUtil.d(TAG, "copyToLocal start: " + location); long startTime = System.currentTimeMillis(); Bundle bundle = null; try { bundle = getBundle(location); if (bundle != null) return bundle; long bundleID = nextBundleID; nextBundleID = 1 + bundleID; bundle = new Bundle(new File(storageLocation, String.valueOf(bundleID)), location, bundleID, inputStream); bundles.put(bundle.getLocation(), bundle); saveToMetadata(); } catch (Exception e) { LogUtil.e(TAG, "copyToLocal failure: " + location, e); } LogUtil.d(TAG, "copyToLocal end: : " + (System.currentTimeMillis() - startTime) + "ms "); return bundle; } public void updateBundle(String location, InputStream inputStream) throws Exception { Bundle bundle = getBundle(location); if (bundle != null) { bundle.update(inputStream); return; } throw new IllegalStateException("Could not update bundle " + location + ", because could not find it"); } public void uninstallBundle(String location) throws Exception { Bundle bundle = getBundle(location); if (bundle != null) bundle.getArchive().clean(); } public List<Bundle> getBundles() { List<Bundle> arrayList = new ArrayList<>(bundles.size()); synchronized (bundles) { arrayList.addAll(bundles.values()); } return arrayList; } public Bundle getBundle(String str) { return bundles.get(str); } public Bundle getBundle(long id) { synchronized (bundles) { for (Bundle bundle : bundles.values()) if (bundle.getBundleId() == id) return bundle; return null; } } private void saveToProfile() { LogUtil.d(TAG, "saveToProfile start"); Bundle[] bundleArray = getBundles().toArray(new Bundle[bundles.size()]); for (Bundle bundle : bundleArray) bundle.updateMetadata(); saveToMetadata(); LogUtil.d(TAG, "saveToProfile end"); } private void saveToMetadata() { LogUtil.d(TAG, "saveToMetadata:start:" + storageLocation + "meta" + ", save nextBundleID==" + nextBundleID); try { DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(new File(storageLocation, "meta"))); dataOutputStream.writeLong(nextBundleID); dataOutputStream.flush(); dataOutputStream.close(); } catch (Throwable e) { LogUtil.e(TAG, "could not save meta data.", e); } LogUtil.d(TAG, "saveToMetadata:end"); } private boolean isLocalMetaFileExists() { return getLocalMetaFile().exists(); } private File getLocalMetaFile() { return new File(storageLocation, "meta"); } private int restoreFromProfile() { LogUtil.w(TAG, "restoreFromProfile start"); try { File localMetaFile = getLocalMetaFile(); if (localMetaFile.exists()) { DataInputStream dataInputStream = new DataInputStream(new FileInputStream(localMetaFile)); nextBundleID = dataInputStream.readLong(); dataInputStream.close(); File file2 = new File(storageLocation); File[] listFiles = file2.listFiles(); int i = 0; while (i < listFiles.length) { if (listFiles[i].isDirectory() && new File(listFiles[i], "meta").exists()) { try { Bundle bundle = new Bundle(listFiles[i]); bundles.put(bundle.getLocation(), bundle); LogUtil.v(TAG, "success to restore bundle: " + bundle.getLocation()); } catch (Exception e) { LogUtil.e(TAG, e.getMessage(), e.getCause()); } } i++; } LogUtil.w(TAG, "restoreFromProfile end , return 1()"); return 1; } LogUtil.w(TAG, "restoreFromProfile end , return -1(meta)"); return -1; } catch (Exception e) { LogUtil.e(TAG, "restoreFromProfile end , return 0()", e); return 0; } } public String getCurrentBundleKey(Application application) { String bundleKey = null; try { PackageInfo packageInfo = application.getPackageManager().getPackageInfo(application.getPackageName(), PackageManager.GET_CONFIGURATIONS); bundleKey = String.valueOf(packageInfo.versionCode) + "_" + packageInfo.versionName; } catch (Exception e) { e.printStackTrace(); } return bundleKey; } private static final String KEY_LAST_BUNDLE = "KEY_LAST_BUNDLE"; private static void saveBundleKey(Application application, String bundleKey) { LogUtil.w(TAG, "saveBundleKey:" + bundleKey); PreferencesUtil.getInstance(application).putString(KEY_LAST_BUNDLE, bundleKey); } public String getLastBundleKey(Application application) { return PreferencesUtil.getInstance(application).getString(KEY_LAST_BUNDLE); } }
package uk.ac.cam.ch.wwmm.opsin; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import static uk.ac.cam.ch.wwmm.opsin.OpsinTools.*; import static uk.ac.cam.ch.wwmm.opsin.XmlDeclarations.*; import nu.xom.Element; import nu.xom.Elements; /** * Assembles fused rings named using fusion nomenclature * @author dl387 * */ class FusedRingBuilder { private final BuildState state; private final List<Element> groupsInFusedRing; private final Element lastGroup; private final Fragment parentRing; private final Map<Integer,Fragment> fragmentInScopeForEachFusionLevel = new HashMap<Integer,Fragment>(); private Map<Atom, Atom> atomsToRemoveToReplacementAtom = new HashMap<Atom, Atom>(); private FusedRingBuilder(BuildState state, List<Element> groupsInFusedRing) { this.state = state; this.groupsInFusedRing = groupsInFusedRing; lastGroup = groupsInFusedRing.get(groupsInFusedRing.size()-1); parentRing = state.xmlFragmentMap.get(lastGroup); fragmentInScopeForEachFusionLevel.put(0, parentRing); } /** * Master method for processing fused rings. Fuses groups together * @param state: contains the current id and fragment manager * @param subOrRoot Element (substituent or root) * @throws StructureBuildingException */ static void processFusedRings(BuildState state, Element subOrRoot) throws StructureBuildingException { List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); if (groups.size() < 2){ return;//nothing to fuse } List<Element> groupsInFusedRing =new ArrayList<Element>(); for (int i = groups.size()-1; i >=0; i--) {//group groups into fused rings Element group =groups.get(i); groupsInFusedRing.add(0, group); if (i!=0){ Element startingEl = group; if ((group.getValue().equals("benz") || group.getValue().equals("benzo")) && FUSIONRING_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ Element beforeBenzo = (Element) XOMTools.getPreviousSibling(group); if (beforeBenzo !=null && beforeBenzo.getLocalName().equals(LOCANT_EL)){ startingEl = beforeBenzo; } } Element possibleGroup = XOMTools.getPreviousSiblingIgnoringCertainElements(startingEl, new String[]{MULTIPLIER_EL, FUSION_EL}); if (!groups.get(i-1).equals(possibleGroup)){//end of fused ring system if (groupsInFusedRing.size()>=2){ //This will be invoked in cases where there are multiple fused ring systems in the same subOrRoot such as some spiro systems new FusedRingBuilder(state, groupsInFusedRing).buildFusedRing(); } groupsInFusedRing.clear(); } } } if (groupsInFusedRing.size()>=2){ new FusedRingBuilder(state, groupsInFusedRing).buildFusedRing(); } } /** * Combines the groups given in the {@link FusedRingBuilder} constructor to destructively create the fused ring system * This fused ring is then numbered * @throws StructureBuildingException */ void buildFusedRing() throws StructureBuildingException{ /* * Apply any nonstandard ring numbering, sorts atomOrder by locant * Aromatises appropriate cycloalkane rings, Rejects groups with acyclic atoms */ processRingNumberingAndIrregularities(); processBenzoFusions();//FR-2.2.8 e.g. in 2H-[1,3]benzodioxino[6',5',4':10,5,6]anthra[2,3-b]azepine benzodioxino is one component List<Element> nameComponents = formNameComponentList(); nameComponents.remove(lastGroup); List<Fragment> componentFragments = new ArrayList<Fragment>();//all the ring fragments (other than the parentRing). These will later be merged into the parentRing List<Fragment> parentFragments = new ArrayList<Fragment>(); parentFragments.add(parentRing); int numberOfParents = 1; Element possibleMultiplier = (Element) XOMTools.getPreviousSibling(lastGroup); if (nameComponents.size()>0 && possibleMultiplier !=null && possibleMultiplier.getLocalName().equals(MULTIPLIER_EL)){ numberOfParents = Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR)); possibleMultiplier.detach(); for (int j = 1; j < numberOfParents; j++) { Fragment copyOfParentRing =state.fragManager.copyFragment(parentRing); parentFragments.add(copyOfParentRing); componentFragments.add(copyOfParentRing); } } /*The indice from nameComponents to use next. Work from right to left i.e. starts at nameComponents.size()-1*/ int ncIndice = processMultiParentSystem(parentFragments, nameComponents, componentFragments);//handle multiparent systems /* * The number of primes on the component to be connected. * This is initially 0 indicating fusion of unprimed locants with the letter locants of the parentRing * Subsequently it will switch to 1 indicating fusion of a second order component (primed locants) with a * first order component (unprimed locants) * Next would be double primed fusing to single primed locants etc. * */ int fusionLevel = (nameComponents.size()-1 -ncIndice)/2; for (; ncIndice>=0; ncIndice Element fusion = null; if (nameComponents.get(ncIndice).getLocalName().equals(FUSION_EL)){ fusion = nameComponents.get(ncIndice } if (ncIndice <0 || !nameComponents.get(ncIndice).getLocalName().equals(GROUP_EL)){ throw new StructureBuildingException("Group not found where group expected. This is probably a bug"); } Fragment nextComponent = state.xmlFragmentMap.get(nameComponents.get(ncIndice)); int multiplier = 1; Element possibleMultiplierEl = (Element) XOMTools.getPreviousSibling(nameComponents.get(ncIndice));//e.g. the di of difuro if (possibleMultiplierEl != null && possibleMultiplierEl.getLocalName().equals(MULTIPLIER_EL)){ multiplier = Integer.parseInt(possibleMultiplierEl.getAttributeValue(VALUE_ATR)); } String[] fusionDescriptors =null; if (fusion !=null){ String fusionDescriptorString = fusion.getValue().toLowerCase().substring(1, fusion.getValue().length()-1); if (multiplier ==1){ fusionDescriptors = new String[]{fusionDescriptorString}; } else{ if (MATCH_SEMICOLON.split(fusionDescriptorString).length >1){ fusionDescriptors = MATCH_SEMICOLON.split(fusionDescriptorString); } else if (MATCH_COLON.split(fusionDescriptorString).length >1){ fusionDescriptors = MATCH_COLON.split(fusionDescriptorString); } else if (MATCH_COMMA.split(fusionDescriptorString).length >1){ fusionDescriptors = MATCH_COMMA.split(fusionDescriptorString); } else{//multiplier does not appear to mean multiplied component. Could be indicating multiplication of the whole fused ring system if (ncIndice!=0){ throw new StructureBuildingException("Unexpected multiplier: " + possibleMultiplierEl.getValue() +" or incorrect fusion descriptor: " + fusionDescriptorString); } multiplier =1; fusionDescriptors = new String[]{fusionDescriptorString}; } } } if (multiplier >1){ possibleMultiplierEl.detach(); } Fragment[] fusionComponents = new Fragment[multiplier]; for (int j = 0; j < multiplier; j++) { if (j>0){ fusionComponents[j] = state.fragManager.copyAndRelabelFragment(nextComponent, j); } else{ fusionComponents[j] = nextComponent; } } for (int j = 0; j < multiplier; j++) { Fragment component = fusionComponents[j]; componentFragments.add(component); if (fusion !=null){ if (MATCH_COLON.split(fusionDescriptors[j]).length==1){//A fusion bracket without a colon is used when applying to the parent component (except in a special case where locants are ommitted) //check for case of omitted locant from a higher order fusion bracket e.g. cyclopenta[4,5]pyrrolo[2,3-c]pyridine if (MATCH_DASH.split(fusionDescriptors[j]).length==1 && MATCH_COMMA.split(fusionDescriptors[j]).length >1 && FragmentTools.allAtomsInRingAreIdentical(component)){ int numberOfPrimes = -j + StringTools.countTerminalPrimes(MATCH_COMMA.split(fusionDescriptors[j])[0]); //note that this is the number of primes on the parent ring. So would expect the child ring and hence the fusionLevel to be 1 higher if (numberOfPrimes + 1 != fusionLevel){ if (numberOfPrimes + 2 == fusionLevel){//ring could be in previous fusion level e.g. the benzo in benzo[10,11]phenanthro[2',3',4',5',6':4,5,6,7]chryseno[1,2,3-bc]coronene fusionLevel } else{ throw new StructureBuildingException("Incorrect number of primes in fusion bracket: " +fusionDescriptors[j]); } } relabelAccordingToFusionLevel(component, fusionLevel); List<String> numericalLocantsOfParent = Arrays.asList(MATCH_COMMA.split(fusionDescriptors[j])); List<String> numericalLocantsOfChild = findPossibleNumericalLocants(component, determineAtomsToFuse(fragmentInScopeForEachFusionLevel.get(fusionLevel), numericalLocantsOfParent, null).size()-1); processHigherOrderFusionDescriptors(component, fragmentInScopeForEachFusionLevel.get(fusionLevel), numericalLocantsOfChild, numericalLocantsOfParent); } else{ fusionLevel = 0; relabelAccordingToFusionLevel(component, fusionLevel); String fusionDescriptor = fusionDescriptors[j]; String[] fusionArray = determineNumericalAndLetterComponents(fusionDescriptor); int numberOfPrimes =0; if (!fusionArray[1].equals("")){ numberOfPrimes =StringTools.countTerminalPrimes(fusionArray[1]); if (fusionArray[0].equals("")){ fusionDescriptor = fusionArray[1].replaceAll("'", ""); } else{ fusionDescriptor = fusionArray[0]+ "-" +fusionArray[1].replaceAll("'", ""); } if (numberOfPrimes >= parentFragments.size()){ throw new StructureBuildingException("Unexpected prime in fusion descriptor"); } } performSimpleFusion(fusionDescriptor, component, parentFragments.get(numberOfPrimes));//e.g. pyrano[3,2-b]imidazo[4,5-e]pyridine where both are level 0 fusions } } else{ //determine number of primes in fusor and hence determine fusion level int numberOfPrimes = -j + StringTools.countTerminalPrimes(MATCH_COMMA.split(fusionDescriptors[j])[0]); if (numberOfPrimes != fusionLevel){ if (fusionLevel == numberOfPrimes +1){ fusionLevel } else{ throw new StructureBuildingException("Incorrect number of primes in fusion bracket: " +fusionDescriptors[j]); } } relabelAccordingToFusionLevel(component, fusionLevel); performHigherOrderFusion(fusionDescriptors[j], component, fragmentInScopeForEachFusionLevel.get(fusionLevel)); } } else{ relabelAccordingToFusionLevel(component, fusionLevel); performSimpleFusion(null, component, fragmentInScopeForEachFusionLevel.get(fusionLevel)); } } fusionLevel++; if (multiplier ==1){//multiplied components may not be substituted onto fragmentInScopeForEachFusionLevel.put(fusionLevel, fusionComponents[0]); } } for (Fragment ring : componentFragments) { state.fragManager.incorporateFragment(ring, parentRing); } removeMergedAtoms(); FusedRingNumberer.numberFusedRing(parentRing);//numbers the fused ring; StringBuilder fusedRingName = new StringBuilder(); for (Element element : nameComponents) { fusedRingName.append(element.getValue()); } fusedRingName.append(lastGroup.getValue()); Element fusedRingEl =lastGroup;//reuse this element to save having to remap suffixes... fusedRingEl.getAttribute(VALUE_ATR).setValue(fusedRingName.toString()); fusedRingEl.removeAttribute(fusedRingEl.getAttribute(VALTYPE_ATR)); fusedRingEl.getAttribute(TYPE_ATR).setValue(RING_TYPE_VAL); fusedRingEl.getAttribute(SUBTYPE_ATR).setValue(FUSEDRING_SUBTYPE_VAL); XOMTools.setTextChild(fusedRingEl, fusedRingName.toString()); for (Element element : nameComponents) { element.detach(); } } private void removeMergedAtoms() { for (Atom a : atomsToRemoveToReplacementAtom.keySet()) { state.fragManager.removeAtomAndAssociatedBonds(a); } atomsToRemoveToReplacementAtom.clear(); } /** * Forms a list a list of all group and fusion elements between the first and last group in the fused ring * @return */ private List<Element> formNameComponentList() { List<Element> nameComponents = new ArrayList<Element>(); Element currentEl = groupsInFusedRing.get(0); while(currentEl != lastGroup){ if (currentEl.getLocalName().equals(GROUP_EL) || currentEl.getLocalName().equals(FUSION_EL)){ nameComponents.add(currentEl); } currentEl = (Element) XOMTools.getNextSibling(currentEl); } return nameComponents; } private void processRingNumberingAndIrregularities() throws StructureBuildingException { for (Element group : groupsInFusedRing) { Fragment ring = state.xmlFragmentMap.get(group); if (ALKANESTEM_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ aromatiseCyclicAlkane(group); } processPartiallyUnsaturatedHWSystems(group, ring); if (group == lastGroup) { //perform a quick check that every atom in this group is infact cyclic. Fusion components are enumerated and hence all guaranteed to be purely cyclic List<Atom> atomList = ring.getAtomList(); for (Atom atom : atomList) { if (!atom.getAtomIsInACycle()) { throw new StructureBuildingException("Inappropriate group used in fusion nomenclature. Only groups composed entirely of atoms in cycles may be used. i.e. not: " + group.getValue()); } } if (group.getAttribute(FUSEDRINGNUMBERING_ATR) != null) { String[] standardNumbering = MATCH_SLASH.split(group.getAttributeValue(FUSEDRINGNUMBERING_ATR), -1); for (int j = 0; j < standardNumbering.length; j++) { atomList.get(j).replaceLocants(standardNumbering[j]); } } else { ring.sortAtomListByLocant();//for those where the order the locants are in is sensible } } for (Atom atom : atomList) { atom.clearLocants();//the parentRing does not have locants, letters are used to indicate the edges } } else if (group.getAttribute(FUSEDRINGNUMBERING_ATR) == null) { ring.sortAtomListByLocant();//for those where the order the locants are in is sensible } } } /** * Interprets the unlocanted unsaturator after a partially unsaturated HW Rings as indication of spare valency and detaches it * This is necessary as this unsaturator can only refer to the HW ring and for names like 2-Benzoxazolinone to avoid confusion as to what the 2 refers to. * @param group * @param ring * @throws StructureBuildingException */ private void processPartiallyUnsaturatedHWSystems(Element group, Fragment ring) throws StructureBuildingException { if (HANTZSCHWIDMAN_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR)) && group.getAttribute(ADDBOND_ATR)!=null){ List<Element> unsaturators = XOMTools.getNextAdjacentSiblingsOfType(group, UNSATURATOR_EL); if (unsaturators.size()>0){ Element unsaturator = unsaturators.get(0); if (unsaturator.getAttribute(LOCANT_ATR)==null && unsaturator.getAttributeValue(VALUE_ATR).equals("2")){ unsaturator.detach(); Bond bondToUnsaturate = StructureBuildingMethods.findBondToUnSaturate(ring.getAtomList(), 2, true); bondToUnsaturate.getFromAtom().setSpareValency(true); bondToUnsaturate.getToAtom().setSpareValency(true); } } } } /** * Given a cyclicAlkaneGroup determines whether or not it should be aromatised. Unlocanted ene will be detached if it is an aromatisation hint * No unsaturators -->aromatise * Just ane -->don't * More than 1 ene or locants on ene -->don't * yne --> don't * @param cyclicAlkaneGroup */ private void aromatiseCyclicAlkane(Element cyclicAlkaneGroup) { Element next = (Element) XOMTools.getNextSibling(cyclicAlkaneGroup); List<Element> unsaturators = new ArrayList<Element>(); while (next!=null && next.getLocalName().equals(UNSATURATOR_EL)){ unsaturators.add(next); next = (Element) XOMTools.getNextSibling(next); } boolean conjugate =true; if (unsaturators.size()==1){ int value = Integer.parseInt(unsaturators.get(0).getAttributeValue(VALUE_ATR)); if (value !=2){ conjugate =false; } else if (unsaturators.get(0).getAttribute(LOCANT_ATR)!=null){ conjugate =false; } } else if (unsaturators.size()==2){ int value1 = Integer.parseInt(unsaturators.get(0).getAttributeValue(VALUE_ATR)); if (value1 !=1){ conjugate =false; } else{ int value2 = Integer.parseInt(unsaturators.get(1).getAttributeValue(VALUE_ATR)); if (value2 !=2 || unsaturators.get(1).getAttribute(LOCANT_ATR)!=null){ conjugate =false; } } } else if (unsaturators.size() >2){ conjugate =false; } if (conjugate){ for (Element unsaturator : unsaturators) { unsaturator.detach(); } List<Atom> atomList =state.xmlFragmentMap.get(cyclicAlkaneGroup).getAtomList(); for (Atom atom : atomList) { atom.setSpareValency(true); } } } private int processMultiParentSystem(List<Fragment> parentFragments, List<Element> nameComponents, List<Fragment> componentFragments) throws StructureBuildingException { int i = nameComponents.size()-1; int fusionLevel =0; if (i>=0 && parentFragments.size()>1){ List<Fragment> previousFusionLevelFragments = parentFragments; for (; i>=0; i if (previousFusionLevelFragments.size()==1){//completed multi parent system fragmentInScopeForEachFusionLevel.put(fusionLevel, previousFusionLevelFragments.get(0)); break; } Element fusion = null; if (nameComponents.get(i).getLocalName().equals(FUSION_EL)){ fusion = nameComponents.get(i } else{ throw new StructureBuildingException("Fusion bracket not found where fusion bracket expected"); } if (i <0 || !nameComponents.get(i).getLocalName().equals(GROUP_EL)){ throw new StructureBuildingException("Group not found where group expected. This is probably a bug"); } Fragment nextComponent = state.xmlFragmentMap.get(nameComponents.get(i)); relabelAccordingToFusionLevel(nextComponent, fusionLevel); int multiplier = 1; Element possibleMultiplierEl = (Element) XOMTools.getPreviousSibling(nameComponents.get(i)); if (possibleMultiplierEl != null && possibleMultiplierEl.getLocalName().equals(MULTIPLIER_EL)){ multiplier = Integer.parseInt(possibleMultiplierEl.getAttributeValue(VALUE_ATR)); possibleMultiplierEl.detach(); } List<Fragment> fusionComponents = new ArrayList<Fragment>(); for (int j = 0; j < multiplier; j++) { if (j>0){ fusionComponents.add(state.fragManager.copyAndRelabelFragment(nextComponent, j)); } else{ fusionComponents.add(nextComponent); } } fusionLevel+=multiplier; if (multiplier>1 && multiplier != previousFusionLevelFragments.size()){ throw new StructureBuildingException("Mismatch between number of components and number of parents in fused ring system"); } String fusionDescriptorString = fusion.getValue().toLowerCase().substring(1, fusion.getValue().length()-1); String[] fusionDescriptors =null; if (MATCH_SEMICOLON.split(fusionDescriptorString).length >1){ fusionDescriptors = MATCH_SEMICOLON.split(fusionDescriptorString); } else if (MATCH_COLON.split(fusionDescriptorString).length >1){ fusionDescriptors = MATCH_COLON.split(fusionDescriptorString); } else if (MATCH_COMMA.split(fusionDescriptorString).length >1){ fusionDescriptors = MATCH_COMMA.split(fusionDescriptorString); } else{ throw new StructureBuildingException("Invalid fusion descriptor: " + fusionDescriptorString); } if (fusionDescriptors.length != previousFusionLevelFragments.size()){ throw new StructureBuildingException("Invalid fusion descriptor: "+fusionDescriptorString +"(Number of locants disagrees with number of parents)"); } for (int j = 0; j < fusionDescriptors.length; j++) { String fusionDescriptor = fusionDescriptors[j]; Fragment component = multiplier>1 ? fusionComponents.get(j) : nextComponent; Fragment parentToUse = previousFusionLevelFragments.get(j); boolean simpleFusion = MATCH_COLON.split(fusionDescriptor).length <= 1; if (simpleFusion){ String[] fusionArray = determineNumericalAndLetterComponents(fusionDescriptor); if (fusionArray[1].length() != 0){ int numberOfPrimes =StringTools.countTerminalPrimes(fusionArray[1]); if (fusionArray[0].length() == 0){ fusionDescriptor = fusionArray[1].replaceAll("'", ""); } else{ fusionDescriptor = fusionArray[0]+ "-" +fusionArray[1].replaceAll("'", ""); } if (numberOfPrimes !=j){//check the number of primes on the letter part agree with the parent to use e.g.[4,5-bcd:1,2-c']difuran throw new StructureBuildingException("Incorrect number of primes in fusion descriptor: " + fusionDescriptor); } } performSimpleFusion(fusionDescriptor, component, parentToUse); } else{ performHigherOrderFusion(fusionDescriptor, component, parentToUse); } } previousFusionLevelFragments = fusionComponents; componentFragments.addAll(fusionComponents); } if (previousFusionLevelFragments.size()!=1){ throw new StructureBuildingException("Invalid fused ring system. Incomplete multiparent system"); } } return i; } /** * Splits a first order fusion component into it's numerical and letter parts * Either one of these can be the blank string as they may have been omitted * The first entry in the array is the numbers and the second the letters * @param fusionDescriptor * @return */ private static String[] determineNumericalAndLetterComponents(String fusionDescriptor) { String[] fusionArray = MATCH_DASH.split(fusionDescriptor); if (fusionArray.length ==2){ return fusionArray; } else{ String[] components = new String[2]; if (fusionArray[0].contains(",")){//the digit section components[0]=fusionArray[0]; components[1]=""; } else{ components[0]=""; components[1]=fusionArray[0]; } return components; } } /** * Searches groups for benz(o) components and fuses them in accordance with * FR-2.2.8 Heterobicyclic components with a benzene ring * @throws StructureBuildingException */ private void processBenzoFusions() throws StructureBuildingException { for(int i= groupsInFusedRing.size() -2;i >=0; i if (groupsInFusedRing.get(i).getValue().equals("benz") || groupsInFusedRing.get(i).getValue().equals("benzo")){ Element possibleFusionbracket = (Element) XOMTools.getNextSibling(groupsInFusedRing.get(i)); if (!possibleFusionbracket.getLocalName().equals(FUSION_EL)){ Element possibleMultiplier = (Element) XOMTools.getPreviousSibling(groupsInFusedRing.get(i)); if (possibleMultiplier==null || !possibleMultiplier.getLocalName().equals(MULTIPLIER_EL)|| possibleMultiplier.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL)){ //e.g. 2-benzofuran. Fused rings of this type are a special case treated as being a single component //and have a special convention for indicating the position of heteroatoms benzoSpecificFusion(groupsInFusedRing.get(i), groupsInFusedRing.get(i+1)); groupsInFusedRing.get(i).detach(); groupsInFusedRing.remove(i); } } } } } /** * Modifies nextComponent's locants according to the fusionLevel. * @param component * @param fusionLevel */ private void relabelAccordingToFusionLevel(Fragment component, int fusionLevel) { if (fusionLevel > 0){ FragmentTools.relabelNumericLocants(component.getAtomList(), StringTools.multiplyString("'", fusionLevel)); } } /** * Handles fusion between components where the fusion descriptor is of the form: * comma separated locants dash letters * e.g imidazo[4,5-d]pyridine * The fusionDescriptor may be given as null or the letter/numerical part omitted. * Sensible defaults will be found instead * @param fusionDescriptor * @param childRing * @param parentRing * @throws StructureBuildingException */ private void performSimpleFusion(String fusionDescriptor, Fragment childRing, Fragment parentRing) throws StructureBuildingException { List<String> numericalLocantsOfChild = null; List<String> letterLocantsOfParent = null; if (fusionDescriptor != null){ String[] fusionArray = MATCH_DASH.split(fusionDescriptor); if (fusionArray.length ==2){ numericalLocantsOfChild = Arrays.asList(MATCH_COMMA.split(fusionArray[0])); char[] tempLetterLocantsOfParent = fusionArray[1].toCharArray(); letterLocantsOfParent = new ArrayList<String>(); for (char letterLocantOfParent : tempLetterLocantsOfParent) { letterLocantsOfParent.add(String.valueOf(letterLocantOfParent)); } } else{ if (fusionArray[0].contains(",")){//only has digits String[] numericalLocantsOfChildTemp = MATCH_COMMA.split(fusionArray[0]); numericalLocantsOfChild = Arrays.asList(numericalLocantsOfChildTemp); } else{//only has letters char[] tempLetterLocantsOfParentCharArray = fusionArray[0].toCharArray(); letterLocantsOfParent = new ArrayList<String>(); for (char letterLocantOfParentCharArray : tempLetterLocantsOfParentCharArray) { letterLocantsOfParent.add(String.valueOf(letterLocantOfParentCharArray)); } } } } int edgeLength =1; if (numericalLocantsOfChild != null){ if (numericalLocantsOfChild.size() <=1){ throw new StructureBuildingException("At least two numerical locants must be provided to perform fusion!"); } edgeLength = numericalLocantsOfChild.size()-1; } else if (letterLocantsOfParent != null){ edgeLength = letterLocantsOfParent.size(); } if (numericalLocantsOfChild == null){ numericalLocantsOfChild = findPossibleNumericalLocants(childRing, edgeLength); } if (letterLocantsOfParent == null){ letterLocantsOfParent = findPossibleLetterLocants(parentRing, edgeLength); } if (numericalLocantsOfChild == null || letterLocantsOfParent ==null){ throw new StructureBuildingException("Unable to find bond to form fused ring system. Some information for forming fused ring system was only supplyed implicitly"); } processFirstOrderFusionDescriptors(childRing, parentRing, numericalLocantsOfChild, letterLocantsOfParent);//fuse the rings } /** * Takes a ring an returns and array with one letter corresponding to a side/s * that contains two adjacent non bridgehead carbons * The number of sides is specified by edgeLength * @param ring * @param edgeLength The number of bonds to be fused along * @return */ private static List<String> findPossibleLetterLocants(Fragment ring, int edgeLength) { List<Atom> atomlist = ring.getAtomList(); List<String> letterLocantsOfParent = null; List<Atom> carbonAtoms = new ArrayList<Atom>(); atomlist.add(0, atomlist.get(atomlist.size()-1));//this atomList is a copy so we can safely do this for (int i =atomlist.size() -1; i >=0; i--) {//iterate backwards in list to use highest locanted edge in preference. //this retains what is currently locant 1 on the parent ring as locant 1 if the first two atoms found match Atom atom = atomlist.get(i); if (atom.getElement().equals("C")){ if (atom.getIncomingValency()>=3){ carbonAtoms.clear(); continue;//don't want bridgehead carbons } carbonAtoms.add(atom); if (carbonAtoms.size() ==edgeLength +1 ){//as many in a row as edgelength ->use this side letterLocantsOfParent = new ArrayList<String>(); Collections.reverse(carbonAtoms); atomlist.remove(0); for (int j = 0; j < edgeLength; j++) { letterLocantsOfParent.add(String.valueOf((char)(97 +atomlist.indexOf(carbonAtoms.get(j)))));//97 is ascii for a } break; } } else{ carbonAtoms.clear(); } } return letterLocantsOfParent; } /** * Takes a ring and returns an array of numbers corresponding to a side/s * that contains two adjacent non bridgehead carbons * The number of sides is specified by edgeLength * @param ring * @param edgeLength The number of bonds to be fused along * @return */ private static List<String> findPossibleNumericalLocants(Fragment ring, int edgeLength) { List<Atom> atomlist = ring.getAtomList(); List<String> numericalLocantsOfChild = null; List<String> carbonLocants = new ArrayList<String>(); atomlist.add(atomlist.get(0));//this atomList is a copy so we can safely do this for (Atom atom : atomlist) { if (atom.getElement().equals("C")){ if (atom.getIncomingValency()>=3){ carbonLocants.clear(); continue;//don't want bridgehead carbons } carbonLocants.add(atom.getFirstLocant()); if (carbonLocants.size()==edgeLength +1){//as many in a row as edgelength ->use this side numericalLocantsOfChild = new ArrayList<String>(); for (String locant : carbonLocants) { numericalLocantsOfChild.add(locant); } break; } } else{ carbonLocants.clear(); } } return numericalLocantsOfChild; } /** * Performs a single ring fusion using the values in numericalLocantsOfChild/letterLocantsOfParent * @param childRing * @param parentRing * @param numericalLocantsOfChild * @param letterLocantsOfParent * @throws StructureBuildingException */ private void processFirstOrderFusionDescriptors(Fragment childRing, Fragment parentRing, List<String> numericalLocantsOfChild, List<String> letterLocantsOfParent) throws StructureBuildingException { List<Atom> childAtoms = determineAtomsToFuse(childRing, numericalLocantsOfChild, letterLocantsOfParent.size() +1); if (childAtoms ==null){ throw new StructureBuildingException("Malformed fusion bracket!"); } List<Atom> parentAtoms = new ArrayList<Atom>(); List<Atom> parentAtomList = parentRing.getAtomList(); //find the indice of the last atom on the surface of the ring. This obviously connects to the first atom. The objective is to exclude any interior atoms. List<Atom> neighbours = parentAtomList.get(0).getAtomNeighbours(); int indice = Integer.MAX_VALUE; for (Atom atom : neighbours) { int indexOfAtom =parentAtomList.indexOf(atom); if (indexOfAtom ==1){//not the next atom continue; } else if (indexOfAtom ==-1){//not in parentRing continue; } if (parentAtomList.indexOf(atom)< indice){ indice = indexOfAtom; } } CyclicAtomList cyclicListAtomsOnSurfaceOfParent = new CyclicAtomList(parentAtomList.subList(0, indice +1), (int)letterLocantsOfParent.get(0).charAt(0) -97);//convert from lower case character through ascii to 0-23 parentAtoms.add(cyclicListAtomsOnSurfaceOfParent.getCurrent()); for (int i = 0; i < letterLocantsOfParent.size(); i++) { parentAtoms.add(cyclicListAtomsOnSurfaceOfParent.getNext()); } fuseRings(childAtoms, parentAtoms); } /** * Handles fusion between components where the fusion descriptor is of the form: * comma separated locants colon comma separated locants * e.g pyrido[1'',2'':1',2']imidazo * @param fusionDescriptor * @param nextComponent * @param fusedRing * @throws StructureBuildingException */ private void performHigherOrderFusion(String fusionDescriptor, Fragment nextComponent, Fragment fusedRing) throws StructureBuildingException { List<String> numericalLocantsOfChild = null; List<String> numericalLocantsOfParent = null; String[] fusionArray = MATCH_COLON.split(fusionDescriptor); if (fusionArray.length ==2){ numericalLocantsOfChild = Arrays.asList(MATCH_COMMA.split(fusionArray[0])); numericalLocantsOfParent = Arrays.asList(MATCH_COMMA.split(fusionArray[1])); } else{ throw new StructureBuildingException("Malformed fusion bracket: This is an OPSIN bug, check regexTokens.xml"); } processHigherOrderFusionDescriptors(nextComponent, fusedRing, numericalLocantsOfChild, numericalLocantsOfParent);//fuse the rings } /** * Performs a single ring fusion using the values in numericalLocantsOfChild/numericalLocantsOfParent * @param childRing * @param parentRing * @param numericalLocantsOfChild * @param numericalLocantsOfParent * @throws StructureBuildingException */ private void processHigherOrderFusionDescriptors(Fragment childRing, Fragment parentRing, List<String> numericalLocantsOfChild, List<String> numericalLocantsOfParent) throws StructureBuildingException { List<Atom> childAtoms =determineAtomsToFuse(childRing, numericalLocantsOfChild, null); if (childAtoms ==null){ throw new StructureBuildingException("Malformed fusion bracket!"); } List<Atom> parentAtoms = determineAtomsToFuse(parentRing, numericalLocantsOfParent, childAtoms.size()); if (parentAtoms ==null){ throw new StructureBuildingException("Malformed fusion bracket!"); } fuseRings(childAtoms, parentAtoms); } /** * Determines which atoms on a ring should be used for fusion given a set of numerical locants. * If from the other ring involved in the fusion it is known how many atoms are expected to be found this should be provided * If this is not known it should be set to null and the smallest number of fusion atoms will be returned. * @param ring * @param numericalLocantsOnRing * @param expectedNumberOfAtomsToBeUsedForFusion * @return * @throws StructureBuildingException */ private static List<Atom> determineAtomsToFuse(Fragment ring, List<String> numericalLocantsOnRing, Integer expectedNumberOfAtomsToBeUsedForFusion) throws StructureBuildingException { List<Atom> parentAtomList = ring.getAtomList(); int indexfirst = parentAtomList.indexOf(ring.getAtomByLocantOrThrow(numericalLocantsOnRing.get(0))); int indexfinal = parentAtomList.indexOf(ring.getAtomByLocantOrThrow(numericalLocantsOnRing.get(numericalLocantsOnRing.size()-1))); CyclicAtomList cyclicRingAtomList = new CyclicAtomList(parentAtomList, indexfirst); List<Atom> fusionAtoms = null; List<Atom> potentialFusionAtomsAscending = new ArrayList<Atom>(); potentialFusionAtomsAscending.add(cyclicRingAtomList.getCurrent()); while (cyclicRingAtomList.getIndice() != indexfinal){//assume numbers are ascending potentialFusionAtomsAscending.add(cyclicRingAtomList.getNext()); } if (expectedNumberOfAtomsToBeUsedForFusion ==null ||expectedNumberOfAtomsToBeUsedForFusion == potentialFusionAtomsAscending.size()){ boolean notInPotentialParentAtoms =false; for (int i =1; i < numericalLocantsOnRing.size()-1 ; i ++){ if (!potentialFusionAtomsAscending.contains(ring.getAtomByLocantOrThrow(numericalLocantsOnRing.get(i)))){ notInPotentialParentAtoms =true; } } if (!notInPotentialParentAtoms){ fusionAtoms = potentialFusionAtomsAscending; } } if (fusionAtoms ==null || expectedNumberOfAtomsToBeUsedForFusion ==null){//that didn't work, so try assuming the numbers are descending cyclicRingAtomList.setIndice(indexfirst); List<Atom> potentialFusionAtomsDescending = new ArrayList<Atom>(); potentialFusionAtomsDescending.add(cyclicRingAtomList.getCurrent()); while (cyclicRingAtomList.getIndice() != indexfinal){//assume numbers are descending potentialFusionAtomsDescending.add(cyclicRingAtomList.getPrevious()); } if (expectedNumberOfAtomsToBeUsedForFusion ==null || expectedNumberOfAtomsToBeUsedForFusion == potentialFusionAtomsDescending.size()){ boolean notInPotentialParentAtoms =false; for (int i =1; i < numericalLocantsOnRing.size()-1 ; i ++){ if (!potentialFusionAtomsDescending.contains(ring.getAtomByLocantOrThrow(numericalLocantsOnRing.get(i)))){ notInPotentialParentAtoms =true; } } if (!notInPotentialParentAtoms){ if (fusionAtoms!=null && expectedNumberOfAtomsToBeUsedForFusion ==null){ //prefer less fusion atoms if (potentialFusionAtomsDescending.size()< fusionAtoms.size()){ fusionAtoms = potentialFusionAtomsDescending; } } else{ fusionAtoms = potentialFusionAtomsDescending; } } } } return fusionAtoms; } /** * Creates the bonds required to fuse two rings together. * The child atoms are recorded as atoms that should be removed later * @param childAtoms * @param parentAtoms * @throws StructureBuildingException */ private void fuseRings(List<Atom> childAtoms, List<Atom> parentAtoms) throws StructureBuildingException { if (parentAtoms.size()!=childAtoms.size()){ throw new StructureBuildingException("Problem with fusion descriptors: Parent atoms specified: " + parentAtoms.size() +" Child atoms specified: " + childAtoms.size() + " These should have been identical!"); } //replace parent atoms if the atom has already been used in fusion with the original atom //This will occur if fusion has resulted in something resembling a spiro centre e.g. cyclopenta[1,2-b:5,1-b']bis[1,4]oxathiine for (int i = parentAtoms.size() -1; i >=0; i if (atomsToRemoveToReplacementAtom.get(parentAtoms.get(i))!=null){ parentAtoms.set(i, atomsToRemoveToReplacementAtom.get(parentAtoms.get(i))); } if (atomsToRemoveToReplacementAtom.get(childAtoms.get(i))!=null){ childAtoms.set(i, atomsToRemoveToReplacementAtom.get(childAtoms.get(i))); } } //sync spareValency and check that element type matches for (int i = 0; i < childAtoms.size(); i++) { Atom parentAtom = parentAtoms.get(i); Atom childAtom = childAtoms.get(i); if (childAtom.hasSpareValency()){ parentAtom.setSpareValency(true); } if (!parentAtom.getElement().equals(childAtom.getElement())){ throw new StructureBuildingException("Invalid fusion descriptor: Heteroatom placement is ambigous as it is not present in both components of the fusion"); } atomsToRemoveToReplacementAtom.put(childAtom, parentAtom); } Set<Bond> fusionEdgeBonds = new HashSet<Bond>();//these bonds already exist in both the child and parent atoms for (int i = 0; i < childAtoms.size() -1; i++) { fusionEdgeBonds.add(childAtoms.get(i).getBondToAtomOrThrow(childAtoms.get(i+1))); fusionEdgeBonds.add(parentAtoms.get(i).getBondToAtomOrThrow(parentAtoms.get(i+1))); } Set<Bond> bondsToAddToParentAtoms = new HashSet<Bond>(); for (Atom childAtom : childAtoms) { for (Bond b : childAtom.getBonds()) { if (!fusionEdgeBonds.contains(b)){ bondsToAddToParentAtoms.add(b); } } } Set<Bond> bondsToAddToChildAtoms = new HashSet<Bond>(); for (Atom parentAtom : parentAtoms) { for (Bond b : parentAtom.getBonds()) { if (!fusionEdgeBonds.contains(b)){ bondsToAddToChildAtoms.add(b); } } } for (Bond bond : bondsToAddToParentAtoms) { Atom from = bond.getFromAtom(); int indiceInChildAtoms = childAtoms.indexOf(from); if (indiceInChildAtoms !=-1){ from = parentAtoms.get(indiceInChildAtoms); } Atom to = bond.getToAtom(); indiceInChildAtoms = childAtoms.indexOf(to); if (indiceInChildAtoms !=-1){ to = parentAtoms.get(indiceInChildAtoms); } state.fragManager.createBond(from, to, 1); } for (Bond bond : bondsToAddToChildAtoms) { Atom from = bond.getFromAtom(); int indiceInParentAtoms = parentAtoms.indexOf(from); if (indiceInParentAtoms !=-1){ from = childAtoms.get(indiceInParentAtoms); } Atom to = bond.getToAtom(); indiceInParentAtoms = parentAtoms.indexOf(to); if (indiceInParentAtoms !=-1){ to = childAtoms.get(indiceInParentAtoms); } Bond newBond = new Bond(from, to, 1); if (childAtoms.contains(from)){ from.addBond(newBond); } else{ to.addBond(newBond); } } } /** * Fuse the benzo with the subsequent ring * Uses locants in front of the benz/benzo group to assign heteroatoms on the now numbered fused ring system * @param benzoEl * @param parentEl * @throws StructureBuildingException */ private void benzoSpecificFusion(Element benzoEl, Element parentEl) throws StructureBuildingException { /* * Perform the fusion, number it and associate it with the parentEl */ Fragment benzoRing = state.xmlFragmentMap.get(benzoEl); Fragment parentRing = state.xmlFragmentMap.get(parentEl); performSimpleFusion(null, benzoRing , parentRing); state.fragManager.incorporateFragment(benzoRing, parentRing); removeMergedAtoms(); FusedRingNumberer.numberFusedRing(parentRing);//numbers the fused ring; Fragment fusedRing =parentRing; /* * Check for locants and use these to set the heteroatom positions */ Element locantEl = (Element) XOMTools.getPreviousSibling(benzoEl); if (locantEl != null && locantEl.getLocalName().equals(LOCANT_EL)) { String[] locants = MATCH_COMMA.split(locantEl.getValue()); Elements suffixes=((Element)benzoEl.getParent()).getChildElements(SUFFIX_EL); int suffixesWithoutLocants =0; for (int i = 0; i < suffixes.size(); i++) { if (suffixes.get(i).getAttribute(LOCANT_ATR)==null){ suffixesWithoutLocants++; } } if (locants.length != suffixesWithoutLocants){//In preference locants will be assigned to suffixes rather than to this nomenclature List<Atom> atomList =fusedRing.getAtomList(); LinkedList<Atom> heteroatoms =new LinkedList<Atom>(); LinkedList<String> elementOfHeteroAtom =new LinkedList<String>(); for (Atom atom : atomList) {//this iterates in the same order as the numbering system if (!atom.getElement().equals("C")){ heteroatoms.add(atom); elementOfHeteroAtom.add(atom.getElement()); } } if (locants.length == heteroatoms.size()){//as many locants as there are heteroatoms to assign for (Atom atom : heteroatoms) { atom.setElement("C"); } FragmentTools.pickUpIndicatedHydrogens(fusedRing); for (int i=0; i< heteroatoms.size(); i ++){ String elementSymbol =elementOfHeteroAtom.get(i); fusedRing.getAtomByLocantOrThrow(locants[i]).setElement(elementSymbol); } locantEl.detach(); } else if (locants.length > 1){ throw new StructureBuildingException("Unable to assign all locants to benzo-fused ring or multiplier was mising"); } } } } }
package hudson.plugins.hadoop; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.MiniDFSCluster; public class HDFSDeployerTest { private String hdfsURI; private MiniDFSCluster hdfsCluster; @Before public void setUp() throws Exception { File baseDir = new File("./target/hdfs").getAbsoluteFile(); FileUtil.fullyDelete(baseDir); Configuration conf = new Configuration(); conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath()); MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf); hdfsCluster = builder.build(); hdfsURI = "hdfs://localhost:"+ hdfsCluster.getNameNodePort() + "/"; } @Test public void testDeploy() throws Exception { File file = File.createTempFile("test", "jar"); HDFSDeployer deployer = new HDFSDeployer(); deployer.deploy(file.getAbsolutePath(), hdfsURI); Assert.assertTrue("File is not deployed to HDFS",hdfsCluster.getFileSystem().exists(new Path(file.getName()))); } }
package com.tacs.deathlist.endpoints; import com.restfb.Connection; import com.restfb.DefaultFacebookClient; import com.restfb.FacebookClient; import com.restfb.types.User; import com.tacs.deathlist.domain.Usuario; import com.tacs.deathlist.endpoints.resources.UserCreationRequest; import com.tacs.deathlist.repository.UsuariosDao; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; @Path("/users/{uid}") public class UsuarioEndpoints { @Autowired private UsuariosDao usuariosDao; /** * Recupera un Usuario. * @param uid * @return the http response */ @GET @Produces(MediaType.APPLICATION_JSON) public Response getUser(@PathParam("uid") String uid) { Usuario user = usuariosDao.getUsuario(uid); return Response.status(Response.Status.OK).entity(user).build(); } /** * Crea un nuevo Usuario. * @param uid * @return the http response */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response createUser(@PathParam("uid") String uid, UserCreationRequest request) { Usuario user = new Usuario(uid, request.getNombre()); usuariosDao.createUsuario(uid, user); return Response.status(Response.Status.CREATED).build(); } /** * Elimina un usuario. * @param uid * @return the http response */ @DELETE public Response deleteUser(@PathParam("uid") String uid) { usuariosDao.deleteUsuario(uid); return Response.status(Response.Status.OK).build(); } /** * Recupera las listas de los amigos de facebook del usuario. * @param uid * @return the http response */ @Path("friends") @GET @Produces(MediaType.APPLICATION_JSON) public Response getFriendLists(@PathParam("uid") String uid) { //TODO: ACCESS TOKEN HARCODEADO, tendria que recibirlo por parametro (cookie me imagino) String MY_ACCESS_TOKEN = "CAACEdEose0cBAG9nvNDXgSQSx3eqcPleUuc0KoVGZBGXqxAsJGNqPHylNM7W1pqQdfLt0kZCqZAKrFLeTgWVvXw8NjODjH5z8YsAnjnvoF951MFExfD4rbABmqxUZCiMVDBmL2boU1Bj1L8hcQ3CAyY8d7bmo3qofOZC2cuuwAdDV6KsQKFbRNhZBBqi6RWqyVhUASVsBZC2AZDZD"; List<Usuario> friendLists = obtenerListasDeAmigosDeFacebook(MY_ACCESS_TOKEN); return Response.status(Response.Status.OK).entity(friendLists).build(); } public List<Usuario> obtenerListasDeAmigosDeFacebook(String accessToken) { List<Usuario> allFriendsLists = new ArrayList<>(); FacebookClient facebookClient = new DefaultFacebookClient(accessToken); Connection<User> myFriends = facebookClient.fetchConnection("me/friends", User.class); if(myFriends != null && myFriends.getData() != null) for (User friend : myFriends.getData()) { String friendId = friend.getId(); Usuario userFriend = usuariosDao.getUsuario(friendId); if (userFriend != null) { allFriendsLists.add(userFriend); } } return allFriendsLists; } }
package io.rocketscience.java.util; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.*; import java.util.Collection; import java.util.List; import java.util.Optional; import org.junit.Test; /** * Conversion of null, boolean values, numbers and strings is straightward. * */ public class ObjectsTest { // -- toBoolean tests @Test public void shouldConvertNullToBoolean() { final Boolean actual = Objects.toBoolean(null); assertThat(actual).isEqualTo(null); } @Test public void shouldConvertTrueToTrue() { final Boolean actual = Objects.toBoolean(true); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertFalseToFalse() { final Boolean actual = Objects.toBoolean(false); assertThat(actual).isEqualTo(false); } @Test public void shouldConvertOneToTrue() { final Boolean actual = Objects.toBoolean(1); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertZeroToFalse() { final Boolean actual = Objects.toBoolean(0); assertThat(actual).isEqualTo(false); } @Test public void shouldConvertDoubleOneToTrue() { final Boolean actual = Objects.toBoolean(1.0d); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertDoubleZeroToFalse() { final Boolean actual = Objects.toBoolean(0.0d); assertThat(actual).isEqualTo(false); } @Test public void shouldConvertLowercaseTrueStringToTrue() { final Boolean actual = Objects.toBoolean("true"); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertUppercaseTrueStringToTrue() { final Boolean actual = Objects.toBoolean("TRUE"); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertLowercaseFalseStringToFalse() { final Boolean actual = Objects.toBoolean("false"); assertThat(actual).isEqualTo(false); } @Test public void shouldConvertUppercaseFalseStringToFalse() { final Boolean actual = Objects.toBoolean("FALSE"); assertThat(actual).isEqualTo(false); } @Test public void shouldConvertOneStringToTrue() { final Boolean actual = Objects.toBoolean("1"); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertZeroStringToFalse() { final Boolean actual = Objects.toBoolean("0"); assertThat(actual).isEqualTo(false); } @Test public void shouldConvertDoubleOneStringToTrue() { final Boolean actual = Objects.toBoolean("1.0"); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertDoubleZeroStringToFalse() { final Boolean actual = Objects.toBoolean("0.0"); assertThat(actual).isEqualTo(false); } @Test public void shouldConvertDoubleStringToTrue() { final Boolean actual = Objects.toBoolean("0.1"); assertThat(actual).isEqualTo(true); } @Test public void shouldConvertEmptyArrayToBoolean() { final Boolean actual = Objects.toBoolean(new byte[] {}); assertThat(actual).isEqualTo(null); } @Test public void shouldConvertSingletonBooleanArrayToBoolean() { // TODO } // TODO: toBoolean(Array of objects) // TODO: toBoolean(Collection) // TODO: toBoolean(Optional) // TODO: toBoolean(Object) // -- unbox(Collection) tests @Test public void shouldUnboxNullCollection() { final Collection<?> c = null; final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } @Test public void shouldUnboxEmptyCollection() { final Collection<?> c = java.util.Arrays.asList(); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } @Test public void shouldUnboxSingletonCollection() { final Collection<?> c = java.util.Arrays.asList(1); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(1); } @Test public void shouldUnboxCollectionWithTwoValues() { final Collection<?> c = java.util.Arrays.asList(1, 2); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } // -- unbox(List) tests @Test public void shouldUnboxNullList() { final List<?> c = null; final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } @Test public void shouldUnboxEmptyList() { final List<?> c = java.util.Arrays.asList(); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } @Test public void shouldUnboxSingletonList() { final List<?> c = java.util.Arrays.asList(1); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(1); } @Test public void shouldUnboxListWithTwoValues() { final List<?> c = java.util.Arrays.asList(1, 2); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } // -- unbox(Optional) tests @Test public void shouldUnboxNullOptional() { final Optional<?> c = null; final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } @Test public void shouldUnboxEmptyOptional() { final Optional<?> c = Optional.empty(); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(null); } @Test public void shouldUnboxDefinedOptional() { final Optional<?> c = Optional.of(1); final Object actual = Objects.unbox(c); assertThat(actual).isEqualTo(1); } }
package com.telekom.m2m.cot.restsdk.audit; import com.telekom.m2m.cot.restsdk.inventory.ManagedObject; import com.telekom.m2m.cot.restsdk.util.ExtensibleObject; import java.util.Date; public class AuditRecord extends ExtensibleObject { /** * Critical (highest severity). */ public static final String SEVERITY_CRITICAL = "CRITICAL"; /** * Major (2nd highest severity). */ public static final String SEVERITY_MAJOR = "MAJOR"; /** * Minor(2nd lowest severity). */ public static final String SEVERITY_MINOR = "MINOR"; /** * Warning (lowest severity). */ public static final String SEVERITY_WARNING = "WARNING"; /** * Just an information. */ public static final String SEVERITY_INFORMATION = "INFORMATION"; /** * Default construction to create a new audit record. */ public AuditRecord() { super(); } /** * Internal constructor to create audit records from base class. * * @param extensibleObject object from base class. */ public AuditRecord(ExtensibleObject extensibleObject) { super(extensibleObject); } /** * Get the unique identifier of the audit record. * If the AuditRecord was retrieved from the platform, it has an ID. If just * created, there is no ID. * * @return String the unique identifier of the audit record or null if not * available. */ public String getId() { return (String) anyObject.get("id"); } /** * Set the unique identifier of the audit record. * Just used internally. * * @param id the new identifier. */ void setId(String id) { anyObject.put("id", id); } /** * Get the type of the audit record. * The type categorizes the audit record. * * @return a String with the type or null if not available. */ public String getType() { return (String) anyObject.get("type"); } /** * Setting the audit record type. * * @param type a String with the audit record type. Use cot_abc_xyz style. */ public void setType(String type) { anyObject.put("type", type); } /** * Get the audit record text. * AuditRecord text is the human readable description of the audit record. * * @return a String with the text. */ public String getText() { return (String) anyObject.get("text"); } /** * Setting the audit record text. * Can be any type of string, CoT just displays plain text. * * @param text a String with the text to display. */ public void setText(String text) { anyObject.put("text", text); } /** * Get the creation time of the audit record in the CoT. * Just setted by platform on creation, not manipulatable. * * @return Date object representing the timestamp when audit record was created in * CoT. */ public Date getCreationTime() { return (Date) anyObject.get("creationTime"); } /** * Get the time when audit entry was recorded. * * @return Date object representing the timestamp when audit entry was recorded. */ public Date getTime() { return (Date) anyObject.get("time"); } /** * Set the time when audit entry was recorded. * * @param time Date object with the time when audit entry was recorded. */ public void setTime(Date time) { anyObject.put("time", time); } /** * Set the {@link ManagedObject} where audit entry was recorded. * * @param source the source ManagedObject where the audit entry was recorded. */ public void setSource(ManagedObject source) { anyObject.put("source", source); } /** * Get the ManagedObject where the audit record originated from. * * It concerns not only the id of a ManagedObject, * but in case of "Operation" type - operation id * and in case of Alarm type - alarm Id. * * @return the originating {@link ManagedObject} */ public ManagedObject getSource() { Object source = anyObject.get("source"); // since source value can be set as ManagedObject via setter in regular way // and as ExtensibleObject via gson ExtensibleObjectSerializer. // At first we need to check the type to avoid an unnecessary wrap into ManagedObject if(source instanceof ManagedObject) { return (ManagedObject)source; } return new ManagedObject((ExtensibleObject) source); } /** * Set the audit record activity. * * @param activity a String with the activity of the audit record. */ public void setActivity(String activity) { anyObject.put("activity", activity); } /** * Get the activity of the audit record. * * @return a String with the activity of the audit record. */ public String getActivity() { return (String) anyObject.get("activity"); } /** * Set the application which is creating this audit record. * * @param application a String with the application which is creating this audit record. */ public void setApplication(String application) { anyObject.put("application", application); } /** * Get the application which created this audit record. * * @return a String with the application which created this audit record. */ public String getApplication() { return (String) anyObject.get("application"); } /** * Set the user which is creating this audit record. * * @param user a String with the user which is creating this audit record. */ public void setUser(String user) { anyObject.put("user", user); } /** * Get the user which created this audit record. * * @return a String with the user which created this audit record. */ public String getUser() { return (String) anyObject.get("user"); } /** * Set the severity of the activity. * * @param severity a String with the severity of the activity. */ public void setSeverity(String severity) { anyObject.put("severity", severity); } /** * Get the severity of the activity. * * @return a String with the severity of the activity. */ public String getSeverity() { return (String) anyObject.get("severity"); } }
package com.oneandone.snmpman.configuration; import com.fasterxml.jackson.annotation.JsonProperty; import com.oneandone.snmpman.configuration.modifier.Modifier; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Represents a device type. * <p /> * You can find example configurations within the test resources of this project. */ @ToString(of = "name") @EqualsAndHashCode public class Device { /** * The device name. * * @return the device name */ @Getter private final String name; /** * The unmodifiable list of modifier definitions. * <p /> * See {@link Modifier} and {@link com.oneandone.snmpman.configuration.modifier.VariableModifier}. * * @return list of modifier definitions */ @Getter private final List<Modifier> modifiers; /** * The unmodifiable list of vlans. * * @return list of vlans represented as {@link Long}. */ @Getter private final List<Long> vlans; /** * Constructs a new device type. * * @param name the name of the device * @param modifiers the modifiers */ Device(@JsonProperty("name") final String name, @JsonProperty("modifiers") final Modifier[] modifiers, @JsonProperty(value = "vlans", required = false) final Long[] vlans) { this.name = name; if (modifiers != null) { this.modifiers = Collections.unmodifiableList(Arrays.asList(modifiers)); } else { this.modifiers = Collections.emptyList(); } if (vlans != null) { this.vlans = Collections.unmodifiableList(Arrays.asList(vlans)); } else { this.vlans = Collections.emptyList(); } } }
package com.themastergeneral.moglowstone.blocks; import java.util.Random; import com.themastergeneral.ctdcore.block.CTDBlock; import com.themastergeneral.moglowstone.MoGlowstone; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.material.MaterialColor; import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraftforge.common.ToolType; import net.minecraftforge.common.extensions.IForgeBlockState; public class GSOre extends CTDBlock { public GSOre(String name) { super(Block.Properties.create(Material.ROCK, MaterialColor.STONE) .sound(SoundType.STONE) .hardnessAndResistance(3F) .harvestTool(ToolType.PICKAXE) .harvestLevel(3), name, MoGlowstone.MODID); } }
package com.palantir.semver; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.NoWorkTreeException; import org.eclipse.jgit.lib.Repository; public class TagBasedVersionFactory { private static final String STABLE_VERSION_REGEX = "^[0-9]+\\.[0-9]+\\.[0-9]+$"; private String prefix; public TagBasedVersionFactory() { prefix = null; } public TagBasedVersionFactory(String prefix) { this.prefix = prefix; } public SemverVersion createVersion(Repository repo, Integer buildNumber) throws MissingObjectException, IncorrectObjectTypeException, IOException, NoWorkTreeException, GitAPIException { return createVersion(repo, buildNumber, false); } public SemverVersion createTopoVersion(Repository repo, Integer buildNumber) throws MissingObjectException, IncorrectObjectTypeException, IOException, NoWorkTreeException, GitAPIException { return createVersion(repo, buildNumber, true); } public SemverVersion createVersion(Repository repo, Integer buildNumber, boolean topo) throws MissingObjectException, IncorrectObjectTypeException, IOException, NoWorkTreeException, GitAPIException { if (repo == null) { throw new SemverGitflowPlugin.VersionApplicationException( "Project is not in a Git repository. Cannot use semver versioning in a non repository."); } TagVersionAndCount latestTagAndCount; if (topo) { latestTagAndCount = Tags.getTopoTagVersionAndCount(repo, prefix); } else { latestTagAndCount = Tags.getLatestTagVersionAndCount(repo, prefix); } String headCommitAbbreviation = GitRepos.getHeadCommitIdAbbreviation(repo); boolean isDirty = GitRepos.isDirty(repo); return generateVersion(latestTagAndCount, headCommitAbbreviation, buildNumber, isDirty); } private SemverVersion generateVersion(TagVersionAndCount latestTagAndCount, String headCommitAbbreviation, Integer buildNumber, boolean isDirty) { StringBuilder versionString = new StringBuilder(); String matchingTag = latestTagAndCount.getVersion(); String version; if (prefix != null) { String versionRegex = "^" + prefix + "-v?(.*)$"; Pattern versionPattern = Pattern.compile(versionRegex); Matcher matcher = versionPattern.matcher(matchingTag); if (!matcher.matches()) { return new SemverVersion("0.0.0", "0.0.0", "000000000000", 0, null, false); } version = matcher.group(1); } else { version = matchingTag; } versionString.append(version); if (isVersionStableRelease(latestTagAndCount)) { if (isDirty) { versionString.append("+dirty"); } } else { String firstSeparator = getFirstSeparator(latestTagAndCount); versionString.append(firstSeparator + latestTagAndCount.getCount()); versionString.append("+g"); versionString.append(headCommitAbbreviation); if (buildNumber != null) { versionString.append(".b" + buildNumber); } if (isDirty) { versionString.append(".dirty"); } } SemverVersion versionObject = new SemverVersion(versionString.toString(), version, headCommitAbbreviation, latestTagAndCount.getCount(), buildNumber, isDirty); return versionObject; } private String getFirstSeparator(TagVersionAndCount latestTag) { if (isAboveStable(latestTag)) { return "-"; } else { return "."; } } private static boolean isAboveStable(TagVersionAndCount latestTagAndCount) { return latestTagAndCount.getVersion().matches(STABLE_VERSION_REGEX) && (latestTagAndCount.getCount() > 1); } private static boolean isVersionStableRelease(TagVersionAndCount latestTagAndCount) { return latestTagAndCount.getVersion().matches(STABLE_VERSION_REGEX) && isTagCountStable(latestTagAndCount.getCount()); } private static boolean isTagCountStable(int count) { return count == 0; } }
package crazypants.enderio.item.darksteel; import crazypants.enderio.config.Config; import crazypants.vecmath.Vector3d; import net.minecraft.entity.Entity; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; public class SoundEntity extends Entity { int lifeSpan = Config.darkSteelSoundLocatorLifespan; float volume; public SoundEntity(World world, Vector3d pos, float volume) { super(world); setPosition(pos.x, pos.y, pos.z); this.volume = volume; } @Override protected void entityInit() { } protected boolean canTriggerWalking() { return false; } @Override public AxisAlignedBB getBoundingBox() { return AxisAlignedBB.getBoundingBox(posX - 0.5, posY - 0.5, posZ - 0.5, posX + 0.5, posY + 0.5, posZ + 0.5); } @Override public void onUpdate() { super.onUpdate(); lifeSpan if(lifeSpan == 0) { setDead(); } } @Override protected void readEntityFromNBT(NBTTagCompound p_70037_1_) { } @Override protected void writeEntityToNBT(NBTTagCompound p_70014_1_) { } }
package com4j; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; final class Wrapper implements InvocationHandler, Com4jObject { /** * name of this wrapper. This is for debug purposes. */ private String name; private static final Method[] DISPOSE_METHODS = new Method[2]; static { try { DISPOSE_METHODS[0] = Wrapper.class.getDeclaredMethod("dispose"); DISPOSE_METHODS[1] = Com4jObject.class.getDeclaredMethod("dispose"); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } /** * interface pointer. */ private final long ptr; private volatile boolean isDisposed = false; /** * Cached hash code. The value of {@code IUnknown*}. */ private volatile long hashCode=0; /** * All the invocation to the wrapper COM object must go through this thread. */ private final ComThread thread; /** * A phantom reference that owns the native pointer. When this ref is enqueue, * the com thread will release() the native pointer. */ final NativePointerPhantomReference ref; /** * Cached of {@link ComMethod} keyed by the method declaration. * * TODO: revisit the cache design */ private Map<Method,ComMethod> cache = Collections.synchronizedMap( new WeakHashMap<Method,ComMethod>()); /** * Wraps a new COM object. The pointer needs to be addRefed by the caller if needed. */ private Wrapper(long ptr) { if(ptr==0) throw new IllegalArgumentException(); assert ComThread.isComThread(); this.ptr = ptr; thread = ComThread.get(); ref = new NativePointerPhantomReference(this, thread.collectableObjects, ptr); thread.addLiveObject(this); } /** * Creates a new proxy object to a given COM pointer. * <p> * Must be run from a {@link ComThread}. This method doesn't do AddRef. */ static <T extends Com4jObject> T create( Class<T> primaryInterface, long ptr ) { Wrapper w = new Wrapper(ptr); T r = primaryInterface.cast(Proxy.newProxyInstance( primaryInterface.getClassLoader(), new Class<?>[]{primaryInterface}, w)); return r; } /** * * @deprecated 64bit unsafe. */ static Com4jObject create( int ptr ) { return create((long)ptr); } /** * Creates a new proxy object to a given COM pointer. * <p> * Must be run from a {@link ComThread}. */ static Com4jObject create( long ptr ) { Wrapper w = new Wrapper(ptr); return w; } /** * Returns the wrapped interface pointer as an integer * @return The wrapped interface pointer. */ @Override public int getPtr() { return (int)ptr; } public long getPointer() { return ptr; } @Override public ComThread getComThread(){ return thread; } private static final Object[] EMPTY_ARRAY = new Object[0]; public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(isDisposed && method != DISPOSE_METHODS[0] && method != DISPOSE_METHODS[1]) throw new IllegalStateException("COM object is already disposed"); if(args==null) // this makes the processing easier args = EMPTY_ARRAY; Class<?> declClazz = method.getDeclaringClass(); if( declClazz==Com4jObject.class || declClazz==Object.class ) { // method declared on Com4jObject is not meant to be delegated. try { return method.invoke(this,args); } catch( IllegalAccessException e ) { throw new IllegalAccessError(e.getMessage()); } catch( InvocationTargetException e ) { throw e.getTargetException(); } } UseDefaultValues useDefaultValues = method.getAnnotation(UseDefaultValues.class); if(useDefaultValues != null){ int defValCount = useDefaultValues.optParamIndex().length; Object[] newArgs = new Object[args.length + defValCount]; // fill in the given arguments to the right place: for(int i = 0; i < args.length; i++){ newArgs[useDefaultValues.paramIndexMapping()[i]] = args[i]; } // Fill in the (optional) default values: ComMethod comMethod = getMethod(method); for(int i = 0; i < defValCount; i++){ Object defParam = comMethod.defaultParameters[i]; newArgs[useDefaultValues.optParamIndex()[i]] = defParam; } args = newArgs; } if(invCache==null) invCache = new InvocationThunk(); try { return invCache.invoke(getMethod(method),args); } catch (ExecutionException e) { if(e.getCause() instanceof ComException) throw new ComException((ComException)e.getCause()); throw e; } } private ComMethod getMethod(Method method) { ComMethod r = cache.get(method); if(r!=null) return r; r = createComMethod(method); cache.put(method,r); return r; } private ComMethod createComMethod(Method method) { ReturnValue rv = method.getAnnotation(ReturnValue.class); if(rv!=null && rv.defaultPropertyThrough().length>0) return new DefaultedComMethod(method,rv); // prefer the custom interface. VTID vtid = method.getAnnotation(VTID.class); if(vtid != null){ return new StandardComMethod(method); } DISPID dispid = method.getAnnotation(DISPID.class); if(dispid!=null) return new DispatchComMethod(method); throw new IllegalAnnotationException("Missing annotation: You need to specify at least one of @DISPID or @VTID"); } public void dispose() { if(!isDisposed) { new Task<Void>() { public Void call() { dispose0(); return null; } }.execute(thread); // Issue 39 fixed. } } private void dispose0() { if (!isDisposed) { ref.releaseNative(); isDisposed = true; } } public <T extends Com4jObject> boolean is( Class<T> comInterface ) { try { GUID iid = COM4J.getIID(comInterface); return new QITestTask(iid).execute(thread)!=0; } catch( ComException e ) { return false; } } /** * Returns whether this object was already disposed. * @return true if this object was disposed, false otherwise. */ public boolean isDisposed() { return isDisposed; } public <T extends Com4jObject> T queryInterface( final Class<T> comInterface ) { return new Task<T>() { public T call() { GUID iid = COM4J.getIID(comInterface); long nptr = Native.queryInterface(ptr,iid); if(nptr==0) return null; // failed to cast return create( comInterface, nptr ); } }.execute(thread); } public <T> EventProxy<?> advise(final Class<T> eventInterface, final T object) { return new Task<EventProxy<?>>() { public EventProxy<?> call() { IConnectionPointContainer cpc = queryInterface(IConnectionPointContainer.class); if(cpc==null) throw new ComException("This object doesn't have event source",-1); GUID iid = COM4J.getIID(eventInterface); Com4jObject cp = cpc.FindConnectionPoint(iid); EventProxy<T> proxy = new EventProxy<T>(eventInterface, object); proxy.nativeProxy = Native.advise(cp.getPointer(), proxy,iid.v[0], iid.v[1]); // clean up resources to be nice cpc.dispose(); cp.dispose(); return proxy; } }.execute(); } @Override public void setName(String name){ this.name = name; } public String toString() { if(name == null) { return "ComObject:"+Long.toHexString(ptr); } else { return name+":"+Long.toHexString(ptr); } } public final int hashCode() { long l = getIUnknownPointer(); return (int)(l ^ (l >>> 32)); } public long getIUnknownPointer() { if(hashCode==0) { if(isDisposed) { hashCode = 0; } else { hashCode = new QITestTask(COM4J.IID_IUnknown).execute(thread); } } return hashCode; } public final boolean equals( Object rhs ) { if(!(rhs instanceof Com4jObject)) return false; return this.getIUnknownPointer()== ((Com4jObject)rhs).getIUnknownPointer(); } /** * Used to pass parameters/return values between the host thread * and the peer {@link ComThread}. */ private class InvocationThunk extends Task<Object> { private ComMethod method; private Object[] args; /** * Invokes the method on the peer {@link ComThread} and returns * its return value. * @param method The {@link ComMethod} to invoke * @param args The arguments of the method * @return Returns the return value of the invoked method */ public synchronized Object invoke( ComMethod method, Object[] args ) { invCache = null; this.method = method; this.args = args; try { return execute(thread); } finally { invCache = this; } } /** * Called from {@link ComThread} to actually carry out the execution. * @return Returns the return value of the invoked method */ public synchronized Object call() { Object r = method.invoke(ptr,args); // clear fields that are no longer necessary method = null; args = null; return r; } } /** * We cache up to one InvocationThunk. */ InvocationThunk invCache; /** * Invokes QueryInterface but immediately releases that pointer. * Useful for checking if an object implements a particular interface. */ private final class QITestTask extends Task<Long> { private final GUID iid; public QITestTask(GUID iid) { this.iid = iid; } public Long call() { long nptr = Native.queryInterface(ptr,iid); if(nptr!=0) { Native.release(nptr); } return nptr; } } }
package daxum.temporalconvergence; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import daxum.temporalconvergence.entity.ModEntities; import daxum.temporalconvergence.gui.GuiHandler; import daxum.temporalconvergence.proxy.IProxy; import daxum.temporalconvergence.recipes.RecipeHandler; import daxum.temporalconvergence.world.DimensionHandler; import daxum.temporalconvergence.world.ModWorldGenerator; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; @Mod(modid = TemporalConvergence.MODID, name = TemporalConvergence.NAME, version = TemporalConvergence.VERSION, acceptedMinecraftVersions="[1.11.2]") public class TemporalConvergence { public static final String MODID = "temporalconvergence"; //Remember to change creative tab name in ModItems and lang file if changed. public static final String NAME = "Temporal Convergence"; public static final String VERSION = "9001.8"; //TODO: Make gradle put in version on build @Instance(MODID) public static TemporalConvergence instance; public static final Logger LOGGER = LogManager.getLogger("tempConv"); //Why on earth did I choose a 19 letter name? @SidedProxy(clientSide = "daxum.temporalconvergence.proxy.ClientProxy", serverSide = "daxum.temporalconvergence.proxy.ServerProxy") public static IProxy proxy; static { FluidRegistry.enableUniversalBucket(); } @SuppressWarnings("unused") @EventHandler public void preInit(FMLPreInitializationEvent event) { ModEntities.init(); RecipeHandler.initOreDict(); DimensionHandler.init(); proxy.registerFluidRenderer(); proxy.registerEntityRenderer(); } @SuppressWarnings("unused") @EventHandler public void init(FMLInitializationEvent event) { NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler()); GameRegistry.registerWorldGenerator(new ModWorldGenerator(), 0); RecipeHandler.init(); LOGGER.info(InitLogBuilder.get()); } @SuppressWarnings("unused") @EventHandler public void postInit(FMLPostInitializationEvent event) { } }
package com.programmaticallyspeaking.tinyws; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Supplier; public class Server { public static final String ServerName = "TinyWS Server"; public static final String ServerVersion = "@VERSION@"; private static final String HANDSHAKE_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private static final int SupportedVersion = 13; private final Executor mainExecutor; private final Executor handlerExecutor; private final Options options; private final Logger logger; private ServerSocket serverSocket; private Map<String, Supplier<WebSocketHandler>> handlerFactories = new HashMap<>(); /** * Constructs a new server instance but doesn't start listening for client connections. * * @param mainExecutor the {@link Executor} instance that will be used to create the main listener task as well as * tasks for handling connected clients. Please note that each task will use excessive blocking * I/O, so use an appropriate executor. * @param handlerExecutor the {@code Executor} instance that will be used to invoke handlers. * @param options server options */ public Server(Executor mainExecutor, Executor handlerExecutor, Options options) { this.mainExecutor = mainExecutor; this.handlerExecutor = handlerExecutor; this.options = options; this.logger = new Logger() { public void log(LogLevel level, String message, Throwable error) { if (isEnabledAt(level)) { try { options.logger.log(level, message, error); } catch (Exception ignore) { // ignore logging errors } } } @Override public boolean isEnabledAt(LogLevel level) { return options.logger != null && options.logger.isEnabledAt(level); } }; } private void lazyLog(LogLevel level, Supplier<String> msgFun) { if (logger.isEnabledAt(level)) logger.log(level, msgFun.get(), null); } public void addHandlerFactory(String endpoint, Supplier<WebSocketHandler> handlerFactory) { if (endpoint == null || "".equals(endpoint)) throw new IllegalArgumentException("Endpoint must be non-empty."); if (serverSocket != null) throw new IllegalStateException("Please add handler factories before starting the server."); handlerFactories.put(endpoint, handlerFactory); } public void start() throws IOException { // Using backlog 0 will force ServerSocket to use the default (50). int backlog = options.backlog != null ? options.backlog : 0; serverSocket = new ServerSocket(options.port, backlog, options.address); mainExecutor.execute(this::acceptInLoop); } /** * Stops listening for client connection. Does nothing if the server has already been stopped (or hasn't been started * to begin with). Any exception from closing the server socket is suppressed but will be logged at WARN level to * any supplied logger. */ public void stop() { if (serverSocket == null) return; try { serverSocket.close(); } catch (IOException e) { logger.log(LogLevel.WARN, "Failed to close server socket.", e); } serverSocket = null; } private void acceptInLoop() { try { lazyLog(LogLevel.INFO, () -> "Receiving WebSocket clients at " + serverSocket.getLocalSocketAddress()); while (true) { Socket clientSocket = serverSocket.accept(); mainExecutor.execute(new ClientHandler(clientSocket)); } } catch (SocketException e) { logger.log(LogLevel.DEBUG, "Server socket was closed, probably because the server was stopped.", e); } catch (Exception ex) { logger.log(LogLevel.ERROR, "Error accepting a client socket.", ex); } } private class ClientHandler implements Runnable { private final Socket clientSocket; private final OutputStream out; private final InputStream in; private final PayloadCoder payloadCoder; private final FrameWriter frameWriter; private WebSocketHandler handler; private volatile boolean isClosed; // potentially set from handler thread ClientHandler(Socket clientSocket) throws IOException { this.clientSocket = clientSocket; out = clientSocket.getOutputStream(); in = clientSocket.getInputStream(); payloadCoder = new PayloadCoder(); frameWriter = new FrameWriter(out, payloadCoder, options.maxFrameSize); } private void invokeHandler(Consumer<WebSocketHandler> fun) { if (handler != null) handlerExecutor.execute(() -> fun.accept(handler)); } @Override public void run() { try { communicate(); } catch (WebSocketClosure ex) { lazyLog(LogLevel.DEBUG, () -> String.format("Closing with code %d (%s)%s", ex.code, ex.reason, ex.debugDetails != null ? (" because: " + ex.debugDetails) : "")); doIgnoringExceptions(() -> frameWriter.writeClose(ex.code, ex.reason)); // If the connection was closed by the client, we expect onClosedByClient to have been invoked and // we must *not* invoke onClosedByServer since that would be a lie... if (!ex.closedByClient) invokeHandler(h -> h.onClosedByServer(ex.code, ex.reason)); } catch (MethodNotAllowedException ex) { lazyLog(LogLevel.WARN, () -> String.format("WebSocket client from %s used a non-allowed method: %s", clientSocket.getRemoteSocketAddress(), ex.method)); sendMethodNotAllowedResponse(); } catch (IllegalArgumentException ex) { lazyLog(LogLevel.WARN, () -> String.format("WebSocket client from %s sent a malformed request.", clientSocket.getRemoteSocketAddress())); sendBadRequestResponse(); } catch (FileNotFoundException ex) { lazyLog(LogLevel.WARN, () -> String.format("WebSocket client from %s requested an unknown endpoint.", clientSocket.getRemoteSocketAddress())); sendNotFoundResponse(); } catch (SocketException ex) { if (!isClosed) { logger.log(LogLevel.ERROR, "Client socket error.", ex); invokeHandler(h -> h.onFailure(ex)); } } catch (Exception ex) { logger.log(LogLevel.ERROR, "Client communication error.", ex); invokeHandler(h -> h.onFailure(ex)); } abort(); } private void abort() { if (isClosed) return; doIgnoringExceptions(clientSocket::close); isClosed = true; } private void communicate() throws IOException, NoSuchAlgorithmException { Headers headers = Headers.read(in); if (!headers.isProperUpgrade()) throw new IllegalArgumentException("Handshake has malformed upgrade."); if (headers.version() != SupportedVersion) throw new IllegalArgumentException("Bad version, must be: " + SupportedVersion); String endpoint = headers.endpoint; Supplier<WebSocketHandler> handlerFactory = handlerFactories.get(endpoint); if (handlerFactory == null || (handler = handlerFactory.get()) == null) throw new FileNotFoundException("Unknown endpoint: " + endpoint); lazyLog(LogLevel.INFO, () -> String.format("New WebSocket client from %s at endpoint '%s'.", clientSocket.getRemoteSocketAddress(), endpoint)); invokeHandler(h -> h.onOpened(new WebSocketClientImpl(frameWriter, this::abort, headers))); String key = headers.key(); if (key == null) throw new IllegalArgumentException("Missing Sec-WebSocket-Key in handshake."); String responseKey = createResponseKey(key); lazyLog(LogLevel.TRACE, () -> String.format("Opening handshake key is '%s', sending response key '%s'.", key, responseKey)); sendHandshakeResponse(responseKey); List<Frame> frameBatch = new ArrayList<>(); while (true) { frameBatch.add(Frame.read(in)); handleBatch(frameBatch); } } private void handleBatch(List<Frame> frameBatch) throws IOException { Frame firstFrame = frameBatch.get(0); if (firstFrame.opCode == 0) throw WebSocketClosure.protocolError("Continuation frame with nothing to continue."); Frame lastOne = frameBatch.get(frameBatch.size() - 1); lazyLog(LogLevel.TRACE, lastOne::toString); if (!lastOne.isFin) return; if (firstFrame != lastOne) { if (lastOne.isControl()) { // Interleaved control frame frameBatch.remove(frameBatch.size() - 1); handleResultFrame(lastOne); return; } else if (lastOne.opCode > 0) { throw WebSocketClosure.protocolError("Continuation frame must have opcode 0."); } } Frame result = frameBatch.size() > 1 ? Frame.merge(frameBatch) : lastOne; frameBatch.clear(); handleResultFrame(result); } private void handleResultFrame(Frame result) throws IOException { switch (result.opCode) { case 1: String data = payloadCoder.decode(result.payloadData); invokeHandler(h -> h.onTextMessage(data)); break; case 2: invokeHandler(h -> h.onBinaryData(result.payloadData)); break; case 8: CloseData cd = result.toCloseData(payloadCoder); if (cd.hasInvalidCode()) throw WebSocketClosure.protocolError("Invalid close frame code: " + cd.code); // 1000 is normal close int i = cd.code != null ? cd.code : 1000; invokeHandler(h -> h.onClosedByClient(i, cd.reason)); throw WebSocketClosure.fromClient(i); case 9: // Ping, send pong! logger.log(LogLevel.TRACE, "Got ping frame, sending pong.", null); frameWriter.writePong(result.payloadData); break; case 10: // Pong is ignored logger.log(LogLevel.TRACE, "Ignoring unsolicited pong frame.", null); break; default: throw WebSocketClosure.protocolError("Invalid opcode: " + result.opCode); } } private void outputLine(PrintWriter writer, String data) { writer.print(data); writer.print("\r\n"); } private void sendHandshakeResponse(String responseKey) { Map<String, String> headers = new HashMap<String, String>() {{ put("Upgrade", "websocket"); put("Connection", "upgrade"); put("Sec-WebSocket-Accept", responseKey); }}; sendResponse(101, "Switching Protocols", headers); } private void sendBadRequestResponse() { // Advertise supported version regardless of what was bad. A bit lazy, but simple. Map<String, String> headers = new HashMap<String, String>() {{ put("Sec-WebSocket-Version", Integer.toString(SupportedVersion)); }}; sendResponse(400, "Bad Request", headers); } private void sendMethodNotAllowedResponse() { Map<String, String> headers = new HashMap<String, String>() {{ put("Allow", "GET"); }}; sendResponse(405, "Method Not Allowed", headers); } private void sendNotFoundResponse() { sendResponse(404, "Not Found", Collections.emptyMap()); } private void sendResponse(int statusCode, String reason, Map<String, String> headers) { PrintWriter writer = new PrintWriter(out, false); outputLine(writer, "HTTP/1.1 " + statusCode + " " + reason); for (Map.Entry<String, String> entry : headers.entrySet()) { outputLine(writer, entry.getKey() + ": " + entry.getValue()); } // https://tools.ietf.org/html/rfc7231#section-7.4.2 outputLine(writer, String.format("Server: %s %s", ServerName, ServerVersion)); // Headers added when we don't do a connection upgrade to WebSocket! if (statusCode >= 200) { // https://tools.ietf.org/html/rfc7230#section-6.1 outputLine(writer, "Connection: close"); // https://tools.ietf.org/html/rfc7230#section-3.3.2 outputLine(writer, "Content-Length: 0"); } outputLine(writer, ""); writer.flush(); // Note: Do NOT close the writer, as the stream must remain open } } static class Frame { final int opCode; final byte[] payloadData; final boolean isFin; public String toString() { return String.format("Frame[opcode=%d, control=%b, payload length=%d, fragmented=%b]", opCode, isControl(), payloadData.length, !isFin); } boolean isControl() { return (opCode & 8) == 8; } private Frame(int opCode, byte[] payloadData, boolean isFin) { this.opCode = opCode; this.payloadData = payloadData; this.isFin = isFin; } private static int readUnsignedByte(InputStream in) throws IOException { int b = in.read(); if (b < 0) throw new IOException("End of stream"); return b; } private static int toUnsigned(byte b) { int result = b; if (result < 0) result += 256; return result; } private static byte[] readBytes(InputStream in, int len) throws IOException { byte[] buf = new byte[len]; int totalRead = 0; int offs = 0; while (totalRead < len) { int readLen = in.read(buf, offs, len - offs); if (readLen < 0) break; totalRead += readLen; offs += readLen; } if (totalRead != len) throw new IOException("Expected to read " + len + " bytes but read " + totalRead); return buf; } private static long toLong(byte[] data, int offset, int len) { long result = 0; for (int i = offset, j = offset + len; i < j; i++) { result = (result << 8) + toUnsigned(data[i]); } return result; } private static long toLong(byte[] data) { return toLong(data, 0, data.length); } static Frame read(InputStream in) throws IOException { int firstByte = readUnsignedByte(in); boolean isFin = (firstByte & 128) == 128; boolean hasZeroReserved = (firstByte & 112) == 0; if (!hasZeroReserved) throw WebSocketClosure.protocolError("Non-zero reserved bits in 1st byte: " + (firstByte & 112)); int opCode = (firstByte & 15); boolean isControlFrame = (opCode & 8) == 8; int secondByte = readUnsignedByte(in); boolean isMasked = (secondByte & 128) == 128; int len = (secondByte & 127); if (isControlFrame) { if (len > 125) throw WebSocketClosure.protocolError("Control frame length exceeding 125 bytes."); if (!isFin) throw WebSocketClosure.protocolError("Fragmented control frame."); } if (len == 126) { // 2 bytes of extended len long tmp = toLong(readBytes(in, 2)); len = (int) tmp; } else if (len == 127) { // 8 bytes of extended len long tmp = toLong(readBytes(in, 8)); if (tmp > Integer.MAX_VALUE) throw WebSocketClosure.protocolError("Frame length greater than 0x7fffffff not supported."); len = (int) tmp; } byte[] maskingKey = isMasked ? readBytes(in, 4) : null; byte[] payloadData = unmaskIfNeededInPlace(readBytes(in, len), maskingKey); return new Frame(opCode, payloadData, isFin); } private static byte[] unmaskIfNeededInPlace(byte[] bytes, byte[] maskingKey) { if (maskingKey != null) { for (int i = 0; i < bytes.length; i++) { int j = i % 4; bytes[i] = (byte) (bytes[i] ^ maskingKey[j]); } } return bytes; } CloseData toCloseData(PayloadCoder payloadCoder) throws WebSocketClosure { if (opCode != 8) throw new IllegalStateException("Not a close frame: " + opCode); if (payloadData.length == 0) return new CloseData(null, null); if (payloadData.length == 1) throw WebSocketClosure.protocolError("Invalid close frame payload length (1)."); int code = (int) toLong(payloadData, 0, 2); String reason = payloadData.length > 2 ? payloadCoder.decode(payloadData, 2, payloadData.length - 2) : null; return new CloseData(code, reason); } static Frame merge(List<Frame> frameBatch) { // Combine payloads! int totalLength = frameBatch.stream().mapToInt(f -> f.payloadData.length).sum(); byte[] allTheData = new byte[totalLength]; int offs = 0; for (Frame frame : frameBatch) { System.arraycopy(frame.payloadData, 0, allTheData, offs, frame.payloadData.length); offs += frame.payloadData.length; } return new Frame(frameBatch.get(0).opCode, allTheData, true); } } private static class CloseData { private final Integer code; private final String reason; CloseData(Integer code, String reason) { this.code = code; this.reason = reason; } boolean hasInvalidCode() { if (code == null) return false; // no code isn't invalid if (code < 1000 || code >= 5000) return true; if (code >= 3000) return false; // 3000-3999 and 4000-4999 are valid return code == 1004 || code == 1005 || code == 1006 || code > 1011; } } static class Headers { private final Map<String, String> headers; final String endpoint; final String query; final String fragment; private Headers(Map<String, String> headers, URI uri) { this.headers = headers; this.endpoint = uri.getPath(); this.query = uri.getQuery(); this.fragment = uri.getFragment(); } boolean isProperUpgrade() { return "websocket".equalsIgnoreCase(headers.get("Upgrade")) && "Upgrade".equalsIgnoreCase(headers.get("Connection")); } int version() { String versionStr = headers.get("Sec-WebSocket-Version"); try { return Integer.parseInt(versionStr); } catch (Exception ignore) { return 0; } } String key() { return headers.get("Sec-WebSocket-Key"); } String userAgent() { return headers.get("User-Agent"); } String host() { return headers.get("Host"); } static Headers read(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String inputLine; URI endpoint = null; Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); boolean isFirstLine = true; while (!"".equals((inputLine = reader.readLine()))) { if (isFirstLine) { String[] parts = inputLine.split(" ", 3); if (parts.length != 3) throw new IllegalArgumentException("Malformed 1st header line: " + inputLine); if (!"GET".equals(parts[0])) throw new MethodNotAllowedException(parts[0]); try { endpoint = new URI("http://server" + parts[1]); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid endpoint: " + parts[1]); } isFirstLine = false; } String[] keyValue = inputLine.split(":", 2); if (keyValue.length != 2) continue; headers.put(keyValue[0], keyValue[1].trim()); } // Note: Do NOT close the reader, because the stream must remain open! return new Headers(headers, endpoint); } } static class PayloadCoder { private final Charset charset = StandardCharsets.UTF_8; private final CharsetDecoder decoder = charset.newDecoder(); String decode(byte[] bytes) throws WebSocketClosure { return decode(bytes, 0, bytes.length); } /** * Decodes the given byte data as UTF-8 and returns the result as a string. * * @param bytes the byte array * @param offset offset into the array where to start decoding * @param len length of data to decode * @return the decoded string * @throws WebSocketClosure (1007) thrown if the data are not valid UTF-8 */ synchronized String decode(byte[] bytes, int offset, int len) throws WebSocketClosure { decoder.reset(); try { CharBuffer buf = decoder.decode(ByteBuffer.wrap(bytes, offset, len)); return buf.toString(); } catch (Exception ex) { throw WebSocketClosure.invalidFramePayloadData(); } } byte[] encode(String s) { return s.getBytes(charset); } } static class WebSocketClosure extends IOException { final int code; final String reason; final String debugDetails; final boolean closedByClient; private WebSocketClosure(int code, String reason, String debugDetails, boolean closedByClient) { this.code = code; this.reason = reason; this.debugDetails = debugDetails; this.closedByClient = closedByClient; } static WebSocketClosure fromClient(int code) { return new WebSocketClosure(code, "", "Closed by client", true); } static WebSocketClosure protocolError(String debugDetails) { return new WebSocketClosure(1002, "Protocol error", debugDetails, false); } static WebSocketClosure invalidFramePayloadData() { return new WebSocketClosure(1007, "Invalid frame payload data", null, false); } } static class FrameWriter { private final OutputStream out; private final PayloadCoder payloadCoder; private final int maxFrameSize; FrameWriter(OutputStream out, PayloadCoder payloadCoder, int maxFrameSize) { this.out = out; this.payloadCoder = payloadCoder; this.maxFrameSize = maxFrameSize; } void writeClose(int code, String reason) throws IOException { byte[] s = payloadCoder.encode(reason); byte[] numBytes = numberToBytes(code, 2); byte[] combined = new byte[numBytes.length + s.length]; System.arraycopy(numBytes, 0, combined, 0, 2); System.arraycopy(s, 0, combined, 2, s.length); writeFrame(8, combined); } void writeText(String text) throws IOException { byte[] s = payloadCoder.encode(text); writePossiblyFragmentedFrames(1, s); } void writeBinary(byte[] data) throws IOException { writePossiblyFragmentedFrames(2, data); } void writePing(byte[] data) throws IOException { writeFrame(9, data); } void writePong(byte[] data) throws IOException { writeFrame(10, data); } private void writePossiblyFragmentedFrames(int opCode, byte[] data) throws IOException { // https://tools.ietf.org/html/rfc6455#section-5.6 implies that a single frame may contain an UTF-8 // sequence that by itself is invalid, as long as the entire message text is valid UTF-8. if (maxFrameSize == 0 || data == null || data.length <= maxFrameSize) { writeFrame(opCode, data); } else { int offset = 0; while (offset < data.length) { int len = Math.min(data.length - offset, maxFrameSize); writeFrame(opCode, data, offset, len); offset += len; } } } private void writeFrame(int opCode, byte[] data) throws IOException { writeFrame(opCode, data, 0, data != null ? data.length : 0); } /** * Writes a frame to the output stream. Since FrameWriter is handed out to potentially different threads, * this method is synchronized. * * @param opCode the opcode of the frame * @param data frame data * @throws IOException thrown if writing to the socket fails */ synchronized private void writeFrame(int opCode, byte[] data, int offset, int len) throws IOException { int totalLen = data != null ? data.length : 0; boolean isFirstFrame = offset == 0; boolean isFinalFrame = offset + len == totalLen; int firstByte = isFirstFrame ? opCode : 0; if (isFinalFrame) firstByte |= 128; // FIN int secondByte; int extraLengthBytes = 0; if (len < 126) { secondByte = len; } else if (len < 65536) { secondByte = 126; extraLengthBytes = 2; } else { secondByte = 127; extraLengthBytes = 8; } out.write(firstByte); out.write(secondByte); if (extraLengthBytes > 0) { out.write(numberToBytes(len, extraLengthBytes)); } if (data != null) out.write(data, offset, len); out.flush(); } } private static class WebSocketClientImpl implements WebSocketClient { private final FrameWriter writer; private final Runnable closeCallback; private final Headers headers; WebSocketClientImpl(FrameWriter writer, Runnable closeCallback, Headers headers) { this.writer = writer; this.closeCallback = closeCallback; this.headers = headers; } public void ping() throws IOException { writer.writePing(null); } public void close() { doIgnoringExceptions(() -> { writer.writeClose(1001, "Going Away"); closeCallback.run(); }); } public void sendTextMessage(String text) throws IOException { writer.writeText(text); } public void sendBinaryData(byte[] data) throws IOException { writer.writeBinary(data); } public String userAgent() { return headers.userAgent(); } public String host() { return headers.host(); } public String query() { return headers.query; } public String fragment() { return headers.fragment; } } static byte[] numberToBytes(int number, int len) { byte[] array = new byte[len]; // Start from the end (network byte order), assume array is filled with zeros. for (int i = len - 1; i >= 0; i array[i] = (byte) (number & 0xff); number = number >> 8; } return array; } static String createResponseKey(String key) throws NoSuchAlgorithmException { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] rawBytes = (key + HANDSHAKE_GUID).getBytes(); byte[] result = sha1.digest(rawBytes); return Base64.getEncoder().encodeToString(result); } private static void doIgnoringExceptions(RunnableThatThrows runnable) { try { runnable.run(); } catch (Exception ex) { // ignore } } private interface RunnableThatThrows { void run() throws Exception; } static class MethodNotAllowedException extends IllegalArgumentException { final String method; public MethodNotAllowedException(String method) { this.method = method; } } /** * Server options, configured using a fluent interface. Start with {@code Options.withPort(int)} since port is * required. */ public static class Options { Integer backlog; int port; Logger logger; InetAddress address; int maxFrameSize; private Options(int port) { this.port = port; } /** * Creates new options with the given port. * * @param port the port to use when listening for WebSocket clients * @return this options instance */ public static Options withPort(int port) { return new Options(port); } /** * Specifies the backlog size, i.e. the size of the client connection queue. If the queue is full, a client * connection is rejected. * * @param backlog the backlog size, which must be greater than 0 * @return this options instance */ public Options andBacklog(int backlog) { if (backlog <= 0) throw new IllegalArgumentException("Backlog must be > 0"); this.backlog = backlog; return this; } /** * Specifies a logger. * * @param logger the logger instance * @return this options instance */ public Options andLogger(Logger logger) { this.logger = logger; return this; } /** * Specifies the address to use when creating the server socket. * * @param address the address to bind to * @return this options instance */ public Options andAddress(InetAddress address) { this.address = address; return this; } /** * Specifies the maximum frame size. The maximum frame size must be at least 126, as it doesn't make much * sense to create frame fragments smaller than that. * * @param size maximum frame size * @return this options instance */ public Options andMaxFrameSize(int size) { if (size <= 125) throw new IllegalArgumentException("Max frame size must be at least 126."); this.maxFrameSize = size; return this; } } /** * Log level for logging. */ public enum LogLevel { TRACE(0), DEBUG(10), INFO(20), WARN(50), ERROR(100); /** * Numeric level corresponding to this log level. ERROR has the highest level and TRACE has the lowest. */ public final int level; LogLevel(int level) { this.level = level; } } /** * A simple interface for logging. */ public interface Logger { /** * Logs a message at a certain level. Note that this method is not called if {@link #isEnabledAt(LogLevel)} * returns {@code false} for the given level. * * @param level the log level * @param message the message to log * @param error an optional error */ void log(LogLevel level, String message, Throwable error); /** * Determines if logging is enabled for the given level. * * @param level a log level * @return {@code true} if logging is enabled at the level, {@code false} otherwise */ boolean isEnabledAt(LogLevel level); } /** * Represents a WebSocket client and exposes methods that makes it possible to interact with the client, as well * as methods for getting information about the client and how it requested the handled resource. * * Methods on this interface can be invoked from any thread. */ public interface WebSocketClient { /** * Sends a ping to the client. This can be used to send keep-alive messages to the client. * * @throws IOException on I/O failure while sending the ping */ void ping() throws IOException; /** * Performs a clean close of the connection to the client. */ void close(); /** * Sends a text message to the client. * * @param text the text to send * @throws IOException on I/O failure while sending */ void sendTextMessage(String text) throws IOException; /** * Sends binary data to the client. * * @param data the data to send * @throws IOException on I/O failure while sending */ void sendBinaryData(byte[] data) throws IOException; /** * Returns the value of the User-Agent header passed by the client when requesting a Websocket connection. If no * User-Agent header was present, returns {@code null}. * * @return the Host header value, or {@code null} */ String userAgent(); /** * Returns the value of the Host header passed by the client when requesting a Websocket connection. If no * Host header was present, returns {@code null}. * * @return the Host header value, or {@code null} */ String host(); String query(); String fragment(); } /** * A handler for a WebSocket client connection. A new handler instance will be created for each connected client. * Handlers are invoked on the handler executor passed to the {@code Server} constructor. */ public interface WebSocketHandler { /** * Invoked right after construction. * * @param client instance for interacting with the client */ void onOpened(WebSocketClient client); /** * Invoked when the client closes the connection in an orderly fashion. * * @param code the close code the client used, if any, otherwise 1000 (Normal Closure). * @param reason the close reason the client used, if any. May be {@code null}. */ void onClosedByClient(int code, String reason); /** * Invoked when the server closes the connection in an orderly fashion, but must likely because of an error. * * @param code the close code sent to the client * @param reason the close reason sent to the client */ void onClosedByServer(int code, String reason); /** * Invoked when the connection is closed abruptly because of an error. * * @param t the error that occurred */ void onFailure(Throwable t); /** * Invoked when the client sends a text message. * * @param text the message */ void onTextMessage(String text); /** * Invoked when the client sends binary data. * * @param data the data */ void onBinaryData(byte[] data); } }
package org.owasp.esapi.reference; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.owasp.esapi.ESAPI; import org.owasp.esapi.Executor; import org.owasp.esapi.SecurityConfiguration; import org.owasp.esapi.SecurityConfigurationWrapper; import org.owasp.esapi.codecs.Codec; import org.owasp.esapi.codecs.WindowsCodec; import org.owasp.esapi.codecs.UnixCodec; /** * The Class ExecutorTest. * * @author Jeff Williams (jeff.williams@aspectsecurity.com) */ public class ExecutorTest extends TestCase { private SecurityConfiguration origConfig; private static class Conf extends SecurityConfigurationWrapper { private List allowedExes; private File workingDir; Conf(SecurityConfiguration orig, List allowedExes, File workingDir) { super(orig); this.allowedExes = allowedExes; this.workingDir = workingDir; } @Override public List getAllowedExecutables() { return allowedExes; } @Override public File getWorkingDirectory() { return workingDir; } } /** * Instantiates a new executor test. * * @param testName * the test name */ public ExecutorTest(String testName) { super(testName); } /** * {@inheritDoc} * * @throws Exception */ protected void setUp() throws Exception { // save configuration as tests may change it origConfig = ESAPI.securityConfiguration(); } /** * {@inheritDoc} * * @throws Exception */ protected void tearDown() throws Exception { // restore configuration as test may change it ESAPI.setSecurityConfiguration(origConfig); } /** * Suite. * * @return the test */ public static Test suite() { TestSuite suite = new TestSuite(ExecutorTest.class); return suite; } /** * Test of executeOSCommand method, of class org.owasp.esapi.Executor * * @throws Exception * the exception */ public void testExecuteWindowsSystemCommand() throws Exception { System.out.println("executeWindowsSystemCommand"); if ( System.getProperty("os.name").indexOf("Windows") == -1 ) { System.out.println("testExecuteWindowsSystemCommand - on non-Windows platform, exiting"); return; // Not windows, not going to execute this path } File tmpDir = new File(System.getProperty("java.io.tmpdir")).getCanonicalFile(); File sysRoot = new File(System.getenv("SystemRoot")).getCanonicalFile(); File sys32 = new File(sysRoot,"system32").getCanonicalFile(); File cmd = new File(sys32,"cmd.exe").getCanonicalFile(); ESAPI.setSecurityConfiguration( new Conf( ESAPI.securityConfiguration(), Collections.singletonList(cmd.getPath()), tmpDir ) ); Codec codec = new WindowsCodec(); System.out.println("executeSystemCommand"); Executor instance = ESAPI.executor(); List params = new ArrayList(); try { params.add("/C"); params.add("dir"); String result = instance.executeSystemCommand(cmd, new ArrayList(params) ); System.out.println( "RESULT: " + result ); assertTrue(result.length() > 0); } catch (Exception e) { e.printStackTrace(); fail(); } try { File exec2 = new File( cmd.getPath() + ";inject.exe" ); String result = instance.executeSystemCommand(exec2, new ArrayList(params) ); System.out.println( "RESULT: " + result ); fail(); } catch (Exception e) { // expected } try { File exec2 = new File( cmd.getPath() + "\\..\\cmd.exe" ); String result = instance.executeSystemCommand(exec2, new ArrayList(params) ); System.out.println( "RESULT: " + result ); fail(); } catch (Exception e) { // expected } try { File workdir = new File( "c:\\ridiculous" ); String result = instance.executeSystemCommand(cmd, new ArrayList(params), workdir, codec, false ); System.out.println( "RESULT: " + result ); fail(); } catch (Exception e) { // expected } try { params.add("&dir"); String result = instance.executeSystemCommand(cmd, new ArrayList(params) ); System.out.println( "RESULT: " + result ); } catch (Exception e) { fail(); } try { params.set( params.size()-1, "c:\\autoexec.bat" ); String result = instance.executeSystemCommand(cmd, new ArrayList(params) ); System.out.println( "RESULT: " + result ); } catch (Exception e) { fail(); } try { params.set( params.size()-1, "c:\\autoexec.bat c:\\config.sys" ); String result = instance.executeSystemCommand(cmd, new ArrayList(params) ); System.out.println( "RESULT: " + result ); } catch (Exception e) { fail(); } } /** * Test of executeOSCommand method, of class org.owasp.esapi.Executor * * @throws Exception * the exception */ public void testExecuteUnixSystemCommand() throws Exception { System.out.println("executeUnixSystemCommand"); if ( System.getProperty("os.name").indexOf("Windows") != -1 ) { System.out.println("executeUnixSystemCommand - on Windows platform, exiting"); return; } // FIXME: need more test cases to use this codec Codec codec = new UnixCodec(); // make sure we have what /bin/sh is pointing at in the allowed exes for the test // and a usable working dir File binSh = new File("/bin/sh").getCanonicalFile(); ESAPI.setSecurityConfiguration( new Conf( ESAPI.securityConfiguration(), Collections.singletonList(binSh.getPath()), new File("/tmp") ) ); Executor instance = ESAPI.executor(); File executable = binSh; List params = new ArrayList(); try { params.add("-c"); params.add("ls"); params.add("/"); String result = instance.executeSystemCommand(executable, new ArrayList(params) ); System.out.println( "RESULT: " + result ); assertTrue(result.length() > 0); } catch (Exception e) { fail(e.getMessage()); } try { File exec2 = new File( executable.getPath() + ";./inject" ); String result = instance.executeSystemCommand(exec2, new ArrayList(params) ); System.out.println( "RESULT: " + result ); fail(); } catch (Exception e) { // expected } try { File exec2 = new File( executable.getPath() + "/../bin/sh" ); String result = instance.executeSystemCommand(exec2, new ArrayList(params) ); System.out.println( "RESULT: " + result ); fail(); } catch (Exception e) { // expected } try { params.add(";ls"); String result = instance.executeSystemCommand(executable, new ArrayList(params) ); System.out.println( "RESULT: " + result ); } catch (Exception e) { fail(); } } }
package com.programmaticallyspeaking.tinyws; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.Executor; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; public class Server { public static final String ServerName = "TinyWS Server"; public static final String ServerVersion = "0.0.1"; //TODO: Get from resource private static final String HANDSHAKE_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private static final int SupportedVersion = 13; private final Executor mainExecutor; private final Executor handlerExecutor; private final Options options; private final Logger logger; private ServerSocket serverSocket; private Map<String, WebSocketHandler> handlers = new HashMap<>(); public Server(Executor mainExecutor, Executor handlerExecutor, Options options) { this.mainExecutor = mainExecutor; this.handlerExecutor = handlerExecutor; this.options = options; this.logger = new Logger() { public void log(LogLevel level, String message, Throwable error) { if (isEnabledAt(level)) { try { options.logger.log(level, message, error); } catch (Exception ignore) { // ignore logging errors } } } @Override public boolean isEnabledAt(LogLevel level) { return options.logger != null && options.logger.isEnabledAt(level); } }; } public void addHandler(String endpoint, WebSocketHandler handler) { if (serverSocket != null) throw new IllegalStateException("Please add handlers before starting the server."); handlers.put(endpoint, handler); } public void start() throws IOException { Integer backlog = options.backlog; serverSocket = backlog == null ? new ServerSocket(options.port) : new ServerSocket(options.port, backlog); mainExecutor.execute(this::acceptInLoop); } public void stop() { if (serverSocket == null) return; try { serverSocket.close(); } catch (IOException e) { logger.log(LogLevel.WARN, "Failed to close server socket.", e); } serverSocket = null; } private void acceptInLoop() { try { if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, "Receiving WebSocket clients at " + serverSocket.getLocalSocketAddress(), null); while (true) { Socket clientSocket = serverSocket.accept(); BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> wrappedHandlerExecutor = (handler, fun) -> { if (handler != null) handlerExecutor.execute(() -> fun.accept(handler)); }; mainExecutor.execute(new ClientHandler(clientSocket, handlers::get, wrappedHandlerExecutor, logger)); } } catch (SocketException e) { logger.log(LogLevel.DEBUG, "Server socket was closed, probably because the server was stopped.", e); } catch (Exception ex) { logger.log(LogLevel.ERROR, "Error accepting a client socket.", ex); } } private static class ClientHandler implements Runnable { private final Socket clientSocket; private final OutputStream out; private final InputStream in; private final Function<String, WebSocketHandler> handlerLookup; private final BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor; private final Logger logger; private final PayloadCoder payloadCoder; private final FrameWriter frameWriter; private WebSocketHandler handler; private volatile boolean isClosed; // potentially set from handler thread ClientHandler(Socket clientSocket, Function<String, WebSocketHandler> handlerLookup, BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor, Logger logger) throws IOException { this.clientSocket = clientSocket; out = clientSocket.getOutputStream(); in = clientSocket.getInputStream(); this.handlerLookup = handlerLookup; this.handlerExecutor = handlerExecutor; this.logger = logger; payloadCoder = new PayloadCoder(); frameWriter = new FrameWriter(out, payloadCoder); } @Override public void run() { try { communicate(); } catch (WebSocketError ex) { if (logger.isEnabledAt(LogLevel.DEBUG)) { String msg = String.format("Closing with code %d (%s)%s", ex.code, ex.reason, ex.debugDetails != null ? (" because: " + ex.debugDetails) : ""); logger.log(LogLevel.DEBUG, msg, null); } doIgnoringExceptions(() -> frameWriter.writeCloseFrame(ex.code, ex.reason)); handlerExecutor.accept(handler, h -> h.onClosedByClient(ex.code, ex.reason)); } catch (IllegalArgumentException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s sent a malformed request.", clientSocket.getRemoteSocketAddress()), null); sendBadRequestResponse(); } catch (FileNotFoundException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s requested an unknown endpoint.", clientSocket.getRemoteSocketAddress()), null); sendNotFoundResponse(); } catch (SocketException ex) { if (!isClosed) { logger.log(LogLevel.ERROR, "Client socket error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } } catch (Exception ex) { logger.log(LogLevel.ERROR, "Client communication error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } abort(); } private void abort() { if (isClosed) return; doIgnoringExceptions(clientSocket::close); isClosed = true; } private void communicate() throws IOException, NoSuchAlgorithmException { Headers headers = Headers.read(in); if (!headers.isProperUpgrade()) throw new IllegalArgumentException("Handshake has malformed upgrade."); if (headers.version() != SupportedVersion) throw new IllegalArgumentException("Bad version, must be: " + SupportedVersion); String endpoint = headers.endpoint; if (endpoint == null) throw new IllegalArgumentException("Missing endpoint."); handler = handlerLookup.apply(endpoint); if (handler == null) throw new FileNotFoundException("Unknown endpoint: " + endpoint); if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, String.format("New WebSocket client from %s at endpoint '%s'.", clientSocket.getRemoteSocketAddress(), endpoint), null); handlerExecutor.accept(handler, h -> h.onOpened(new WebSocketClientImpl(frameWriter, this::abort))); String key = headers.key(); String responseKey = createResponseKey(key); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, String.format("Opening handshake key is '%s', sending response key '%s'.", key, responseKey), null); sendHandshakeResponse(responseKey); List<Frame> frameBatch = new ArrayList<>(); while (true) { frameBatch.add(Frame.read(in)); handleBatch(frameBatch); } } private void handleBatch(List<Frame> frameBatch) throws IOException { Frame firstFrame = frameBatch.get(0); if (firstFrame.opCode == 0) throw WebSocketError.protocolError("Continuation frame with nothing to continue."); Frame lastOne = frameBatch.get(frameBatch.size() - 1); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, lastOne.toString(), null); if (!lastOne.isFin) return; if (firstFrame != lastOne) { if (lastOne.isControl()) { // Interleaved control frame frameBatch.remove(frameBatch.size() - 1); handleResultFrame(lastOne); return; } else if (lastOne.opCode > 0) { throw WebSocketError.protocolError("Continuation frame must have opcode 0."); } } Frame result; if (frameBatch.size() > 1) { // Combine payloads! int totalLength = frameBatch.stream().mapToInt(f -> f.payloadData.length).sum(); byte[] allTheData = new byte[totalLength]; int offs = 0; for (Frame frame : frameBatch) { System.arraycopy(frame.payloadData, 0, allTheData, offs, frame.payloadData.length); offs += frame.payloadData.length; } result = new Frame(firstFrame.opCode, allTheData, true); } else result = lastOne; frameBatch.clear(); handleResultFrame(result); } private void handleResultFrame(Frame result) throws IOException { switch (result.opCode) { case 1: String data = payloadCoder.decode(result.payloadData); handlerExecutor.accept(handler, h -> h.onTextMessage(data)); break; case 2: handlerExecutor.accept(handler, h -> h.onBinaryData(result.payloadData)); break; case 8: CloseData cd = result.toCloseData(payloadCoder); if (cd.hasInvalidCode()) throw WebSocketError.protocolError("Invalid close frame code: " + cd.code); // 1000 is normal close int i = cd.code != null ? cd.code : 1000; throw new WebSocketError(i, "", null); case 9: // Ping, send pong! logger.log(LogLevel.TRACE, "Got ping frame, sending pong.", null); frameWriter.writePongFrame(result.payloadData); break; case 10: // Pong is ignored logger.log(LogLevel.TRACE, "Ignoring unsolicited pong frame.", null); break; default: throw WebSocketError.protocolError("Invalid opcode: " + result.opCode); } } private void outputLine(PrintWriter writer, String data) { System.out.println("> " + data); writer.print(data); writer.print("\r\n"); } private void sendHandshakeResponse(String responseKey) { Map<String, String> headers = new HashMap<String, String>() {{ put("Upgrade", "websocket"); put("Connection", "upgrade"); put("Sec-WebSocket-Accept", responseKey); }}; sendResponse(101, "Switching Protocols", headers); } private void sendBadRequestResponse() { // Advertise supported version regardless of what was bad. A bit lazy, but simple. Map<String, String> headers = new HashMap<String, String>() {{ put("Sec-WebSocket-Version", Integer.toString(SupportedVersion)); }}; sendResponse(400, "Bad Request", Collections.emptyMap()); } private void sendNotFoundResponse() { sendResponse(404, "Not Found", Collections.emptyMap()); } private void sendResponse(int statusCode, String reason, Map<String, String> headers) { PrintWriter writer = new PrintWriter(out, false); outputLine(writer, "HTTP/1.1 " + statusCode + " " + reason); for (Map.Entry<String, String> entry : headers.entrySet()) { outputLine(writer, entry.getKey() + ": " + entry.getValue()); } // https://tools.ietf.org/html/rfc7231#section-7.4.2 outputLine(writer, String.format("Server: %s %s", ServerName, ServerVersion)); // https://tools.ietf.org/html/rfc7230#section-6.1 if (statusCode >= 200) outputLine(writer, "Connection: close"); outputLine(writer, ""); writer.flush(); // Note: Do NOT close the writer, as the stream must remain open } } private static class Frame { final int opCode; final byte[] payloadData; final boolean isFin; public String toString() { return String.format("Frame[opcode=%d, control=%b, payload length=%d, fragmented=%b]", opCode, isControl(), payloadData.length, !isFin); } boolean isControl() { return (opCode & 8) == 8; } private Frame(int opCode, byte[] payloadData, boolean isFin) { this.opCode = opCode; this.payloadData = payloadData; this.isFin = isFin; } private static int readUnsignedByte(InputStream in) throws IOException { int b = in.read(); if (b < 0) throw new IOException("End of stream"); return b; } private static int toUnsigned(byte b) { int result = b; if (result < 0) result += 256; return result; } private static byte[] readBytes(InputStream in, int len) throws IOException { byte[] buf = new byte[len]; int totalRead = 0; int offs = 0; while (totalRead < len) { int readLen = in.read(buf, offs, len - offs); if (readLen < 0) break; totalRead += readLen; offs += readLen; } if (totalRead != len) throw new IOException("Expected to read " + len + " bytes but read " + totalRead); return buf; } private static long toLong(byte[] data, int offset, int len) { long result = 0; for (int i = offset, j = offset + len; i < j; i++) { result = (result << 8) + toUnsigned(data[i]); } return result; } private static long toLong(byte[] data) { return toLong(data, 0, data.length); } static Frame read(InputStream in) throws IOException { int firstByte = readUnsignedByte(in); boolean isFin = (firstByte & 128) == 128; boolean hasZeroReserved = (firstByte & 112) == 0; if (!hasZeroReserved) throw WebSocketError.protocolError("Non-zero reserved bits in 1st byte: " + (firstByte & 112)); int opCode = (firstByte & 15); boolean isControlFrame = (opCode & 8) == 8; int secondByte = readUnsignedByte(in); boolean isMasked = (secondByte & 128) == 128; int len = (secondByte & 127); if (isControlFrame) { if (len > 125) throw WebSocketError.protocolError("Control frame length exceeding 125 bytes."); if (!isFin) throw WebSocketError.protocolError("Fragmented control frame."); } if (len == 126) { // 2 bytes of extended len long tmp = toLong(readBytes(in, 2)); len = (int) tmp; } else if (len == 127) { // 8 bytes of extended len long tmp = toLong(readBytes(in, 8)); if (tmp > Integer.MAX_VALUE) throw WebSocketError.protocolError("Frame length greater than 0x7fffffff not supported."); len = (int) tmp; } byte[] maskingKey = isMasked ? readBytes(in, 4) : null; byte[] payloadData = unmaskIfNeededInPlace(readBytes(in, len), maskingKey); return new Frame(opCode, payloadData, isFin); } private static byte[] unmaskIfNeededInPlace(byte[] bytes, byte[] maskingKey) { if (maskingKey != null) { for (int i = 0; i < bytes.length; i++) { int j = i % 4; bytes[i] = (byte) (bytes[i] ^ maskingKey[j]); } } return bytes; } CloseData toCloseData(PayloadCoder payloadCoder) throws WebSocketError { if (opCode != 8) throw new IllegalStateException("Not a close frame: " + opCode); if (payloadData.length == 0) return new CloseData(null, null); if (payloadData.length == 1) throw WebSocketError.protocolError("Invalid close frame payload length (1)."); int code = (int) toLong(payloadData, 0, 2); String reason = payloadData.length > 2 ? payloadCoder.decode(payloadData, 2, payloadData.length - 2) : null; return new CloseData(code, reason); } } private static class CloseData { private final Integer code; private final String reason; CloseData(Integer code, String reason) { this.code = code; this.reason = reason; } boolean hasInvalidCode() { if (code == null) return false; // no code isn't invalid if (code < 1000 || code >= 5000) return true; if (code >= 3000) return false; // 3000-3999 and 4000-4999 are valid return code == 1004 || code == 1005 || code == 1006 || code > 1011; } } private static class Headers { private final Map<String, String> headers; final String endpoint; private Headers(Map<String, String> headers, String endpoint) { this.headers = headers; this.endpoint = endpoint; } boolean isProperUpgrade() { return "websocket".equalsIgnoreCase(headers.get("Upgrade")) && "Upgrade".equalsIgnoreCase(headers.get("Connection")); } int version() { String versionStr = headers.get("Sec-WebSocket-Version"); try { return Integer.parseInt(versionStr); } catch (Exception ignore) { return 0; } } String key() { String key = headers.get("Sec-WebSocket-Key"); if (key == null) throw new IllegalArgumentException("Missing Sec-WebSocket-Key in handshake."); return key; } static Headers read(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String inputLine, endpoint = null; Map<String, String> headers = new HashMap<>(); while (!"".equals((inputLine = reader.readLine()))) { if (inputLine.startsWith("GET ")) { String[] parts = inputLine.split(" ", 3); if (parts.length != 3) throw new IOException("Unexpected GET line: " + inputLine); endpoint = parts[1]; } String[] keyValue = inputLine.split(":", 2); if (keyValue.length != 2) continue; System.out.println("< " + inputLine); headers.put(keyValue[0], keyValue[1].trim()); } // Note: Do NOT close the reader, because the stream must remain open! return new Headers(headers, endpoint); } } static class PayloadCoder { private final Charset charset; private final CharsetDecoder decoder; PayloadCoder() { charset = Charset.forName("UTF-8"); decoder = charset.newDecoder(); } String decode(byte[] bytes) throws WebSocketError { return decode(bytes, 0, bytes.length); } /** * Decodes the given byte data as UTF-8 and returns the result as a string. * * @param bytes the byte array * @param offset offset into the array where to start decoding * @param len length of data to decode * @return the decoded string * @throws WebSocketError (1007) thrown if the data are not valid UTF-8 */ synchronized String decode(byte[] bytes, int offset, int len) throws WebSocketError { decoder.reset(); try { CharBuffer buf = decoder.decode(ByteBuffer.wrap(bytes, offset, len)); return buf.toString(); } catch (Exception ex) { throw WebSocketError.invalidFramePayloadData(); } } byte[] encode(String s) { return s.getBytes(charset); } } static class WebSocketError extends IOException { final int code; final String reason; final String debugDetails; WebSocketError(int code, String reason, String debugDetails) { this.code = code; this.reason = reason; this.debugDetails = debugDetails; } static WebSocketError protocolError(String debugDetails) { return new WebSocketError(1002, "Protocol error", debugDetails); } static WebSocketError invalidFramePayloadData() { return new WebSocketError(1007, "Invalid frame payload data", null); } } static class FrameWriter { private final OutputStream out; private final PayloadCoder payloadCoder; FrameWriter(OutputStream out, PayloadCoder payloadCoder) { this.out = out; this.payloadCoder = payloadCoder; } void writeCloseFrame(int code, String reason) throws IOException { byte[] s = payloadCoder.encode(reason); byte[] numBytes = numberToBytes(code, 2); byte[] combined = new byte[numBytes.length + s.length]; System.arraycopy(numBytes, 0, combined, 0, 2); System.arraycopy(s, 0, combined, 2, s.length); writeFrame(8, combined); } void writeTextFrame(String text) throws IOException { byte[] s = payloadCoder.encode(text); writeFrame(1, s); } void writeBinaryFrame(byte[] data) throws IOException { writeFrame(2, data); } void writePongFrame(byte[] data) throws IOException { writeFrame(10, data); } /** * Writes a frame to the output stream. Since FrameWriter is handed out to potentially different threads, * this method is synchronized. * * @param opCode the opcode of the frame * @param data frame data * @throws IOException thrown if writing to the socket fails */ synchronized void writeFrame(int opCode, byte[] data) throws IOException { int firstByte = 128 | opCode; // FIN + opCode int dataLen = data.length; int secondByte; int extraLengthBytes = 0; if (dataLen < 126) { secondByte = dataLen; // no masking } else if (dataLen < 65536) { secondByte = 126; extraLengthBytes = 2; } else { secondByte = 127; extraLengthBytes = 8; } out.write(firstByte); out.write(secondByte); if (extraLengthBytes > 0) { out.write(numberToBytes(data.length, extraLengthBytes)); } out.write(data); out.flush(); } } private static class WebSocketClientImpl implements WebSocketClient { private final FrameWriter writer; private final Runnable closeCallback; WebSocketClientImpl(FrameWriter writer, Runnable closeCallback) { this.writer = writer; this.closeCallback = closeCallback; } public void close(int code, String reason) throws IOException { writer.writeCloseFrame(code, reason); closeCallback.run(); } public void sendTextMessage(String text) throws IOException { writer.writeTextFrame(text); } public void sendBinaryData(byte[] data) throws IOException { writer.writeBinaryFrame(data); } } static byte[] numberToBytes(int number, int len) { byte[] array = new byte[len]; // Start from the end (network byte order), assume array is filled with zeros. for (int i = len - 1; i >= 0; i array[i] = (byte) (number & 0xff); number = number >> 8; } return array; } private static String createResponseKey(String key) throws NoSuchAlgorithmException { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] rawBytes = (key + HANDSHAKE_GUID).getBytes(); byte[] result = sha1.digest(rawBytes); return Base64.getEncoder().encodeToString(result); } private static void doIgnoringExceptions(RunnableThatThrows runnable) { try { runnable.run(); } catch (Exception ex) { // ignore } } private interface RunnableThatThrows { void run() throws Exception; } public static class Options { Integer backlog; int port; Logger logger; private Options(int port) { this.port = port; } public static Options withPort(int port) { return new Options(port); } public Options withBacklog(int backlog) { if (backlog < 0) throw new IllegalArgumentException("Backlog must be >= 0"); this.backlog = backlog; return this; } public Options withLogger(Logger logger) { this.logger = logger; return this; } } public enum LogLevel { TRACE(0), DEBUG(10), INFO(20), WARN(50), ERROR(100); public final int level; LogLevel(int level) { this.level = level; } } public interface Logger { void log(LogLevel level, String message, Throwable error); boolean isEnabledAt(LogLevel level); } public interface WebSocketClient { void close(int code, String reason) throws IOException; void sendTextMessage(String text) throws IOException; void sendBinaryData(byte[] data) throws IOException; // TODO: Get user-agent, query string params } public interface WebSocketHandler { void onOpened(WebSocketClient client); void onClosedByClient(int code, String reason); void onFailure(Throwable t); void onTextMessage(String text); void onBinaryData(byte[] data); } }
package org.kitesdk.apps.cli; import com.beust.jcommander.JCommander; import com.beust.jcommander.MissingCommandException; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.log4j.Level; import org.apache.log4j.PropertyConfigurator; import org.kitesdk.apps.cli.commands.InstallCommand; import org.kitesdk.cli.Command; import org.kitesdk.cli.Help; import org.kitesdk.data.DatasetIOException; import org.kitesdk.data.DatasetNotFoundException; import org.kitesdk.data.ValidationException; import org.kitesdk.data.spi.DefaultConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; public class Main extends Configured implements Tool { public static void main (String[] args) throws Exception { // reconfigure logging with the kite CLI configuration PropertyConfigurator.configure( Main.class.getResource("/kite-apps-cli-logging.properties")); Logger console = LoggerFactory.getLogger(Main.class); Configuration conf = new Configuration(); conf.addResource("yarn-site.xml"); conf.addResource("hive-site.xml"); int rc = ToolRunner.run(conf, new Main(console), args); System.exit(rc); } @Parameter(names = {"-v", "--verbose", "--debug"}, description = "Print extra debugging information") private boolean debug = false; @VisibleForTesting @Parameter(names="--dollar-zero", description="A way for the runtime path to be passed in", hidden=true) String programName = DEFAULT_PROGRAM_NAME; @VisibleForTesting static final String DEFAULT_PROGRAM_NAME = "kite-dataset"; private static Set<String> HELP_ARGS = ImmutableSet.of("-h", "-help", "--help", "help"); private final Logger console; private final JCommander jc; private Main(Logger console) { this.console = console; this.jc = new JCommander(this); jc.addCommand("install", new InstallCommand(console)); } @Override public int run(String[] args) throws Exception { if (getConf() != null) { DefaultConfiguration.set(getConf()); } try { jc.parse(args); } catch (MissingCommandException e) { console.error(e.getMessage()); return 1; } catch (ParameterException e) { console.error(e.getMessage()); return 1; } // configure log4j if (debug) { org.apache.log4j.Logger console = org.apache.log4j.Logger.getLogger(Main.class); console.setLevel(Level.DEBUG); } String parsed = jc.getParsedCommand(); if (parsed == null) { console.error("Unable to parse command."); return 1; } Command command = (Command) jc.getCommands().get(parsed).getObjects().get(0); if (command == null) { console.error("Unable to find command."); return 1; } try { if (command instanceof Configurable) { ((Configurable) command).setConf(getConf()); } return command.run(); } catch (IllegalArgumentException e) { if (debug) { console.error("Argument error", e); } else { console.error("Argument error: {}", e.getMessage()); } return 1; } catch (IllegalStateException e) { if (debug) { console.error("State error", e); } else { console.error("State error: {}", e.getMessage()); } return 1; } catch (ValidationException e) { if (debug) { console.error("Validation error", e); } else { console.error("Validation error: {}", e.getMessage()); } return 1; } catch (DatasetNotFoundException e) { if (debug) { console.error("Cannot find dataset", e); } else { // the error message already contains "No such dataset: <name>" console.error(e.getMessage()); } return 1; } catch (DatasetIOException e) { if (debug) { console.error("IO error", e); } else { console.error("IO error: {}", e.getMessage()); } return 1; } catch (Exception e) { if (debug) { console.error("Unknown error", e); } else { console.error("Unknown error: {}", e.getMessage()); } return 1; } } }
package de.fred4jupiter.fredbet.web.bet; import java.util.List; import javax.validation.Valid; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import de.fred4jupiter.fredbet.domain.Bet; import de.fred4jupiter.fredbet.domain.Match; import de.fred4jupiter.fredbet.service.BettingService; import de.fred4jupiter.fredbet.service.NoBettingAfterMatchStartedAllowedException; import de.fred4jupiter.fredbet.web.MessageUtil; import de.fred4jupiter.fredbet.web.SecurityBean; @Controller @RequestMapping("/bet") public class BetController { @Autowired private BettingService bettingService; @Autowired private SecurityBean securityBean; @Autowired private MessageUtil messageUtil; @RequestMapping public ModelAndView list() { List<Bet> allBets = bettingService.findAllByUsername(securityBean.getCurrentUserName()); return new ModelAndView("bet/list", "allBets", allBets); } @RequestMapping("/open") public ModelAndView listStillOpen(ModelMap modelMap) { List<Match> matchesToBet = bettingService.findMatchesToBet(securityBean.getCurrentUserName()); if (CollectionUtils.isEmpty(matchesToBet)) { messageUtil.addInfoMsg(modelMap, "Derzeit alle Spiele getippt!"); } return new ModelAndView("bet/list_open", "matchesToBet", matchesToBet); } @RequestMapping(value = "/createOrUpdate/{matchId}", method = RequestMethod.GET) public ModelAndView createOrUpdate(@PathVariable("matchId") String matchId) { BetCommand betCommand = bettingService.findOrCreateBetForMatch(matchId); return new ModelAndView("bet/form", "betCommand", betCommand); } @RequestMapping(method = RequestMethod.POST) public ModelAndView createOrUpdate(@Valid BetCommand betCommand, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("bet/form", "formErrors", result.getAllErrors()); } try { bettingService.save(betCommand); messageUtil.addInfoMsg(redirect, "Tippspiel angelegt/aktualisiert!"); } catch (NoBettingAfterMatchStartedAllowedException e) { messageUtil.addErrorMsg(redirect, "Das Spiel hat bereits begonnen! Keine Tippabgabe mehr möglich!"); } return new ModelAndView("redirect:/matches"); } }
package de.hhu.stups.plues.modelgenerator; import de.hhu.stups.plues.data.Store; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @SuppressWarnings("unused") public class XmlExporter { private static final String DATA_TEMPLATE = "/xml/data.xml.twig"; private static final String DATA_FILE = "Moduldaten.xml"; private static final String TREE_TEMPLATE = "/xml/tree.xml.twig"; private static final String TREE_FILE = "Modulbaum.xml"; private final Logger logger = Logger.getLogger(getClass().getSimpleName()); private final Renderer renderer; public XmlExporter(final Store db) { this.renderer = new Renderer(db); } /** * Export data to a zip file containting an xml file for the module tree and an xml file for * the module data. * * @return ByteArrayOutputStream representing the generated ZIP file * @throws IOException in case there is an error creating the ZIP file */ public ByteArrayOutputStream export() throws IOException { final ByteArrayOutputStream renderedData = renderer.renderFor(FileType.MODULE_DATA); final ByteArrayOutputStream renderedTree = renderer.renderFor(FileType.MODULE_TREE); return buildZipFile(renderedTree, renderedData); } private ByteArrayOutputStream buildZipFile(final ByteArrayOutputStream tree, final ByteArrayOutputStream data) throws IOException { final byte[] treeBytes = getBytesForRenderer(tree); final byte[] dataBytes = getBytesForRenderer(data); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ZipOutputStream zos = new ZipOutputStream(baos)) { ZipEntry entry = new ZipEntry(TREE_FILE); zos.putNextEntry(entry); zos.write(treeBytes); zos.closeEntry(); entry = new ZipEntry(DATA_FILE); zos.putNextEntry(entry); zos.write(dataBytes); zos.closeEntry(); } catch (final IOException ioe) { logger.log(Level.SEVERE, "Exception creating ZIP file for xml data", ioe); throw ioe; } return baos; } private byte[] getBytesForRenderer(final ByteArrayOutputStream stream) { return stream.toByteArray(); } }
package de.morrox.fontinator; import android.content.Context; import android.util.AttributeSet; import android.util.Pair; import android.widget.AutoCompleteTextView; import de.morrox.fontinator.utilities.TypefaceLoader; import de.morrox.fontinator.utilities.Typefaceable; public class FontAutoCompleteTextView extends AutoCompleteTextView implements Typefaceable { private TypefaceLoader typefaceLoader; public FontAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); typefaceLoader = TypefaceLoader.get(this, context, attrs); } @Override public void setText(CharSequence text, BufferType type) { Pair<CharSequence, BufferType> pair = TypefaceLoader.inject(typefaceLoader, text, type); super.setText(pair.first, pair.second); } }
package com.rox.emu.processor.mos6502.util; import com.rox.emu.processor.mos6502.op.OpCode; import java.util.*; /** * An immutable 6502 Program which is essentially a byte array which can * be added to from different types neatly. * * @author Ross Drew */ public class Program { private final int[] programBytes; private final Map<String, Integer> programLabels; private final List<Reference> references; /** * An inline label reference */ public static class Reference { private final String targetLabel; private final int rootAddress; public Reference(final String target, final int root){ this.targetLabel = target; this.rootAddress = root; } } public Reference referenceBuilder(String targetLabel){ return new Reference(targetLabel, programBytes.length); } public Program(){ this(new int[]{}); } private Program(int[] programBytes){ this.programBytes = programBytes; this.programLabels = Collections.emptyMap(); this.references = new ArrayList<>(); } private Program(int[] programBytes, Map<String, Integer> programLabels, List<Reference> references){ this.programBytes = programBytes; this.programLabels = programLabels; this.references = references; } /** * Create a new {@link Program} with a byte value appended * * @param byteValue ({@link int}) to append * @return a new {@link Program} that is a copy of this one with the new value appended */ public Program with(int byteValue){ int[] newProgramBytes = new int[programBytes.length + 1]; System.arraycopy(programBytes,0, newProgramBytes, 0, programBytes.length); newProgramBytes[newProgramBytes.length-1] = byteValue; return new Program(newProgramBytes, this.programLabels, references); } /** * Create a new {@link Program} with a {@link OpCode} appended * * @param opCode ({@link OpCode}) to append * @return a new {@link Program} that is a copy of this one with the new {@link OpCode} appended */ public Program with(OpCode opCode) { return this.with(opCode.getByteValue()); } /** * Create a new {@link Program} with a label appended * * @param label {@link String} id of the desired label * @return a new {@link Program} that is a copy of this one with the new label appended */ public Program with(String label){ final Map<String, Integer> newProgramLabels = new HashMap<>(programLabels); newProgramLabels.put(label, programBytes.length); return new Program(this.programBytes, newProgramLabels, references); } public Program with(Reference reference){ int[] newProgramBytes = new int[programBytes.length + 1]; System.arraycopy(programBytes,0, newProgramBytes, 0, programBytes.length); newProgramBytes[newProgramBytes.length-1] = 0b1111111100000000; final List<Reference> newReferences = new ArrayList<>(references); newReferences.add(new Reference(reference.targetLabel, newProgramBytes.length-1)); return new Program(newProgramBytes, this.programLabels, newReferences); } /** * Create a new {@link Program} with new entry appended * * @param value [{@link int} | {@link OpCode} | {@link String}] to append * @return a new {@link Program} that is a copy of this one with the new entry appended */ public Program with(Object value){ //XXX I'd need to abstract away the concept of program-byte in order to make this nicer if (value instanceof OpCode) return this.with((OpCode) value); if (value instanceof String) return this.with((String) value); if (value instanceof Reference) return this.with((Reference) value); return this.with((int)value); } /** * Create a new {@link Program} with new entries appended * * @param values [{@link int} | {@link OpCode} | {@link String}] to append * @return a new {@link Program} that is a copy of this one with the new entries appended */ public Program with(Object ... values){ Program tmpProgram = this; for (Object value : values) { tmpProgram = tmpProgram.with(value); } return tmpProgram; } /** * @return This {@link Program} compiled to a "byte" array. */ public int[] getProgramAsByteArray() { int[] clonedBytes = programBytes.clone(); for (Reference reference : references) { if (programLabels.containsKey(reference.targetLabel)){ int targetAddress = programLabels.get(reference.targetLabel); //XXX Should be a binary subtraction? int relativeAddress = ((targetAddress & 0xFF) - (reference.rootAddress & 0xFF)) & 0xFF; clonedBytes[reference.rootAddress] = relativeAddress; }else{ throw new RuntimeException("Unknown label reference '" + reference.targetLabel + "'"); } } return clonedBytes; } /** * @return The byte length of this {@link Program} */ public int getLength() { return programBytes.length; } /** * @return The list of labels held for this {@link Program} */ public Set<String> getLabels() { return programLabels.keySet(); } /** * @param labelName A {@link String} label representing a location in the program * @return the {@link int} location of this label in the {@link Program} */ public int getLocationOf(String labelName) { return programLabels.get(labelName); } }
package com.syncleus.ferma; import java.util.*; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Predicate; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.gremlin.Tokens.T; import com.tinkerpop.gremlin.java.GremlinPipeline; import com.tinkerpop.pipes.Pipe; import com.tinkerpop.pipes.branch.LoopPipe; import com.tinkerpop.pipes.transform.TransformPipe.Order; import com.tinkerpop.pipes.util.structures.Pair; import com.tinkerpop.pipes.util.structures.Table; import com.tinkerpop.pipes.util.structures.Tree; /** * Vertex specific traversal. This class is abstract and as such is never instantiated directly. * * @param <C> The cap of the current pipe. * @param <S> The SideEffect of the current pipe. * @param <M> The current marked type for the current pipe. */ abstract class AbstractVertexTraversal<C, S, M> extends AbstractTraversal<VertexFrame, C, S, M> implements VertexTraversal<C, S, M> { @Override public VertexFrame next() { return graph().frameElement((Vertex) pipeline().next(), VertexFrame.class); } @Override public VertexFrame nextOrAdd() { return nextOrAdd(VertexFrame.class); } @Override public <N> Iterable<? extends N> frameExplicit(final Class<N> kind) { return Iterables.transform(pipeline(), new Function() { public Object apply(final Object input) { return graph().frameElementExplicit((Element) input, kind); } }); } @Override public VertexTraversal<Table, Table, M> table() { return (VertexTraversal<Table, Table, M>) super.table(); } @Override public VertexTraversal<Table, Table, M> table(final TraversalFunction... columnFunctions) { return (VertexTraversal<Table, Table, M>) super.table(columnFunctions); } @Override public VertexTraversal<Table, Table, M> table(final Table table) { return (VertexTraversal<Table, Table, M>) super.table(table); } @Override public VertexTraversal<Table, Table, M> table(final Table table, final Collection stepNames, final TraversalFunction... columnFunctions) { return (VertexTraversal<Table, Table, M>) super.table(table, stepNames, columnFunctions); } @Override public VertexTraversal<Table, Table, M> table(final Table table, final TraversalFunction<?, ?>... columnFunctions) { return (VertexTraversal) super.table(table, columnFunctions); } @Override public <N> VertexTraversal<Tree<N>, Tree<N>, M> tree(final Tree<N> tree) { return (VertexTraversal) super.tree(tree); } @Override public Traversal<VertexFrame, Collection<? extends VertexFrame>, VertexFrame, M> store() { return super.store(new FramingTraversalFunction(graph(), VertexFrame.class)); } @Override public <N> Traversal<VertexFrame, Collection<? extends N>, N, M> store(final Collection<? super N> storage) { return super.store(storage); } @Override public <N> Traversal<VertexFrame, Collection<? extends N>, N, M> store(final Collection<? super N> storage, final TraversalFunction<VertexFrame, N> storageFunction) { return super.store(storage); } @Override public <N> Traversal<VertexFrame, Collection<? extends N>, N, M> store(final TraversalFunction<VertexFrame, N> storageFunction) { return (VertexTraversal) super.store(storageFunction); } @Override public VertexTraversal<Map<VertexFrame, Long>, Map<VertexFrame, Long>, M> groupCount() { return (VertexTraversal) super.groupCount(); } @Override public VertexTraversal<Map<VertexFrame, Long>, Map<VertexFrame, Long>, M> groupCount(final Map<VertexFrame, Long> map) { return (VertexTraversal<Map<VertexFrame, Long>, Map<VertexFrame, Long>, M>) super.groupCount(map); } @Override public <K> VertexTraversal<Map<K, Long>, Map<K, Long>, M> groupCount(final Map<K, Long> map, final TraversalFunction<VertexFrame, K> keyFunction) { return (VertexTraversal<Map<K, Long>, Map<K, Long>, M>) super.groupCount(map, keyFunction); } @Override public <K> VertexTraversal<Map<K, Long>, Map<K, Long>, M> groupCount(final Map<K, Long> map, final TraversalFunction<VertexFrame, K> keyFunction, final TraversalFunction<Pair<VertexFrame, Long>, Long> valueFunction) { return (VertexTraversal<Map<K, Long>, Map<K, Long>, M>) super.groupCount(map, keyFunction, valueFunction); } @Override public <K> VertexTraversal<Map<K, Long>, Map<K, Long>, M> groupCount(final TraversalFunction<VertexFrame, K> keyFunction) { return (VertexTraversal<Map<K, Long>, Map<K, Long>, M>) super.groupCount(keyFunction); } @Override public <K> VertexTraversal<Map<K, Long>, Map<K, Long>, M> groupCount(final TraversalFunction<VertexFrame, K> keyFunction, final TraversalFunction<Pair<VertexFrame, Long>, Long> valueFunction) { return (VertexTraversal<Map<K, Long>, Map<K, Long>, M>) super.groupCount(keyFunction, valueFunction); } @Override public <K, V, V2> VertexTraversal<Map<K, V2>, Map<K, V2>, M> groupBy(final TraversalFunction<VertexFrame, K> keyFunction, final TraversalFunction<VertexFrame, Iterator<V>> valueFunction, final TraversalFunction<List<V>, V2> reduceFunction) { return (VertexTraversal<Map<K, V2>, Map<K, V2>, M>) super.groupBy(keyFunction, valueFunction, reduceFunction); } @Override public <K, V> VertexTraversal<Map<K, List<V>>, Map<K, List<V>>, M> groupBy(final TraversalFunction<VertexFrame, K> keyFunction, final TraversalFunction<VertexFrame, Iterator<V>> valueFunction) { return (VertexTraversal<Map<K, List<V>>, Map<K, List<V>>, M>) super.groupBy(keyFunction, valueFunction); } @Override public <K, V, V2> VertexTraversal<Map<K, V2>, Map<K, V2>, M> groupBy(final Map<K, V2> reduceMap, final TraversalFunction<VertexFrame, K> keyFunction, final TraversalFunction<VertexFrame, Iterator<V>> valueFunction, final TraversalFunction<List<V>, V2> reduceFunction) { return (VertexTraversal<Map<K, V2>, Map<K, V2>, M>) super.groupBy(reduceMap, keyFunction, valueFunction, reduceFunction); } @Override public <K, V> VertexTraversal<Map<K, List<V>>, Map<K, List<V>>, M> groupBy(final Map<K, List<V>> map, final TraversalFunction<VertexFrame, K> keyFunction, final TraversalFunction<VertexFrame, Iterator<V>> valueFunction) { return (VertexTraversal<Map<K, List<V>>, Map<K, List<V>>, M>) super.groupBy(map, keyFunction, valueFunction); } @Override public VertexTraversal<?, ?, M> filter(final TraversalFunction<VertexFrame, Boolean> filterFunction) { return (VertexTraversal<?, ?, M>) super.filter(filterFunction); } @Override public VertexTraversal<Collection<? extends VertexFrame>, Collection<? extends VertexFrame>, M> aggregate() { return (VertexTraversal<Collection<? extends VertexFrame>, Collection<? extends VertexFrame>, M>) super.aggregate(); } @Override public VertexTraversal<Collection<? extends VertexFrame>, Collection<? extends VertexFrame>, M> aggregate(final Collection<? super VertexFrame> aggregate) { return (VertexTraversal<Collection<? extends VertexFrame>, Collection<? extends VertexFrame>, M>) super.aggregate(aggregate); } @Override public <N> VertexTraversal<Collection<? extends N>, Collection<? extends N>, M> aggregate(final Collection<? super N> aggregate, final TraversalFunction<VertexFrame, ? extends N> aggregateFunction) { return (VertexTraversal<Collection<? extends N>, Collection<? extends N>, M>) super.aggregate(aggregate, aggregateFunction); } @Override public <N> VertexTraversal<Collection<? extends N>, Collection<? extends N>, M> aggregate(final TraversalFunction<VertexFrame, ? extends N> aggregateFunction) { return (VertexTraversal<Collection<? extends N>, Collection<? extends N>, M>) super.aggregate(aggregateFunction); } @Override public VertexTraversal<?, ?, M> sideEffect(final SideEffectFunction<VertexFrame> sideEffectFunction) { return (VertexTraversal<?, ?, M>) super.sideEffect(sideEffectFunction); } @Override public VertexTraversal<?, ?, M> random(final double bias) { return (VertexTraversal<?, ?, M>) super.random(bias); } @Override public VertexTraversal<?, ?, M> dedup(final TraversalFunction<VertexFrame, ?> dedupFunction) { return (VertexTraversal) super.dedup(dedupFunction); } @Override public VertexTraversal<?, ?, M> except(final String... namedSteps) { return (VertexTraversal<?, ?, M>) super.except(namedSteps); } @Override public VertexTraversal<?, ?, M> except(final Iterable<?> collection) { return (VertexTraversal<?, ?, M>) super.except(Lists.newArrayList(collection)); } @Override public VertexTraversal<?, ?, M> range(final int low, final int high) { return (VertexTraversal<?, ?, M>) super.range(low, high); } @Override public VertexTraversal<?, ?, M> and(final TraversalFunction<VertexFrame, Traversal<?, ?, ?, ?>>... traversals) { final Collection<Pipe> extractedPipes = Collections2.transform(Arrays.asList(traversals), new Function<TraversalFunction, Pipe>() { @Override public Pipe apply(final TraversalFunction input) { return ((AbstractTraversal) input.compute(new TVertex())).pipeline(); } }); pipeline().and(extractedPipes.toArray(new Pipe[extractedPipes.size()])); return this; } @Override public VertexTraversal<?, ?, M> or(final TraversalFunction<VertexFrame, Traversal<?, ?, ?, ?>>... traversals) { final Collection<Pipe> extractedPipes = Collections2.transform(Arrays.asList(traversals), new Function<TraversalFunction, Pipe>() { @Override public Pipe apply(final TraversalFunction input) { return ((AbstractTraversal) input.compute(new TVertex())).pipeline(); } }); pipeline().or(extractedPipes.toArray(new Pipe[extractedPipes.size()])); return this; } @Override public VertexTraversal<?, ?, M> order() { return (VertexTraversal<?, ?, M>) super.order(); } @Override public VertexTraversal<?, ?, M> order(final Order order) { return (VertexTraversal<?, ?, M>) super.order(order); } @Override public VertexTraversal<?, ?, M> order(final Comparator<? super VertexFrame> compareFunction) { return (VertexTraversal<?, ?, M>) super.order(compareFunction); } @Override public VertexTraversal<?, ?, M> order(final T order) { return (VertexTraversal<?, ?, M>) super.order(order); } @Override public VertexTraversal<?, ?, M> dedup() { return (VertexTraversal<?, ?, M>) super.dedup(); } @Override public VertexTraversal<?, ?, M> retain(final String... namedSteps) { return (VertexTraversal<?, ?, M>) super.retain(namedSteps); } @Override public VertexTraversal<?, ?, M> simplePath() { return (VertexTraversal<?, ?, M>) super.simplePath(); } @Override public VertexTraversal<?, ?, M> memoize(final String namedStep) { return (VertexTraversal<?, ?, M>) super.memoize(namedStep); } @Override public VertexTraversal<?, ?, M> memoize(final String namedStep, final Map<?, ?> map) { return (VertexTraversal<?, ?, M>) super.memoize(namedStep, map); } @Override public VertexTraversal<?, ?, M> out(final int branchFactor, final String... labels) { pipeline().out(branchFactor, labels); return this; } @Override public VertexTraversal<?, ?, M> out(final String... labels) { pipeline().out(labels); return this; } @Override public VertexTraversal<?, ?, M> in(final int branchFactor, final String... labels) { pipeline().in(branchFactor, labels); return this; } @Override public VertexTraversal<?, ?, M> in(final String... labels) { pipeline().in(labels); return this; } @Override public VertexTraversal<?, ?, M> both(final int branchFactor, final String... labels) { pipeline().both(branchFactor, labels); return this; } @Override public VertexTraversal<?, ?, M> both(final String... labels) { pipeline().both(labels); return this; } @Override public EdgeTraversal<?, ?, M> outE(final int branchFactor, final String... labels) { pipeline().outE(branchFactor, labels); return castToEdges(); } @Override public EdgeTraversal<?, ?, M> outE(final String... labels) { pipeline().outE(labels); return castToEdges(); } @Override public EdgeTraversal<?, ?, M> inE(final int branchFactor, final String... labels) { pipeline().inE(branchFactor, labels); return castToEdges(); } @Override public EdgeTraversal<?, ?, M> inE(final String... labels) { pipeline().inE(labels); return castToEdges(); } @Override public EdgeTraversal<?, ?, M> bothE(final int branchFactor, final String... labels) { pipeline().bothE(branchFactor, labels); return castToEdges(); } @Override public EdgeTraversal<?, ?, M> bothE(final String... labels) { pipeline().bothE(labels); return castToEdges(); } @Override public <Z> VertexTraversal<?, ?, M> interval(final String key, final Comparable<Z> startValue, final Comparable<Z> endValue) { return (VertexTraversal<?, ?, M>) super.interval(key, startValue, endValue); } @Override public <N> N next(final Class<N> kind) { return graph().frameElement((Element) pipeline().next(), kind); } @Override public <N> N nextExplicit(final Class<N> kind) { return graph().frameElementExplicit((Element) pipeline().next(), kind); } @Override public <N> N nextOrDefault(final Class<N> kind, final N defaultValue) { if (pipeline().hasNext()) return next(kind); else return defaultValue; } @Override public <N> N nextOrDefaultExplicit(final Class<N> kind, final N defaultValue) { if (pipeline().hasNext()) return nextExplicit(kind); else return defaultValue; } @Override public <N> N nextOrAdd(final Class<N> kind) { try { return graph().frameElement((Element) pipeline().next(), kind); } catch (final NoSuchElementException e) { return graph().addFramedVertex(kind); } } @Override public <N> N nextOrAddExplicit(final Class<N> kind) { try { return graph().frameElementExplicit((Element) pipeline().next(), kind); } catch (final NoSuchElementException e) { return graph().addFramedVertex(kind); } } @Override public <N> List<? extends N> next(final int amount, final Class<N> kind) { return Lists.transform(pipeline().next(amount), new Function() { public Object apply(final Object input) { return graph().frameElement((Element) input, kind); } }); } @Override public <N> List<? extends N> nextExplicit(final int amount, final Class<N> kind) { return Lists.transform(pipeline().next(amount), new Function() { public Object apply(final Object input) { return graph().frameElementExplicit((Element) input, kind); } }); } @Override public <N> Iterable<N> frame(final Class<N> kind) { return Iterables.transform(pipeline(), new Function() { public Object apply(final Object input) { return graph().frameElement((Element) input, kind); } }); } @Override public <N> List<? extends N> toList(final Class<N> kind) { return Lists.transform(pipeline().toList(), new Function() { public Object apply(final Object input) { return graph().frameElement((Element) input, kind); } }); } @Override public <N> List<? extends N> toListExplicit(final Class<N> kind) { return Lists.transform(pipeline().toList(), new Function() { public Object apply(final Object input) { return graph().frameElementExplicit((Element) input, kind); } }); } @Override public <N> Set<? extends N> toSet(final Class<N> kind) { return Sets.newHashSet(toList(kind)); } @Override public <N> Set<? extends N> toSetExplicit(final Class<N> kind) { return Sets.newHashSet(toListExplicit(kind)); } @Override public List<? extends VertexFrame> toList() { return toListExplicit(VertexFrame.class); } @Override public Set<? extends VertexFrame> toSet() { return toSetExplicit(VertexFrame.class); } @Override public VertexTraversal<?, ?, M> has(final String key) { return (VertexTraversal<?, ?, M>) super.has(key); } @Override public VertexTraversal has(final String key, final Object value) { return (VertexTraversal) super.has(key, value); } @Override public VertexTraversal<?, ?, M> has(final String key, final Predicate predicate, final Object value) { return (VertexTraversal<?, ?, M>) super.has(key, predicate, value); } @Override public VertexTraversal<?, ?, M> has(final String key, final com.tinkerpop.gremlin.Tokens.T compareToken, final Object value) { return (VertexTraversal<?, ?, M>) super.has(key, compareToken, value); } @Override public VertexTraversal<?, ?, M> hasNot(final String key) { return (VertexTraversal<?, ?, M>) super.hasNot(key); } @Override public VertexTraversal<?, ?, M> hasNot(final String key, final Object value) { return (VertexTraversal<?, ?, M>) super.hasNot(key, value); } @Override public VertexTraversal<?, ?, M> as(final String name) { return (VertexTraversal<?, ?, M>) super.as(name); } @Override public VertexTraversal<?, ?, M> identity() { return (VertexTraversal<?, ?, M>) super.identity(); } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkOut(final String label, final String namedStep) { pipeline().linkOut(label, namedStep); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkIn(final String label, final String namedStep) { pipeline().linkIn(label, namedStep); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkBoth(final String label, final String namedStep) { pipeline().linkBoth(label, namedStep); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkOut(final String label, final Vertex other) { pipeline().linkOut(label, other); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkIn(final String label, final Vertex other) { pipeline().linkIn(label, other); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkBoth(final String label, final Vertex other) { pipeline().linkBoth(label, other); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkOut(final String label, final VertexFrame other) { pipeline().linkOut(label, other.getElement()); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkIn(final String label, final VertexFrame other) { pipeline().linkIn(label, other.getElement()); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public VertexTraversal<List<EdgeFrame>, EdgeFrame, M> linkBoth(final String label, final VertexFrame other) { pipeline().linkBoth(label, other.getElement()); return (VertexTraversal<List<EdgeFrame>, EdgeFrame, M>) this; } @Override public <N> Collection<? extends N> fill(final Collection<? super N> collection, final Class<N> kind) { return pipeline().fill(new FramingCollection<>(collection, graph(), kind)); } @Override public <N> Collection<? extends N> fillExplicit(final Collection<? super N> collection, final Class<N> kind) { return pipeline().fill(new FramingCollection<>(collection, graph(), kind, true)); } @Override public VertexTraversal<?, ?, M> gatherScatter() { return (VertexTraversal<?, ?, M>) super.gatherScatter(); } @Override public VertexTraversal<?, ?, M> divert(final SideEffectFunction<S> sideEffectFunction) { return (VertexTraversal<?, ?, M>) super.divert(sideEffectFunction); } @Override public VertexTraversal<?, ?, M> retain(final VertexFrame... vertices) { return (VertexTraversal<?, ?, M>) super.retain(Arrays.asList(vertices)); } @Override public VertexTraversal<?, ?, M> except(final VertexFrame... vertices) { return (VertexTraversal<?, ?, M>) super.except(Arrays.asList(vertices)); } @Override public VertexTraversal<?, ?, M> shuffle() { return (VertexTraversal<?, ?, M>) super.shuffle(); } @Override public VertexTraversal<?, ?, M> retain(final Iterable<?> collection) { return (VertexTraversal<?, ?, M>) super.retain(Lists.newArrayList(collection)); } @Override public VertexTraversal<C, S, ? extends VertexTraversal<C, S, M>> mark() { return (VertexTraversal<C, S, VertexTraversal<C, S, M>>) super.mark(); } @Override public void removeAll() { pipeline().remove(); } @Override public <N> SplitTraversal<? extends Traversal<N, ?, ?, M>> copySplit(final TraversalFunction<VertexFrame, ? extends Traversal<N, ?, ?, ?>>... traversals) { final Collection<Pipe> extractedPipes = Collections2.transform(Arrays.asList(traversals), new Function<TraversalFunction, Pipe>() { @Override public Pipe apply(final TraversalFunction input) { return ((AbstractTraversal) input.compute(new TVertex())).pipeline(); } }); pipeline().copySplit(extractedPipes.toArray(new Pipe[extractedPipes.size()])); return castToSplit(); } @Override public VertexTraversal<Tree<VertexFrame>, Tree<VertexFrame>, M> tree() { return (VertexTraversal<Tree<VertexFrame>, Tree<VertexFrame>, M>) super.tree(); } @Override public VertexTraversal<?, ?, M> loop(final TraversalFunction<VertexFrame, ? extends VertexTraversal<?, ?, ?>> traversal) { final GremlinPipeline pipeline = ((AbstractTraversal) traversal.compute(new TVertex())).pipeline(); pipeline().add(new LoopPipe(pipeline, LoopPipe.createTrueFunction(), null)); return this; } @Override public VertexTraversal<?, ?, M> loop(final TraversalFunction<VertexFrame, ? extends VertexTraversal<?, ?, ?>> traversal, final int depth) { final GremlinPipeline pipeline = ((AbstractTraversal) traversal.compute(new TVertex())).pipeline(); pipeline().add(new LoopPipe(pipeline, LoopPipe.createLoopsFunction(depth), null)); return this; } @Override public VertexTraversal<?, ?, M> limit(final int limit) { return (VertexTraversal) super.limit(limit); } }
package ec.edu.espe.isi.examen.examenprac; /** * * @author sony */ public class Operaciones { private int num1; private int num2; private int resultado; public Operaciones(int num1, int num2) { this.num1 = num1; this.num2 = num2; } public int suma(){ return num1 + num2; } public int resta(){ return num1 - num2; } /** * metodo que devuelve la multiplicacion entre dos numeros * @return multiplicacion */ public int multiplicacion(){ return num1 * num2; } /** * metodo que devuelve la division entre dos numeros * @return division entre numeros */ public int division(){ if (num2<0){ System.out.println("Ingrese denominador positivo"); } return num1 / num2; } /** * metodo que devuelve la potencia n de un numero entero * @return resultado de la potencia */ public int potencia(){ if (num2>0){ resultado = (int) Math.pow(num1, num2); } else{ System.out.println("Ingrese una potencia positiva"); } return resultado; } /** * metodo que devuelve la el mod de dos numeros * @return mod entre numeros */ public int modulo(){ return num1%num2; } }
package com.tterrag.k9.commands; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.io.IOUtils; import com.google.common.base.Charsets; import com.tterrag.k9.K9; import com.tterrag.k9.commands.api.Argument; import com.tterrag.k9.commands.api.Command; import com.tterrag.k9.commands.api.CommandBase; import com.tterrag.k9.commands.api.CommandContext; import com.tterrag.k9.commands.api.CommandException; import com.tterrag.k9.commands.api.Flag; import com.tterrag.k9.util.Requirements; import com.tterrag.k9.util.Requirements.RequiredType; import sx.blah.discord.handle.obj.Permissions; import sx.blah.discord.util.MessageHistory; import sx.blah.discord.util.RequestBuffer; import sx.blah.discord.util.RequestBuffer.IRequest; import sx.blah.discord.util.RequestBuffer.RequestFuture; import sx.blah.discord.util.RequestBuilder; @Command public class CommandInfoChannel extends CommandBase { private static final Flag FLAG_REPLACE = new SimpleFlag('r', "replace", "Replace the current contents of the channel.", false); private static final Argument<String> ARG_URL = new WordArgument("url", "The url to load the content from", true); public CommandInfoChannel() { super("info", false); } @Override public void process(CommandContext ctx) throws CommandException { try { ctx.getChannel().setTypingStatus(true); URL url = new URL(ctx.getArg(ARG_URL)); List<String> lines = IOUtils.readLines(new InputStreamReader(url.openConnection().getInputStream(), Charsets.UTF_8)); RequestBuilder builder = new RequestBuilder(K9.instance).shouldBufferRequests(true).doAction(() -> true); if (ctx.hasFlag(FLAG_REPLACE)) { RequestFuture<MessageHistory> future = RequestBuffer.request((IRequest<MessageHistory>) () -> ctx.getChannel().getFullMessageHistory()); try { MessageHistory history = future.get(30, TimeUnit.SECONDS); if (history.size() > 250) { throw new CommandException("Too many messages in this channel!"); } for (int i = 0; i < history.size(); i++) { final int idx = i; builder.andThen(() -> { history.get(idx).delete(); return true; }); } } catch (TimeoutException e) { throw new CommandException("Sorry, the message history in this channel is too long, or otherwise took too long to load."); } catch (InterruptedException e) { throw new CommandException("Gathering message history was interrupted for an unknown reason."); } } StringBuilder sb = new StringBuilder(); for (String s : lines) { if (s.equals("=>")) { final String msg = sb.toString(); builder.andThen(() -> { // SKIP SANITIZATION ctx.getChannel().sendMessage(msg); return true; }); sb = new StringBuilder(); } else { sb.append(s + "\n"); } } builder.andThen(() -> { ctx.getMessage().delete(); return true; }); builder.execute(); ctx.getChannel().setTypingStatus(false); } catch (IOException e) { throw new CommandException(e); } } @Override public String getDescription() { return "Loads messages in a channel from a URL."; } @Override public Requirements requirements() { return Requirements.builder().with(Permissions.ADMINISTRATOR, RequiredType.ALL_OF).build(); } }
package co.paystack.android.api.service; import java.util.HashMap; import co.paystack.android.api.model.TokenApiResponse; import co.paystack.android.api.model.TransactionApiResponse; import retrofit2.Call; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * ApiService */ public interface ApiService { /** * call for creating token * * @param fields - the fields of postData to send * @return Call - a call that can be executed directly `call.execute()` (synchronous implementation) * or enqueued `call.enqueue(params)` (asynchronous implementation) * @see retrofit2.Call */ @FormUrlEncoded @POST("/bosco/createmobiletoken") Call<TokenApiResponse> createToken(@FieldMap HashMap<String, String> fields); @FormUrlEncoded @POST("/charge/mobile_charge") Call<TransactionApiResponse> charge(@FieldMap HashMap<String, String> fields); @FormUrlEncoded @POST("/charge/validate") Call<TransactionApiResponse> validateCharge(@FieldMap HashMap<String, String> fields); }
package com.wegas.leaderway.persistence; import com.wegas.core.persistence.AbstractEntity; import javax.persistence.*; import javax.xml.bind.annotation.XmlTransient; import org.codehaus.jackson.annotate.JsonBackReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Francois-Xavier Aeberhard <fx@red-agent.com> */ @Entity public class Assignment extends AbstractEntity { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(Assignment.class); @Id @GeneratedValue private Long id; private Long startTime; @ManyToOne @JoinColumn(name = "taskDescriptor_id") private TaskDescriptor taskDescriptor; @Column(name = "taskDescriptor_id", nullable = false, insertable = false, updatable = false) private Long taskDescriptorId; @ManyToOne(optional = false) @JoinColumn(name = "variableinstance_id", nullable = false) @JsonBackReference private ResourceInstance resourceInstance; public Assignment() { } /** * * @param startTime * @param taskDescriptor */ public Assignment(Long startTime, TaskDescriptor taskDescriptor) { this.startTime = startTime; this.taskDescriptor = taskDescriptor; this.taskDescriptorId = taskDescriptor.getId(); } /** * * @param a */ @Override public void merge(AbstractEntity a) { Assignment other = (Assignment) a; this.setTaskDescriptor(other.getTaskDescriptor()); this.setResourceInstance(other.getResourceInstance()); this.setStartTime(other.getStartTime()); this.taskDescriptorId = this.getTaskDescriptor().getId(); } @PostPersist @PostUpdate @PostRemove private void onUpdate() { this.getResourceInstance().onInstanceUpdate(); } @Override public Long getId() { return this.id; } /** * @return the MCQDescriptor */ @XmlTransient @JsonBackReference public ResourceInstance getResourceInstance() { return resourceInstance; } /** * @param resourceInstance */ @JsonBackReference public void setResourceInstance(ResourceInstance resourceInstance) { this.resourceInstance = resourceInstance; } /** * @return the startTime */ public Long getStartTime() { return startTime; } /** * @param startTime the startTime to set */ public void setStartTime(Long startTime) { this.startTime = startTime; } /** * @return the choiceDescriptor */ @XmlTransient public TaskDescriptor getTaskDescriptor() { return taskDescriptor; } /** * @param taskDescriptor */ public void setTaskDescriptor(TaskDescriptor taskDescriptor) { this.taskDescriptor = taskDescriptor; } /** * * @return */ public Long getTaskDescriptorId() { return this.taskDescriptorId; } /** * * @return */ public Long setTaskDescriptorId(long newTaskDescriptorId) { return this.taskDescriptorId = newTaskDescriptorId; } }
package io.permazen.kv.raft; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.util.concurrent.ListenableFuture; import io.permazen.kv.KVDatabase; import io.permazen.kv.KVPair; import io.permazen.kv.KVTransactionException; import io.permazen.kv.KeyRange; import io.permazen.kv.RetryTransactionException; import io.permazen.kv.mvcc.AtomicKVStore; import io.permazen.kv.mvcc.Writes; import io.permazen.kv.raft.msg.AppendRequest; import io.permazen.kv.raft.msg.AppendResponse; import io.permazen.kv.raft.msg.CommitRequest; import io.permazen.kv.raft.msg.CommitResponse; import io.permazen.kv.raft.msg.GrantVote; import io.permazen.kv.raft.msg.InstallSnapshot; import io.permazen.kv.raft.msg.Message; import io.permazen.kv.raft.msg.MessageSwitch; import io.permazen.kv.raft.msg.PingRequest; import io.permazen.kv.raft.msg.PingResponse; import io.permazen.kv.raft.msg.RequestVote; import io.permazen.kv.util.KeyWatchTracker; import io.permazen.util.ByteUtil; import io.permazen.util.CloseableIterator; import io.permazen.util.LongEncoder; import io.permazen.util.ThrowableUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import org.dellroad.stuff.io.ByteBufferInputStream; import org.dellroad.stuff.java.TimedWait; import org.dellroad.stuff.net.Network; import org.dellroad.stuff.net.TCPNetwork; import org.dellroad.stuff.util.LongMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ThreadSafe public class RaftKVDatabase implements KVDatabase { /** * Default minimum election timeout ({@value #DEFAULT_MIN_ELECTION_TIMEOUT}ms). * * @see #setMinElectionTimeout */ public static final int DEFAULT_MIN_ELECTION_TIMEOUT = 750; /** * Default maximum election timeout ({@value #DEFAULT_MAX_ELECTION_TIMEOUT}ms). * * @see #setMaxElectionTimeout */ public static final int DEFAULT_MAX_ELECTION_TIMEOUT = 1000; /** * Default heartbeat timeout ({@value DEFAULT_HEARTBEAT_TIMEOUT}ms). * * @see #setHeartbeatTimeout */ public static final int DEFAULT_HEARTBEAT_TIMEOUT = 200; /** * Default maximum supported outstanding transaction duration ({@value DEFAULT_MAX_TRANSACTION_DURATION}ms). * * @see #setMaxTransactionDuration */ public static final int DEFAULT_MAX_TRANSACTION_DURATION = 5 * 1000; /** * Default maximum supported applied log entry memory usage ({@value DEFAULT_MAX_UNAPPLIED_LOG_MEMORY} bytes). * * @see #setMaxUnappliedLogMemory */ public static final long DEFAULT_MAX_UNAPPLIED_LOG_MEMORY = 100 * 1024 * 1024; // 100MB /** * Default maximum number of unapplied log entries ({@value DEFAULT_MAX_UNAPPLIED_LOG_ENTRIES} bytes). * * @see #setMaxUnappliedLogEntries */ public static final int DEFAULT_MAX_UNAPPLIED_LOG_ENTRIES = 64; /** * Default maximum number of heartbeat intervals a leader will wait for a follower to acknowledge receipt of a log entry. * * @see #setMaxFollowerAckHeartbeats */ public static final int DEFAULT_MAX_FOLLOWER_ACK_HEARTBEATS = 5; /** * Default transaction commit timeout ({@value DEFAULT_COMMIT_TIMEOUT}). * * @see #setCommitTimeout * @see RaftKVTransaction#setTimeout */ public static final int DEFAULT_COMMIT_TIMEOUT = 5000; // 5 seconds /** * Default TCP port ({@value #DEFAULT_TCP_PORT}) used to communicate with peers. */ public static final int DEFAULT_TCP_PORT = 9660; /** * Option key for {@link #createTransaction(Map)}. Value should be a {@link Consistency} instance, * or the {@link Consistency#name name()} thereof. */ public static final String OPTION_CONSISTENCY = "consistency"; /** * Option key for {@link #createTransaction(Map)}. Value should be a Boolean, or else {@code "true"} or {@code "false"}. * * @see RaftKVTransaction#setHighPriority */ public static final String OPTION_HIGH_PRIORITY = "highPriority"; // Internal constants static final int MAX_SNAPSHOT_TRANSMIT_AGE = (int)TimeUnit.SECONDS.toMillis(90); // 90 seconds static final int FOLLOWER_LINGER_HEARTBEATS = 3; // how long to keep updating removed followers static final float MAX_CLOCK_DRIFT = 0.01f; // max clock drift per heartbeat as a percentage ratio static final int MAX_APPLIED_TERMS = 128; // how many already-applied log entry terms to rememeber // File prefixes and suffixes static final String TX_FILE_PREFIX = "tx-"; static final String TEMP_FILE_PREFIX = "temp-"; static final String TEMP_FILE_SUFFIX = ".tmp"; static final Pattern TEMP_FILE_PATTERN = Pattern.compile(".*" + Pattern.quote(TEMP_FILE_SUFFIX)); // Keys for persistent Raft state static final byte[] CLUSTER_ID_KEY = ByteUtil.parse("0001"); static final byte[] CURRENT_TERM_KEY = ByteUtil.parse("0002"); static final byte[] LAST_APPLIED_TERM_KEY = ByteUtil.parse("0003"); static final byte[] LAST_APPLIED_INDEX_KEY = ByteUtil.parse("0004"); static final byte[] LAST_APPLIED_CONFIG_KEY = ByteUtil.parse("0005"); static final byte[] VOTED_FOR_KEY = ByteUtil.parse("0006"); static final byte[] FLIP_FLOP_KEY = ByteUtil.parse("0007"); // Prefix for all state machine key/value keys (we alternate between these to handle snapshot installs) private static final byte[] STATE_MACHINE_PREFIXES = new byte[] { (byte)0x80, (byte)0x81 }; // Logging final Logger log = LoggerFactory.getLogger(this.getClass()); // Configuration state @GuardedBy("this") Network network = new TCPNetwork(DEFAULT_TCP_PORT); @GuardedBy("this") String identity; @GuardedBy("this") int minElectionTimeout = DEFAULT_MIN_ELECTION_TIMEOUT; @GuardedBy("this") int maxElectionTimeout = DEFAULT_MAX_ELECTION_TIMEOUT; @GuardedBy("this") int heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT; @GuardedBy("this") int maxTransactionDuration = DEFAULT_MAX_TRANSACTION_DURATION; @GuardedBy("this") int commitTimeout = DEFAULT_COMMIT_TIMEOUT; @GuardedBy("this") long maxUnappliedLogMemory = DEFAULT_MAX_UNAPPLIED_LOG_MEMORY; @GuardedBy("this") int maxUnappliedLogEntries = DEFAULT_MAX_UNAPPLIED_LOG_ENTRIES; @GuardedBy("this") int maxFollowerAckHeartbeats = DEFAULT_MAX_FOLLOWER_ACK_HEARTBEATS; @GuardedBy("this") int threadPriority = -1; @GuardedBy("this") boolean followerProbingEnabled; @GuardedBy("this") boolean disableSync; @GuardedBy("this") boolean dumpConflicts; @GuardedBy("this") File logDir; // Raft runtime state @GuardedBy("this") Role role; // Raft state: LEADER, FOLLOWER, or CANDIDATE @GuardedBy("this") SecureRandom random; // used to randomize election timeout, etc. @GuardedBy("this") boolean flipflop; // determines which state machine prefix we are using @GuardedBy("this") int clusterId; // cluster ID (zero if unconfigured - usually) @GuardedBy("this") long currentTerm; // current Raft term (zero if unconfigured) @GuardedBy("this") long currentTermStartTime; // timestamp of the start of the current Raft term @GuardedBy("this") long commitIndex; // current Raft commit index (zero if unconfigured) @GuardedBy("this") long keyWatchIndex; // index of last log entry that triggered key watches @GuardedBy("this") long lastAppliedTerm; // key/value store last applied term (zero if unconfigured) @GuardedBy("this") long lastAppliedIndex; // key/value store last applied index (zero if unconfigured) @GuardedBy("this") final long[] appliedTerms = new long[MAX_APPLIED_TERMS]; // terms of log entries already applied to state machine @GuardedBy("this") final ArrayList<LogEntry> raftLog = new ArrayList<>(); // unapplied log entries (empty if unconfigured) @GuardedBy("this") Map<String, String> lastAppliedConfig; // key/value store last applied config (empty if none) @GuardedBy("this") Map<String, String> currentConfig; // most recent cluster config (empty if unconfigured) @GuardedBy("this") Map<String, Integer> protocolVersionMap = new HashMap<>(); // peer message encoding protocol versions // Non-Raft runtime state @GuardedBy("this") AtomicKVStore kv; @GuardedBy("this") FileChannel logDirChannel; // null on Windows - no support for sync'ing directories @GuardedBy("this") String returnAddress; // return address for message currently being processed @GuardedBy("this") IOThread ioThread; // performs background I/O tasks @GuardedBy("this") ScheduledExecutorService serviceExecutor; // does stuff for us asynchronously @GuardedBy("this") final HashSet<String> transmitting = new HashSet<>(); // network addresses whose output queues are not empty @GuardedBy("this") final LongMap<RaftKVTransaction> openTransactions = new LongMap<>(); // transactions open on this instance @GuardedBy("this") final LinkedHashSet<Service> pendingService = new LinkedHashSet<>(); // pending work for serviceExecutor @GuardedBy("this") KeyWatchTracker keyWatchTracker; // instantiated on demand @GuardedBy("this") Timestamp linearizableCommitTimestamp; // time of most recent successful commit of linearizable tx @GuardedBy("this") boolean performingService; // true when serviceExecutor does not need to be woken up @GuardedBy("this") boolean shuttingDown; // prevents new transactions from being created @GuardedBy("this") Throwable lastInternalError; // most recent exception in service executor // High priority transaction RaftKVTransaction highPrioTx; // current high priority transaction, if any // Configuration public synchronized void setKVStore(AtomicKVStore kvstore) { Preconditions.checkState(this.role == null, "already started"); this.kv = kvstore; } public synchronized void setLogDirectory(File directory) { Preconditions.checkState(this.role == null, "already started"); this.logDir = directory; } /** * Get the directory in which uncommitted log entries are stored. * * @return configured log directory */ public synchronized File getLogDirectory() { return this.logDir; } public synchronized void setNetwork(Network network) { Preconditions.checkState(this.role == null, "already started"); this.network = network; } public synchronized void setIdentity(String identity) { Preconditions.checkState(this.role == null, "already started"); this.identity = identity; } /** * Get this node's Raft identity. * * @return the unique identity of this node in its cluster */ public synchronized String getIdentity() { return this.identity; } public synchronized void setMinElectionTimeout(int timeout) { Preconditions.checkArgument(timeout > 0, "timeout <= 0"); Preconditions.checkState(this.role == null, "already started"); this.minElectionTimeout = timeout; } /** * Get the configured minimum election timeout. * * @return minimum election timeout in milliseconds */ public synchronized int getMinElectionTimeout() { return this.minElectionTimeout; } public synchronized void setMaxElectionTimeout(int timeout) { Preconditions.checkArgument(timeout > 0, "timeout <= 0"); Preconditions.checkState(this.role == null, "already started"); this.maxElectionTimeout = timeout; } /** * Get the configured maximum election timeout. * * @return maximum election timeout in milliseconds */ public synchronized int getMaxElectionTimeout() { return this.maxElectionTimeout; } public synchronized void setHeartbeatTimeout(int timeout) { Preconditions.checkArgument(timeout > 0, "timeout <= 0"); Preconditions.checkState(this.role == null, "already started"); this.heartbeatTimeout = timeout; } /** * Get the configured heartbeat timeout. * * @return heartbeat timeout in milliseconds */ public synchronized int getHeartbeatTimeout() { return this.heartbeatTimeout; } public synchronized void setMaxTransactionDuration(int duration) { Preconditions.checkArgument(duration > 0, "duration <= 0"); this.maxTransactionDuration = duration; } /** * Get the configured maximum supported duration for outstanding transactions. * * @return maximum supported duration for outstanding transactions in milliseconds */ public synchronized int getMaxTransactionDuration() { return this.maxTransactionDuration; } public synchronized void setMaxUnappliedLogMemory(long maxUnappliedLogMemory) { Preconditions.checkArgument(maxUnappliedLogMemory > 0, "maxUnappliedLogMemory <= 0"); this.maxUnappliedLogMemory = maxUnappliedLogMemory; } /** * Get the configured maximum allowed memory used for unapplied log entries. * * @return maximum allowed memory usage for cached applied log entries */ public synchronized long getMaxUnappliedLogMemory() { return this.maxUnappliedLogMemory; } public synchronized void setMaxUnappliedLogEntries(int maxUnappliedLogEntries) { Preconditions.checkArgument(maxUnappliedLogEntries > 0, "maxUnappliedLogEntries <= 0"); this.maxUnappliedLogEntries = maxUnappliedLogEntries; } /** * Get the configured maximum number of unapplied log entries. * * @return maximum number of unapplied log entries */ public synchronized long getMaxUnappliedLogEntries() { return this.maxUnappliedLogEntries; } public synchronized void setMaxFollowerAckHeartbeats(int maxFollowerAckHeartbeats) { Preconditions.checkArgument(maxFollowerAckHeartbeats > 0, "maxFollowerAckHeartbeats <= 0"); this.maxFollowerAckHeartbeats = maxFollowerAckHeartbeats; } /** * Get the maximum number of heartbeat intervals a leader will wait for a follower to acknowledge * receipt of a log entry before compacting it. * * @return maximum number of heartbeats for a leader to wait on a follower before compacting a log entry */ public synchronized long getMaxFollowerAckHeartbeats() { return this.maxFollowerAckHeartbeats; } public synchronized void setCommitTimeout(int timeout) { Preconditions.checkArgument(timeout >= 0, "timeout < 0"); this.commitTimeout = timeout; } /** * Get the configured default transaction commit timeout. * * @return transaction commit timeout in milliseconds, or zero for unlimited */ public synchronized int getCommitTimeout() { return this.commitTimeout; } /** * Configure whether followers should be required to probe for network connectivity with a majority of the * cluster after an election timeout prior to becoming a candidate. * * <p> * This value may be changed at any time. * * <p> * The default is enabled. * * @param followerProbingEnabled true to enable, false to disable */ public synchronized void setFollowerProbingEnabled(boolean followerProbingEnabled) { this.followerProbingEnabled = followerProbingEnabled; } /** * Determine whether follower probing prior to becoming a candidate is enabled. * * @return true if follower probing is enabled, otherwise false */ public synchronized boolean isFollowerProbingEnabled() { return this.followerProbingEnabled; } /** * Disable filesystem data sync. * * <p> * This gives higher performance in exchange for losing the guarantee of durability if the system crashes. * Note: this feature is experimental and may violate consistency and/or durability guaratees. * * <p> * Default is false. * * @param disableSync true to disable data sync */ public synchronized void setDisableSync(boolean disableSync) { this.disableSync = disableSync; } /** * Determine whether filesystem sync is disabled. * * @return true if filesystem sync is disabled, otherwise false */ public synchronized boolean isDisableSync() { return this.disableSync; } /** * Enable explicit logging of transaction conflicts. * * <p> * If enabled, when a transaction fails to due to conflicts, the conflicting key ranges are logged. * * <p> * Default is false. * * @param dumpConflicts true to disable data sync */ public synchronized void setDumpConflicts(boolean dumpConflicts) { this.dumpConflicts = dumpConflicts; } /** * Determine whether explicit logging of transaction conflicts is enabled. * * @return true if explicit logging of transaction conflicts is enabled, otherwise false */ public synchronized boolean isDumpConflicts() { return this.dumpConflicts; } public synchronized void setThreadPriority(int threadPriority) { Preconditions.checkArgument(threadPriority == -1 || (threadPriority >= Thread.MIN_PRIORITY && threadPriority <= Thread.MAX_PRIORITY), "invalid threadPriority"); Preconditions.checkState(this.role == null, "already started"); this.threadPriority = threadPriority; } /** * Get the configured internal service thread priority. * * @param internal service thread priority, or -1 if not configured */ public synchronized int getThreadPriority() { return this.threadPriority; } // Status /** * Retrieve the unique 32-bit ID for this node's cluster. * * <p> * A value of zero indicates an unconfigured system. Usually the reverse true, though an unconfigured system * can have a non-zero cluster ID in the rare case where an error occurred persisting the initial log entry. * * @return the unique ID of this node's cluster, or zero if this node is unconfigured */ public synchronized int getClusterId() { return this.clusterId; } /** * Retrieve the current cluster configuration as understood by this node. * * <p> * Configuration changes are performed and committed in the context of a normal transaction; see * {@link RaftKVTransaction#configChange RaftKVTransaction.configChange()}. * * <p> * If this system is unconfigured, an empty map is returned (and vice-versa). * * <p> * The returned map is a copy; changes have no effect on this instance. * * @return current configuration mapping from node identity to network address, * or empty if this node is not started or unconfigured */ public synchronized Map<String, String> getCurrentConfig() { return this.currentConfig != null ? new TreeMap<>(this.currentConfig) : new TreeMap<>(); } /** * Determine whether this instance is configured. * * <p> * A node is configured if and only if it has at least one log entry. The first log entry always * includes a configuration change that adds the node that created it to the (previously empty) cluster. * * @return true if this instance is started and configured, otherwise false */ public synchronized boolean isConfigured() { return this.lastAppliedIndex > 0 || !this.raftLog.isEmpty(); } /** * Determine whether this node thinks that it is part of its cluster, as determined by its * {@linkplain #getCurrentConfig current configuration}. * * @return true if this instance is started and part of the cluster, otherwise false */ public synchronized boolean isClusterMember() { return this.isClusterMember(this.identity); } /** * Determine whether this node thinks that the specified node is part of the cluster, as determined by its * {@linkplain #getCurrentConfig current configuration}. * * @param node node identity * @return true if this instance is started and the specified node is part of the cluster, otherwise false */ public synchronized boolean isClusterMember(String node) { return this.currentConfig != null ? this.currentConfig.containsKey(node) : false; } /** * Get this instance's current role: leadeer, follower, or candidate. * * @return current {@link Role}, or null if not running */ public synchronized Role getCurrentRole() { return this.role; } /** * Get this instance's current term. * * @return current term, or zero if not running */ public synchronized long getCurrentTerm() { return this.currentTerm; } /** * Get the time at which this instance's current term advanced to its current value. * * @return current term's start time in milliseconds since the epoch, or zero if unknown */ public synchronized long getCurrentTermStartTime() { return this.currentTermStartTime; } /** * Get this instance's current commit index.. * * @return current commit index, or zero if not running */ public synchronized long getCommitIndex() { return this.commitIndex; } /** * Get this instance's last applied log entry term. * * @return last applied term, or zero if not running */ public synchronized long getLastAppliedTerm() { return this.lastAppliedTerm; } /** * Get this instance's last applied log entry index. * * @return last applied index, or zero if not running */ public synchronized long getLastAppliedIndex() { return this.lastAppliedIndex; } /** * Get the unapplied {@link LogEntry}s in this instance's Raft log. * * <p> * The returned list is a copy; changes have no effect on this instance. * * @return unapplied log entries; or null if this instance is not running */ public synchronized List<LogEntry> getUnappliedLog() { return this.raftLog != null ? new ArrayList<>(this.raftLog) : null; } /** * Get the estimated total memory used by unapplied log entries. * * @return unapplied log entry memory usage, or zero if this instance is not running */ public synchronized long getUnappliedLogMemoryUsage() { long total = 0; for (LogEntry logEntry : this.raftLog) total += logEntry.getFileSize(); return total; } /** * Get the set of open transactions associated with this database. * * <p> * The returned set is a copy; changes have no effect on this instance. * * @return all open transactions */ public synchronized List<RaftKVTransaction> getOpenTransactions() { final ArrayList<RaftKVTransaction> list; synchronized (this) { list = new ArrayList<>(this.openTransactions.values()); } Collections.sort(list, RaftKVTransaction.SORT_BY_ID); return list; } /** * Get the timestamp of the most recently committed linearizable transaction. * * <p> * This value can be used to confirm that the cluster is healthy. * * @return time of the most recent successful commit of a linearizable transaction, or null if none */ public synchronized Timestamp getLinearizableCommitTimestamp() { if (this.linearizableCommitTimestamp != null && !this.linearizableCommitTimestamp.hasOccurred()) this.linearizableCommitTimestamp = null; // TODO: fix rollover better return this.linearizableCommitTimestamp; } // Lifecycle @Override @PostConstruct public synchronized void start() { // Sanity check assert this.checkState(); if (this.role != null) return; Preconditions.checkState(!this.shuttingDown, "shutdown in progress"); Preconditions.checkState(this.logDir != null, "no Raft log directory configured"); Preconditions.checkState(this.kv != null, "no Raft local persistence key/value store configured"); Preconditions.checkState(this.network != null, "no Raft network configured"); Preconditions.checkState(this.minElectionTimeout <= this.maxElectionTimeout, "minElectionTimeout > maxElectionTimeout"); Preconditions.checkState(this.heartbeatTimeout < this.minElectionTimeout, "heartbeatTimeout >= minElectionTimeout"); Preconditions.checkState(this.identity != null, "no Raft identity configured"); // Log if (this.log.isDebugEnabled()) this.debug("starting " + this.getClass().getName() + " in directory " + this.logDir); // Start up local database boolean success = false; try { // Create/verify log directory if (!this.logDir.exists()) Files.createDirectories(this.logDir.toPath()); if (!this.logDir.isDirectory()) throw new IOException("file `" + this.logDir + "' is not a directory"); // Start k/v store this.kv.start(); // Open directory containing log entry files so we have a way to fsync() it assert this.logDirChannel == null; try { this.logDirChannel = FileChannel.open(this.logDir.toPath()); } catch (IOException e) { if (!this.isWindows()) throw e; } // Create randomizer assert this.random == null; this.random = new SecureRandom(); // Start background I/O thread assert this.ioThread == null; final String ioThreadName = "Raft I/O [" + this.identity + "]"; this.ioThread = new IOThread(this.logDir, ioThreadName); if (this.threadPriority != -1) this.ioThread.setPriority(this.threadPriority); this.ioThread.start(); // Start up service executor thread assert this.serviceExecutor == null; final String serviceThreadName = "Raft Service [" + this.identity + "]"; this.serviceExecutor = Executors.newSingleThreadScheduledExecutor(action -> { final Thread thread = new Thread(action); synchronized (this) { if (this.threadPriority != -1) thread.setPriority(this.threadPriority); } thread.setName(serviceThreadName); return thread; }); // Start network this.network.start(new Network.Handler() { @Override public void handle(String sender, ByteBuffer buf) { RaftKVDatabase.this.handle(sender, buf); } @Override public void outputQueueEmpty(String address) { RaftKVDatabase.this.outputQueueEmpty(address); } }); // Reload persistent raft info this.clusterId = (int)this.decodeLong(CLUSTER_ID_KEY, 0); this.currentTerm = this.decodeLong(CURRENT_TERM_KEY, 0); this.currentTermStartTime = System.currentTimeMillis(); final String votedFor = this.decodeString(VOTED_FOR_KEY, null); this.lastAppliedTerm = this.decodeLong(LAST_APPLIED_TERM_KEY, 0); this.lastAppliedIndex = this.decodeLong(LAST_APPLIED_INDEX_KEY, 0); Arrays.fill(this.appliedTerms, 0); this.lastAppliedConfig = this.decodeConfig(LAST_APPLIED_CONFIG_KEY); this.flipflop = this.decodeBoolean(FLIP_FLOP_KEY); this.currentConfig = this.buildCurrentConfig(); // Reset protocol version info this.protocolVersionMap.clear(); // If we crashed part way through a snapshot install, recover by discarding partial install if (this.discardFlipFloppedStateMachine() && this.log.isDebugEnabled()) this.debug("detected partially applied snapshot install, discarding"); // Initialize commit index and key watch index this.commitIndex = this.lastAppliedIndex; this.keyWatchIndex = this.commitIndex; // Reload outstanding log entries from disk this.loadLog(); // Show recovered state if (this.log.isDebugEnabled()) { this.debug("recovered Raft state:" + "\n clusterId=" + (this.clusterId != 0 ? String.format("0x%08x", this.clusterId) : "none") + "\n currentTerm=" + this.currentTerm + "\n lastApplied=" + this.lastAppliedIndex + "t" + this.lastAppliedTerm + "\n lastAppliedConfig=" + this.lastAppliedConfig + "\n currentConfig=" + this.currentConfig + "\n votedFor=" + (votedFor != null ? "\"" + votedFor + "\"" : "nobody") + "\n log=" + this.raftLog); } // Validate recovered state if (this.isConfigured()) { Preconditions.checkArgument(this.clusterId != 0); Preconditions.checkArgument(this.currentTerm > 0); Preconditions.checkArgument(this.getLastLogTerm() > 0); Preconditions.checkArgument(this.getLastLogIndex() > 0); Preconditions.checkArgument(!this.currentConfig.isEmpty()); } else { Preconditions.checkArgument(this.lastAppliedTerm == 0); Preconditions.checkArgument(this.lastAppliedIndex == 0); Preconditions.checkArgument(this.getLastLogTerm() == 0); Preconditions.checkArgument(this.getLastLogIndex() == 0); Preconditions.checkArgument(this.currentConfig.isEmpty()); Preconditions.checkArgument(this.raftLog.isEmpty()); } // Start as follower (with unknown leader) this.changeRole(new FollowerRole(this, null, null, votedFor)); // Done this.info("successfully started " + this + " in directory " + this.logDir); success = true; } catch (IOException e) { throw new RuntimeException("error starting up database", e); } finally { if (!success) this.cleanup(); } // Sanity check assert this.checkState(); } @Override @PreDestroy public void stop() { // Set flag to prevent new transactions final IOThread ioThreadToShutdown; synchronized (this) { // Sanity check assert this.checkState(); if (this.role == null || this.shuttingDown) return; // Set shutting down flag this.info("starting shutdown of " + this); this.shuttingDown = true; // Fail all remaining open transactions for (RaftKVTransaction tx : new ArrayList<>(this.openTransactions.values())) { switch (tx.getState()) { case EXECUTING: case COMMIT_READY: case COMMIT_WAITING: this.fail(tx, new KVTransactionException(tx, "database shutdown")); break; case COMPLETED: break; default: assert false; break; } } // Sleep while we wait for transactions to clean themselves up try { if (!TimedWait.wait(this, 5000, this.openTransactions::isEmpty)) this.warn("open transactions not cleaned up during shutdown"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // Snapshot field while synchronized ioThreadToShutdown = this.ioThread; } // Shut down the service executor and wait for pending tasks to finish this.serviceExecutor.shutdownNow(); try { this.serviceExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // Shutdown I/O thread ioThreadToShutdown.shutdown(); try { ioThreadToShutdown.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // Final cleanup synchronized (this) { this.serviceExecutor = null; this.ioThread = null; this.cleanup(); } // Done this.info("completed shutdown of " + this); } /** * Get the exception most recently thrown by the internal service thread, if any. * This is used mainly during testing. * * @return most recent service exception, or null if none */ public synchronized Throwable getLastInternalError() { return this.lastInternalError; } private void cleanup() { assert Thread.holdsLock(this); assert this.openTransactions.isEmpty(); if (this.role != null) { this.role.shutdown(); this.role = null; } if (this.serviceExecutor != null) { this.serviceExecutor.shutdownNow(); try { this.serviceExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.serviceExecutor = null; } if (this.ioThread != null) { this.ioThread.shutdown(); try { this.ioThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.ioThread = null; } this.kv.stop(); Util.closeIfPossible(this.logDirChannel); this.logDirChannel = null; this.raftLog.clear(); this.random = null; this.network.stop(); this.currentTerm = 0; this.currentTermStartTime = 0; this.commitIndex = 0; this.keyWatchIndex = 0; this.clusterId = 0; this.lastAppliedTerm = 0; this.lastAppliedIndex = 0; Arrays.fill(this.appliedTerms, 0); this.lastAppliedConfig = null; this.currentConfig = null; this.protocolVersionMap.clear(); if (this.keyWatchTracker != null) { this.keyWatchTracker.close(); this.keyWatchTracker = null; } this.linearizableCommitTimestamp = null; this.transmitting.clear(); this.pendingService.clear(); this.shuttingDown = false; } /** * Initialize our in-memory state from the persistent state reloaded from disk. * This is invoked on initial startup. */ private void loadLog() throws IOException { // Sanity check assert Thread.holdsLock(this); assert this.raftLog.isEmpty(); // Scan for log entry files this.raftLog.clear(); try (DirectoryStream<Path> files = Files.newDirectoryStream(this.logDir.toPath())) { for (Path path : files) { final File file = path.toFile(); // Ignore sub-directories (typically owned by the underlying k/v store) if (file.isDirectory()) continue; // Is this a log entry file? if (LogEntry.LOG_FILE_PATTERN.matcher(file.getName()).matches()) { if (this.log.isDebugEnabled()) this.debug("recovering log file " + file.getName()); final LogEntry logEntry = LogEntry.fromFile(file); this.raftLog.add(logEntry); continue; } // Is this a leftover temporary file? if (TEMP_FILE_PATTERN.matcher(file.getName()).matches()) { if (this.log.isDebugEnabled()) this.debug("deleting leftover temporary file " + file.getName()); this.deleteFile(file, "leftover temporary file"); continue; } // Unknown this.warn("ignoring unrecognized file " + file.getName() + " in my log directory"); } } // Verify we have a contiguous range of log entries starting from the snapshot index; discard bogus log files Collections.sort(this.raftLog, LogEntry.SORT_BY_INDEX); long lastTermSeen = this.lastAppliedTerm; long expectedIndex = this.lastAppliedIndex + 1; for (Iterator<LogEntry> i = this.raftLog.iterator(); i.hasNext(); ) { final LogEntry logEntry = i.next(); String error = null; if (logEntry.getTerm() < lastTermSeen) error = "term " + logEntry.getTerm() + " < last applied term " + lastTermSeen; else if (logEntry.getIndex() < this.lastAppliedIndex) error = "index " + logEntry.getIndex() + " < last applied index " + this.lastAppliedIndex; else if (logEntry.getIndex() != expectedIndex) error = "index " + logEntry.getIndex() + " != expected index " + expectedIndex; if (error != null) { this.warn("deleting bogus log file " + logEntry.getFile().getName() + ": " + error); this.deleteFile(logEntry.getFile(), "bogus log file"); i.remove(); } else { expectedIndex++; lastTermSeen = logEntry.getTerm(); } } if (this.log.isDebugEnabled()) { this.debug("recovered " + this.raftLog.size() + " log entries: " + this.raftLog + " (" + this.getUnappliedLogMemoryUsage() + " total bytes)"); } // Rebuild current configuration this.currentConfig = this.buildCurrentConfig(); } /** * Reconstruct the current config by starting with the last applied config and applying * configuration deltas from unapplied log entries. */ Map<String, String> buildCurrentConfig() { // Start with last applied config final HashMap<String, String> config = new HashMap<>(this.lastAppliedConfig); // Apply any changes found in uncommitted log entries for (LogEntry logEntry : this.raftLog) logEntry.applyConfigChange(config); // Done return config; } // Key Watches synchronized ListenableFuture<Void> watchKey(RaftKVTransaction tx, byte[] key) { Preconditions.checkState(this.role != null, "not started"); tx.verifyExecuting(); if (this.keyWatchTracker == null) this.keyWatchTracker = new KeyWatchTracker(); return this.keyWatchTracker.register(key); } // Transactions @Override public RaftKVTransaction createTransaction() { return this.createTransaction(Consistency.LINEARIZABLE); } @Override public RaftKVTransaction createTransaction(Map<String, ?> options) { // Any options? if (options == null) return this.createTransaction(Consistency.LINEARIZABLE); // Look for options from the PermazenTransactionManager Consistency consistency = null; Object isolation = options.get("org.springframework.transaction.annotation.Isolation"); if (isolation instanceof Enum) isolation = ((Enum<?>)isolation).name(); if (isolation != null) { switch (isolation.toString()) { case "READ_UNCOMMITTED": consistency = Consistency.UNCOMMITTED; break; case "READ_COMMITTED": consistency = Consistency.EVENTUAL_COMMITTED; break; case "REPEATABLE_READ": consistency = Consistency.EVENTUAL; break; case "SERIALIZABLE": consistency = Consistency.LINEARIZABLE; break; default: break; } } // Look for OPTION_CONSISTENCY option try { final Object value = options.get(OPTION_CONSISTENCY); if (value instanceof Consistency) consistency = (Consistency)value; else if (value instanceof String) consistency = Consistency.valueOf((String)value); } catch (Exception e) { // ignore } // Look for OPTION_HIGH_PRIORITY option boolean highPriority = false; final Object value = options.get(OPTION_HIGH_PRIORITY); if (value instanceof Boolean) highPriority = (Boolean)value; else if (value instanceof String) highPriority = Boolean.valueOf((String)value); // Configure consistency level return this.createTransaction(consistency != null ? consistency : Consistency.LINEARIZABLE, highPriority); } public RaftKVTransaction createTransaction(Consistency consistency) { return this.createTransaction(consistency, false); } public synchronized RaftKVTransaction createTransaction(Consistency consistency, boolean highPriority) { // Sanity check assert this.checkState(); Preconditions.checkState(consistency != null, "null consistency"); Preconditions.checkState(this.role != null, "not started"); Preconditions.checkState(!this.shuttingDown, "shutting down"); // Base transaction on the most recent log entry (if !committed). This is itself a form of optimistic locking: we assume // that the most recent log entry has a high probability of being committed (in the Raft sense), which is of course // required in order to commit any transaction based on it. final MostRecentView view = new MostRecentView(this, consistency.isBasedOnCommittedLogEntry() ? this.commitIndex : -1); final long baseTerm = view.getTerm(); final long baseIndex = view.getIndex(); // Create transaction final RaftKVTransaction tx = new RaftKVTransaction(this, consistency, baseTerm, baseIndex, view.getSnapshot(), view.getView()); tx.setTimeout(this.commitTimeout); this.openTransactions.put(tx.txId, tx); // Set commit term+index if already known switch (consistency) { case UNCOMMITTED: tx.setCommittable(); break; case EVENTUAL_COMMITTED: tx.setCommitInfo(baseTerm, baseIndex, null); tx.setCommittable(); break; case EVENTUAL: tx.setCommitInfo(baseTerm, baseIndex, null); this.role.checkCommittable(tx); break; case LINEARIZABLE: break; default: assert false; break; } // Set high priority if (highPriority) tx.setHighPriority(true); // Done if (this.log.isDebugEnabled()) this.debug("created new transaction " + tx); return tx; } /** * Make a transaction the high priority transaction on this node. */ synchronized boolean setHighPriority(RaftKVTransaction tx, boolean highPriority) { // Demoting? That's easy. if (!highPriority) { if (tx == this.highPrioTx) this.highPrioTx = null; return true; } // Check transaction consistency if (!tx.getConsistency().equals(Consistency.LINEARIZABLE)) return false; // Check transaction state switch (tx.getState()) { case EXECUTING: case COMMIT_READY: case COMMIT_WAITING: break; default: return false; } // Make transaction special if (this.log.isDebugEnabled()) { if (this.highPrioTx != null) this.log.debug("setting high priority transaction {} (replacing {})", tx, this.highPrioTx); else this.log.debug("setting new high priority transaction {}", tx); } this.highPrioTx = tx; // Try to become leader if we're currently a follower and some other leader is established if (this.role instanceof FollowerRole) { final FollowerRole followerRole = (FollowerRole)this.role; if (followerRole.getLeaderIdentity() != null && followerRole.electionTimer.isRunning() && !followerRole.electionTimer.getDeadline().hasOccurred()) { if (this.log.isDebugEnabled()) this.log.debug("starting early election on behalf of high priority transaction {}", tx); followerRole.startElection(); } } // Done return true; } /** * Commit a transaction. */ void commit(final RaftKVTransaction tx) { try { // Mark transaction as "commit ready" - service thread will do the rest synchronized (this) { // Sanity check assert this.checkState(); assert this.role != null; // Check tx state switch (tx.getState()) { case EXECUTING: // Transition to COMMIT_READY state if (this.log.isDebugEnabled()) this.debug("committing transaction " + tx); tx.setState(TxState.COMMIT_READY); this.requestService(new CheckReadyTransactionService(this.role, tx)); // From this point on, throw a StaleTransactionException if accessed, instead of retry exception or whatever tx.setFailure(null); // Setup commit timer if (tx.getTimeout() != 0) { final Timer commitTimer = new Timer(this, "commit timer for " + tx, new Service("commit timeout for tx#" + tx.txId) { @Override public void run() { switch (tx.getState()) { case COMMIT_READY: case COMMIT_WAITING: RaftKVDatabase.this.fail(tx, new RetryTransactionException(tx, "transaction failed to complete within " + tx.getTimeout() + "ms (in state " + tx.getState() + ")")); break; default: break; } } }); commitTimer.timeoutAfter(tx.getTimeout()); tx.setCommitTimer(commitTimer); } break; case CLOSED: // this transaction has already been committed or rolled back try { tx.verifyExecuting(); // always throws some kind of exception } finally { tx.setFailure(null); // from now on, throw StaleTransactionException if accessed } assert false; return; default: // another thread is already doing the commit this.warn("simultaneous commit()'s requested for " + tx + " by two different threads"); break; } } // Wait for completion try { tx.getCommitFuture().get(); } catch (InterruptedException e) { throw new KVTransactionException(tx, "thread interrupted while waiting for commit", e); } catch (ExecutionException e) { final Throwable cause = e.getCause(); ThrowableUtil.prependCurrentStackTrace(cause); Throwables.throwIfUnchecked(cause); throw new KVTransactionException(tx, "commit failed", cause); // should never get here } } finally { this.cleanupTransaction(tx); } } /** * Rollback a transaction. */ synchronized void rollback(RaftKVTransaction tx) { // Sanity check assert this.checkState(); assert this.role != null; // From this point on, throw a StaleTransactionException if accessed, instead of retry exception or whatever tx.setFailure(null); // Check tx state switch (tx.getState()) { case EXECUTING: if (this.log.isDebugEnabled()) this.debug("rolling back transaction " + tx); this.cleanupTransaction(tx); break; case CLOSED: break; default: // another thread is currently committing! this.warn("simultaneous commit() and rollback() requested for " + tx + " by two different threads"); break; } } // Clean up transaction and transition to state CLOSED. It's OK to invoke this more than once. synchronized void cleanupTransaction(RaftKVTransaction tx) { // Debug if (this.log.isTraceEnabled()) this.trace("cleaning up transaction " + tx); // Do any per-role cleanups if (this.role != null) this.role.cleanupForTransaction(tx); // Cancel commit timer if (tx.getCommitTimer() != null) tx.getCommitTimer().cancel(); // Remove from open transactions set this.openTransactions.remove(tx.txId); // Transition to CLOSED tx.setState(TxState.CLOSED); tx.setNoLongerRebasable(); // Notify waiting thread if doing shutdown if (this.shuttingDown) this.notify(); } // Mark a transaction as having succeeded; it must be in COMMIT_READY or COMMIT_WAITING void succeed(RaftKVTransaction tx) { // Sanity check assert Thread.holdsLock(this); assert this.role != null; assert tx.getState().equals(TxState.COMMIT_READY) || tx.getState().equals(TxState.COMMIT_WAITING); // Succeed transaction if (this.log.isDebugEnabled()) this.debug("successfully committed " + tx); tx.getCommitFuture().set(null); tx.setState(TxState.COMPLETED); tx.setNoLongerRebasable(); if (tx.getConsistency().isGuaranteesUpToDateReads()) this.linearizableCommitTimestamp = new Timestamp(); this.role.cleanupForTransaction(tx); } // Mark a transaction as having failed void fail(RaftKVTransaction tx, KVTransactionException e) { // Sanity check assert Thread.holdsLock(this); assert this.role != null; assert e != null; // Fail transaction if (this.log.isDebugEnabled()) this.debug("failing transaction " + tx + ": " + e); switch (tx.getState()) { case EXECUTING: assert tx.getFailure() == null; tx.setFailure(e); this.cleanupTransaction(tx); break; case COMMIT_READY: case COMMIT_WAITING: tx.getCommitFuture().setException(e); tx.setState(TxState.COMPLETED); tx.setNoLongerRebasable(); this.role.cleanupForTransaction(tx); break; default: // too late, nobody cares return; } } // Service /** * Request service to be invoked after the current service (if any) completes. * * <p> * If {@code service} has an associated {@link Role}, and that {@link Role} is no longer active * when the service is handled, nothing will be done. * * @param service the service to perform */ void requestService(Service service) { assert Thread.holdsLock(this); assert service != null; if (!this.pendingService.add(service) || this.performingService) return; try { this.serviceExecutor.submit(() -> { try { this.handlePendingService(); } catch (Throwable t) { RaftKVDatabase.this.error("exception in handlePendingService()", t); this.lastInternalError = t; } }); } catch (RejectedExecutionException e) { if (!this.shuttingDown) { this.warn("service executor task rejected, skipping", e); this.lastInternalError = e; } } } // Performs pending service requests (do not invoke directly) private synchronized void handlePendingService() { // Sanity check assert this.checkState(); if (this.role == null) return; // While there is work to do, do it this.performingService = true; try { while (!this.pendingService.isEmpty()) { final Iterator<Service> i = this.pendingService.iterator(); final Service service = i.next(); i.remove(); assert service != null; assert service.getRole() == null || service.getRole() == this.role; if (this.log.isTraceEnabled()) this.trace("SERVICE [" + service + "] in " + this.role); try { service.run(); } catch (Throwable t) { RaftKVDatabase.this.error("exception in " + service, t); this.lastInternalError = t; } } } finally { this.performingService = false; } } // Raft state /** * Discard all key/value pairs in the "flip-flopped" state machine, i.e., the one that we are not currently using. * * @return true if there was anything to remove, otherwise false */ boolean discardFlipFloppedStateMachine() { final byte[] dirtyPrefix = this.getFlipFloppedStateMachinePrefix(); final boolean dirty; try (final CloseableIterator<KVPair> i = this.kv.getRange(KeyRange.forPrefix(dirtyPrefix))) { dirty = i.hasNext(); } if (dirty) this.kv.removeRange(dirtyPrefix, ByteUtil.getKeyAfterPrefix(dirtyPrefix)); return dirty; } /** * Perform a state machine flip-flop operation. Normally this would happen after a successful snapshot install. */ boolean flipFlopStateMachine(long term, long index, Map<String, String> config) { // Sanity check assert Thread.holdsLock(this); assert term >= 0; assert index >= 0; if (this.log.isDebugEnabled()) this.debug("performing state machine flip-flop to " + index + "t" + term + " with config " + config); if (config == null) config = new HashMap<>(0); // Prepare updates final Writes writes = new Writes(); writes.getPuts().put(LAST_APPLIED_TERM_KEY, LongEncoder.encode(term)); writes.getPuts().put(LAST_APPLIED_INDEX_KEY, LongEncoder.encode(index)); writes.getPuts().put(LAST_APPLIED_CONFIG_KEY, this.encodeConfig(config)); writes.getPuts().put(FLIP_FLOP_KEY, this.encodeBoolean(!this.flipflop)); // Update persistent store try { this.kv.mutate(writes, true); } catch (Exception e) { this.error("flip-flop error updating key/value store term/index to " + index + "t" + term, e); return false; } // Delete all unapplied log files (no longer applicable) this.raftLog.clear(); try (DirectoryStream<Path> files = Files.newDirectoryStream(this.logDir.toPath())) { for (Path path : files) { final File file = path.toFile(); if (LogEntry.LOG_FILE_PATTERN.matcher(file.getName()).matches()) this.deleteFile(file, "unapplied log file"); } } catch (IOException e) { this.error("error deleting unapplied log files in " + this.logDir + " (ignoring)", e); } // Update in-memory copy of persistent state this.flipflop = !this.flipflop; this.lastAppliedTerm = term; this.lastAppliedIndex = index; Arrays.fill(this.appliedTerms, 0); this.lastAppliedConfig = config; this.commitIndex = this.lastAppliedIndex; final TreeMap<String, String> previousConfig = new TreeMap<>(this.currentConfig); this.currentConfig = this.buildCurrentConfig(); if (!this.currentConfig.equals(previousConfig)) this.info("apply new cluster configuration after snapshot install: " + this.currentConfig); // Discard the flip-flopped state machine this.discardFlipFloppedStateMachine(); // Trigger key watches this.requestService(this.role.triggerKeyWatchesService); // Done return true; } /** * Update and persist a new current term. */ boolean advanceTerm(long newTerm) { // Sanity check assert Thread.holdsLock(this); assert newTerm > this.currentTerm; if (this.log.isDebugEnabled()) this.debug("advancing current term from " + this.currentTerm + " -> " + newTerm); // Update persistent store final Writes writes = new Writes(); writes.getPuts().put(CURRENT_TERM_KEY, LongEncoder.encode(newTerm)); writes.getRemoves().add(new KeyRange(VOTED_FOR_KEY)); try { this.kv.mutate(writes, true); } catch (Exception e) { this.error("error persisting new term " + newTerm, e); return false; } // Update in-memory copy this.currentTerm = newTerm; this.currentTermStartTime = System.currentTimeMillis(); return true; } boolean joinCluster(int newClusterId) { // Sanity check assert Thread.holdsLock(this); Preconditions.checkArgument(newClusterId != 0); Preconditions.checkState(this.clusterId == 0); // Persist it this.info("joining cluster with ID " + String.format("0x%08x", newClusterId)); final Writes writes = new Writes(); writes.getPuts().put(CLUSTER_ID_KEY, LongEncoder.encode(newClusterId)); try { this.kv.mutate(writes, true); } catch (Exception e) { this.error("error updating key/value store with new cluster ID", e); return false; } // Done this.clusterId = newClusterId; return true; } /** * Get the prefix for state machine we are currently using. */ byte[] getStateMachinePrefix() { return this.getStateMachinePrefix(false); } /** * Get the prefix for the flip-flopped state machine. */ byte[] getFlipFloppedStateMachinePrefix() { return this.getStateMachinePrefix(true); } private byte[] getStateMachinePrefix(boolean flipFlopped) { return new byte[] { STATE_MACHINE_PREFIXES[flipFlopped ^ this.flipflop ? 1 : 0] }; } /** * Set the Raft role. * * @param role new role */ void changeRole(Role role) { // Sanity check assert Thread.holdsLock(this); assert role != null; // Shutdown previous role (if any) if (this.role != null) { this.role.shutdown(); for (Iterator<Service> i = this.pendingService.iterator(); i.hasNext(); ) { final Service service = i.next(); if (service.getRole() != null) i.remove(); } } // Setup new role this.role = role; this.role.setup(); if (this.log.isDebugEnabled()) this.debug("changing role to " + role); // Check state assert this.checkState(); } /** * Append a log entry to the Raft log. * * @param term new log entry term * @param entry entry to add; the {@linkplain NewLogEntry#getTempFile temporary file} must be already durably persisted, * and will be renamed * @return new {@link LogEntry} * @throws Exception if an error occurs */ LogEntry appendLogEntry(long term, NewLogEntry newLogEntry) throws Exception { // Sanity check assert Thread.holdsLock(this); assert this.role != null; assert newLogEntry != null; // Get file length final LogEntry.Data data = newLogEntry.getData(); final File tempFile = newLogEntry.getTempFile(); final long fileLength = Util.getLength(tempFile); // Create new log entry final LogEntry logEntry = new LogEntry(term, this.getLastLogIndex() + 1, this.logDir, data, fileLength); if (this.log.isDebugEnabled()) this.debug("adding new log entry " + logEntry + " using " + tempFile.getName()); // Atomically rename file and fsync() directory to durably persist Files.move(tempFile.toPath(), logEntry.getFile().toPath(), StandardCopyOption.ATOMIC_MOVE); if (this.logDirChannel != null && !this.disableSync) this.logDirChannel.force(true); // Temp file no longer exists, so don't try to delete it later newLogEntry.resetTempFile(); // Add new log entry to in-memory log this.raftLog.add(logEntry); // Update current config if (logEntry.applyConfigChange(this.currentConfig)) this.info("applying new cluster configuration from log entry " + logEntry + ": " + this.currentConfig); // Done return logEntry; } long getLastLogIndex() { assert Thread.holdsLock(this); return this.lastAppliedIndex + this.raftLog.size(); } long getLastLogTerm() { assert Thread.holdsLock(this); return this.getLogTermAtIndex(this.getLastLogIndex()); } // Get the term of the not-yet-applied log entry at the specified index long getLogTermAtIndex(long index) { assert Thread.holdsLock(this); assert index >= this.lastAppliedIndex; assert index <= this.getLastLogIndex(); return index == this.lastAppliedIndex ? this.lastAppliedTerm : this.getLogEntryAtIndex(index).getTerm(); } // Get the not-yet-applied log entry at the specified index LogEntry getLogEntryAtIndex(long index) { assert Thread.holdsLock(this); assert index > this.lastAppliedIndex; assert index <= this.getLastLogIndex(); return this.raftLog.get((int)(index - this.lastAppliedIndex - 1)); } // Increment the index of the last applied log entry void incrementLastAppliedIndex(long term) { assert Thread.holdsLock(this); this.appliedTerms[(int)(this.lastAppliedIndex % MAX_APPLIED_TERMS)] = this.lastAppliedTerm; this.lastAppliedIndex++; this.lastAppliedTerm = term; } // Get the term of an already-applied log entry, if known, otherwise zero long getAppliedLogEntryTerm(long index) { assert index < this.lastAppliedIndex; if (index < this.lastAppliedIndex - MAX_APPLIED_TERMS) return 0; return this.appliedTerms[(int)(index % MAX_APPLIED_TERMS)]; } // Get the term of a log entry (either applied or not-yet-applied), if known, otherwise zero long getLogTermAtIndexIfKnown(long index) { return index >= this.lastAppliedIndex ? this.getLogTermAtIndex(index) : this.getAppliedLogEntryTerm(index); } // Object @Override public synchronized String toString() { return this.getClass().getSimpleName() + "[identity=" + (this.identity != null ? "\"" + this.identity + "\"" : null) + ",logDir=" + this.logDir + ",term=" + this.currentTerm + ",commitIndex=" + this.commitIndex + ",lastApplied=" + this.lastAppliedIndex + "t" + this.lastAppliedTerm + ",raftLog=" + this.raftLog + ",role=" + this.role + (this.shuttingDown ? ",shuttingDown" : "") + "]"; } // Network.Handler and Messaging private void handle(String sender, ByteBuffer buf) { // Decode message final int protocolVersion; final Message msg; try { protocolVersion = Message.decodeProtocolVersion(buf); msg = Message.decode(buf, protocolVersion); } catch (IllegalArgumentException e) { this.error("rec'd bogus message from " + sender + ", ignoring", e); return; } // If message contains serialized mutation data, at some point we are going to need to write that data to a log entry file. // Instead of doing that (slow) operation while holding the lock, do it now, before we acquire the lock. ByteBuffer mutationData = msg instanceof AppendRequest ? ((AppendRequest)msg).getMutationData() : msg instanceof CommitRequest ? ((CommitRequest)msg).getMutationData() : null; final NewLogEntry newLogEntry; if (mutationData != null) { File tempFile = null; try { // Write serialized mutation data into temporary file tempFile = this.getTempFile(); try (FileWriter output = new FileWriter(tempFile, this.disableSync)) { final FileChannel channel = output.getFileOutputStream().getChannel(); for (ByteBuffer writeBuf = mutationData.asReadOnlyBuffer(); writeBuf.hasRemaining(); ) channel.write(writeBuf); } // Deserialize mutation data and create new log entry instance try (ByteBufferInputStream input = new ByteBufferInputStream(mutationData)) { newLogEntry = new NewLogEntry(LogEntry.readData(input), tempFile); } // Indicate success tempFile = null; } catch (IOException e) { this.error("error persisting mutations from " + msg + ", ignoring", e); return; } finally { if (tempFile != null) this.deleteFile(tempFile, "new log entry temp file"); } } else newLogEntry = null; // Handle message try { this.receiveMessage(sender, msg, protocolVersion, newLogEntry); } finally { if (newLogEntry != null) newLogEntry.cleanup(this); } } private synchronized void outputQueueEmpty(String address) { // Sanity check assert this.checkState(); // Update transmitting status if (!this.transmitting.remove(address)) return; if (this.log.isTraceEnabled()) this.trace("QUEUE_EMPTY address " + address + " in " + this.role); // Notify role if (this.role == null) return; this.role.outputQueueEmpty(address); } boolean isTransmitting(String address) { return this.transmitting.contains(address); } // Messages synchronized boolean sendMessage(Message msg) { // Sanity check assert Thread.holdsLock(this); // Get peer's address; if unknown, use the return address of the message being processed (if any) final String peer = msg.getRecipientId(); String address = this.currentConfig.get(peer); if (address == null) address = this.returnAddress; if (address == null) { this.warn("can't send " + msg + " to unknown peer \"" + peer + "\""); return false; } // Determine protocol version to use final int protocolVersion = this.protocolVersionMap.getOrDefault(peer, Message.getCurrentProtocolVersion()); // Encode messagse if (this.log.isTraceEnabled()) this.trace("XMIT " + msg + " to " + address + " (version " + protocolVersion + ")"); final ByteBuffer encodedMessage; try { encodedMessage = msg.encode(protocolVersion); } catch (IllegalArgumentException e) { // can happen if peer running older code this.warn("can't send " + msg + " to peer \"" + peer + "\": " + e, e); return false; } // Send message if (this.network.send(address, encodedMessage)) { this.transmitting.add(address); return true; } // Transmit failed this.warn("transmit of " + msg + " to \"" + peer + "\" failed locally"); return false; } synchronized void receiveMessage(String address, Message msg, int protocolVersion, final NewLogEntry newLogEntry) { // Sanity check newLogEntry assert newLogEntry == null || (msg instanceof AppendRequest || msg instanceof CommitRequest); // Sanity check assert Thread.holdsLock(this); assert this.checkState(); if (this.role == null) { if (this.log.isDebugEnabled()) this.debug("rec'd " + msg + " rec'd in shutdown state; ignoring"); return; } // Sanity check cluster ID if (msg.getClusterId() == 0) { this.warn("rec'd " + msg + " with zero cluster ID from " + address + "; ignoring"); return; } if (this.clusterId != 0 && msg.getClusterId() != this.clusterId) { this.warn("rec'd " + msg + " with foreign cluster ID " + String.format("0x%08x", msg.getClusterId()) + " != " + String.format("0x%08x", this.clusterId) + "; ignoring"); return; } // Sanity check sender final String peer = msg.getSenderId(); if (peer.equals(this.identity)) { this.warn("rec'd " + msg + " from myself (\"" + peer + "\", address " + address + "); ignoring"); return; } // Sanity check recipient final String dest = msg.getRecipientId(); if (!dest.equals(this.identity)) { this.warn("rec'd misdirected " + msg + " intended for \"" + dest + "\" from " + address + "; ignoring"); return; } // Update sender's protocol version if (protocolVersion != -1) { final Integer previousVersion = this.protocolVersionMap.put(peer, protocolVersion); if (!((Integer)protocolVersion).equals(previousVersion) && this.log.isDebugEnabled()) this.debug("set protocol encoding version for peer \"" + peer + "\" to " + protocolVersion); } // Is my term too low? If so update and revert to follower if (msg.getTerm() > this.currentTerm) { // First check with current role; in some special cases we ignore this if (!this.role.mayAdvanceCurrentTerm(msg)) { if (this.log.isTraceEnabled()) { this.trace("rec'd " + msg + " with term " + msg.getTerm() + " > " + this.currentTerm + " from \"" + peer + "\" but current role says to ignore it"); } return; } // Revert to follower if (this.log.isDebugEnabled()) { this.debug("rec'd " + msg.getClass().getSimpleName() + " with term " + msg.getTerm() + " > " + this.currentTerm + " from \"" + peer + "\", updating term and " + (this.role instanceof FollowerRole ? "remaining a" : "reverting to") + " follower"); } if (!this.advanceTerm(msg.getTerm())) return; this.changeRole(msg.isLeaderMessage() ? new FollowerRole(this, peer, address) : new FollowerRole(this)); } // Is sender's term too low? Ignore it (except ping request) if (msg.getTerm() < this.currentTerm && !(msg instanceof PingRequest)) { if (this.log.isDebugEnabled()) { this.debug("rec'd " + msg + " with term " + msg.getTerm() + " < " + this.currentTerm + " from \"" + peer + "\" at " + address + ", ignoring"); } return; } // Debug if (this.log.isTraceEnabled()) this.trace("RECV " + msg + " in " + this.role + " from " + address + " (protocol version " + protocolVersion + ")"); // Handle message this.returnAddress = address; try { msg.visit(new MessageSwitch() { @Override public void caseAppendRequest(AppendRequest msg) { RaftKVDatabase.this.role.caseAppendRequest(msg, newLogEntry); } @Override public void caseAppendResponse(AppendResponse msg) { RaftKVDatabase.this.role.caseAppendResponse(msg); } @Override public void caseCommitRequest(CommitRequest msg) { RaftKVDatabase.this.role.caseCommitRequest(msg, newLogEntry); } @Override public void caseCommitResponse(CommitResponse msg) { RaftKVDatabase.this.role.caseCommitResponse(msg); } @Override public void caseGrantVote(GrantVote msg) { RaftKVDatabase.this.role.caseGrantVote(msg); } @Override public void caseInstallSnapshot(InstallSnapshot msg) { RaftKVDatabase.this.role.caseInstallSnapshot(msg); } @Override public void casePingRequest(PingRequest msg) { RaftKVDatabase.this.role.casePingRequest(msg); } @Override public void casePingResponse(PingResponse msg) { RaftKVDatabase.this.role.casePingResponse(msg); } @Override public void caseRequestVote(RequestVote msg) { RaftKVDatabase.this.role.caseRequestVote(msg); } }); } finally { this.returnAddress = null; } } // I/O Thread synchronized void deleteFile(File file, String description) { if (this.ioThread == null) { // should never happen Util.delete(file, description); return; } this.ioThread.deleteFile(file, description); } synchronized File getTempFile() throws IOException { if (this.ioThread == null) throw new IOException("instance is shutdown"); return this.ioThread.getTempFile(); } private static final class IOThread extends Thread { private static final long MAX_WAIT_SECONDS = 1; private static final int MAX_TEMP_FILES = 10; private static final int MAX_DELETE_FILES = 1000; private final Logger log = LoggerFactory.getLogger(this.getClass()); private final File tempDir; private final ArrayBlockingQueue<FileInfo> availableTempFiles = new ArrayBlockingQueue<>(MAX_TEMP_FILES); private final ArrayBlockingQueue<FileInfo> filesToDelete = new ArrayBlockingQueue<>(MAX_DELETE_FILES); private boolean shutdown; private boolean didWarnDelete; private boolean didWarnTempFile; private IOThread(File tempDir, String threadName) { super(threadName); Preconditions.checkArgument(tempDir != null); this.tempDir = tempDir; } public synchronized void shutdown() { this.shutdown = true; this.notifyAll(); } public synchronized void deleteFile(File file, String description) { assert file != null; assert description != null; try { this.filesToDelete.add(new FileInfo(file, description)); } catch (IllegalStateException e) { if (!this.didWarnDelete) { this.log.error("file deletion queue is full (suppressing further warnings)", e); this.didWarnDelete = true; } Util.delete(file, description); return; } this.notifyAll(); } public synchronized File getTempFile() throws IOException { final FileInfo fileInfo; try { fileInfo = this.availableTempFiles.remove(); } catch (NoSuchElementException e) { return File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX, this.tempDir); } this.notifyAll(); return fileInfo.getFile(); } @Override public void run() { try { while (true) { // Sleep until there's something to do synchronized (this) { // Wait for something to do while (!this.shutdown && this.filesToDelete.isEmpty() && this.availableTempFiles.remainingCapacity() == 0) { try { this.wait(); } catch (InterruptedException e) { this.log.warn(this + " interrupted, ignoring", e); } } // Shutdown, if needed if (this.shutdown) break; } // Delete deletable files, if any if (!this.filesToDelete.isEmpty()) this.deleteFiles(this.filesToDelete, true); // Create a new temporary file, if needed if (this.availableTempFiles.remainingCapacity() > 0) { try { this.availableTempFiles.add(new FileInfo( File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX, this.tempDir), "ready temporary file")); } catch (IOException e) { if (!this.didWarnTempFile) { this.log.error("error creating temporary file in " + this.tempDir + " (suppressing further warnings)", e); this.didWarnTempFile = true; } } } } } catch (ThreadDeath t) { throw t; } catch (Throwable t) { this.log.error("error in " + this + ", bailing out", t); } finally { this.cleanup(); } } private void cleanup() { this.deleteFiles(this.availableTempFiles, false); this.deleteFiles(this.filesToDelete, true); } private void deleteFiles(ArrayBlockingQueue<FileInfo> queue, boolean warn) { while (true) { // Get next file final FileInfo fileInfo; try { fileInfo = queue.remove(); } catch (NoSuchElementException e) { break; } // Delete file Util.delete(fileInfo.getFile(), warn ? fileInfo.getDescription() : null); } } } private static class FileInfo { private final File file; private final String description; FileInfo(File file) { this(file, null); } FileInfo(File file, String description) { Preconditions.checkArgument(file != null); this.file = file; this.description = description; } public File getFile() { return this.file; } public String getDescription() { return this.description; } } // Utility methods byte[] encodeBoolean(boolean value) { return new byte[] { value ? (byte)1 : (byte)0 }; } boolean decodeBoolean(byte[] key) throws IOException { final byte[] value = this.kv.get(key); return value != null && value.length > 0 && value[0] != 0; } long decodeLong(byte[] key, long defaultValue) throws IOException { final byte[] value = this.kv.get(key); if (value == null) return defaultValue; try { return LongEncoder.decode(value); } catch (IllegalArgumentException e) { throw new IOException("can't interpret encoded long value " + ByteUtil.toString(value) + " under key " + ByteUtil.toString(key), e); } } String decodeString(byte[] key, String defaultValue) throws IOException { final byte[] value = this.kv.get(key); if (value == null) return defaultValue; final DataInputStream input = new DataInputStream(new ByteArrayInputStream(value)); try { return input.readUTF(); } catch (IOException e) { throw new IOException("can't interpret encoded string value " + ByteUtil.toString(value) + " under key " + ByteUtil.toString(key), e); } } byte[] encodeString(String value) { final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final DataOutputStream output = new DataOutputStream(buf); try { output.writeUTF(value); output.flush(); } catch (IOException e) { throw new RuntimeException("unexpected error", e); } return buf.toByteArray(); } Map<String, String> decodeConfig(byte[] key) throws IOException { final Map<String, String> config = new HashMap<>(); final byte[] value = this.kv.get(key); if (value == null) return config; try { final DataInputStream data = new DataInputStream(new ByteArrayInputStream(value)); while (true) { data.mark(1); if (data.read() == -1) break; data.reset(); config.put(data.readUTF(), data.readUTF()); } } catch (IOException e) { throw new IOException("can't interpret encoded config " + ByteUtil.toString(value) + " under key " + ByteUtil.toString(key), e); } return config; } byte[] encodeConfig(Map<String, String> config) { final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final DataOutputStream data = new DataOutputStream(buf); try { for (Map.Entry<String, String> entry : config.entrySet()) { data.writeUTF(entry.getKey()); data.writeUTF(entry.getValue()); } data.flush(); } catch (IOException e) { throw new RuntimeException("unexpected error", e); } return buf.toByteArray(); } // Logging void trace(String msg, Throwable t) { this.log.trace(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } void trace(String msg) { this.log.trace(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } void debug(String msg, Throwable t) { this.log.debug(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } void debug(String msg) { this.log.debug(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } void info(String msg, Throwable t) { this.log.info(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } void info(String msg) { this.log.info(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } void warn(String msg, Throwable t) { this.log.warn(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } void warn(String msg) { this.log.warn(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } void error(String msg, Throwable t) { this.log.error(String.format("%s %s: %s", new Timestamp(), this.identity, msg), t); } void error(String msg) { this.log.error(String.format("%s %s: %s", new Timestamp(), this.identity, msg)); } // Debug/Sanity Checking private boolean checkState() { try { this.doCheckState(); } catch (AssertionError e) { throw new AssertionError("checkState() failure for " + this, e); } return true; } private void doCheckState() { assert Thread.holdsLock(this); // Handle stopped state if (this.role == null) { assert this.random == null; assert this.currentTerm == 0; assert this.currentTermStartTime == 0; assert this.commitIndex == 0; assert this.lastAppliedTerm == 0; assert this.lastAppliedIndex == 0; assert this.lastAppliedConfig == null; assert this.currentConfig == null; assert this.clusterId == 0; assert this.raftLog.isEmpty(); assert this.logDirChannel == null; assert this.serviceExecutor == null; assert this.keyWatchTracker == null; assert this.linearizableCommitTimestamp == null; assert this.transmitting.isEmpty(); assert this.openTransactions.isEmpty(); assert this.highPrioTx == null; assert this.pendingService.isEmpty(); assert !this.shuttingDown; return; } // Handle running state assert this.kv != null; assert this.random != null; assert this.serviceExecutor != null; assert this.logDirChannel != null || this.isWindows(); assert !this.serviceExecutor.isShutdown() || this.shuttingDown; assert this.currentTerm >= 0; assert this.commitIndex >= 0; assert this.lastAppliedTerm >= 0; assert this.lastAppliedIndex >= 0; assert this.lastAppliedConfig != null; assert this.currentConfig != null; assert this.currentTerm >= this.lastAppliedTerm; assert this.commitIndex >= this.lastAppliedIndex; assert this.commitIndex <= this.lastAppliedIndex + this.raftLog.size(); assert this.keyWatchIndex <= this.commitIndex; long index = this.lastAppliedIndex; long term = this.lastAppliedTerm; for (LogEntry logEntry : this.raftLog) { assert logEntry.getIndex() == index + 1; assert logEntry.getTerm() >= term; index = logEntry.getIndex(); term = logEntry.getTerm(); } // Check configured vs. unconfigured if (this.isConfigured()) { assert this.clusterId != 0; assert this.currentTerm > 0; assert this.lastAppliedTerm >= 0; assert this.lastAppliedIndex >= 0; assert !this.currentConfig.isEmpty(); assert this.currentConfig.equals(this.buildCurrentConfig()); assert this.getLastLogTerm() > 0; assert this.getLastLogIndex() > 0; } else { assert this.lastAppliedTerm == 0; assert this.lastAppliedIndex == 0; assert this.lastAppliedConfig.isEmpty(); assert this.currentConfig.isEmpty(); assert this.raftLog.isEmpty(); } // Check role assert this.role.checkState(); // Check transactions assert this.highPrioTx == null || this.openTransactions.containsKey(this.highPrioTx.txId); assert this.highPrioTx == null || this.highPrioTx.getState().compareTo(TxState.COMPLETED) < 0; for (RaftKVTransaction tx : this.openTransactions.values()) { try { assert !tx.getState().equals(TxState.CLOSED); tx.checkStateOpen(this.currentTerm, this.getLastLogIndex(), this.commitIndex); this.role.checkTransaction(tx); } catch (AssertionError e) { throw new AssertionError("checkState() failure for " + tx, e); } } } private boolean isWindows() { return System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH).contains("win"); } }
package com.xorlev.gatekeeper.manager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; /** * cat /opt/nginx/logs/nginx.pid | sudo xargs -I{} kill -HUP {} * * @author Michael Rose <elementation@gmail.com> */ public class NginxManager { private static final Logger log = LoggerFactory.getLogger(NginxManager.class); public static int reloadNginx(String filename) throws FileNotFoundException { return reloadNginx(new PidReader(filename).getPid()); } public static int reloadNginx(int pid) { log.info("Sending HUP to NGINX on {}", pid); try { int code = new ProcessBuilder().command( "sudo", "kill", "-HUP", Integer.toString(pid) ).start().waitFor(); log.info("HUP returned with {}", code); return code; } catch (Exception e) { log.error("Error attempting to restart NGINX: " + e.getMessage(), e); return 1; } } public static void main(String[] args) throws IOException { NginxManager.reloadNginx(31935); } }
package edu.sdsc.scigraph.annotation; import javax.xml.bind.annotation.XmlRootElement; /*** * Represents an annotated section of text */ @XmlRootElement(name = "annotation") public final class EntityAnnotation extends Token<Entity> implements Comparable<EntityAnnotation> { protected EntityAnnotation() { this(null, 0, 0); } public EntityAnnotation(Entity entity, int start, int end) { super(entity, start, end); } public int length() { return getEnd() - getStart(); } /*** * @param annotation * @return true if annotation contains or overlaps this */ public boolean intersects(EntityAnnotation annotation) { return range.isConnected(annotation.range); } @Override public int compareTo(EntityAnnotation o) { if (range.equals(o.range)) return 0; else if (getEnd() > o.getEnd()) return 1; else if (getEnd() < o.getEnd()) return -1; else if (getStart() < o.getStart()) return 1; else return -1; } }
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; 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") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png").getImage()); } else { frame = new JFrame("ATACS"); 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"); 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"); 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(); 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_R, ShortCutKey)); importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey)); importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, ShortCutKey)); importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ShortCutKey)); importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, 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); 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_R); importDot.setMnemonic(KeyEvent.VK_E); importDot.setDisplayedMnemonicIndex(14); importSbml.setMnemonic(KeyEvent.VK_B); importVhdl.setMnemonic(KeyEvent.VK_H); importLhpn.setMnemonic(KeyEvent.VK_N); 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); 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.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(); 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 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); 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 (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(); verPane.add(new Verification(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(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 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); 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 -lxodds " + 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 -lsodds " + 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) { // TODO Auto-generated catch block e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "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(".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")) { 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 cn.cerc.mis.core; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import cn.cerc.core.IHandle; import cn.cerc.db.core.IAppConfig; import cn.cerc.db.core.ServerConfig; import cn.cerc.mis.config.IAppStaticFile; import cn.cerc.mis.other.BufferType; import cn.cerc.mis.other.MemoryBuffer; import cn.cerc.mis.page.JspPage; import cn.cerc.mis.page.RedirectPage; import lombok.extern.slf4j.Slf4j; @Slf4j public class StartForms implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String uri = req.getRequestURI(); int prefix = uri.indexOf("/", 2); if (prefix < 0) { IAppConfig conf = Application.getAppConfig(); resp.sendRedirect(String.format("/public/%s", conf.getFormWelcome())); return; } IAppStaticFile staticFile = Application.getBean(IAppStaticFile.class, "appStaticFile", "appStaticFileDefault"); if (staticFile.isStaticFile(uri)) { // TODO jar if (uri.contains("imgZoom")) { chain.doFilter(req, resp); return; } /* * 1 getPathForms forms AppConfig * 2 3/ /131001/images/systeminstall-pc.png -> * /forms/images/systeminstall-pc.png */ log.info("before {}", uri); IAppConfig conf = Application.getAppConfig(); String source = "/" + conf.getPathForms() + uri.substring(uri.indexOf("/", 2)); request.getServletContext().getRequestDispatcher(source).forward(request, response); log.info("after {}", source); return; } if (uri.contains("service/")) { chain.doFilter(req, resp); return; } if (uri.contains("task/")) { chain.doFilter(req, resp); return; } if (uri.contains("docs/")) { chain.doFilter(req, resp); return; } // 2Url String childCode = getRequestCode(req); if (childCode == null) { outputErrorPage(req, resp, new RuntimeException("" + req.getServletPath())); return; } String[] params = childCode.split("\\."); String formId = params[0]; String funcCode = params.length == 1 ? "execute" : params[1]; // TODO ??? req.setAttribute("logon", false); // TODO ??? IFormFilter formFilter = Application.getBean(IFormFilter.class, "AppFormFilter"); if (formFilter != null) { if (formFilter.doFilter(resp, formId, funcCode)) { return; } } try { IForm form = Application.getForm(req, resp, formId); if (form == null) { outputErrorPage(req, resp, new RuntimeException("error servlet:" + req.getServletPath())); return; } ClientDevice info = new ClientDevice(); info.setRequest(req); req.setAttribute("_showMenu_", !ClientDevice.device_ee.equals(info.getDevice())); form.setClient(info); IHandle handle = Application.getHandle(); try { handle.setProperty(Application.sessionId, req.getSession().getId()); handle.setProperty(Application.deviceLanguage, info.getLanguage()); req.setAttribute("myappHandle", handle); form.setHandle(handle); log.debug(""); if (!form.logon()) { IAppLogin page = Application.getBean(IAppLogin.class, "appLogin", "appLoginManage", "appLoginDefault"); page.init(form); String cmd = page.checkToken(info.getSid()); if (cmd != null) { if (cmd.startsWith("redirect:")) { resp.sendRedirect(cmd.substring(9)); } else { String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(), cmd); request.getServletContext().getRequestDispatcher(url).forward(request, response); } } else callForm(form, funcCode); } else { callForm(form, funcCode); } } catch (Exception e) { outputErrorPage(req, resp, e); } finally { if (handle != null) { handle.close(); } } } catch (Exception e) { outputErrorPage(req, resp, e); } } private void outputErrorPage(HttpServletRequest request, HttpServletResponse response, Throwable e) throws ServletException, IOException { Throwable err = e.getCause(); if (err == null) { err = e; } IAppErrorPage errorPage = Application.getBean(IAppErrorPage.class, "appErrorPage", "appErrorPageDefault"); if (errorPage != null) { String result = errorPage.getErrorPage(request, response, err); if (result != null) { String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(), result); request.getServletContext().getRequestDispatcher(url).forward(request, response); } } else { log.warn("not define bean: errorPage"); log.error(err.getMessage()); err.printStackTrace(); } } protected IAppConfig createConfig() { return Application.getAppConfig(); } protected boolean checkEnableTime() { // Calendar cal = Calendar.getInstance(); // if (TDate.Today().compareTo(TDate.Today().monthEof()) == 0) { // if (cal.get(Calendar.HOUR_OF_DAY) >= 23) // throw new // RuntimeException("235"); // if (TDate.Today().compareTo(TDate.Today().monthBof()) == 0) // if (cal.get(Calendar.HOUR_OF_DAY) < 5) // throw new // RuntimeException("235"); return true; } protected boolean passDevice(IForm form) { // iPhone if (isExperienceAccount(form)) { return true; } String deviceId = form.getClient().getId(); // TODO String verifyCode = form.getRequest().getParameter("verifyCode"); log.debug(String.format(", deviceId=%s", deviceId)); String userId = (String) form.getHandle().getProperty(Application.userId); try (MemoryBuffer buff = new MemoryBuffer(BufferType.getSessionInfo, userId, deviceId)) { if (!buff.isNull()) { if (buff.getBoolean("VerifyMachine")) { log.debug(""); return true; } } boolean result = false; LocalService app = new LocalService(form.getHandle()); app.setService("SvrUserLogin.verifyMachine"); app.getDataIn().getHead().setField("deviceId", deviceId); if (verifyCode != null && !"".equals(verifyCode)) app.getDataIn().getHead().setField("verifyCode", verifyCode); if (app.exec()) result = true; else { int used = app.getDataOut().getHead().getInt("Used_"); if (used == 1) result = true; else form.setParam("message", app.getMessage()); } if (result) buff.setField("VerifyMachine", true); return result; } } protected void callForm(IForm form, String funcCode) throws ServletException, IOException { HttpServletResponse response = form.getResponse(); HttpServletRequest request = form.getRequest(); if ("excel".equals(funcCode)) { response.setContentType("application/vnd.ms-excel; charset=UTF-8"); response.addHeader("Content-Disposition", "attachment; filename=excel.csv"); } else response.setContentType("text/html;charset=UTF-8"); Object pageOutput = ""; String sid = request.getParameter(RequestData.appSession_Key); if (sid == null || sid.equals("")) sid = request.getSession().getId(); Method method = null; long startTime = System.currentTimeMillis(); try { String CLIENTVER = request.getParameter("CLIENTVER"); if (CLIENTVER != null) request.getSession().setAttribute("CLIENTVER", CLIENTVER); if (!Application.getPassport(form.getHandle()).passForm(form)) { log.warn(String.format(" %s", request.getRequestURL())); throw new RuntimeException(""); } if (isExperienceAccount(form)) { try { if (form.getClient().isPhone()) { try { method = form.getClass().getMethod(funcCode + "_phone"); } catch (NoSuchMethodException e) { method = form.getClass().getMethod(funcCode); } } else method = form.getClass().getMethod(funcCode); pageOutput = method.invoke(form); } catch (PageException e) { form.setParam("message", e.getMessage()); pageOutput = e.getViewFile(); } } else { if (form.getHandle().getProperty(Application.userId) == null || form.passDevice() || passDevice(form)) { try { if (form.getClient().isPhone()) { try { method = form.getClass().getMethod(funcCode + "_phone"); } catch (NoSuchMethodException e) { method = form.getClass().getMethod(funcCode); } } else { method = form.getClass().getMethod(funcCode); } pageOutput = method.invoke(form); } catch (PageException e) { form.setParam("message", e.getMessage()); pageOutput = e.getViewFile(); } } else { log.debug(""); ServerConfig config = ServerConfig.getInstance(); String supCorpNo = config.getProperty("vine.mall.supCorpNo", ""); // APPiPhoneiPhone if (!"".equals(supCorpNo) && form.getClient().getDevice().equals(ClientDevice.device_iphone)) { try { method = form.getClass().getMethod(funcCode + "_phone"); } catch (NoSuchMethodException e) { method = form.getClass().getMethod(funcCode); } form.getRequest().setAttribute("needVerify", "true"); pageOutput = method.invoke(form); } else { pageOutput = new RedirectPage(form, Application.getAppConfig().getFormVerifyDevice()); } } } if (pageOutput != null) { if (pageOutput instanceof IPage) { IPage output = (IPage) pageOutput; String cmd = output.execute(); if (cmd != null) { if (cmd.startsWith("redirect:")) response.sendRedirect(cmd.substring(9)); else { String url = String.format("/WEB-INF/%s/%s", Application.getAppConfig().getPathForms(), cmd); request.getServletContext().getRequestDispatcher(url).forward(request, response); } } } else { log.warn(String.format("%s pageOutput is not IPage: %s", funcCode, pageOutput)); JspPage output = new JspPage(form); output.setJspFile((String) pageOutput); output.execute(); } } } catch (Exception e) { outputErrorPage(request, response, e); } finally { if (method != null) { long timeout = 1000; Webpage webpage = method.getAnnotation(Webpage.class); if (webpage != null) timeout = webpage.timeout(); checkTimeout(form, funcCode, startTime, timeout); } } } protected void checkTimeout(IForm form, String funcCode, long startTime, long timeout) { long totalTime = System.currentTimeMillis() - startTime; if (totalTime > timeout) { String tmp[] = form.getClass().getName().split("\\."); String pageCode = tmp[tmp.length - 1] + "." + funcCode; String dataIn = new Gson().toJson(form.getRequest().getParameterMap()); if (dataIn.length() > 200) dataIn = dataIn.substring(0, 200); log.warn(String.format("pageCode:%s, tickCount:%s, dataIn: %s", pageCode, totalTime, dataIn)); } } protected String getRequestCode(HttpServletRequest req) { String url = null; log.info("servletPath {}", req.getServletPath()); String args[] = req.getServletPath().split("/"); if (args.length == 2 || args.length == 3) { if ("".equals(args[0]) && !"".equals(args[1])) { if (args.length == 3) url = args[2]; else { String sid = (String) req.getAttribute(RequestData.appSession_Key); IAppConfig conf = Application.getAppConfig(); if (sid != null && !"".equals(sid)) url = conf.getFormDefault(); else url = conf.getFormWelcome(); } } } return url; } protected boolean isExperienceAccount(IForm form) { return getIphoneAppstoreAccount().equals(form.getHandle().getUserCode()) || getBaseVerAccount().equals(form.getHandle().getUserCode()) || getLineWinderAccount().equals(form.getHandle().getUserCode()) || getTaiWanAccount().equals(form.getHandle().getUserCode()); } // iPhone protected String getIphoneAppstoreAccount() { return "15202406"; } protected String getBaseVerAccount() { return "16307405"; } // APPiPhone protected String getSimagoAccount() { return "47583201"; } // APPiPhone protected String getLineWinderAccount() { return "15531101"; } protected String getTaiWanAccount() { return "47598601"; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
package com.yammer.metrics.reporting; import org.apache.http.entity.ContentType; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import static org.apache.http.client.fluent.Request.*; public class HttpTransport implements Transport { private final String seriesUrl; public HttpTransport(String apiKey) { this.seriesUrl = String.format("https://app.datadoghq.com/api/v1/series?api_key=%s", apiKey); } public Request prepare() throws IOException { return new HttpRequest(this); } public static class HttpRequest implements Transport.Request { private final HttpTransport transport; private final ByteArrayOutputStream out; public HttpRequest(HttpTransport transport) throws IOException { this.transport = transport; this.out = new ByteArrayOutputStream(); } public OutputStream getBodyWriter() { return out; } public void send() throws Exception { this.out.flush(); this.out.close(); Post(this.transport.seriesUrl) .useExpectContinue() .bodyString(out.toString("UTF-8"), ContentType.APPLICATION_JSON) .execute() .discardContent(); } } }
// Connect SDK Sample App by LG Electronics // To the extent possible under law, the person who associated CC0 with // to the sample app. package com.connectsdk.sampler.fragments; import java.io.InputStream; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.connectsdk.core.MediaInfo; import com.connectsdk.device.ConnectableDevice; import com.connectsdk.sampler.R; import com.connectsdk.service.capability.MediaControl; import com.connectsdk.service.capability.MediaControl.DurationListener; import com.connectsdk.service.capability.MediaControl.PlayStateListener; import com.connectsdk.service.capability.MediaControl.PlayStateStatus; import com.connectsdk.service.capability.MediaControl.PositionListener; import com.connectsdk.service.capability.MediaPlayer; import com.connectsdk.service.capability.MediaPlayer.MediaInfoListener; import com.connectsdk.service.capability.MediaPlayer.MediaLaunchObject; import com.connectsdk.service.capability.VolumeControl; import com.connectsdk.service.capability.VolumeControl.VolumeListener; import com.connectsdk.service.capability.listeners.ResponseListener; import com.connectsdk.service.command.ServiceCommandError; import com.connectsdk.service.sessions.LaunchSession; public class MediaPlayerFragment extends BaseFragment { public Button photoButton; public Button videoButton; public Button audioButton; public Button playButton; public Button pauseButton; public Button stopButton; public Button rewindButton; public Button fastForwardButton; public Button closeButton; public Button mediaInfoButton; public static LaunchSession launchSession; public TextView positionTextView; public TextView durationTextView; public TextView mediaInfoTextView; public SeekBar mSeekBar; public boolean mIsUserSeeking; public SeekBar mVolumeBar; public ImageView mediaInfoImageView; public boolean mSeeking; public Runnable mRefreshRunnable; public static final int REFRESH_INTERVAL_MS = (int) TimeUnit.SECONDS.toMillis(1); public Handler mHandler; public long totalTimeDuration; public boolean mIsGettingPlayPosition; static boolean isPlayingImage = false; static boolean isPlaying = false; private MediaControl mMediaControl = null; private Timer refreshTimer; public MediaPlayerFragment() {}; public MediaPlayerFragment(Context context) { super(context); mIsUserSeeking = false; mSeeking = false; mIsGettingPlayPosition = false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setRetainInstance(true); View rootView = inflater.inflate( R.layout.fragment_media_player, container, false); photoButton = (Button) rootView.findViewById(R.id.photoButton); videoButton = (Button) rootView.findViewById(R.id.videoButton); audioButton = (Button) rootView.findViewById(R.id.audioButton); playButton = (Button) rootView.findViewById(R.id.playButton); pauseButton = (Button) rootView.findViewById(R.id.pauseButton); stopButton = (Button) rootView.findViewById(R.id.stopButton); rewindButton = (Button) rootView.findViewById(R.id.rewindButton); fastForwardButton = (Button) rootView.findViewById(R.id.fastForwardButton); closeButton = (Button) rootView.findViewById(R.id.closeButton); mediaInfoButton = (Button) rootView.findViewById(R.id.mediaInfo_button); positionTextView = (TextView) rootView.findViewById(R.id.stream_position); durationTextView = (TextView) rootView.findViewById(R.id.stream_duration); mediaInfoTextView = (TextView) rootView.findViewById(R.id.mediaInfo_textView); mSeekBar = (SeekBar) rootView.findViewById(R.id.stream_seek_bar); mVolumeBar = (SeekBar) rootView.findViewById(R.id.volume_seek_bar); mediaInfoImageView = (ImageView) rootView.findViewById(R.id.mediaInfo_imageView); buttons = new Button[] { photoButton, videoButton, audioButton, playButton, pauseButton, stopButton, rewindButton, fastForwardButton, closeButton, mediaInfoButton }; mHandler = new Handler(); return rootView; } @Override public void setTv(ConnectableDevice tv) { super.setTv(tv); if (tv == null) { stopUpdating(); mMediaControl = null; } } @Override public void onResume() { super.onResume(); if (isPlaying) { startUpdating(); } } @Override public void onPause() { stopUpdating(); super.onPause(); } @Override public void enableButtons() { if ( getTv().hasCapability(MediaPlayer.Display_Image) ) { photoButton.setEnabled(true); photoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (launchSession != null) { launchSession.close(null); launchSession = null; closeButton.setEnabled(false); closeButton.setOnClickListener(null); stopUpdating(); isPlaying = isPlayingImage = false; } disableMedia(); String imagePath = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/photo.jpg"; String mimeType = "image/jpeg"; String title = "Sintel Character Design"; String description = "Blender Open Movie Project"; String icon = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/photoIcon.jpg"; getMediaPlayer().displayImage(imagePath, mimeType, title, description, icon, new MediaPlayer.LaunchListener() { @Override public void onSuccess(MediaLaunchObject object) { launchSession = object.launchSession; closeButton.setEnabled(true); closeButton.setOnClickListener(closeListener); stopUpdating(); isPlayingImage = true; disconnectWebAppSession(); } @Override public void onError(ServiceCommandError error) { Log.e("Error", error.getMessage()); } }); } }); } else { disableButton(photoButton); } totalTimeDuration = -1; if ( getTv().hasCapability(MediaPlayer.Display_Video) ) { videoButton.setEnabled(true); videoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (launchSession != null) { launchSession.close(null); launchSession = null; stopUpdating(); disableMedia(); isPlaying = isPlayingImage = false; } String videoPath = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/video.mp4"; String mimeType = "video/mp4"; String title = "Sintel Trailer"; String description = "Blender Open Movie Project"; String icon = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/videoIcon.jpg"; getMediaPlayer().playMedia(videoPath, mimeType, title, description, icon, false, new MediaPlayer.LaunchListener() { public void onSuccess(MediaLaunchObject object) { launchSession = object.launchSession; mMediaControl = object.mediaControl; stopUpdating(); enableMedia(); isPlaying = true; disconnectWebAppSession(); } @Override public void onError(ServiceCommandError error) { } }); } }); } else { disableButton(videoButton); } if (getTv().hasCapability(MediaPlayer.Display_Audio)) { audioButton.setEnabled(true); audioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (launchSession != null) { launchSession.close(null); launchSession = null; stopUpdating(); disableMedia(); isPlaying = isPlayingImage = false; } String mediaURL = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/audio.mp3"; String iconURL = "http://ec2-54-201-108-205.us-west-2.compute.amazonaws.com/samples/media/audioIcon.jpg"; String title = "The Song that Doesn't End"; String description = "Lamb Chop's Play Along"; String mimeType = "audio/mp3"; boolean shouldLoop = false; getMediaPlayer().playMedia(mediaURL, mimeType, title, description, iconURL, shouldLoop, new MediaPlayer.LaunchListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "Error playing audio"); } @Override public void onSuccess(MediaLaunchObject object) { Log.d("LG", "Started playing audio"); launchSession = object.launchSession; mMediaControl = object.mediaControl; stopUpdating(); enableMedia(); isPlaying = true; disconnectWebAppSession(); } }); } }); } else { disableButton(audioButton); } mVolumeBar.setEnabled(getTv().hasCapability(VolumeControl.Volume_Set)); mVolumeBar.setOnSeekBarChangeListener(volumeListener); if (getTv().hasCapability(VolumeControl.Volume_Get)) { getVolumeControl().getVolume(getVolumeListener); } if (getTv().hasCapability(VolumeControl.Volume_Subscribe)) { getVolumeControl().subscribeVolume(getVolumeListener); } if (getTv().hasCapability(MediaPlayer.MediaInfo_Get)) { mediaInfoButton.setEnabled(true); mediaInfoButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getMediaPlayer().getMediaInfo(mediaInfoListener); } }); } else mediaInfoButton.setEnabled(false); if (getTv().hasCapability(MediaPlayer.MediaInfo_Subscribe)) { getMediaPlayer().subscribeMediaInfo(mediaInfoListener); } if (!isPlaying || !isPlayingImage) disableMedia(); if (isPlaying) enableMedia(); else if (isPlayingImage) { closeButton.setEnabled(true); closeButton.setOnClickListener(closeListener); stopUpdating(); } } @Override public void disableButtons() { mSeekBar.setEnabled(false); mVolumeBar.setEnabled(false); mVolumeBar.setOnSeekBarChangeListener(null); positionTextView.setEnabled(false); durationTextView.setEnabled(false); mediaInfoTextView.setText(""); mediaInfoImageView.setImageBitmap(null); super.disableButtons(); } protected void onSeekBarMoved(long position) { if (mMediaControl != null && getTv().hasCapability(MediaControl.Seek)) { mSeeking = true; mMediaControl.seek(position, new ResponseListener<Object>() { @Override public void onSuccess(Object response) { Log.d("LG", "Success on Seeking"); mSeeking = false; startUpdating(); } @Override public void onError(ServiceCommandError error) { Log.w("Connect SDK", "Unable to seek: " + error.getCode()); mSeeking = false; startUpdating(); } }); } } public void enableMedia() { playButton.setEnabled(getTv().hasCapability(MediaControl.Play)); pauseButton.setEnabled(getTv().hasCapability(MediaControl.Pause)); stopButton.setEnabled(getTv().hasCapability(MediaControl.Stop)); rewindButton.setEnabled(getTv().hasCapability(MediaControl.Rewind)); fastForwardButton.setEnabled(getTv().hasCapability(MediaControl.FastForward)); mSeekBar.setEnabled(getTv().hasCapability(MediaControl.Seek)); closeButton.setEnabled(getTv().hasCapability(MediaPlayer.Close)); fastForwardButton.setOnClickListener(fastForwardListener); mSeekBar.setOnSeekBarChangeListener(seekListener); rewindButton.setOnClickListener(rewindListener); stopButton.setOnClickListener(stopListener); playButton.setOnClickListener(playListener); pauseButton.setOnClickListener(pauseListener); closeButton.setOnClickListener(closeListener); if (getTv().hasCapability(MediaControl.PlayState_Subscribe) && !isPlaying) { mMediaControl.subscribePlayState(playStateListener); } else { if (mMediaControl != null) { mMediaControl.getDuration(durationListener); } startUpdating(); } } public void disableMedia() { closeButton.setEnabled(false); closeButton.setOnClickListener(null); stopMedia(); } public void stopMedia() { playButton.setEnabled(false); playButton.setOnClickListener(null); pauseButton.setEnabled(false); pauseButton.setOnClickListener(null); stopButton.setEnabled(false); stopButton.setOnClickListener(null); rewindButton.setEnabled(false); rewindButton.setOnClickListener(null); fastForwardButton.setEnabled(false); fastForwardButton.setOnClickListener(null); mSeekBar.setEnabled(false); mSeekBar.setOnSeekBarChangeListener(null); mSeekBar.setProgress(0); positionTextView.setText(" durationTextView.setText(" totalTimeDuration = -1; } public View.OnClickListener playListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.play(null); } }; public View.OnClickListener pauseListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.pause(null); } }; public View.OnClickListener closeListener = new View.OnClickListener() { @Override public void onClick(View view) { if (getMediaPlayer() != null) { if (launchSession != null) launchSession.close(null); launchSession = null; disableMedia(); stopUpdating(); isPlaying = isPlayingImage = false; } } }; public View.OnClickListener stopListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.stop(new ResponseListener<Object>() { @Override public void onSuccess(Object response) { stopMedia(); stopUpdating(); isPlaying = false; isPlayingImage = true; } @Override public void onError(ServiceCommandError error) { } }); } }; public View.OnClickListener rewindListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.rewind(null); } }; public View.OnClickListener fastForwardListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mMediaControl != null) mMediaControl.fastForward(null); } }; public OnSeekBarChangeListener seekListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { mIsUserSeeking = false; mSeekBar.setSecondaryProgress(0); onSeekBarMoved(seekBar.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { mIsUserSeeking = true; mSeekBar.setSecondaryProgress(seekBar.getProgress()); stopUpdating(); } @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { } }; public OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar arg0) { } @Override public void onStartTrackingTouch(SeekBar arg0) { } @Override public void onProgressChanged(SeekBar seekBar, int position, boolean fromUser) { if (fromUser) getVolumeControl().setVolume((float) mVolumeBar.getProgress() / 100.0f, null); } }; public VolumeListener getVolumeListener = new VolumeListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "Error getting Volume: " + error); } @Override public void onSuccess(Float object) { mVolumeBar.setProgress((int) (object * 100.0f)); } }; public PlayStateListener playStateListener = new PlayStateListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "Playstate Listener error = " + error); } @Override public void onSuccess(PlayStateStatus playState) { Log.d("LG", "Playstate changed | playState = " + playState); switch (playState) { case Playing: startUpdating(); if (mMediaControl != null && getTv().hasCapability(MediaControl.Duration)) { mMediaControl.getDuration(durationListener); } break; case Finished: positionTextView.setText(" durationTextView.setText(" mSeekBar.setProgress(0); default: stopUpdating(); break; } } }; private void startUpdating() { if (refreshTimer != null) { refreshTimer.cancel(); refreshTimer = null; } refreshTimer = new Timer(); refreshTimer.schedule(new TimerTask() { @Override public void run() { Log.d("LG", "Updating information"); if (mMediaControl != null && getTv() != null && getTv().hasCapability(MediaControl.Position)) { mMediaControl.getPosition(positionListener); } if (mMediaControl != null && getTv() != null && getTv().hasCapability(MediaControl.Duration) && !getTv().hasCapability(MediaControl.PlayState_Subscribe) && totalTimeDuration <= 0) { mMediaControl.getDuration(durationListener); } } }, 0, REFRESH_INTERVAL_MS); } private void stopUpdating() { if (refreshTimer == null) return; refreshTimer.cancel(); refreshTimer = null; } private PositionListener positionListener = new PositionListener() { @Override public void onError(ServiceCommandError error) { } @Override public void onSuccess(Long position) { positionTextView.setText(formatTime(position.intValue())); mSeekBar.setProgress(position.intValue()); } }; private DurationListener durationListener = new DurationListener() { @Override public void onError(ServiceCommandError error) { } @Override public void onSuccess(Long duration) { totalTimeDuration = duration; mSeekBar.setMax(duration.intValue()); durationTextView.setText(formatTime(duration.intValue())); } }; private MediaInfoListener mediaInfoListener = new MediaInfoListener() { @Override public void onSuccess(MediaInfo mediaInfo) { String text = mediaInfo.getTitle(); text += "\n"; text += mediaInfo.getDescription(); mediaInfoTextView.setText(text); final String stringUrl = mediaInfo.getImages().get(0).getUrl(); if (stringUrl!=null) new DownloadImageTask(mediaInfoImageView).execute(stringUrl); } @Override public void onError(ServiceCommandError error) { } }; private String formatTime(long millisec) { int seconds = (int) (millisec / 1000); int hours = seconds / (60 * 60); seconds %= (60 * 60); int minutes = seconds / 60; seconds %= 60; String time; if (hours > 0) { time = String.format(Locale.US, "%d:%02d:%02d", hours, minutes, seconds); } else { time = String.format(Locale.US, "%d:%02d", minutes, seconds); } return time; } private void disconnectWebAppSession() { if (WebAppFragment.mWebAppSession != null) { WebAppFragment.mWebAppSession.setWebAppSessionListener(null); WebAppFragment.mWebAppSession.close(null); WebAppFragment.isLaunched = false; } } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } }
package net.sf.farrago.query; import java.io.*; import java.net.*; import java.util.*; import java.util.logging.*; import javax.jmi.reflect.*; import net.sf.farrago.catalog.*; import net.sf.farrago.cwm.core.*; import net.sf.farrago.cwm.relational.*; import net.sf.farrago.fem.fennel.*; import net.sf.farrago.fem.med.*; import net.sf.farrago.fem.sql2003.*; import net.sf.farrago.fem.security.*; import net.sf.farrago.fennel.*; import net.sf.farrago.namespace.*; import net.sf.farrago.resource.*; import net.sf.farrago.session.*; import net.sf.farrago.trace.*; import net.sf.farrago.type.*; import net.sf.farrago.util.*; import openjava.mop.*; import openjava.ptree.*; import org.eigenbase.oj.rel.JavaRelImplementor; import org.eigenbase.oj.stmt.*; import org.eigenbase.oj.util.*; import org.eigenbase.rel.*; import org.eigenbase.rel.convert.*; import org.eigenbase.rel.metadata.*; import org.eigenbase.relopt.*; import org.eigenbase.reltype.*; import org.eigenbase.rex.*; import org.eigenbase.sql.*; import org.eigenbase.sql.validate.*; import org.eigenbase.sql.util.*; import org.eigenbase.sql.parser.*; import org.eigenbase.sql2rel.*; import org.eigenbase.util.*; import java.util.List; /** * FarragoPreparingStmt subclasses OJPreparingStmt to implement the * {@link FarragoSessionPreparingStmt} interface. * * @author John V. Sichi * @version $Id$ */ public class FarragoPreparingStmt extends OJPreparingStmt implements FarragoSessionPreparingStmt, RelOptConnection, RelOptSchema, SqlValidatorCatalogReader { // NOTE jvs 8-June-2004: this tracer is special in that it controls // preservation of dynamically generated Java code private static final Logger dynamicTracer = FarragoTrace.getDynamicTracer(); private static final Logger streamGraphTracer = FarragoTrace.getPreparedStreamGraphTracer(); private static final Logger planDumpTracer = FarragoTrace.getPlanDumpTracer(); private final FarragoSessionStmtValidator stmtValidator; private boolean needRestore; protected SqlToRelConverter sqlToRelConverter; private Object savedDeclarer; private FarragoAllocation javaCodeDir; protected SqlValidatorImpl sqlValidator; private Set directDependencies; private Set allDependencies; private Set jarUrlSet; protected SqlOperatorTable sqlOperatorTable; private final FarragoUserDefinedRoutineLookup routineLookup; private int expansionDepth; private RelDataType originalRowType; private SqlIdentifier dmlTarget; private PrivilegedAction dmlAction; private TableAccessMap tableAccessMap; private ChainedRelMetadataProvider relMetadataProvider; private boolean allowPartialImplementation; private final Map<String, RelDataType> resultSetTypeMap; /** * Name of Java package containing code generated for this statement. */ private String packageName; /** * Directory containing code generated for this statement. */ private File packageDir; /** * Root directory for all generated Java. */ private File classesRoot; // attributes of the openjava code generated to implement the statement: private ClassDeclaration implementingClassDecl; private Argument [] implementingArgs; private Set loadedServerClassNameSet; private FarragoSessionPlanner planner; private FarragoRelImplementor relImplementor; /** * Creates a new FarragoPreparingStmt object. * * @param stmtValidator generic stmt validator */ public FarragoPreparingStmt(FarragoSessionStmtValidator stmtValidator) { super(null); this.stmtValidator = stmtValidator; stmtValidator.addAllocation(this); loadedServerClassNameSet = new HashSet(); super.setResultCallingConvention(CallingConvention.ITERATOR); directDependencies = new HashSet(); allDependencies = new HashSet(); jarUrlSet = new LinkedHashSet(); classesRoot = new File(FarragoProperties.instance().homeDir.get(true)); classesRoot = new File(classesRoot, "classes"); // Save some global state for reentrancy needRestore = true; savedDeclarer = OJUtil.threadDeclarers.get(); OJSystem.env.pushThreadTempFrame(); routineLookup = new FarragoUserDefinedRoutineLookup( stmtValidator, this, null); resultSetTypeMap = new HashMap<String, RelDataType>(); clearDmlValidation(); relMetadataProvider = new DefaultRelMetadataProvider(); // Chain Farrago metadata just above the default. This allows it to // provide metadata for rels that are not handled by other providers, // but not to override the behavior of other providers. relMetadataProvider.addProvider( new FarragoRelMetadataProvider(getRepos())); } // implement FarragoSessionPreparingStmt public boolean mayCacheImplementation() { return true; } public FarragoSessionStmtValidator getStmtValidator() { return stmtValidator; } public void setPlanner(FarragoSessionPlanner planner) { assert(this.planner == null); this.planner = planner; getSession().getPersonality().definePlannerListeners(planner); } /** * Tells this statement not to throw an exception if optimizer can't find a * valid physical plan. This is intended for use mainly by unit tests * which need to peer into intermediate query optimization states. */ public void enablePartialImplementation() { allowPartialImplementation = true; } public FarragoSessionPlanner getPlanner() { return planner; } // implement FarragoSessionPreparingStmt public SqlOperatorTable getSqlOperatorTable() { if (sqlOperatorTable != null) { return sqlOperatorTable; } SqlOperatorTable systemOperators = getSession().getPersonality().getSqlOperatorTable(this); ChainedSqlOperatorTable table = new ChainedSqlOperatorTable(); table.add(routineLookup); table.add(systemOperators); sqlOperatorTable = table; return sqlOperatorTable; } public boolean hasSqlValidator() { return sqlValidator != null; } // implement FarragoSessionPreparingStmt public SqlValidator getSqlValidator() { if (sqlValidator == null) { sqlValidator = new FarragoSqlValidator(this); } return sqlValidator; } // implement FarragoSessionPreparingStmt public FarragoSessionExecutableStmt prepare(SqlNode sqlNode) { boolean needValidation = false; if (sqlValidator == null) { getSqlValidator(); needValidation = true; } definePackageName(); PreparedResult preparedResult = super.prepareSql( sqlNode, getSession().getPersonality().getRuntimeContextClass( this), sqlValidator, needValidation); return implement(preparedResult); } // implement FarragoSessionPreparingStmt public void preImplement() { definePackageName(); implementingArgs = new Argument [] { new Argument( connectionVariable, getSession().getPersonality().getRuntimeContextClass( this), this) }; implementingClassDecl = super.init(implementingArgs); } protected ClassDeclaration getImplementingClassDecl() { return implementingClassDecl; } protected Argument[] getImplementingArgs() { return implementingArgs; } protected TableAccessMap getTableAccessMap() { return tableAccessMap; } protected Map<String, RelDataType> getResultSetTypeMap() { return resultSetTypeMap; } // implement FarragoSessionPreparingStmt public void postValidate(SqlNode sqlNode) { analyzeRoutineDependencies(sqlNode); // Now that we're done with validation, perform any deferred // privilege checks. stmtValidator.getPrivilegeChecker().checkAccess(); } // implement FarragoSessionPreparingStmt public FarragoSessionExecutableStmt implement( RelNode rootRel, SqlKind sqlKind, boolean logical) { PreparedResult preparedResult = prepareSql( rootRel.getRowType(), rootRel, sqlKind, logical, implementingClassDecl, implementingArgs); // When rootRel is a logical plan, optimize() sets the map, but for a // physical plan, set it here: if (!logical) { tableAccessMap = new TableAccessMap(rootRel); } return implement(preparedResult); } /** * @return lookup table for user-defined routines */ public FarragoUserDefinedRoutineLookup getRoutineLookup() { return routineLookup; } void addJarUrl(String jarUrl) { try { jarUrlSet.add(new URL(jarUrl)); } catch (MalformedURLException ex) { // this shouldn't happen, because the caller is already // supposed to have verified the URL throw Util.newInternal(); } } protected void prepareForCompilation() { // REVIEW jvs 20-Jan-2005: The idea here is to gather up all jars // referenced by external user-defined routines and provide them to the // classloader. However, this loses the associations between jars and // routines, meaning if two classes in different jars have the same // name, there will be trouble. The alternative is to always use // reflection, which would be bad for UDF performance. What to do? // Also, need to implement jar paths. List jarUrlList = new ArrayList(jarUrlSet); URL [] urls = (URL []) jarUrlList.toArray(new URL[0]); URLClassLoader urlClassLoader = URLClassLoader.newInstance( urls, getSession().getPluginClassLoader()); javaCompiler.getArgs().setClassLoader(urlClassLoader); } private void definePackageName() { // TODO: once and only once packageDir = classesRoot; packageDir = new File(packageDir, "net"); packageDir = new File(packageDir, "sf"); packageDir = new File(packageDir, "farrago"); packageDir = new File(packageDir, "dynamic"); try { packageDir.mkdirs(); packageDir = File.createTempFile("stmt", "", packageDir); } catch (IOException ex) { throw Util.newInternal(ex); } packageName = "net.sf.farrago.dynamic." + packageDir.getName(); // Normally, we want to make sure all generated code gets cleaned up. // To disable this for debugging, you can explicitly set // net.sf.farrago.dynamic.level=FINE. (This is not inherited via // parent logger.) if (!shouldAlwaysWriteJavaFile()) { javaCodeDir = new FarragoFileAllocation(packageDir); } // createTempFile created a normal file; we want a directory packageDir.delete(); packageDir.mkdir(); } // Override OJPreparingStmt protected BoundMethod compileAndBind( ClassDeclaration decl, ParseTree parseTree, Argument[] arguments) { BoundMethod boundMethod = super.compileAndBind(decl, parseTree, arguments); compileTransforms(); return boundMethod; } /** * Compiles the FarragoTransform implementations associated with this * statement. */ private void compileTransforms() { // Compile any FarragoTransform implementations String packageName = getTempPackageName(); for(ClassDeclaration transformDecl: relImplementor.getTransforms()) { CompilationUnit compUnit = new CompilationUnit(packageName, new String[0], new ClassDeclarationList(transformDecl)); Class clazz = super.compileClass( packageName, transformDecl.getName(), compUnit.toString()); Util.discard(clazz); } } protected FarragoSessionExecutableStmt implement( PreparedResult preparedResult) { FarragoSessionExecutableStmt executableStmt; if (preparedResult instanceof PreparedExecution) { PreparedExecution preparedExecution = (PreparedExecution) preparedResult; RelDataType rowType = preparedExecution.getPhysicalRowType(); OJClass ojRowClass = OJUtil.typeToOJClass(rowType, getFarragoTypeFactory()); Class rowClass; try { String ojRowClassName = ojRowClass.getName(); int i = ojRowClassName.lastIndexOf('.'); assert (i != -1); ojRowClassName = OJUtil.replaceDotWithDollar(ojRowClassName, i); rowClass = Class.forName( ojRowClassName, true, javaCompiler.getClassLoader()); } catch (ClassNotFoundException ex) { throw Util.newInternal(ex); } RelDataType dynamicParamRowType = getParamRowType(); String xmiFennelPlan = null; Set streamDefSet = relImplementor.getStreamDefSet(); if (!streamDefSet.isEmpty()) { FemCmdPrepareExecutionStreamGraph cmdPrepareStream = getRepos().newFemCmdPrepareExecutionStreamGraph(); Collection streamDefs = cmdPrepareStream.getStreamDefs(); streamDefs.addAll(streamDefSet); xmiFennelPlan = JmiUtil.exportToXmiString( Collections.singleton(cmdPrepareStream)); streamGraphTracer.fine(xmiFennelPlan); } assert(tableAccessMap != null); executableStmt = new FarragoExecutableJavaStmt( packageDir, rowClass, javaCompiler.getClassLoader(), (originalRowType == null) ? rowType : originalRowType, dynamicParamRowType, preparedExecution.getMethod(), xmiFennelPlan, preparedResult.isDml(), getReferencedObjectIds(), tableAccessMap, resultSetTypeMap); } else { assert (preparedResult instanceof PreparedExplanation); executableStmt = new FarragoExecutableExplainStmt( getFarragoTypeFactory().createStructType( new RelDataType[0], new String[0]), preparedResult.getCode()); } // generated code is now the responsibility of executableStmt if (javaCodeDir != null) { executableStmt.addAllocation(javaCodeDir); javaCodeDir = null; } return executableStmt; } // implement FarragoSessionPreparingStmt public void analyzeSql( SqlNode sqlNode, final FarragoSessionAnalyzedSql analyzedSql) { RelNode rootRel = null; getSqlToRelConverter(); if (analyzedSql.paramRowType == null) { // query expression rootRel = sqlToRelConverter.convertQuery(sqlNode, false, true); analyzedSql.setResultType(rootRel.getRowType()); analyzedSql.paramRowType = getParamRowType(); } else { // parameterized row expression analyzedSql.resultType = getSqlValidator().getValidatedNodeType(sqlNode); } analyzedSql.dependencies = Collections.unmodifiableSet(directDependencies); // walk the expression looking for dynamic parameters SqlVisitor dynamicParamFinder = new SqlBasicVisitor<Void>() { public Void visit(SqlDynamicParam param) { analyzedSql.hasDynamicParams = true; return super.visit(param); } }; sqlNode.accept(dynamicParamFinder); // For queries, fill in some more information. if (rootRel != null) { // Make sure we have RelMetadataProvider set up. finalizeRelMetadata(rootRel); if (analyzedSql.optimized) { rootRel = optimize(rootRel.getRowType(), rootRel); // From here on, use the planner's notion of root, because the // rootRel it returned to us may have lost some metadata. // TODO: clean this up. rootRel = planner.getRoot(); } // Derive information about origin of each column List<Set<RelColumnOrigin>> columnOrigins = new ArrayList<Set<RelColumnOrigin>>(); List fieldList = analyzedSql.resultType.getFieldList(); for (int i = 0; i < fieldList.size(); ++i) { Set<RelColumnOrigin> rcoSet = RelMetadataQuery.getColumnOrigins(rootRel, i); if (rcoSet == null) { // If we don't know, assume none. columnOrigins.add(Collections.EMPTY_SET); } else { columnOrigins.add(rcoSet); } } analyzedSql.columnOrigins = Collections.unmodifiableList(columnOrigins); if (analyzedSql.optimized) { analyzedSql.rowCount = RelMetadataQuery.getRowCount( rootRel); } } } void analyzeRoutineDependencies(SqlNode sqlNode) { // Round up all the dependencies on UDF's. We can't do this during // function lookup because overloads need to be resolved first. And we // can't do this during SqlToRelConverter because then we stop // collecting direct dependencies. SqlVisitor udfInvocationFinder = new SqlBasicVisitor<Void>() { public Void visit(SqlCall call) { if (call.getOperator() instanceof FarragoUserDefinedRoutine) { FarragoUserDefinedRoutine function = (FarragoUserDefinedRoutine) call.getOperator(); addDependency( function.getFemRoutine(), PrivilegedActionEnum.EXECUTE); } return super.visit(call); } }; sqlNode.accept(udfInvocationFinder); } protected Set getReferencedObjectIds() { Set set = new HashSet(); Iterator iter = allDependencies.iterator(); while (iter.hasNext()) { RefObject refObj = (RefObject) iter.next(); set.add(refObj.refMofId()); } return set; } // implement FarragoSessionPreparingStmt public SqlToRelConverter getSqlToRelConverter() { return getSqlToRelConverter(sqlValidator, this); } // implement FarragoSessionPreparingStmt public RelOptCluster getRelOptCluster() { return getSqlToRelConverter().getCluster(); } // override OJPreparingStmt protected RelNode optimize(RelDataType rowType, RelNode rootRel) { boolean dumpPlan = planDumpTracer.isLoggable(Level.FINE); if (dumpPlan) { planDumpTracer.fine( RelOptUtil.dumpPlan( "Plan before flattening", rootRel, false, SqlExplainLevel.DIGEST_ATTRIBUTES)); } originalRowType = rowType; rootRel = flattenTypes(rootRel, true); if (dumpPlan) { planDumpTracer.fine( RelOptUtil.dumpPlan( "Plan after flattening", rootRel, false, SqlExplainLevel.DIGEST_ATTRIBUTES)); } // Now that all plugins have been seen (flattening above expanded // views), we can finalize the relational expression metadata query // providers to use during optimization. finalizeRelMetadata(rootRel); RelTraitSet desiredTraits = getDesiredRootTraitSet(rootRel); rootRel = super.optimize(rowType, rootRel); if (dumpPlan) { planDumpTracer.fine( RelOptUtil.dumpPlan( "Plan after optimization", rootRel, false, SqlExplainLevel.ALL_ATTRIBUTES)); } // Validate that plan satisfies all required trait conversions. This // implicitly validates that a physical implementation was found for // every node. RelNode problemRel = null; if (!allowPartialImplementation) { problemRel = validatePlan(rootRel, desiredTraits); } if (problemRel != null) { // Dump plan unless we already did above. if (!dumpPlan) { planDumpTracer.severe( RelOptUtil.dumpPlan( "Plan without full implementation", rootRel, false, SqlExplainLevel.ALL_ATTRIBUTES)); } throw FarragoResource.instance().SessionOptimizerFailed.ex( problemRel.toString()); } // REVIEW jvs 9-Mar-2006: Perhaps we should compute two // tableAccessMaps, one before and one after optimization, and then // merge them. Leaving out ones from before could lead us to avoid // locking a table which gets pruned, which might be good for // concurrency in some circumstances, but bad for correctness in // others. Leaving out ones from after would screw up an optimizer // which supports materialized view rewrite. tableAccessMap = new TableAccessMap(rootRel); return rootRel; } private RelNode validatePlan(RelNode rel, RelTraitSet desiredTraits) { if (!rel.getTraits().matches(desiredTraits)) { return rel; } if (rel instanceof ConverterRel) { ConverterRel converterRel = (ConverterRel) rel; return validatePlan( converterRel.getChild(), converterRel.getInputTraits()); } else { for (RelNode child : rel.getInputs()) { RelNode problemChild = validatePlan( child, rel.getTraits()); if (problemChild != null) { return problemChild; } } } return null; } private void finalizeRelMetadata(RelNode rootRel) { if (relMetadataProvider == null) { // already finalized return; } // Give personality priority over anything set up so far. getSession().getPersonality().registerRelMetadataProviders( relMetadataProvider); // Add caching on top of all that. CachingRelMetadataProvider cacheProvider = new CachingRelMetadataProvider(relMetadataProvider, planner); // Put the planner at the head of its own chain before all the rest. // It's a bad idea to cache the planner's results. ChainedRelMetadataProvider plannerChain = new ChainedRelMetadataProvider(); plannerChain.addProvider(cacheProvider); planner.registerMetadataProviders(plannerChain); rootRel.getCluster().setMetadataProvider(plannerChain); // Remind ourselves that we're done setting this guy up, // so any further access to it is an error. relMetadataProvider = null; } protected RelNode flattenTypes(RelNode rootRel, boolean restructure) { RelStructuredTypeFlattener typeFlattener = new RelStructuredTypeFlattener( sqlToRelConverter.getRexBuilder()); rootRel = typeFlattener.rewrite(rootRel, restructure); return rootRel; } protected RelDataType getParamRowType() { return getFarragoTypeFactory().createStructType( new RelDataTypeFactory.FieldInfo() { public int getFieldCount() { return sqlToRelConverter.getDynamicParamCount(); } public String getFieldName(int index) { return "?" + index; } public RelDataType getFieldType(int index) { return sqlToRelConverter.getDynamicParamType(index); } }); } // implement FarragoAllocation public void closeAllocation() { if (!needRestore) { // already closed or else never opened return; } OJSystem.env.popThreadTempFrame(); OJUtil.threadDeclarers.set(savedDeclarer); // TODO: obtain locks to ensure that objects we intend to operate // on don't change after we end repository txn. if (javaCodeDir != null) { javaCodeDir.closeAllocation(); javaCodeDir = null; } needRestore = false; } RelNode expandView(String queryString) { expansionDepth++; FarragoSessionParser parser = getSession().getPersonality().newParser(getSession()); final SqlNode sqlQuery; try { sqlQuery = (SqlNode) parser.parseSqlText( stmtValidator, null, queryString, true); } catch (Throwable e) { throw Util.newInternal(e, "Error while parsing view definition: " + queryString); } RelNode relNode = sqlToRelConverter.convertQuery(sqlQuery, true, false); --expansionDepth; return relNode; } RexNode expandInvocationExpression( SqlNode sqlExpr, FarragoRoutineInvocation invocation) { expansionDepth++; // NOTE jvs 2-Jan-2005: We already validated the expression during DDL, // but we stored the original pre-validation expression, and validation // may have involved rewrites relied on by sqlToRelConverter. So // we must recapitulate here. sqlExpr = getSqlValidator().validateParameterizedExpression( sqlExpr, invocation.getParamNameToTypeMap()); // TODO jvs 1-Jan-2005: support a RexVariableBinding (like "let" in // Lisp), and avoid expansion of parameters which are referenced more // than once RexNode rexNode = sqlToRelConverter.convertExpression( sqlExpr, invocation.getParamNameToArgMap()); --expansionDepth; return rexNode; } void setDmlValidation(SqlIdentifier target, PrivilegedAction action) { dmlTarget = target; dmlAction = action; } void clearDmlValidation() { dmlTarget = null; dmlAction = null; } /** * @return true iff currently expanding a view or function */ public boolean isExpandingDefinition() { return expansionDepth > 0; } protected SqlToRelConverter getSqlToRelConverter( SqlValidator validator, RelOptConnection connection) { // REVIEW: recycling may be dangerous since SqlToRelConverter is // stateful if (sqlToRelConverter == null) { sqlToRelConverter = new SqlToRelConverter( validator, connection.getRelOptSchema(), getEnvironment(), planner, connection, new FarragoRexBuilder(this)); sqlToRelConverter.setDefaultValueFactory( new ReposDefaultValueFactory(this)); sqlToRelConverter.enableTableAccessConversion(false); } return sqlToRelConverter; } // implement FarragoSessionPreparingStmt public JavaRelImplementor getRelImplementor(RexBuilder rexBuilder) { if (relImplementor == null) { relImplementor = newRelImplementor(rexBuilder); } return relImplementor; } protected FarragoRelImplementor newRelImplementor(RexBuilder rexBuilder) { return new FarragoRelImplementor(this, rexBuilder); } // implement FarragoSessionPreparingStmt public FarragoRepos getRepos() { return stmtValidator.getRepos(); } // implement FarragoSessionPreparingStmt public FennelDbHandle getFennelDbHandle() { return stmtValidator.getFennelDbHandle(); } // implement FarragoSessionPreparingStmt public FarragoTypeFactory getFarragoTypeFactory() { return stmtValidator.getTypeFactory(); } // implement FarragoSessionPreparingStmt public FarragoSessionIndexMap getIndexMap() { return stmtValidator.getIndexMap(); } // implement FarragoSessionPreparingStmt public FarragoSession getSession() { return stmtValidator.getSession(); } // implement RelOptConnection public RelOptSchema getRelOptSchema() { return this; } // implement RelOptConnection public Object contentsAsArray( String qualifier, String tableName) { throw new UnsupportedOperationException( "FarragoPreparingStmt.contentsAsArray() should have been replaced"); } // implement FarragoSessionPreparingStmt public RelOptTable loadColumnSet(SqlIdentifier name) { return getTableForMember(name.names); } // implement RelOptSchema public RelOptTable getTableForMember(String [] names) { FarragoSessionResolvedObject resolved = stmtValidator.resolveSchemaObjectName( names, getRepos().getRelationalPackage().getCwmNamedColumnSet()); if (resolved.object == null) { return getForeignTableFromNamespace(resolved); } assert (resolved.object instanceof CwmNamedColumnSet); CwmNamedColumnSet columnSet = (CwmNamedColumnSet) resolved.object; if (columnSet instanceof FemLocalTable) { FemLocalTable table = (FemLocalTable) columnSet; // REVIEW: maybe defer this until physical implementation? if (table.isTemporary()) { getIndexMap().instantiateTemporaryTable( stmtValidator.getDataWrapperCache(), table); } } RelOptTable relOptTable; if (columnSet instanceof FemBaseColumnSet) { FemBaseColumnSet table = (FemBaseColumnSet) columnSet; FemDataServer femServer = table.getServer(); loadDataServerFromCache(femServer); relOptTable = stmtValidator.getDataWrapperCache().loadColumnSetFromCatalog( table, getFarragoTypeFactory()); } else if (columnSet instanceof FemLocalView) { RelDataType rowType = createTableRowType(columnSet); relOptTable = new FarragoView(columnSet, rowType); } else { throw Util.needToImplement(columnSet); } initializeQueryColumnSet(relOptTable, columnSet); return relOptTable; } private void initializeQueryColumnSet( RelOptTable relOptTable, CwmNamedColumnSet cwmColumnSet) { if (relOptTable == null) { return; } if (!(relOptTable instanceof FarragoQueryColumnSet)) { return; } FarragoQueryColumnSet queryColumnSet = (FarragoQueryColumnSet) relOptTable; queryColumnSet.setPreparingStmt(this); queryColumnSet.setCwmColumnSet(cwmColumnSet); } private FarragoMedColumnSet getForeignTableFromNamespace( FarragoSessionResolvedObject resolved) { FemDataServer femServer = (FemDataServer) FarragoCatalogUtil.getModelElementByName( getRepos().getMedPackage().getFemDataServer().refAllOfType(), resolved.catalogName); if (femServer == null) { return null; } // TODO jvs 27-Aug-2005: decide on required privileges for direct // access to foreign tables // When a foreign table is referenced directly via a namespace, we have // nothing to hang a direct dependency on. Instead, we // remember the dependency on the server, so that if the server // gets dropped, dependent views will cascade. addDependency(femServer, null); FarragoMedDataServer server = loadDataServerFromCache(femServer); try { FarragoMedNameDirectory directory = server.getNameDirectory(); if (directory == null) { return null; } directory = directory.lookupSubdirectory(resolved.schemaName); if (directory == null) { return null; } FarragoMedColumnSet medColumnSet = directory.lookupColumnSet( getFarragoTypeFactory(), resolved.objectName, resolved.getQualifiedName()); initializeQueryColumnSet(medColumnSet, null); return medColumnSet; } catch (Throwable ex) { // TODO: better name formatting throw FarragoResource.instance(). ValidatorForeignTableLookupFailed.ex( Arrays.asList(resolved.getQualifiedName()).toString(), ex); } } private FarragoMedDataServer loadDataServerFromCache( FemDataServer femServer) { FarragoMedDataServer server = stmtValidator.getDataWrapperCache().loadServerFromCatalog( femServer); if (loadedServerClassNameSet.add(server.getClass().getName())) { // This is the first time we've seen this server class, so give it // a chance to register any planner info such as calling // conventions and rules. REVIEW: the discrimination is based on // class name, on the assumption that it should be unique regardless // of classloader, JAR, etc. Is that correct? planner.beginMedPluginRegistration(server.getClass().getName()); server.registerRules(planner); assert(relMetadataProvider != null); server.registerRelMetadataProviders(relMetadataProvider); planner.endMedPluginRegistration(); } return server; } // implement RelOptSchema public RelDataTypeFactory getTypeFactory() { return getFarragoTypeFactory(); } // implement RelOptSchema public void registerRules(RelOptPlanner planner) { // nothing to do } // implement SqlValidator.CatalogReader public SqlValidatorTable getTable(String [] names) { FarragoSessionResolvedObject resolved = stmtValidator.resolveSchemaObjectName( names, getRepos().getRelationalPackage().getCwmNamedColumnSet()); if (resolved == null) { return null; } if (resolved.object == null) { return getForeignTableFromNamespace(resolved); } if (!(resolved.object instanceof CwmNamedColumnSet)) { // TODO: give a more helpful error // in case a non-relational object is referenced return null; } CwmNamedColumnSet table = (CwmNamedColumnSet) resolved.object; ModalityType modality = ModalityTypeEnum.MODALITYTYPE_RELATIONAL; if (table instanceof FemAbstractColumnSet) { modality = ((FemAbstractColumnSet) table).getModality(); } PrivilegedAction action = PrivilegedActionEnum.SELECT; if (dmlTarget != null) { if (Arrays.equals(names, dmlTarget.names)) { assert(dmlAction != null); action = dmlAction; // REVIEW jvs 27-Aug-2005: This is a hack to handle the case // of self-insert, where the same table is both the source and // target. We need to require SELECT for the source role // and INSERT for the target role. It only works because // SqlValidatorImpl happens to validate the target first, so // this is very brittle. clearDmlValidation(); } } addDependency(table, action); if (table.getVisibility() == null) { throw new FarragoUnvalidatedDependencyException(); } RelDataType rowType = createTableRowType(table); SqlAccessType allowedAccess = FarragoCatalogUtil.getTableAllowedAccess(table); return newValidatorTable(resolved.getQualifiedName(), rowType, allowedAccess, modality); } /** * Creates a row-type for a given table. * This row-type includes any system columns which are implicit for this * type of type. * * @param table Repository table * @return Row type including system columns */ protected RelDataType createTableRowType(CwmNamedColumnSet table) { return getFarragoTypeFactory().createStructTypeFromClassifier( table); } /** * Factory method, creates a table. */ protected SqlValidatorTable newValidatorTable( String[] qualifiedName, RelDataType rowType, SqlAccessType allowedAccess, ModalityType modality) { return new ValidatorTable(qualifiedName, rowType, allowedAccess, modality); } // implement SqlValidator.CatalogReader public RelDataType getNamedType(SqlIdentifier typeName) { CwmSqldataType cwmType = stmtValidator.findSqldataType(typeName); if (!(cwmType instanceof FemSqlobjectType)) { // TODO jvs 12-Feb-2005: throw an excn stating that only // user-defined structured type is allowed here return null; } // FIXME jvs 27-Aug-2005: this should be USAGE, not REFERENCES; // need to add to FEM addDependency(cwmType, PrivilegedActionEnum.REFERENCES); return getFarragoTypeFactory().createCwmType(cwmType); } // implement SqlValidator.CatalogReader public SqlMoniker [] getAllSchemaObjectNames(String [] names) { return stmtValidator.getAllSchemaObjectNames(names); } public void addDependency(CwmModelElement supplier, PrivilegedAction action) { if (!isExpandingDefinition()) { directDependencies.add(supplier); if (action != null) { stmtValidator.requestPrivilege( supplier, action.toString()); } } allDependencies.add(supplier); } void mapResultSetType( String resultSetName, RelDataType rowType) { resultSetTypeMap.put(resultSetName, rowType); } public Variable getConnectionVariable() { return new Variable(connectionVariable); } // override OJPreparingStmt protected String getCompilerClassName() { return getRepos().getCurrentConfig().getJavaCompilerClassName(); } // override OJPreparingStmt protected boolean shouldSetConnectionInfo() { return false; } // override OJPreparingStmt protected boolean shouldAlwaysWriteJavaFile() { Level dynamicLevel = dynamicTracer.getLevel(); if ((dynamicLevel == null) || !dynamicTracer.isLoggable(Level.FINE)) { return false; } else { return true; } } // override OJPreparingStmt protected String getClassRoot() { return classesRoot.getPath(); } // override OJPreparingStmt protected String getJavaRoot() { return classesRoot.getPath(); } // override OJPreparingStmt protected String getTempPackageName() { return packageName; } // override OJPreparingStmt protected String getTempClassName() { return "ExecutableStmt"; } // override OJPreparingStmt protected String getTempMethodName() { return "execute"; } //~ Inner Classes protected static class ValidatorTable implements SqlValidatorTable { private final String [] qualifiedName; private final RelDataType rowType; private final SqlAccessType accessType; private final ModalityType modality; /** * Creates a new ValidatorTable object. */ public ValidatorTable( String [] qualifiedName, RelDataType rowType, SqlAccessType accessType, ModalityType modality) { this.qualifiedName = qualifiedName; this.rowType = rowType; this.accessType = accessType; this.modality = modality; } // implement SqlValidatorTable public String [] getQualifiedName() { return qualifiedName; } // implement SqlValidatorTable public boolean isMonotonic(String columnName) { return false; } // implement SqlValidatorTable public SqlAccessType getAllowedAccess() { return accessType; } // implement SqlValidatorTable public RelDataType getRowType() { return rowType; } public ModalityType getModality() { return modality; } } } // End FarragoPreparingStmt.java
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; 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.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; 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 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 { public static 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; public static String SBMLLevelVersion; private JCheckBox Undeclared, Units, viewerCheck; private JComboBox LevelVersion; 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, saveAsVerilog, viewSG, viewModGraph, viewLearnedModel, viewModBrowser, createAnal, createLearn, createSbml, createSynth, createVer, close, closeAll; public String ENVVAR; public static int SBML_LEVEL = 3; public static int SBML_VERSION = 1; 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 static Object ICON_EXPAND = UIManager.get("Tree.expandedIcon"); public static Object ICON_COLLAPSE = UIManager.get("Tree.collapsedIcon"); 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 Learned LPN"); } else { saveModel = new JMenuItem("Save GCM"); } saveAsVerilog = new JMenuItem("Save as Verilog"); saveAsVerilog.addActionListener(this); saveAsVerilog.setActionCommand("saveAsVerilog"); saveAsVerilog.setEnabled(false); 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"); viewLHPN = new JMenuItem("Model"); viewModGraph = new JMenuItem("Model"); viewLearnedModel = new JMenuItem("Learned 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); viewLearnedModel.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"); } viewLHPN.setActionCommand("viewModel"); 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, // viewVHDL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, // viewVerilog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 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); viewLearnedModel.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); 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); if (lema) file.add(saveAsVerilog); // 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(viewLearnedModel); 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(viewLearnedModel); 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.sbml.level_version", "").equals("L2V4")) { SBMLLevelVersion = "L2V4"; SBML_LEVEL = 2; SBML_VERSION = 4; } else { SBMLLevelVersion = "L3V1"; SBML_LEVEL = 3; SBML_VERSION = 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.ACTIVATED_RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVATED_RNAP_BINDING_VALUE", "1"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.KCOMPLEX_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KCOMPLEX_VALUE", "0.05"); } 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); if (biosimrc.get("biosim.general.tree_icons", "").equals("")) { biosimrc.put("biosim.general.tree_icons", "default"); } else if (biosimrc.get("biosim.general.tree_icons", "").equals("plus_minus")) { tree.setExpandibleIcons(false); } 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) { String[] Versions = { "L2V4", "L3V1" }; JLabel SBMLlabel = new JLabel("SBML Level/Version"); LevelVersion = new JComboBox(Versions); if (SBMLLevelVersion.equals("L2V4")) { LevelVersion.setSelectedItem("L2V4"); } else { LevelVersion.setSelectedItem("L3V1"); } 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); } JCheckBox icons = new JCheckBox("Use Plus/Minus For Expanding/Collapsing File Tree"); if (biosimrc.get("biosim.general.tree_icons", "").equals("default")) { icons.setSelected(false); } else { icons.setSelected(true); } 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 ACTIVATED_RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.ACTIVATED_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", "")); final JTextField KCOMPLEX_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KCOMPLEX_VALUE", "")); JPanel labels = new JPanel(new GridLayout(14, 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.ACTIVATED_RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVATED_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) + "):")); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KCOMPLEX_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KCOMPLEX_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(14, 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(ACTIVATED_RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); fields.add(KCOMPLEX_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", "gillespieJava", "mpde", "mp", "mp-adaptive", "mp-event", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "steady-state-markov-chain-analysis", "transient-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("gillespieJava"); 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("steady-state-markov-chain-analysis"); sim.addItem("transient-markov-chain-analysis"); 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 generalPrefsBordered = new JPanel(new BorderLayout()); JPanel generalPrefs = new JPanel(); generalPrefsBordered.add(dialog, "North"); generalPrefsBordered.add(icons, "Center"); generalPrefs.add(generalPrefsBordered); ((FlowLayout) generalPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); JPanel levelPrefs = new JPanel(new GridLayout(1, 2)); levelPrefs.add(SBMLlabel); levelPrefs.add(LevelVersion); sbmlPrefsBordered.add(levelPrefs, "North"); sbmlPrefsBordered.add(Undeclared, "Center"); sbmlPrefsBordered.add(Units, "South"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", generalPrefs); 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 (icons.isSelected()) { biosimrc.put("biosim.general.tree_icons", "plus_minus"); tree.setExpandibleIcons(false); } else { biosimrc.put("biosim.general.tree_icons", "default"); tree.setExpandibleIcons(true); } if (LevelVersion.getSelectedItem().equals("L2V4")) { SBMLLevelVersion = "L2V4"; SBML_LEVEL = 2; SBML_VERSION = 4; biosimrc.put("biosim.sbml.level_version", "L2V4"); } else { SBMLLevelVersion = "L3V1"; SBML_LEVEL = 3; SBML_VERSION = 1; biosimrc.put("biosim.sbml.level_version", "L3V1"); } 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(ACTIVATED_RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVATED_RNAP_BINDING_VALUE", ACTIVATED_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(KCOMPLEX_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KCOMPLEX_VALUE", KCOMPLEX_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); } JCheckBox icons = new JCheckBox("Use Plus/Minus For Expanding/Collapsing File Tree"); if (biosimrc.get("biosim.general.tree_icons", "").equals("default")) { icons.setSelected(false); } else { icons.setSelected(true); } JPanel generalPrefsBordered = new JPanel(new BorderLayout()); JPanel generalPrefs = new JPanel(); generalPrefsBordered.add(dialog, "North"); generalPrefsBordered.add(icons, "Center"); generalPrefs.add(generalPrefsBordered); ((FlowLayout) generalPrefs.getLayout()).setAlignment(FlowLayout.LEFT); prefPanel.add(generalPrefs); 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"); } if (icons.isSelected()) { biosimrc.put("biosim.general.tree_icons", "plus_minus"); tree.setExpandibleIcons(false); } else { biosimrc.put("biosim.general.tree_icons", "default"); tree.setExpandibleIcons(true); } } } } 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.5.1", 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.5.1", 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.5.1", JLabel.CENTER); developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen\nNicolas Roehner\nTyler Patterson"; } 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 (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) { for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof Learn) { ((Learn) component).viewLog(); return; } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLog(); return; } } } } else if (e.getSource() == viewCoverage) { Component comp = tab.getSelectedComponent(); for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewCoverage(); return; } } } /* * 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(); LhpnFile lhpn = new LhpnFile(log); * lhpn.load(root + separator + filename); lhpn.printDot(root + * separator + theFile); // 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); } } */ 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() == saveAsVerilog) { new Lpn2verilog(tree.getFile()); 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); } addToTree(theFile.replace(".lpn", ".sv")); } 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() == 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")); addToTree(theFile.replace(".lpn", ".xml")); } else if (e.getActionCommand().equals("convertToVerilog")) { new Lpn2verilog(tree.getFile()); 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); } addToTree(theFile.replace(".lpn", ".sv")); } 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); } addToTree(synthName.trim()); 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); synthPane.add(synth); 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) == 0) { 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); } addToTree(verName.trim()); Verification verify = new Verification(root + separator + verName, verName, circuitFileNoPath, log, this, lema, atacs); verify.save(); addTab(verName, verify, "Verification"); } } } 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()) { String dirName = tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(dirName)) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } deleteFromTree(dirName); } else { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]); if (views.length == 0) { String fileName = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(fileName)) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); deleteFromTree(fileName); } else { String view = ""; String gcms = ""; for (int i = 0; i < views.length; i++) { if (views[i].endsWith(".gcm")) { gcms += views[i] + "\n"; } else { view += views[i] + "\n"; } } String message; if (gcms.equals("")) { message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "Delete these views first."; } else if (view.equals("")) { message = "Unable to delete the selected file." + "\nIt is linked to the following gcms:\n" + gcms + "Delete these gcms first."; } else { message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "It is also linked to the following gcms:\n" + gcms + "Delete these views and gcms 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 { 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 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"); addToTree(theFile.replace(".gcm", "") + ".xml"); 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"); addToTree(theFile.replace(".gcm", "") + ".xml"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLHPN")) { 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) == 0) { return; } break; } } 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) == 0) { 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(); LhpnFile lhpn = new LhpnFile(log); lhpn.load(directory + separator + theFile); lhpn.printDot(directory + separator + file); // 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(); } catch (InterruptedException e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == viewLearnedModel) { Component comp = tab.getSelectedComponent(); for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof Learn) { ((Learn) component).viewGcm(); return; } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); return; } } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { 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) == 0) { 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(); LhpnFile lhpn = new LhpnFile(log); lhpn.load(root + separator + file); lhpn.printDot(root + separator + dot); // 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(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException 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; 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) == 0) { 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 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(); } else if (component instanceof MovieContainer) { ((MovieContainer) component).savePreferences(); } } } 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); addToTree(newName); } 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) { // int index = -1; for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof Reb2Sac) { ((Reb2Sac) component).getRunButton().doClick(); break; } else if (component instanceof Learn) { ((Learn) component).save(); new Thread((Learn) component).start(); break; } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); ((LearnLHPN) component).learn(); break; } } } 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"); addToTree(f.getName()); } } } } 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(BioSim.SBML_LEVEL, BioSim.SBML_VERSION); document.createModel(); // document.setLevel(2); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); c.setSpatialDimensions(3); 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"); addToTree(f.split(separator)[f.split(separator).length - 1]); } } } } 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(); addToTree(vhdlName); 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(); addToTree(SName); 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(); addToTree(InstName); 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(); addToTree(vhdlName); 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.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"); addToTree(f.getName()); } } } } 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(); addToTree(cspName); 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(); addToTree(hseName); 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(); addToTree(uncName); 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(); addToTree(rsgName); 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(); addToTree(spiceName); 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(); s = s.replaceAll("[^a-zA-Z0-9_.]+", "_"); writer.writeSBML(document, root + separator + s); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } addToTree(s); } 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(); String newFile = file[file.length - 1]; newFile = newFile.replaceAll("[^a-zA-Z0-9_.]+", "_"); writer.writeSBML(document, root + separator + newFile); addToTree(newFile); } } 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]); addToTree(file[file.length - 1]); } } 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)); s = s.replaceAll("[^a-zA-Z0-9_.]+", "_"); 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(); addToTree(s); } } 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()); file[file.length - 1] = file[file.length - 1].replaceAll( "[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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()) { file[file.length - 1] = file[file.length - 1].replaceAll( "[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); // log.addText(filename); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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(); lpnName = lpnName.replaceAll("[^a-zA-Z0-9_.]+", "_"); 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(); addToTree(file[file.length - 1].replace(".g", ".lpn")); } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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(); addToTree(graphName.trim()); } } } 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 Histogram:", "Histogram 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, "Histogram"); g.save(); addToTree(graphName.trim()); } } } 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) == 0) { 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); } addToTree(lrnName); 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); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Learn"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Advanced Options"); } else { Learn learn = new Learn(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Learn"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Advanced Options"); } Graph tsdGraph; tsdGraph = new Graph(null, "Number of molecules", lrnName + " data", "tsd.printer", root + separator + lrnName, "Time", this, null, log, null, true, false); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "TSD Graph"); addTab(lrnName, lrnTab, null); } } } 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."); if (sg.performSteadyStateMarkovianAnalysis(0.01, 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(); LhpnFile lhpn = new LhpnFile(log); lhpn.load(tree.getFile()); lhpn.printDot(root + separator + theFile); // 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(frame, scrolls, "VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "VHDL-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view VHDL-AMS model.", "Error", JOptionPane.ERROR_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(frame, scrolls, "Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "Verilog-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(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(frame, scrolls, "SystemVerilog Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "SystemVerilog model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(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) == 0) { 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(); } } } } addToTree(copy); } } 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)) { String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; 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) == 0) { 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")) { reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm")) { 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); } SBML_Editor sbml = null; Reb2Sac reb2sac = null; 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"))); try { 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); } catch (Exception e1) { e1.printStackTrace(); } 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) { reb2sac = (Reb2Sac) c; t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1) .setName("Simulate"); } else if (c instanceof MovieContainer) { t.addTab("Schematic", c); t.getComponentAt(t.getComponents().length - 1) .setName("ModelViewMovie"); } else if (c instanceof SBML_Editor) { sbml = (SBML_Editor) c; t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("SBML Editor"); } else if (c instanceof GCM2SBMLEditor) { GCM2SBMLEditor gcm = (GCM2SBMLEditor) c; if (!gcm.getSBMLFile().equals("--none sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + rename, root + separator + rename + separator + rename + ".sim"); } t.addTab("Parameters", 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("Histogram", c); t.getComponentAt( t.getComponents().length - 1) .setName("ProbGraph"); } } else if (c instanceof JScrollPane) { if (sbml != null) { t.addTab("SBML Elements", sbml .getElementsPanel()); t.getComponentAt( t.getComponents().length - 1) .setName(""); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); t.addTab("SBML Elements", scroll); t.getComponentAt( t.getComponents().length - 1) .setName(""); } } 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); } } else if (tab.getComponentAt(i) instanceof JTabbedPane) { 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).getBackgroundFile() .equals(oldName)) { ((Reb2Sac) c).updateBackgroundFile(rename); } else if (c instanceof Learn && ((Learn) c).getBackgroundFile().equals(oldName)) { ((Learn) c).updateBackgroundFile(rename); } } } } // updateAsyncViews(rename); updateViewNames(tree.getFile(), rename); deleteFromTree(oldName); addToTree(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), "Histogram"); } } } 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() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema, atacs); mainPanel.add(tree, "West"); updateGCM(); mainPanel.validate(); } public void addToTree(String item) { tree.addToTree(item, root); updateGCM(); mainPanel.validate(); } public void deleteFromTree(String item) { tree.deleteFromTree(item); 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") || tab.getComponentAt(index).getName().equals("Histogram")) { 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(); addToTree(filename); } } 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(); addToTree(filename); } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to save LPN.", "Error", JOptionPane.ERROR_MESSAGE); } } public void updateMenu(boolean logEnabled, boolean othersEnabled) { viewLearnedModel.setEnabled(othersEnabled); viewCoverage.setEnabled(othersEnabled); save.setEnabled(othersEnabled); viewLog.setEnabled(logEnabled); // Do saveas & save button too } 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"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createAnalysis"); 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("Save as 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 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(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) { 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(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 open this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } 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), "Histogram"); } } 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) { } 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 { 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) { 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); } */ addToTree(simName); 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); addModelViewTab(reb2sac, simTab, gcm); simTab.addTab("Parameters", 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 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("Histogram", 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("Histogram", 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"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options"); 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"); 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; } DataManager data = new DataManager(tree.getFile(), this, lema); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options"); 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); lrnTab.addTab("TSD Graph", tsdGraph); 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; if (gcmFile.contains(".lpn")) { reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile, lhpnAbstraction); } else { reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile, null); } 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); addModelViewTab(reb2sac, simTab, gcm); simTab.addTab("Parameters", 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); } } 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("Histogram", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "ProbGraph"); /* * } else if (!probFile.equals("")) { * simTab.addTab("Histogram", * 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("Histogram", * 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 MovieContainer movieContainer = new MovieContainer(reb2sac, gcm2sbml.getGCM(), this, gcm2sbml); tabPane.addTab("Schematic", 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()); if (!(selectedTab.getComponent(selectedTab.getSelectedIndex()) instanceof JScrollPane)) { JPanel selectedPanel = (JPanel) selectedTab.getComponent(selectedTab .getSelectedIndex()); String className = selectedPanel.getClass().getName(); // The new Schematic 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) { } public void mouseExited(MouseEvent e) { } 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 windowLostFocus(WindowEvent e) { } 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); } } } } addToTree(newSim); 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); addModelViewTab(reb2sac, simTab, gcm); simTab.addTab("Parameters", 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); } } 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("Histogram", probGraph); 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 if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { 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"); } } } } } } 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) { 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"; if (new File(properties).exists()) { Verification verify = ((Verification) (this.tab.getComponentAt(i))); verify.reload(updatedFile); } if (new File(properties1).exists()) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("Synthesis")) { ((Synthesis) (sim.getComponentAt(j))).reload(updatedFile); } } } 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) { e.printStackTrace(); } 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"))); try { 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); } catch (Exception e) { e.printStackTrace(); } 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"))); try { 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); } catch (Exception e) { e.printStackTrace(); } 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.endsWith(".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) { viewSG.setEnabled(false); viewLearnedModel.setEnabled(false); if (selectedTab != -1) { tab.setSelectedIndex(selectedTab); } Component comp = tab.getSelectedComponent(); 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(true); saveTemp.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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); } 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(true); saveTemp.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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); Component learnComponent = null; Boolean learn = false; Boolean learnLHPN = 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; learnComponent = c; } else if (c instanceof LearnLHPN) { learnLHPN = true; learnComponent = c; } } if (component instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); viewLog.setEnabled(false); viewCoverage.setEnabled(false); run.setEnabled(true); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(false); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(((Learn) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((Learn) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled()); } 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); // 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); 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); saveModel.setEnabled(false); saveAsVerilog.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); 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); saveModel.setEnabled(false); saveAsVerilog.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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((Learn) component).getViewLogEnabled()); viewCoverage.setEnabled(false); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof LearnLHPN) { 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled()); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof DataManager) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); 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); 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); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(((Learn) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((Learn) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled()); } } 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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(((Learn) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((Learn) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled()); } } 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); 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); saveModel.setEnabled(false); saveAsVerilog.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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); // always false?? viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); // Should // true // only // verification // result // available??? viewCircuit.setEnabled(false); // always true??? viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); // Should // true // only // verification // result // available??? viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled()); viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); 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); saveModel.setEnabled(false); saveAsVerilog.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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } private void enableTreeMenu() { if (tree.getFile() != null) { if (tree.getFile().equals(root)) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createVer.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewModel.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else 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); createVer.setEnabled(false); 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); saveAsVerilog.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); createVer.setEnabled(false); 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); saveAsVerilog.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); createVer.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); saveAsVerilog.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); createVer.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(true); // save.setEnabled(true); // should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); createVer.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(true); // save.setEnabled(true); // should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // save.setEnabled(true); // should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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 ????? // viewCoverage.setEnabled(false); // viewVHDL.setEnabled(false); // viewVerilog.setEnabled(false); viewLHPN.setEnabled(true); // true ??? since lpn // save.setEnabled(true); // should exist ??? // saveas too??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(true); 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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (new File(tree.getFile()).isDirectory()) { 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); createVer.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createVer.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createVer.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewModel.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } public String getRoot() { return root; } public void setGlassPane(boolean visible) { // frame.getGlassPane().setVisible(visible); } public boolean checkFiles(String input, String output) { input = input.replaceAll(" output = output.replaceAll(" if (input.equals(output)) { Object[] options = { "Ok" }; JOptionPane .showOptionDialog(frame, "Files are the same.", "Files Same", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); return false; } return true; } 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 = ""; String gcms = ""; for (int i = 0; i < views.length; i++) { if (views[i].endsWith(".gcm")) { gcms += views[i] + "\n"; } else { view += views[i] + "\n"; } } String message; if (gcms.equals("")) { message = "The file, " + name + ", already exists, and\nit is linked to the following views:\n\n" + view + "\n\nAre you sure you want to overwrite?"; /* * message = "Unable to overwrite the selected file." + * "\nIt is linked to the following views:\n" + view + * "Delete these views first."; */ } else if (view.equals("")) { message = "The file, " + name + ", already exists, and\nit is linked to the following gcms:\n\n" + gcms + "\n\nAre you sure you want to overwrite?"; /* * message = "Unable to overwrite the selected file." + * "\nIt is linked to the following gcms:\n" + gcms + * "Delete these gcms first."; */ } else { message = "The file, " + name + ", already exists, and\nit is linked to the following views:\n\n" + views + "\n\nand\nit is linked to the following gcms:\n\n" + gcms + "\n\nAre you sure you want to overwrite?"; /* * message = "Unable to overwrite the selected file." + * "\nIt is linked to the following views:\n" + view + * "It is also linked to the following gcms:\n" + gcms + * "Delete these views and gcms 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); */ value = JOptionPane.showOptionDialog(frame, scroll, "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); value = JOptionPane.NO_OPTION; } 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 void updateTabName(String oldName, String newName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (oldName.equals(tab)) { this.tab.setTitleAt(i, newName); } } } 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); } } else if (s.endsWith(".gcm") && (filename.endsWith(".gcm") || filename.endsWith(".xml") || filename .endsWith(".sbml"))) { GCMFile gcm = new GCMFile(root); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(filename)) { views.add(s); } for (String comp : gcm.getComponents().keySet()) { if (gcm.getComponents().get(comp).getProperty("gcm").equals(filename)) { views.add(s); break; } } } } 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 = 0; if (SBMLLevelVersion.equals("L2V4")) { numErrors = document.checkL2v4Compatibility(); } else { numErrors = document.checkL3v1Compatibility(); } 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); } if (document.getLevel() < 3) { document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, filename); document = reader.readSBML(filename); } 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 com.intellij.diagnostic; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.AppScheduledExecutorService; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.management.ListenerNotFoundException; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.swing.*; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.ThreadInfo; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.Consumer; public final class PerformanceWatcher implements Disposable { private static final Logger LOG = Logger.getInstance(PerformanceWatcher.class); private static final int TOLERABLE_LATENCY = 100; private static final String THREAD_DUMPS_PREFIX = "threadDumps-"; static final String DUMP_PREFIX = "threadDump-"; private static final String DURATION_FILE_NAME = ".duration"; private ScheduledFuture<?> myThread; private volatile SamplingTask myDumpTask; private final File myLogDir = new File(PathManager.getLogPath()); private List<StackTraceElement> myStacktraceCommonPart; private volatile ApdexData mySwingApdex = ApdexData.EMPTY; private volatile ApdexData myGeneralApdex = ApdexData.EMPTY; private volatile long myLastSampling = System.currentTimeMillis(); private long myLastDumpTime; private long myFreezeStart; private int myActiveEvents; private boolean myFreezeDuringStartup; private final AtomicInteger myEdtRequestsQueued = new AtomicInteger(0); private static final long ourIdeStart = System.currentTimeMillis(); private long myLastEdtAlive = System.currentTimeMillis(); private final ScheduledExecutorService myExecutor = AppExecutorUtil.createBoundedScheduledExecutorService("EDT Performance Checker", 1); private FreezeCheckerTask myCurrentEDTEventChecker; private static final boolean PRECISE_MODE = shouldWatch() && Registry.is("performance.watcher.precise"); @NotNull public static PerformanceWatcher getInstance() { LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred(); return ServiceManager.getService(PerformanceWatcher.class); } public PerformanceWatcher() { if (!shouldWatch()) return; AppScheduledExecutorService service = (AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService(); service.setNewThreadListener(new Consumer<Thread>() { private final int ourReasonableThreadPoolSize = Registry.intValue("core.pooled.threads"); @Override public void accept(Thread thread) { if (service.getBackendPoolExecutorSize() > ourReasonableThreadPoolSize && ApplicationInfoImpl.getShadowInstance().isEAP()) { File file = dumpThreads("newPooledThread/", true); LOG.info("Not enough pooled threads" + (file != null ? "; dumped threads into file '" + file.getPath() + "'" : "")); } } }); ApplicationManager.getApplication().executeOnPooledThread(() -> { for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) { if ("Code Cache".equals(bean.getName())) { watchCodeCache(bean); break; } } cleanOldFiles(myLogDir, 0); }); myThread = myExecutor.scheduleWithFixedDelay(this::samplePerformance, getSamplingInterval(), getSamplingInterval(), TimeUnit.MILLISECONDS); } @NotNull private static IdePerformanceListener getPublisher() { return ApplicationManager.getApplication().getMessageBus().syncPublisher(IdePerformanceListener.TOPIC); } private static int getMaxAttempts() { return Registry.intValue("performance.watcher.unresponsive.max.attempts.before.log"); } private void watchCodeCache(final MemoryPoolMXBean bean) { final long threshold = bean.getUsage().getMax() - 5 * 1024 * 1024; if (!bean.isUsageThresholdSupported() || threshold <= 0) return; bean.setUsageThreshold(threshold); final NotificationEmitter emitter = (NotificationEmitter)ManagementFactory.getMemoryMXBean(); emitter.addNotificationListener(new NotificationListener() { @Override public void handleNotification(Notification n, Object hb) { if (bean.getUsage().getUsed() > threshold) { LOG.info("Code Cache is almost full"); dumpThreads("codeCacheFull", true); try { emitter.removeNotificationListener(this); } catch (ListenerNotFoundException e) { LOG.error(e); } } } }, null, null); } public void processUnfinishedFreeze(BiConsumer<File, Integer> consumer) { File[] files = myLogDir.listFiles(); if (files != null) { Arrays.stream(files) .filter(file -> file.getName().startsWith(THREAD_DUMPS_PREFIX)) .filter(file -> Files.exists(file.toPath().resolve(DURATION_FILE_NAME))) .findFirst().ifPresent(f -> { File marker = new File(f, DURATION_FILE_NAME); try { String s = FileUtil.loadFile(marker); cleanup(f); consumer.accept(f, Integer.parseInt(s)); } catch (Exception ignored) { } }); } } private static void cleanOldFiles(File dir, final int level) { File[] children = dir.listFiles((dir1, name) -> level > 0 || name.startsWith(THREAD_DUMPS_PREFIX)); if (children == null) return; Arrays.sort(children); for (int i = 0; i < children.length; i++) { File child = children[i]; if (i < children.length - 100 || ageInDays(child) > 10) { FileUtil.delete(child); } else if (level < 3) { cleanOldFiles(child, level + 1); } } } private static long ageInDays(File file) { return TimeUnit.DAYS.convert(System.currentTimeMillis() - file.lastModified(), TimeUnit.MILLISECONDS); } @Override public void dispose() { if (myThread != null) { myThread.cancel(true); } myExecutor.shutdownNow(); } private static boolean shouldWatch() { return !ApplicationManager.getApplication().isHeadlessEnvironment() && getUnresponsiveInterval() != 0 && getMaxAttempts() != 0; } private void samplePerformance() { long millis = System.currentTimeMillis(); long diff = millis - myLastSampling - getSamplingInterval(); myLastSampling = millis; // an unexpected delay of 3 seconds is considered as several delays: of 3, 2 and 1 seconds, because otherwise // this background thread would be sampled 3 times. while (diff >= 0) { myGeneralApdex = myGeneralApdex.withEvent(TOLERABLE_LATENCY, diff); diff -= getSamplingInterval(); } if (!PRECISE_MODE) { int edtRequests = myEdtRequestsQueued.get(); if (edtRequests >= getMaxAttempts()) { edtFrozen(millis); } else if (edtRequests == 0) { edtResponds(millis); } } myEdtRequestsQueued.incrementAndGet(); //noinspection SSBasedInspection SwingUtilities.invokeLater(new SwingThreadRunnable(millis)); } @NotNull public static String printStacktrace(@NotNull String headerMsg, @NotNull Thread thread, @NotNull StackTraceElement[] stackTrace) { @SuppressWarnings("NonConstantStringShouldBeStringBuffer") StringBuilder trace = new StringBuilder( headerMsg + thread + " (" + (thread.isAlive() ? "alive" : "dead") + ") " + thread.getState() + "\n--- its stacktrace:\n"); for (final StackTraceElement stackTraceElement : stackTrace) { trace.append(" at ").append(stackTraceElement).append("\n"); } trace.append(" return trace.toString(); } private static int getSamplingInterval() { return Registry.intValue("performance.watcher.sampling.interval.ms"); } static int getDumpInterval() { return getSamplingInterval() * getMaxAttempts(); } static int getUnresponsiveInterval() { return Registry.intValue("performance.watcher.unresponsive.interval.ms"); } static int getMaxDumpDuration() { return Registry.intValue("performance.watcher.dump.duration.s") * 1000; } private void edtFrozen(long currentMillis) { if (currentMillis - myLastDumpTime >= getUnresponsiveInterval()) { myLastDumpTime = currentMillis; if (myFreezeStart == 0) { myFreezeStart = myLastEdtAlive; myFreezeDuringStartup = !LoadingState.INDEXING_FINISHED.isOccurred(); getPublisher().uiFreezeStarted(); } dumpThreads(); } } @NotNull private String getFreezeFolderName(long freezeStartMs) { return THREAD_DUMPS_PREFIX + (myFreezeDuringStartup ? "freeze-startup-" : "freeze-") + formatTime(freezeStartMs) + "-" + buildName(); } private static String buildName() { return ApplicationInfo.getInstance().getBuild().asString(); } private static String formatTime(long timeMs) { return new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(timeMs)); } private void stopDumping() { SamplingTask task = myDumpTask; if (task != null) { task.stop(); } } private void edtResponds(long currentMillis) { stopDumping(); if (myFreezeStart != 0) { int unresponsiveDuration = (int)(currentMillis - myFreezeStart) / 1000; File dir = new File(myLogDir, getFreezeFolderName(myFreezeStart)); File reportDir = null; if (dir.exists()) { cleanup(dir); reportDir = new File(myLogDir, dir.getName() + getFreezePlaceSuffix() + "-" + unresponsiveDuration + "sec"); if (!dir.renameTo(reportDir)) { reportDir = null; } } getPublisher().uiFreezeFinished(currentMillis - myFreezeStart, reportDir); myFreezeStart = 0; myStacktraceCommonPart = null; } } private static void cleanup(File dir) { FileUtil.delete(new File(dir, DURATION_FILE_NAME)); } public void edtEventStarted(long start) { myActiveEvents++; if (PRECISE_MODE) { finishTracking(); startTracking(start); } } public void edtEventFinished() { myActiveEvents finishTracking(); if (PRECISE_MODE && myActiveEvents > 0) { startTracking(System.currentTimeMillis()); } } private void startTracking(long start) { myCurrentEDTEventChecker = new FreezeCheckerTask(start); } private void finishTracking() { FreezeCheckerTask currentChecker = myCurrentEDTEventChecker; if (currentChecker != null) { currentChecker.stop(); myCurrentEDTEventChecker = null; } } private String getFreezePlaceSuffix() { if (myStacktraceCommonPart != null && !myStacktraceCommonPart.isEmpty()) { final StackTraceElement element = myStacktraceCommonPart.get(0); return "-" + StringUtil.getShortName(element.getClassName()) + "." + element.getMethodName(); } return ""; } private void dumpThreads() { if (myFreezeStart != 0 && System.currentTimeMillis() - myFreezeStart <= getMaxDumpDuration()) { dumpThreads(getFreezeFolderName(myFreezeStart) + "/", false, ThreadDumper.getThreadInfos(), true); } else { stopDumping(); } } @Nullable public File dumpThreads(@NotNull String pathPrefix, boolean millis) { return dumpThreads(pathPrefix, millis, ThreadDumper.getThreadInfos(), false); } @Nullable private File dumpThreads(@NotNull String pathPrefix, boolean millis, ThreadInfo[] threadInfos, boolean notify) { if (!shouldWatch()) return null; if (!pathPrefix.contains("/")) { pathPrefix = THREAD_DUMPS_PREFIX + pathPrefix + "-" + formatTime(ourIdeStart) + "-" + buildName() + "/"; } else if (!pathPrefix.startsWith(THREAD_DUMPS_PREFIX)) { pathPrefix = THREAD_DUMPS_PREFIX + pathPrefix; } long now = System.currentTimeMillis(); String suffix = millis ? "-" + now : ""; File file = new File(myLogDir, pathPrefix + DUMP_PREFIX + formatTime(now) + suffix + ".txt"); File dir = file.getParentFile(); if (!(dir.isDirectory() || dir.mkdirs())) { return null; } checkMemoryUsage(file); ThreadDump threadDump = ThreadDumper.getThreadDumpInfo(threadInfos); try { FileUtil.writeToFile(file, threadDump.getRawDump()); if (notify) { if (myFreezeStart != 0) { FileUtil.writeToFile(new File(dir, DURATION_FILE_NAME), String.valueOf((now - myFreezeStart) / 1000)); } StackTraceElement[] edtStack = threadDump.getEDTStackTrace(); if (edtStack != null) { if (myStacktraceCommonPart == null) { myStacktraceCommonPart = ContainerUtil.newArrayList(edtStack); } else { myStacktraceCommonPart = getStacktraceCommonPart(myStacktraceCommonPart, edtStack); } } getPublisher().dumpedThreads(file, threadDump); } } catch (IOException e) { LOG.info("failed to write thread dump file: " + e.getMessage()); } return file; } private static void checkMemoryUsage(File file) { Runtime rt = Runtime.getRuntime(); long maxMemory = rt.maxMemory(); long usedMemory = rt.totalMemory() - rt.freeMemory(); long freeMemory = maxMemory - usedMemory; if (freeMemory < maxMemory / 5) { LOG.info("High memory usage (free " + freeMemory / 1024 / 1024 + " of " + maxMemory / 1024 / 1024 + " MB) while dumping threads to " + file); } } @SuppressWarnings("UseOfSystemOutOrSystemErr") public static void dumpThreadsToConsole(String message) { System.err.println(message); System.err.println(ThreadDumper.dumpThreadsToString()); } static List<StackTraceElement> getStacktraceCommonPart(final List<StackTraceElement> commonPart, final StackTraceElement[] stackTraceElements) { for (int i = 0; i < commonPart.size() && i < stackTraceElements.length; i++) { StackTraceElement el1 = commonPart.get(commonPart.size() - i - 1); StackTraceElement el2 = stackTraceElements[stackTraceElements.length - i - 1]; if (!compareStackTraceElements(el1, el2)) { return commonPart.subList(commonPart.size() - i, commonPart.size()); } } return commonPart; } // same as java.lang.StackTraceElement.equals, but do not care about the line number static boolean compareStackTraceElements(StackTraceElement el1, StackTraceElement el2) { if (el1 == el2) { return true; } return el1.getClassName().equals(el2.getClassName()) && Objects.equals(el1.getMethodName(), el2.getMethodName()) && Objects.equals(el1.getFileName(), el2.getFileName()); } private class SwingThreadRunnable implements Runnable { private final long myCreationMillis; SwingThreadRunnable(long creationMillis) { myCreationMillis = creationMillis; } @Override public void run() { myEdtRequestsQueued.decrementAndGet(); myLastEdtAlive = System.currentTimeMillis(); final long latency = System.currentTimeMillis() - myCreationMillis; mySwingApdex = mySwingApdex.withEvent(TOLERABLE_LATENCY, latency); final Application application = ApplicationManager.getApplication(); if (application.isDisposed()) return; getPublisher().uiResponded(latency); } } public class Snapshot { private final ApdexData myStartGeneralSnapshot = myGeneralApdex; private final ApdexData myStartSwingSnapshot = mySwingApdex; private final long myStartMillis = System.currentTimeMillis(); private Snapshot() { } public void logResponsivenessSinceCreation(@NotNull String activityName) { LOG.info(activityName + " took " + (System.currentTimeMillis() - myStartMillis) + "ms" + "; general responsiveness: " + myGeneralApdex.summarizePerformanceSince(myStartGeneralSnapshot) + "; EDT responsiveness: " + mySwingApdex.summarizePerformanceSince(myStartSwingSnapshot)); } } @NotNull public static Snapshot takeSnapshot() { return getInstance().new Snapshot(); } ScheduledExecutorService getExecutor() { return myExecutor; } private enum CheckerState { CHECKING, FREEZE, FINISHED } private class FreezeCheckerTask { private final AtomicReference<CheckerState> myState = new AtomicReference<>(CheckerState.CHECKING); private final Future<?> myFuture; FreezeCheckerTask(long start) { myFuture = myExecutor.schedule(() -> edtFrozenPrecise(start), getUnresponsiveInterval(), TimeUnit.MILLISECONDS); } void stop() { myFuture.cancel(false); if (myState.getAndSet(CheckerState.FINISHED) == CheckerState.FREEZE) { long end = System.currentTimeMillis(); stopDumping(); // stop sampling as early as possible try { myExecutor.submit(() -> edtResponds(end)).get(); } catch (Exception e) { LOG.warn(e); } } } private void edtFrozenPrecise(long start) { if (myState.compareAndSet(CheckerState.CHECKING, CheckerState.FREEZE)) { myFreezeStart = start; getPublisher().uiFreezeStarted(); stopDumping(); myDumpTask = new SamplingTask(getDumpInterval(), getMaxDumpDuration()) { @Override protected void dumpedThreads(ThreadInfo[] infos) { if (myState.get() == CheckerState.FINISHED) { stop(); } else { dumpThreads(getFreezeFolderName(myFreezeStart) + "/", false, infos, true); } } }; } } } }
package com.zutubi.diff.unified; import com.zutubi.diff.PatchParseException; import com.zutubi.diff.PatchParser; import com.zutubi.diff.PeekReader; import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UnifiedPatchParser implements PatchParser { private static final Pattern RE_EPOCH = Pattern.compile(".*(1970-01-01|\\(revision 0\\)).*"); private static final Pattern RE_HUNK = Pattern.compile("\\s*@@\\s+-(\\d+)(?:,(\\d+))?\\s+\\+(\\d+)(?:,(\\d+))?\\s+@@\\s*"); private static char[] QUOTE_CHARS = new char[] { '"', '\'' }; /** * Struct to hold information for a patch header line. */ private static class PatchHeader { private String filename; private boolean isEpoch; private PatchHeader(String filename, boolean epoch) { this.filename = filename; isEpoch = epoch; } } public boolean isPatchHeader(String line) { return line.startsWith(UnifiedPatch.HEADER_OLD_FILE); } public UnifiedPatch parse(PeekReader reader) throws IOException, PatchParseException { // Headers are: // '+++ ' new-filename '\t' date ' ' time ' ' timezone // The portion after the filenames is optional - and may have a // completely different format. PatchHeader oldHead = parsePatchHeader(reader, UnifiedPatch.HEADER_OLD_FILE); PatchHeader newHead = parsePatchHeader(reader, UnifiedPatch.HEADER_NEW_FILE); UnifiedPatch patch = new UnifiedPatch(oldHead.filename, oldHead.isEpoch, newHead.filename, newHead.isEpoch); while (!reader.spent()) { String line = reader.peek(); if (isPatchHeader(line)) { // Hit the next patch. break; } else { reader.next(); Matcher matcher = RE_HUNK.matcher(line); if (matcher.matches()) { int hunkLineNumber = reader.getLineNumber(); long oldOffset = Long.parseLong(matcher.group(1)); long oldLength = parseOptionalLong(matcher.group(2)); long newOffset = Long.parseLong(matcher.group(3)); long newLength = parseOptionalLong(matcher.group(4)); UnifiedHunk hunk = new UnifiedHunk(oldOffset, oldLength, newOffset, newLength); if (readHunkLines(reader, hunk)) { patch.setNewlineTerminated(false); } if (checkConsistency(patch, hunk, hunkLineNumber)) { patch.addHunk(hunk); } } } } return patch; } private PatchHeader parsePatchHeader(PeekReader reader, String indicator) throws IOException, PatchParseException { String line = reader.next(); if (!line.startsWith(indicator)) { throw new PatchParseException(reader.getLineNumber(), "Expecting a line starting with '" + indicator + "'; got '" + line + "'"); } String trim = line.substring(indicator.length()).trim(); String[] parts = trim.split("\\t", 2); String filename = parts[0]; int length = filename.length(); // If the filename is quoted, strip the quotes if (length >= 2) { // Only run if the length of the filename has two or more chars char firstChar = filename.charAt(0); char lastChar = filename.charAt(length - 1); // Check each of the possible quote characters for (char quoteChar : QUOTE_CHARS) { // If both the first and last character of the filename match // the quote character, strip the quotes and break the loop so // that we do not accidently strip multiple different types of // quotes. if (firstChar == quoteChar && lastChar == quoteChar) { filename = filename.substring(1, length - 1); length -= 2; break; } } } if (length == 0) { throw new PatchParseException(reader.getLineNumber(), "Patch header line '" + line + "' is missing filename"); } boolean isEpoch = parts.length == 2 && RE_EPOCH.matcher(parts[1]).matches(); return new PatchHeader(filename, isEpoch); } private long parseOptionalLong(String s) { if (s != null && !s.isEmpty()) { return Long.parseLong(s); } else { return 1; } } private boolean readHunkLines(PeekReader reader, UnifiedHunk hunk) throws IOException, PatchParseException { boolean previousWasNoNewline = false; while (!reader.spent()) { String line = reader.peek(); if (line.length() > 0) { char first = line.charAt(0); if (first == '\\' && line.equalsIgnoreCase(UnifiedPatch.NO_NEWLINE)) { previousWasNoNewline = true; } else { UnifiedHunk.LineType lineType = UnifiedHunk.LineType.valueOf(first); if (lineType == null) { break; } previousWasNoNewline = false; hunk.addLine(lineType, line.substring(1)); } } reader.next(); } return previousWasNoNewline; } private boolean checkConsistency(UnifiedPatch patch, UnifiedHunk hunk, int lineNumber) throws PatchParseException { int oldCount = 0; int newCount = 0; // Check this hunk comes after the previous one. List<UnifiedHunk> previousHunks = patch.getHunks(); if (!previousHunks.isEmpty()) { UnifiedHunk previousHunk = previousHunks.get(previousHunks.size() - 1); if (hunk.getOldOffset() < previousHunk.getOldOffset() + previousHunk.getOldLength()) { throw new PatchParseException(lineNumber, "Hunk old offset " + hunk.getOldOffset() + " comes before the end of the previous hunk in the old file"); } if (hunk.getNewOffset() < previousHunk.getNewOffset() + previousHunk.getNewLength()) { throw new PatchParseException(lineNumber, "Hunk new offset " + hunk.getOldOffset() + " comes before the end of the previous hunk in the new file"); } } // Check this hunk is internally consistent. for (UnifiedHunk.Line line: hunk.getLines()) { UnifiedHunk.LineType type = line.getType(); if (type.inOriginal()) { oldCount++; } if (type.inNew()) { newCount++; } } if (oldCount != hunk.getOldLength()) { throw new PatchParseException(lineNumber, "Hunk old length " + hunk.getOldLength() + " is not consistent with hunk lines"); } if (newCount != hunk.getNewLength()) { throw new PatchParseException(lineNumber, "Hunk new length " + hunk.getOldLength() + " is not consistent with hunk lines"); } // Return true if this hunk is empty and can be ignored. return oldCount + newCount > 0; } }
package eu.socialsensor.focused.crawler; import java.net.UnknownHostException; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.log4j.Logger; import eu.socialsensor.focused.crawler.bolts.media.ClustererBolt; import eu.socialsensor.focused.crawler.bolts.media.ConceptDetectionBolt; import eu.socialsensor.focused.crawler.bolts.media.MediaRankerBolt; import eu.socialsensor.focused.crawler.bolts.media.MediaUpdaterBolt; import eu.socialsensor.focused.crawler.bolts.media.VisualIndexerBolt; import eu.socialsensor.focused.crawler.bolts.metrics.MediaCounterBolt; import eu.socialsensor.focused.crawler.spouts.RedisSpout; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.StormSubmitter; import backtype.storm.generated.AlreadyAliveException; import backtype.storm.generated.InvalidTopologyException; import backtype.storm.topology.IRichBolt; import backtype.storm.topology.TopologyBuilder; import backtype.storm.topology.base.BaseRichSpout; public class VisualIndexer { /** * @param args * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException { Logger logger = Logger.getLogger(VisualIndexer.class); XMLConfiguration config; try { if(args.length == 1) config = new XMLConfiguration(args[0]); else config = new XMLConfiguration("./conf/focused.crawler.xml"); } catch(ConfigurationException ex) { logger.error(ex); return; } String redisHost = config.getString("redis.hostname", "xxx.xxx.xxx.xxx"); String redisMediaChannel = config.getString("redis.mediaItemsChannel", "media"); String mongodbHostname = config.getString("mongodb.hostname", "xxx.xxx.xxx.xxx"); String mediaItemsDB = config.getString("mongodb.mediaItemsDB", "Prototype"); String mediaItemsCollection = config.getString("mongodb.mediaItemsCollection", "MediaItems_WP"); String streamUsersDB = config.getString("mongodb.streamUsersDB", "Prototype"); String streamUsersCollection = config.getString("mongodb.streamUsersCollection", "StreamUsers"); String clustersDB = config.getString("mongodb.clustersDB", "Prototype"); String clustersCollection = config.getString("mongodb.clustersCollection", "MediaClusters"); String conceptDetectorMatlabfile = config.getString("conceptdetector.matlabfile"); String visualIndexHostname = config.getString("visualindex.hostname"); String visualIndexCollection = config.getString("visualindex.collection"); String learningFiles = config.getString("visualindex.learningfiles"); if(!learningFiles.endsWith("/")) learningFiles = learningFiles + "/"; String[] codebookFiles = { learningFiles + "surf_l2_128c_0.csv", learningFiles + "surf_l2_128c_1.csv", learningFiles + "surf_l2_128c_2.csv", learningFiles + "surf_l2_128c_3.csv" }; String pcaFile = learningFiles + "pca_surf_4x128_32768to1024.txt"; BaseRichSpout miSpout; IRichBolt miRanker, mediaCounter, visualIndexer, clusterer, mediaUpdater, conceptDetector; try { miSpout = new RedisSpout(redisHost, redisMediaChannel, "id"); miRanker = new MediaRankerBolt(redisMediaChannel); mediaCounter = new MediaCounterBolt(mongodbHostname, "Statistics"); visualIndexer = new VisualIndexerBolt(visualIndexHostname, visualIndexCollection, codebookFiles, pcaFile); clusterer = new ClustererBolt(mongodbHostname, mediaItemsDB, mediaItemsCollection, clustersDB, clustersCollection, visualIndexHostname, visualIndexCollection); conceptDetector = new ConceptDetectionBolt(conceptDetectorMatlabfile); mediaUpdater = new MediaUpdaterBolt(mongodbHostname, mediaItemsDB, mediaItemsCollection, streamUsersDB, streamUsersCollection); } catch (Exception e) { logger.error(e); return; } // Create topology TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("miInjector", miSpout, 1); builder.setBolt("miRanker", miRanker, 4).shuffleGrouping("miInjector"); builder.setBolt("counter", mediaCounter, 1).shuffleGrouping("miRanker"); builder.setBolt("indexer", visualIndexer, 16).shuffleGrouping("miRanker"); //builder.setBolt("clusterer", clusterer, 1).shuffleGrouping("indexer"); builder.setBolt("conceptDetector", conceptDetector, 1).shuffleGrouping("indexer"); builder.setBolt("mediaupdater", mediaUpdater, 1) .shuffleGrouping("conceptDetector"); // Run topology String name = config.getString("topology.focusedCrawlerName", "VisualIndexer"); boolean local = config.getBoolean("topology.local", true); Config conf = new Config(); conf.setDebug(false); if(!local) { System.out.println("Submit topology to Storm cluster"); try { int workers = config.getInt("topology.workers", 2); conf.setNumWorkers(workers); StormSubmitter.submitTopology(name, conf, builder.createTopology()); } catch(NumberFormatException e) { logger.error(e); } catch (AlreadyAliveException e) { logger.error(e); } catch (InvalidTopologyException e) { logger.error(e); } } else { logger.info("Run topology in local mode"); LocalCluster cluster = new LocalCluster(); cluster.submitTopology(name, conf, builder.createTopology()); } } }
package edu.umd.cs.findbugs.workflow; import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; import org.dom4j.DocumentException; import edu.umd.cs.findbugs.AppVersion; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.DetectorFactoryCollection; import edu.umd.cs.findbugs.Project; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.VersionInsensitiveBugComparator; import edu.umd.cs.findbugs.config.CommandLine; import edu.umd.cs.findbugs.model.MovedClassMap; /** * Java main application to compute update a historical bug collection with * results from another build/analysis. * * @author William Pugh */ public class Update { private static final String USAGE = "Usage: " + Update.class.getName() + " [options] data1File data2File data3File ... "; private static HashMap<BugInstance, BugInstance> mapFromNewToOldBug = new HashMap<BugInstance, BugInstance>(); private static HashSet<BugInstance> matchedOldBugs = new HashSet<BugInstance>(); static class UpdateCommandLine extends CommandLine { boolean overrideRevisionNames = false; String outputFilename; UpdateCommandLine() { addSwitch("-overrideRevisionNames", "override revision names for each version with names computed filenames"); addSwitch("-precisePriorityMatch", "only consider two warnings to be the same if their prioritys match exactly"); addOption("-output", "output file", "explicit filename for merged results (standard out used if not specified)"); } @Override protected void handleOption(String option, String optionExtraPart) throws IOException { if (option.equals("-overrideRevisionNames")) { if (optionExtraPart.length() == 0) overrideRevisionNames = true; else overrideRevisionNames = Boolean.parseBoolean(optionExtraPart); } else if (option.equals("-precisePriorityMatch")) versionInsensitiveBugComparator.setComparePriorities(true); else throw new IllegalArgumentException("no option " + option); } @Override protected void handleOptionWithArgument(String option, String argument) throws IOException { if (option.equals("-output")) outputFilename = argument; else throw new IllegalArgumentException("Can't handle option " + option); } } static VersionInsensitiveBugComparator versionInsensitiveBugComparator = new VersionInsensitiveBugComparator(); public static BugCollection mergeCollections(BugCollection origCollection, BugCollection newCollection) { mapFromNewToOldBug.clear(); matchedOldBugs.clear(); BugCollection resultCollection = newCollection .createEmptyCollectionWithMetadata(); // Previous sequence number long lastSequence = origCollection.getSequenceNumber(); // The AppVersion history is retained from the orig collection, // adding an entry for the sequence/timestamp of the current state // of the orig collection. resultCollection.clearAppVersions(); for (Iterator<AppVersion> i = origCollection.appVersionIterator(); i .hasNext();) { AppVersion appVersion = i.next(); resultCollection.addAppVersion((AppVersion) appVersion.clone()); } AppVersion origCollectionVersion = new AppVersion(lastSequence); origCollectionVersion.setTimestamp(origCollection .getCurrentAppVersion().getTimestamp()); origCollectionVersion.setReleaseName(origCollection .getCurrentAppVersion().getReleaseName()); origCollectionVersion.setNumClasses(origCollection.getProjectStats().getNumClasses()); origCollectionVersion.setCodeSize(origCollection.getProjectStats().getCodeSize()); resultCollection.addAppVersion(origCollectionVersion); // We assign a sequence number to the new collection as one greater than // the // original collection. long currentSequence = origCollection.getSequenceNumber() + 1; resultCollection.setSequenceNumber(currentSequence); matchBugs(SortedBugCollection.BugInstanceComparator.instance, origCollection, newCollection); matchBugs(versionInsensitiveBugComparator, origCollection, newCollection); VersionInsensitiveBugComparator movedBugComparator = new VersionInsensitiveBugComparator(); movedBugComparator.setClassNameRewriter(new MovedClassMap(origCollection,newCollection)); matchBugs(movedBugComparator, origCollection, newCollection); // matchBugs(new SloppyBugComparator(), origCollection, newCollection); int oldBugs = 0; int newlyDeadBugs = 0; int persistantBugs = 0; int addedBugs = 0; int addedInNewCode = 0; int deadBugInDeadCode = 0; // Copy unmatched bugs for (BugInstance bug : origCollection.getCollection()) if (!matchedOldBugs.contains(bug)) { if (bug.getLastVersion() == -1) newlyDeadBugs++; else oldBugs++; BugInstance newBug = (BugInstance) bug.clone(); if (newBug.getLastVersion() == -1) { newBug.setLastVersion(lastSequence); ClassAnnotation classBugFoundIn = bug.getPrimaryClass(); String className = classBugFoundIn.getClassName(); if (newCollection.getProjectStats() .getClassStats(className) != null) newBug.setRemovedByChangeOfPersistingClass(true); else deadBugInDeadCode++; } if (newBug.getFirstVersion() > newBug.getLastVersion()) throw new IllegalStateException("Illegal Version range: " + newBug.getFirstVersion() + ".." + newBug.getLastVersion()); resultCollection.add(newBug, false); } // Copy matched bugs for (BugInstance bug : newCollection.getCollection()) { BugInstance newBug = (BugInstance) bug.clone(); if (mapFromNewToOldBug.containsKey(bug)) { BugInstance origWarning = mapFromNewToOldBug.get(bug); assert origWarning.getLastVersion() == -1; newBug.setUniqueId(origWarning.getUniqueId()); copyBugHistory(origWarning, newBug); String annotation = newBug.getAnnotationText(); if (annotation.length() == 0) newBug.setAnnotationText(origWarning.getAnnotationText()); persistantBugs++; } else { newBug.setFirstVersion(lastSequence + 1); addedBugs++; ClassAnnotation classBugFoundIn = bug.getPrimaryClass(); String className = classBugFoundIn.getClassName(); if (origCollection.getProjectStats().getClassStats(className) != null) { newBug.setIntroducedByChangeOfExistingClass(true); // System.out.println("added bug to existing code " + // newBug.getUniqueId() + " : " + newBug.getAbbrev() + " in // " + classBugFoundIn); } else addedInNewCode++; } assert newBug.getLastVersion() == -1; if (newBug.getLastVersion() != -1) throw new IllegalStateException("Illegal Version range: " + newBug.getFirstVersion() + ".." + newBug.getLastVersion()); int oldSize = resultCollection.getCollection().size(); resultCollection.add(newBug, false); int newSize = resultCollection.getCollection().size(); if (newSize != oldSize + 1) { System.out.println("Failed to add bug #" + newBug.getUniqueId() + " : " + newBug.getMessage()); } } if (false && verbose) { System.out.println(origCollection.getCollection().size() + " orig bugs, " + newCollection.getCollection().size() + " new bugs"); System.out.println("Bugs: " + oldBugs + " old, " + deadBugInDeadCode + " in removed code, " + (newlyDeadBugs - deadBugInDeadCode) + " died, " + persistantBugs + " persist, " + addedInNewCode + " in new code, " + (addedBugs - addedInNewCode) + " added"); } return resultCollection; } public static boolean verbose = false; public static String [] getFilePathParts(String filePath) { return filePath.split(File.separator); } public static void main(String[] args) throws IOException, DocumentException { DetectorFactoryCollection.instance(); UpdateCommandLine commandLine = new UpdateCommandLine(); int argCount = commandLine.parse(args, 2, Integer.MAX_VALUE, USAGE); verbose = commandLine.outputFilename != null; String[] firstPathParts = getFilePathParts(args[argCount]); int commonPrefix = firstPathParts.length; for(int i = argCount+1; i <= (args.length - 1); i++) { commonPrefix = Math.min(commonPrefix, lengthCommonPrefix( firstPathParts, getFilePathParts(args[i]))); } String origFilename = args[argCount++]; Project project = new Project(); BugCollection origCollection; origCollection = new SortedBugCollection( SortedBugCollection.MultiversionBugInstanceComparator.instance); if (verbose) System.out.println("Starting with " + origFilename); origCollection.readXML(origFilename, project); if (commandLine.overrideRevisionNames || origCollection.getReleaseName() == null || origCollection.getReleaseName().length() == 0) origCollection.setReleaseName(firstPathParts[commonPrefix]); for (BugInstance bug : origCollection.getCollection()) if (bug.getLastVersion() >= 0 && bug.getFirstVersion() > bug.getLastVersion()) throw new IllegalStateException("Illegal Version range: " + bug.getFirstVersion() + ".." + bug.getLastVersion()); while (argCount <= (args.length - 1)) { BugCollection newCollection = new SortedBugCollection( SortedBugCollection.MultiversionBugInstanceComparator.instance); String newFilename = args[argCount++]; if (verbose) System.out.println("Merging " + newFilename); project = new Project(); newCollection.readXML(newFilename, project); if (commandLine.overrideRevisionNames || newCollection.getReleaseName() == null || newCollection.getReleaseName().length() == 0) newCollection.setReleaseName(getFilePathParts(newFilename)[commonPrefix]); origCollection = mergeCollections(origCollection, newCollection); } if (commandLine.outputFilename != null) origCollection.writeXML(commandLine.outputFilename, project); else origCollection.writeXML(System.out, project); } private static int lengthCommonPrefix(String[] string, String[] string2) { int maxLength = Math.min(string.length, string2.length); for (int result = 0; result < maxLength; result++) if (!string[result].equals(string2[result])) return result; return maxLength; } private static void copyBugHistory(BugInstance src, BugInstance dest) { dest.setFirstVersion(src.getFirstVersion()); dest.setLastVersion(src.getLastVersion()); dest.setIntroducedByChangeOfExistingClass(src .isIntroducedByChangeOfExistingClass()); dest.setRemovedByChangeOfPersistingClass(src .isRemovedByChangeOfPersistingClass()); } private static void matchBugs( Comparator<BugInstance> bugInstanceComparator, BugCollection origCollection, BugCollection newCollection) { TreeMap<BugInstance, LinkedList<BugInstance>> set = new TreeMap<BugInstance, LinkedList<BugInstance>>( bugInstanceComparator); int oldBugs = 0; int newBugs = 0; int matchedBugs = 0; for (BugInstance bug : origCollection.getCollection()) if (bug.getLastVersion() == -1 && !matchedOldBugs.contains(bug)) { oldBugs++; LinkedList<BugInstance> q = set.get(bug); if (q == null) { q = new LinkedList<BugInstance>(); set.put(bug, q); } q.offer(bug); } for (BugInstance bug : newCollection.getCollection()) if (!mapFromNewToOldBug.containsKey(bug)) { newBugs++; LinkedList<BugInstance> q = set.get(bug); if (q != null && !q.isEmpty()) { matchedBugs++; BugInstance matchedBug = q.remove(); mapFromNewToOldBug.put(bug, matchedBug); matchedOldBugs.add(matchedBug); } } if (false && verbose) System.out.println("matched " + matchedBugs + " of " + oldBugs +"o/" + newBugs + "n bugs using " + bugInstanceComparator.getClass().getName()); } }
package org.zstack.kvm; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestClientException; import org.springframework.web.util.UriComponentsBuilder; import org.zstack.compute.host.HostBase; import org.zstack.compute.host.HostSystemTags; import org.zstack.compute.host.MigrateNetworkExtensionPoint; import org.zstack.compute.vm.IsoOperator; import org.zstack.compute.vm.VmGlobalConfig; import org.zstack.compute.vm.VmSystemTags; import org.zstack.core.CoreGlobalProperty; import org.zstack.core.MessageCommandRecorder; import org.zstack.core.Platform; import org.zstack.core.ansible.AnsibleGlobalProperty; import org.zstack.core.ansible.AnsibleRunner; import org.zstack.core.ansible.SshFileMd5Checker; import org.zstack.core.cloudbus.CloudBusCallBack; import org.zstack.core.db.Q; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.timeout.ApiTimeoutManager; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.Constants; import org.zstack.header.core.AsyncLatch; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.ReturnValueCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.*; import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy; import org.zstack.header.image.ImagePlatform; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.MessageReply; import org.zstack.header.message.NeedReplyMessage; import org.zstack.header.network.l2.*; import org.zstack.header.rest.JsonAsyncRESTCallback; import org.zstack.header.rest.RESTFacade; import org.zstack.header.storage.primary.*; import org.zstack.header.storage.snapshot.VolumeSnapshotInventory; import org.zstack.header.tag.SystemTagInventory; import org.zstack.header.vm.*; import org.zstack.header.volume.VolumeInventory; import org.zstack.header.volume.VolumeType; import org.zstack.header.volume.VolumeVO; import org.zstack.kvm.KVMAgentCommands.*; import org.zstack.kvm.KVMConstant.KvmVmState; import org.zstack.tag.SystemTagCreator; import org.zstack.tag.TagManager; import org.zstack.utils.*; import org.zstack.utils.logging.CLogger; import org.zstack.utils.network.NetworkUtils; import org.zstack.utils.path.PathUtil; import org.zstack.utils.ssh.Ssh; import org.zstack.utils.ssh.SshResult; import org.zstack.utils.ssh.SshShell; import javax.persistence.TypedQuery; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.zstack.core.Platform.*; import static org.zstack.utils.CollectionDSL.e; import static org.zstack.utils.CollectionDSL.map; public class KVMHost extends HostBase implements Host { private static final CLogger logger = Utils.getLogger(KVMHost.class); @Autowired @Qualifier("KVMHostFactory") private KVMHostFactory factory; @Autowired private RESTFacade restf; @Autowired private KVMExtensionEmitter extEmitter; @Autowired private ErrorFacade errf; @Autowired private TagManager tagmgr; @Autowired private ApiTimeoutManager timeoutManager; private KVMHostContext context; // ///////////////////// REST URL ////////////////////////// private String baseUrl; private String connectPath; private String pingPath; private String checkPhysicalNetworkInterfacePath; private String startVmPath; private String stopVmPath; private String pauseVmPath; private String resumeVmPath; private String rebootVmPath; private String destroyVmPath; private String attachDataVolumePath; private String detachDataVolumePath; private String echoPath; private String attachNicPath; private String detachNicPath; private String migrateVmPath; private String snapshotPath; private String mergeSnapshotPath; private String hostFactPath; private String attachIsoPath; private String detachIsoPath; private String checkVmStatePath; private String getConsolePortPath; private String onlineIncreaseCpuPath; private String onlineIncreaseMemPath; private String deleteConsoleFirewall; private String updateHostOSPath; private String agentPackageName = KVMGlobalProperty.AGENT_PACKAGE_NAME; KVMHost(KVMHostVO self, KVMHostContext context) { super(self); this.context = context; baseUrl = context.getBaseUrl(); UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_CONNECT_PATH); connectPath = ub.build().toUriString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_PING_PATH); pingPath = ub.build().toUriString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_CHECK_PHYSICAL_NETWORK_INTERFACE_PATH); checkPhysicalNetworkInterfacePath = ub.build().toUriString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_START_VM_PATH); startVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_STOP_VM_PATH); stopVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_PAUSE_VM_PATH); pauseVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_RESUME_VM_PATH); resumeVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_REBOOT_VM_PATH); rebootVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DESTROY_VM_PATH); destroyVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ATTACH_VOLUME); attachDataVolumePath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DETACH_VOLUME); detachDataVolumePath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ECHO_PATH); echoPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ATTACH_NIC_PATH); attachNicPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DETACH_NIC_PATH); detachNicPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_MIGRATE_VM_PATH); migrateVmPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_TAKE_VOLUME_SNAPSHOT_PATH); snapshotPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_MERGE_SNAPSHOT_PATH); mergeSnapshotPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_HOST_FACT_PATH); hostFactPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_ATTACH_ISO_PATH); attachIsoPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DETACH_ISO_PATH); detachIsoPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_VM_CHECK_STATE); checkVmStatePath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_GET_VNC_PORT_PATH); getConsolePortPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_CPU); onlineIncreaseCpuPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_MEMORY); onlineIncreaseMemPath = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH); deleteConsoleFirewall = ub.build().toString(); ub = UriComponentsBuilder.fromHttpUrl(baseUrl); ub.path(KVMConstant.KVM_UPDATE_HOST_OS_PATH); updateHostOSPath = ub.build().toString(); } class Http<T> { String path; AgentCommand cmd; Class<T> responseClass; String commandStr; TimeUnit unit; Long timeout; public Http(String path, String cmd, Class<T> rspClz, TimeUnit unit, Long timeout) { this.path = path; this.commandStr = cmd; this.responseClass = rspClz; this.unit = unit; this.timeout = timeout; } public Http(String path, AgentCommand cmd, Class<T> rspClz) { this.path = path; this.cmd = cmd; this.responseClass = rspClz; } void call(ReturnValueCompletion<T> completion) { call(null, completion); } void call(String resourceUuid, ReturnValueCompletion<T> completion) { Map<String, String> header = new HashMap<>(); header.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, resourceUuid == null ? self.getUuid() : resourceUuid); if (commandStr != null) { restf.asyncJsonPost(path, commandStr, header, new JsonAsyncRESTCallback<T>(completion) { @Override public void fail(ErrorCode err) { completion.fail(err); } @Override public void success(T ret) { completion.success(ret); } @Override public Class<T> getReturnClass() { return responseClass; } }, unit, timeout); } else { restf.asyncJsonPost(path, cmd, header, new JsonAsyncRESTCallback<T>(completion) { @Override public void fail(ErrorCode err) { completion.fail(err); } @Override public void success(T ret) { completion.success(ret); } @Override public Class<T> getReturnClass() { return responseClass; } }); // DO NOT pass unit, timeout here, they are null } } } @Override protected void handleApiMessage(APIMessage msg) { super.handleApiMessage(msg); } @Override protected void handleLocalMessage(Message msg) { if (msg instanceof CheckNetworkPhysicalInterfaceMsg) { handle((CheckNetworkPhysicalInterfaceMsg) msg); } else if (msg instanceof StartVmOnHypervisorMsg) { handle((StartVmOnHypervisorMsg) msg); } else if (msg instanceof CreateVmOnHypervisorMsg) { handle((CreateVmOnHypervisorMsg) msg); } else if (msg instanceof StopVmOnHypervisorMsg) { handle((StopVmOnHypervisorMsg) msg); } else if (msg instanceof RebootVmOnHypervisorMsg) { handle((RebootVmOnHypervisorMsg) msg); } else if (msg instanceof DestroyVmOnHypervisorMsg) { handle((DestroyVmOnHypervisorMsg) msg); } else if (msg instanceof AttachVolumeToVmOnHypervisorMsg) { handle((AttachVolumeToVmOnHypervisorMsg) msg); } else if (msg instanceof DetachVolumeFromVmOnHypervisorMsg) { handle((DetachVolumeFromVmOnHypervisorMsg) msg); } else if (msg instanceof VmAttachNicOnHypervisorMsg) { handle((VmAttachNicOnHypervisorMsg) msg); } else if (msg instanceof MigrateVmOnHypervisorMsg) { handle((MigrateVmOnHypervisorMsg) msg); } else if (msg instanceof TakeSnapshotOnHypervisorMsg) { handle((TakeSnapshotOnHypervisorMsg) msg); } else if (msg instanceof MergeVolumeSnapshotOnKvmMsg) { handle((MergeVolumeSnapshotOnKvmMsg) msg); } else if (msg instanceof KVMHostAsyncHttpCallMsg) { handle((KVMHostAsyncHttpCallMsg) msg); } else if (msg instanceof KVMHostSyncHttpCallMsg) { handle((KVMHostSyncHttpCallMsg) msg); } else if (msg instanceof DetachNicFromVmOnHypervisorMsg) { handle((DetachNicFromVmOnHypervisorMsg) msg); } else if (msg instanceof AttachIsoOnHypervisorMsg) { handle((AttachIsoOnHypervisorMsg) msg); } else if (msg instanceof DetachIsoOnHypervisorMsg) { handle((DetachIsoOnHypervisorMsg) msg); } else if (msg instanceof CheckVmStateOnHypervisorMsg) { handle((CheckVmStateOnHypervisorMsg) msg); } else if (msg instanceof GetVmConsoleAddressFromHostMsg) { handle((GetVmConsoleAddressFromHostMsg) msg); } else if (msg instanceof KvmRunShellMsg) { handle((KvmRunShellMsg) msg); } else if (msg instanceof VmDirectlyDestroyOnHypervisorMsg) { handle((VmDirectlyDestroyOnHypervisorMsg) msg); } else if (msg instanceof OnlineChangeVmCpuMemoryMsg) { handle((OnlineChangeVmCpuMemoryMsg) msg); } else if (msg instanceof IncreaseVmCpuMsg) { handle((IncreaseVmCpuMsg) msg); } else if (msg instanceof IncreaseVmMemoryMsg) { handle((IncreaseVmMemoryMsg) msg); } else if (msg instanceof PauseVmOnHypervisorMsg) { handle((PauseVmOnHypervisorMsg) msg); } else if (msg instanceof ResumeVmOnHypervisorMsg) { handle((ResumeVmOnHypervisorMsg) msg); } else { super.handleLocalMessage(msg); } } private void handle(final IncreaseVmCpuMsg msg) { IncreaseVmCpuReply reply = new IncreaseVmCpuReply(); IncreaseCpuCmd cmd = new IncreaseCpuCmd(); cmd.setVmUuid(msg.getVmInstanceUuid()); cmd.setCpuNum(msg.getCpuNum()); new Http<>(onlineIncreaseCpuPath, cmd, IncreaseCpuResponse.class).call(new ReturnValueCompletion<IncreaseCpuResponse>(msg) { @Override public void success(IncreaseCpuResponse ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); } else { reply.setCpuNum(ret.getCpuNum()); } bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final IncreaseVmMemoryMsg msg) { IncreaseVmMemoryReply reply = new IncreaseVmMemoryReply(); IncreaseMemoryCmd cmd = new IncreaseMemoryCmd(); cmd.setVmUuid(msg.getVmInstanceUuid()); cmd.setMemorySize(msg.getMemorySize()); new Http<>(onlineIncreaseMemPath, cmd, IncreaseMemoryResponse.class).call(new ReturnValueCompletion<IncreaseMemoryResponse>(msg) { @Override public void success(IncreaseMemoryResponse ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); } else { reply.setMemorySize(ret.getMemorySize()); } bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void directlyDestroy(final VmDirectlyDestroyOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmDirectlyDestroyOnHypervisorReply reply = new VmDirectlyDestroyOnHypervisorReply(); DestroyVmCmd cmd = new DestroyVmCmd(); cmd.setUuid(msg.getVmUuid()); new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(completion) { @Override public void success(DestroyVmResponse ret) { if (!ret.isSuccess()) { reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); completion.done(); } }); } private void handle(final VmDirectlyDestroyOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { directlyDestroy(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("directly-delete-vm-%s-msg-on-kvm-%s", msg.getVmUuid(), self.getUuid()); } }); } private SshResult runShell(String script) { Ssh ssh = new Ssh(); ssh.setHostname(self.getManagementIp()); ssh.setPort(getSelf().getPort()); ssh.setUsername(getSelf().getUsername()); ssh.setPassword(getSelf().getPassword()); ssh.shell(script); return ssh.runAndClose(); } private void handle(KvmRunShellMsg msg) { SshResult result = runShell(msg.getScript()); KvmRunShellReply reply = new KvmRunShellReply(); if (result.isSshFailure()) { reply.setError(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d ] to do DNS check," + " please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), result.getExitErrorMessage())); } else { reply.setStdout(result.getStdout()); reply.setStderr(result.getStderr()); reply.setReturnCode(result.getReturnCode()); } bus.reply(msg, reply); } private void handle(final OnlineChangeVmCpuMemoryMsg msg) { // final OnlineChangeVmCpuMemoryReply reply = new OnlineChangeVmCpuMemoryReply(); // ChangeCpuMemoryCmd cmd = new ChangeCpuMemoryCmd(); // cmd.setVmUuid(msg.getVmInstanceUuid()); // cmd.setCpuNum(msg.getCpuNum()); // cmd.setMemorySize(msg.getMemorySize()); // new Http<>(onlineChangeCpuMemoryPath, cmd, ChangeCpuMemoryResponse.class).call(new ReturnValueCompletion<ChangeCpuMemoryResponse>(msg) { // @Override // public void success(ChangeCpuMemoryResponse ret) { // if (!ret.isSuccess()) { // reply.setError(operr("operation error, because:%s", ret.getError())); // } else { // reply.setCpuNum(ret.getCpuNum()); // reply.setMemorySize(ret.getMemorySize()); // bus.reply(msg, reply); // @Override // public void fail(ErrorCode errorCode) { // reply.setError(errorCode); // bus.reply(msg, reply); } private void handle(final GetVmConsoleAddressFromHostMsg msg) { final GetVmConsoleAddressFromHostReply reply = new GetVmConsoleAddressFromHostReply(); GetVncPortCmd cmd = new GetVncPortCmd(); cmd.setVmUuid(msg.getVmInstanceUuid()); new Http<>(getConsolePortPath, cmd, GetVncPortResponse.class).call(new ReturnValueCompletion<GetVncPortResponse>(msg) { @Override public void success(GetVncPortResponse ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); } else { reply.setHostIp(self.getManagementIp()); reply.setProtocol(ret.getProtocol()); reply.setPort(ret.getPort()); } bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final CheckVmStateOnHypervisorMsg msg) { final CheckVmStateOnHypervisorReply reply = new CheckVmStateOnHypervisorReply(); if (self.getStatus() != HostStatus.Connected) { reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus())); bus.reply(msg, reply); return; } // NOTE: don't run this message in the sync task // there can be many such kind of messages // running in the sync task may cause other tasks starved CheckVmStateCmd cmd = new CheckVmStateCmd(); cmd.vmUuids = msg.getVmInstanceUuids(); cmd.hostUuid = self.getUuid(); new Http<>(checkVmStatePath, cmd, CheckVmStateRsp.class).call(new ReturnValueCompletion<CheckVmStateRsp>(msg) { @Override public void success(CheckVmStateRsp ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); } else { Map<String, String> m = new HashMap<>(); for (Map.Entry<String, String> e : ret.states.entrySet()) { m.put(e.getKey(), KvmVmState.valueOf(e.getValue()).toVmInstanceState().toString()); } reply.setStates(m); } bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final DetachIsoOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { detachIso(msg, new NoErrorCompletion(msg, chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("detach-iso-%s-on-host-%s", msg.getIsoUuid(), self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void detachIso(final DetachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) { final DetachIsoOnHypervisorReply reply = new DetachIsoOnHypervisorReply(); DetachIsoCmd cmd = new DetachIsoCmd(); cmd.isoUuid = msg.getIsoUuid(); cmd.vmUuid = msg.getVmInstanceUuid(); cmd.deviceId = IsoOperator.getIsoDeviceId(msg.getVmInstanceUuid(), msg.getIsoUuid()); KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KVMPreDetachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreDetachIsoExtensionPoint.class)) { ext.preDetachIsoExtensionPoint(inv, cmd); } new Http<>(detachIsoPath, cmd, DetachIsoRsp.class).call(new ReturnValueCompletion<DetachIsoRsp>(msg, completion) { @Override public void success(DetachIsoRsp ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); completion.done(); } }); } private void handle(final AttachIsoOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { attachIso(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-iso-%s-on-host-%s", msg.getIsoSpec().getImageUuid(), self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void attachIso(final AttachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) { final AttachIsoOnHypervisorReply reply = new AttachIsoOnHypervisorReply(); IsoTO iso = new IsoTO(); iso.setImageUuid(msg.getIsoSpec().getImageUuid()); iso.setPath(msg.getIsoSpec().getInstallPath()); iso.setDeviceId(msg.getIsoSpec().getDeviceId()); AttachIsoCmd cmd = new AttachIsoCmd(); cmd.vmUuid = msg.getVmInstanceUuid(); cmd.iso = iso; KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KVMPreAttachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreAttachIsoExtensionPoint.class)) { ext.preAttachIsoExtensionPoint(inv, cmd); } new Http<>(attachIsoPath, cmd, AttachIsoRsp.class).call(new ReturnValueCompletion<AttachIsoRsp>(msg, completion) { @Override public void success(AttachIsoRsp ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } }); } private void handle(final DetachNicFromVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { detachNic(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "detach-nic-on-kvm-host-" + self.getUuid(); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void detachNic(final DetachNicFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) { final DetachNicFromVmOnHypervisorReply reply = new DetachNicFromVmOnHypervisorReply(); NicTO to = completeNicInfo(msg.getNic()); DetachNicCommand cmd = new DetachNicCommand(); cmd.setVmUuid(msg.getVmInstanceUuid()); cmd.setNic(to); new Http<>(detachNicPath, cmd, DetachNicRsp.class).call(new ReturnValueCompletion<DetachNicRsp>(msg, completion) { @Override public void success(DetachNicRsp ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); completion.done(); } }); } private void handle(final KVMHostSyncHttpCallMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { executeSyncHttpCall(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("execute-sync-http-call-on-kvm-host-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void executeSyncHttpCall(KVMHostSyncHttpCallMsg msg, NoErrorCompletion completion) { if (!msg.isNoStatusCheck()) { checkStatus(); } String url = buildUrl(msg.getPath()); MessageCommandRecorder.record(msg.getCommandClassName()); Map<String, String> headers = new HashMap<>(); headers.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, self.getUuid()); LinkedHashMap rsp = restf.syncJsonPost(url, msg.getCommand(), headers, LinkedHashMap.class); KVMHostSyncHttpCallReply reply = new KVMHostSyncHttpCallReply(); reply.setResponse(rsp); bus.reply(msg, reply); completion.done(); } private void handle(final KVMHostAsyncHttpCallMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { executeAsyncHttpCall(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("execute-async-http-call-on-kvm-host-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private String buildUrl(String path) { UriComponentsBuilder ub = UriComponentsBuilder.newInstance(); ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME); ub.host(self.getManagementIp()); ub.port(KVMGlobalProperty.AGENT_PORT); if (!"".equals(KVMGlobalProperty.AGENT_URL_ROOT_PATH)) { ub.path(KVMGlobalProperty.AGENT_URL_ROOT_PATH); } ub.path(path); return ub.build().toUriString(); } private void executeAsyncHttpCall(final KVMHostAsyncHttpCallMsg msg, final NoErrorCompletion completion) { if (!msg.isNoStatusCheck()) { checkStatus(); } String url = buildUrl(msg.getPath()); MessageCommandRecorder.record(msg.getCommandClassName()); new Http<>(url, msg.getCommand(), LinkedHashMap.class, TimeUnit.MILLISECONDS, msg.getCommandTimeout()) .call(new ReturnValueCompletion<LinkedHashMap>(msg, completion) { @Override public void success(LinkedHashMap ret) { KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply(); reply.setResponse(ret); bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply(); if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) { reply.setError(errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "cannot do the operation on the KVM host", err)); } else { reply.setError(err); } bus.reply(msg, reply); completion.done(); } }); } private void handle(final MergeVolumeSnapshotOnKvmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { mergeVolumeSnapshot(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("merge-volume-snapshot-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void mergeVolumeSnapshot(final MergeVolumeSnapshotOnKvmMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); final MergeVolumeSnapshotOnKvmReply reply = new MergeVolumeSnapshotOnKvmReply(); VolumeInventory volume = msg.getTo(); if (volume.getVmInstanceUuid() != null) { SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.state); q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid()); VmInstanceState state = q.findValue(); if (state != VmInstanceState.Stopped && state != VmInstanceState.Running) { throw new OperationFailureException(operr("cannot do volume snapshot merge when vm[uuid:%s] is in state of %s." + " The operation is only allowed when vm is Running or Stopped", volume.getUuid(), state)); } if (state == VmInstanceState.Running) { String libvirtVersion = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN); if (new VersionComparator(KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION).compare(libvirtVersion) > 0) { throw new OperationFailureException(operr("live volume snapshot merge needs libvirt version greater than %s," + " current libvirt version is %s. Please stop vm and redo the operation or detach the volume if it's data volume", KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION, libvirtVersion)); } } } VolumeSnapshotInventory snapshot = msg.getFrom(); MergeSnapshotCmd cmd = new MergeSnapshotCmd(); cmd.setFullRebase(msg.isFullRebase()); cmd.setDestPath(volume.getInstallPath()); cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath()); cmd.setVmUuid(volume.getVmInstanceUuid()); cmd.setDeviceId(volume.getDeviceId()); extEmitter.beforeMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd); new Http<>(mergeSnapshotPath, cmd, MergeSnapshotRsp.class) .call(new ReturnValueCompletion<MergeSnapshotRsp>(msg, completion) { @Override public void success(MergeSnapshotRsp ret) { if (!ret.isSuccess()) { reply.setError(operr("operation error, because:%s", ret.getError())); extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError()); } extEmitter.afterMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd); bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError()); bus.reply(msg, reply); completion.done(); } }); } private void handle(final TakeSnapshotOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { takeSnapshot(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("take-snapshot-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void takeSnapshot(final TakeSnapshotOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); final TakeSnapshotOnHypervisorReply reply = new TakeSnapshotOnHypervisorReply(); TakeSnapshotCmd cmd = new TakeSnapshotCmd(); if (msg.getVmUuid() != null) { SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.state); q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid()); VmInstanceState vmState = q.findValue(); if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) { throw new OperationFailureException(operr("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState)); } if (!HostSystemTags.LIVE_SNAPSHOT.hasTag(self.getUuid())) { if (vmState != VmInstanceState.Stopped) { throw new OperationFailureException(errf.instantiateErrorCode(SysErrors.NO_CAPABILITY_ERROR, String.format("kvm host[uuid:%s, name:%s, ip:%s] doesn't not support live snapshot. please stop vm[uuid:%s] and try again", self.getUuid(), self.getName(), self.getManagementIp(), msg.getVmUuid()) )); } } cmd.setVolumeUuid(msg.getVolume().getUuid()); cmd.setVmUuid(msg.getVmUuid()); cmd.setDeviceId(msg.getVolume().getDeviceId()); } cmd.setVolumeInstallPath(msg.getVolume().getInstallPath()); cmd.setInstallPath(msg.getInstallPath()); cmd.setFullSnapshot(msg.isFullSnapshot()); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("before-take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid())); chain.then(new NoRollbackFlow() { @Override public void run(FlowTrigger trigger, Map data) { extEmitter.beforeTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { @Override public void run(FlowTrigger trigger, Map data) { new Http<>(snapshotPath, cmd, TakeSnapshotResponse.class).call(new ReturnValueCompletion<TakeSnapshotResponse>(msg, trigger) { @Override public void success(TakeSnapshotResponse ret) { if (ret.isSuccess()) { extEmitter.afterTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, ret); reply.setNewVolumeInstallPath(ret.getNewVolumeInstallPath()); reply.setSnapshotInstallPath(ret.getSnapshotInstallPath()); reply.setSize(ret.getSize()); } else { ErrorCode err = operr("operation error, because:%s", ret.getError()); extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, ret, err); reply.setError(err); } trigger.next(); } @Override public void fail(ErrorCode errorCode) { extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, null, errorCode); reply.setError(errorCode); trigger.fail(errorCode); } }); } }).done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { bus.reply(msg, reply); completion.done(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { reply.setError(errCode); bus.reply(msg, reply); completion.done(); } }).start(); } private void migrateVm(final Iterator<MigrateStruct> it, final Completion completion) { final String dstHostMigrateIp, dstHostMnIp, dstHostUuid; final String vmUuid; final StorageMigrationPolicy storageMigrationPolicy; final boolean migrateFromDestination; final String srcHostMigrateIp, srcHostMnIp, srcHostUuid; synchronized (it) { if (!it.hasNext()) { completion.success(); return; } MigrateStruct s = it.next(); vmUuid = s.vmUuid; dstHostMigrateIp = s.dstHostMigrateIp; dstHostMnIp = s.dstHostMnIp; dstHostUuid = s.dstHostUuid; storageMigrationPolicy = s.storageMigrationPolicy; migrateFromDestination = s.migrateFromDestition; srcHostMigrateIp = s.srcHostMigrateIp; srcHostMnIp = s.srcHostMnIp; srcHostUuid = s.srcHostUuid; } SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.internalId); q.add(VmInstanceVO_.uuid, Op.EQ, vmUuid); final Long vmInternalId = q.findValue(); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("migrate-vm-%s-on-kvm-host-%s", vmUuid, self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "migrate-vm"; @Override public void run(final FlowTrigger trigger, Map data) { MigrateVmCmd cmd = new MigrateVmCmd(); cmd.setDestHostIp(dstHostMigrateIp); cmd.setSrcHostIp(srcHostMigrateIp); cmd.setMigrateFromDestination(migrateFromDestination); cmd.setStorageMigrationPolicy(storageMigrationPolicy == null ? null : storageMigrationPolicy.toString()); cmd.setVmUuid(vmUuid); cmd.setUseNuma(VmGlobalConfig.NUMA.value(Boolean.class)); UriComponentsBuilder ub = UriComponentsBuilder.newInstance(); ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME); ub.host(migrateFromDestination ? dstHostMnIp : srcHostMnIp); ub.port(KVMGlobalProperty.AGENT_PORT); ub.path(KVMConstant.KVM_MIGRATE_VM_PATH); String migrateUrl = ub.build().toString(); new Http<>(migrateUrl, cmd, MigrateVmResponse.class).call(migrateFromDestination ? dstHostUuid : srcHostUuid, new ReturnValueCompletion<MigrateVmResponse>(trigger) { @Override public void success(MigrateVmResponse ret) { if (!ret.isSuccess()) { ErrorCode err = errf.instantiateErrorCode(HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR, String.format("failed to migrate vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), dstHostMigrateIp, ret.getError()) ); trigger.fail(err); } else { String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]", vmUuid, self.getUuid(), self.getManagementIp(), dstHostMigrateIp); logger.debug(info); trigger.next(); } } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); flow(new NoRollbackFlow() { String __name__ = "harden-vm-console-on-dst-host"; @Override public void run(final FlowTrigger trigger, Map data) { HardenVmConsoleCmd cmd = new HardenVmConsoleCmd(); cmd.vmInternalId = vmInternalId; cmd.vmUuid = vmUuid; cmd.hostManagementIp = dstHostMnIp; UriComponentsBuilder ub = UriComponentsBuilder.newInstance(); ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME); ub.host(dstHostMnIp); ub.port(KVMGlobalProperty.AGENT_PORT); ub.path(KVMConstant.KVM_HARDEN_CONSOLE_PATH); String url = ub.build().toString(); new Http<>(url, cmd, AgentResponse.class).call(dstHostUuid, new ReturnValueCompletion<AgentResponse>(trigger) { @Override public void success(AgentResponse ret) { if (!ret.isSuccess()) { //TODO: add GC logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, ret.getError())); } trigger.next(); } @Override public void fail(ErrorCode errorCode) { //TODO add GC logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, errorCode)); // continue trigger.next(); } }); } }); flow(new NoRollbackFlow() { String __name__ = "delete-vm-console-firewall-on-source-host"; @Override public void run(final FlowTrigger trigger, Map data) { DeleteVmConsoleFirewallCmd cmd = new DeleteVmConsoleFirewallCmd(); cmd.vmInternalId = vmInternalId; cmd.vmUuid = vmUuid; cmd.hostManagementIp = srcHostMnIp; new Http<>(deleteConsoleFirewall, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) { @Override public void success(AgentResponse ret) { if (!ret.isSuccess()) { logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" + " the source host[uuid:%s, ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), ret.getError())); } trigger.next(); } @Override public void fail(ErrorCode errorCode) { //TODO logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" + " the source host[uuid:%s, ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), errorCode)); trigger.next(); } }); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]", vmUuid, self.getUuid(), self.getManagementIp(), dstHostMigrateIp); logger.debug(info); migrateVm(it, completion); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final MigrateVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("migrate-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } class MigrateStruct { String vmUuid; String dstHostMigrateIp; String dstHostMnIp; String dstHostUuid; StorageMigrationPolicy storageMigrationPolicy; boolean migrateFromDestition; String srcHostMigrateIp; String srcHostMnIp; String srcHostUuid; } private MigrateStruct buildMigrateStuct(final MigrateVmOnHypervisorMsg msg){ MigrateStruct s = new MigrateStruct(); s.vmUuid = msg.getVmInventory().getUuid(); s.srcHostUuid = msg.getSrcHostUuid(); s.dstHostUuid = msg.getDestHostInventory().getUuid(); s.storageMigrationPolicy = msg.getStorageMigrationPolicy(); s.migrateFromDestition = msg.isMigrateFromDestination(); MigrateNetworkExtensionPoint.MigrateInfo migrateIpInfo = null; for (MigrateNetworkExtensionPoint ext: pluginRgty.getExtensionList(MigrateNetworkExtensionPoint.class)) { MigrateNetworkExtensionPoint.MigrateInfo r = ext.getMigrationAddressForVM(s.srcHostUuid, s.dstHostUuid); if (r == null) { continue; } migrateIpInfo = r; } s.dstHostMnIp = msg.getDestHostInventory().getManagementIp(); s.dstHostMigrateIp = migrateIpInfo == null ? s.dstHostMnIp : migrateIpInfo.dstMigrationAddress; s.srcHostMnIp = Q.New(HostVO.class).eq(HostVO_.uuid, msg.getSrcHostUuid()).select(HostVO_.managementIp).findValue(); s.srcHostMigrateIp = migrateIpInfo == null ? s.srcHostMnIp : migrateIpInfo.srcMigrationAddress; return s; } private void migrateVm(final MigrateVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); List<MigrateStruct> lst = new ArrayList<>(); MigrateStruct s = buildMigrateStuct(msg); lst.add(s); final MigrateVmOnHypervisorReply reply = new MigrateVmOnHypervisorReply(); migrateVm(lst.iterator(), new Completion(msg, completion) { @Override public void success() { bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); completion.done(); } }); } private void handle(final VmAttachNicOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { attachNic(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-nic-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void attachNic(final VmAttachNicOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); NicTO to = completeNicInfo(msg.getNicInventory()); final VmAttachNicOnHypervisorReply reply = new VmAttachNicOnHypervisorReply(); AttachNicCommand cmd = new AttachNicCommand(); cmd.setVmUuid(msg.getNicInventory().getVmInstanceUuid()); cmd.setNic(to); KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KvmPreAttachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreAttachNicExtensionPoint.class)) { ext.preAttachNicExtensionPoint(inv, cmd); } new Http<>(attachNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) { @Override public void success(AttachNicResponse ret) { if (!ret.isSuccess()) { reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," + "because %s", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError())); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); completion.done(); } }); } private void handle(final DetachVolumeFromVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { detachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("detach-volume-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void detachVolume(final DetachVolumeFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); VolumeTO to = new VolumeTO(); final VolumeInventory vol = msg.getInventory(); final VmInstanceInventory vm = msg.getVmInventory(); to.setInstallPath(vol.getInstallPath()); if (vol.getDeviceId() != null) { to.setDeviceId(vol.getDeviceId()); } to.setDeviceType(getVolumeTOType(vol)); to.setVolumeUuid(vol.getUuid()); // volumes can only be attached on Windows if the virtio is enabled // so for Windows, use virtio as well to.setUseVirtio(ImagePlatform.Windows.toString().equals(vm.getPlatform()) || ImagePlatform.valueOf(vm.getPlatform()).isParaVirtualization()); to.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(vol.getUuid())); to.setWwn(setVolumeWwn(vol.getUuid())); to.setShareable(vol.isShareable()); final DetachVolumeFromVmOnHypervisorReply reply = new DetachVolumeFromVmOnHypervisorReply(); final DetachDataVolumeCmd cmd = new DetachDataVolumeCmd(); cmd.setVolume(to); cmd.setVmUuid(vm.getUuid()); extEmitter.beforeDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); new Http<>(detachDataVolumePath, cmd, DetachDataVolumeResponse.class).call(new ReturnValueCompletion<DetachDataVolumeResponse>(msg, completion) { @Override public void success(DetachDataVolumeResponse ret) { if (!ret.isSuccess()) { ErrorCode err = operr("failed to detach data volume[uuid:%s, installPath:%s] from vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()); reply.setError(err); extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError()); } else { extEmitter.afterDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err); completion.done(); } }); } private void handle(final AttachVolumeToVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { attachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-volume-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private String setVolumeWwn(String volumeUUid) { String wwn; String tag = KVMSystemTags.VOLUME_WWN.getTag(volumeUUid); if (tag != null) { wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(tag, KVMSystemTags.VOLUME_WWN_TOKEN); } else { SystemTagCreator creator = KVMSystemTags.VOLUME_WWN.newSystemTagCreator(volumeUUid); creator.ignoreIfExisting = true; creator.inherent = true; creator.setTagByTokens(map(e(KVMSystemTags.VOLUME_WWN_TOKEN, new WwnUtils().getRandomWwn()))); SystemTagInventory inv = creator.create(); wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(inv.getTag(), KVMSystemTags.VOLUME_WWN_TOKEN); } DebugUtils.Assert(new WwnUtils().isValidWwn(wwn), String.format("Not a valid wwn[%s] for volume[uuid:%s]", wwn, volumeUUid)); return wwn; } private void attachVolume(final AttachVolumeToVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); VolumeTO to = new VolumeTO(); final VolumeInventory vol = msg.getInventory(); final VmInstanceInventory vm = msg.getVmInventory(); to.setInstallPath(vol.getInstallPath()); to.setDeviceId(vol.getDeviceId()); to.setDeviceType(getVolumeTOType(vol)); to.setVolumeUuid(vol.getUuid()); // volumes can only be attached on Windows if the virtio is enabled // so for Windows, use virtio as well to.setUseVirtio(ImagePlatform.Windows.toString().equals(vm.getPlatform()) || ImagePlatform.valueOf(vm.getPlatform()).isParaVirtualization()); to.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(vol.getUuid())); to.setWwn(setVolumeWwn(vol.getUuid())); to.setShareable(vol.isShareable()); to.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value()); final AttachVolumeToVmOnHypervisorReply reply = new AttachVolumeToVmOnHypervisorReply(); final AttachDataVolumeCmd cmd = new AttachDataVolumeCmd(); cmd.setVolume(to); cmd.setVmUuid(msg.getVmInventory().getUuid()); extEmitter.beforeAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); new Http<>(attachDataVolumePath, cmd, AttachDataVolumeResponse.class).call(new ReturnValueCompletion<AttachDataVolumeResponse>(msg, completion) { @Override public void success(AttachDataVolumeResponse ret) { if (!ret.isSuccess()) { reply.setError(operr("failed to attach data volume[uuid:%s, installPath:%s] to vm[uuid:%s, name:%s]" + " on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError())); extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError()); } else { extEmitter.afterAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err); reply.setError(err); bus.reply(msg, reply); completion.done(); } }); } private void handle(final DestroyVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { destroyVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("destroy-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void destroyVm(final DestroyVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); try { extEmitter.beforeDestroyVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv); } catch (KVMException e) { ErrorCode err = operr("failed to destroy vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); throw new OperationFailureException(err); } DestroyVmCmd cmd = new DestroyVmCmd(); cmd.setUuid(vminv.getUuid()); new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(msg, completion) { @Override public void success(DestroyVmResponse ret) { DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply(); if (!ret.isSuccess()) { String err = String.format("unable to destroy vm[uuid:%s, name:%s] on kvm host [uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, err)); extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); } else { logger.debug(String.format("successfully destroyed vm[uuid:%s] on kvm host[uuid:%s]", vminv.getUuid(), self.getUuid())); extEmitter.destroyVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply(); if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR, SysErrors.TIMEOUT)) { err = errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "unable to destroy a vm", err); } reply.setError(err); extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); bus.reply(msg, reply); completion.done(); } }); } private void handle(final RebootVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { rebootVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("reboot-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private List<String> toKvmBootDev(List<String> order) { List<String> ret = new ArrayList<String>(); for (String o : order) { if (VmBootDevice.HardDisk.toString().equals(o)) { ret.add(BootDev.hd.toString()); } else if (VmBootDevice.CdRom.toString().equals(o)) { ret.add(BootDev.cdrom.toString()); } else { throw new CloudRuntimeException(String.format("unknown boot device[%s]", o)); } } return ret; } private void rebootVm(final RebootVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStateAndStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); try { extEmitter.beforeRebootVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv); } catch (KVMException e) { String err = String.format("failed to reboot vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); logger.warn(err, e); throw new OperationFailureException(operr(err)); } RebootVmCmd cmd = new RebootVmCmd(); long timeout = TimeUnit.MILLISECONDS.toSeconds(msg.getTimeout()); cmd.setUuid(vminv.getUuid()); cmd.setTimeout(timeout); cmd.setBootDev(toKvmBootDev(msg.getBootOrders())); new Http<>(rebootVmPath, cmd, RebootVmResponse.class).call(new ReturnValueCompletion<RebootVmResponse>(msg, completion) { @Override public void success(RebootVmResponse ret) { RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply(); if (!ret.isSuccess()) { String err = String.format("unable to reboot vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR, err)); extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); } else { extEmitter.rebootVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply(); reply.setError(err); extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err); bus.reply(msg, reply); completion.done(); } }); } private void handle(final StopVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { stopVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("stop-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void stopVm(final StopVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); try { extEmitter.beforeStopVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv); } catch (KVMException e) { ErrorCode err = operr("failed to stop vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); throw new OperationFailureException(err); } StopVmCmd cmd = new StopVmCmd(); cmd.setUuid(vminv.getUuid()); cmd.setType(msg.getType()); cmd.setTimeout(120); new Http<>(stopVmPath, cmd, StopVmResponse.class).call(new ReturnValueCompletion<StopVmResponse>(msg, completion) { @Override public void success(StopVmResponse ret) { StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply(); if (!ret.isSuccess()) { String err = String.format("unable to stop vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err)); logger.warn(err); extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError()); } else { extEmitter.stopVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply(); if (err.isError(SysErrors.IO_ERROR, SysErrors.HTTP_ERROR)) { err = errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "unable to stop a vm", err); } reply.setError(err); extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err); bus.reply(msg, reply); completion.done(); } }); } @Transactional private void setDataVolumeUseVirtIOSCSI(final VmInstanceSpec spec) { String vmUuid = spec.getVmInventory().getUuid(); Map<String, Integer> diskOfferingUuid_Num = new HashMap<>(); List<Map<String, String>> tokenList = KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI.getTokensOfTagsByResourceUuid(vmUuid); for (Map<String, String> tokens : tokenList) { String diskOfferingUuid = tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_TOKEN); Integer num = Integer.parseInt(tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_NUM_TOKEN)); diskOfferingUuid_Num.put(diskOfferingUuid, num); } for (VolumeInventory volumeInv : spec.getDestDataVolumes()) { if (volumeInv.getType().equals(VolumeType.Root.toString())) { continue; } if (diskOfferingUuid_Num.containsKey(volumeInv.getDiskOfferingUuid()) && diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) > 0) { tagmgr.createNonInherentSystemTag(volumeInv.getUuid(), KVMSystemTags.VOLUME_VIRTIO_SCSI.getTagFormat(), VolumeVO.class.getSimpleName()); diskOfferingUuid_Num.put(volumeInv.getDiskOfferingUuid(), diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) - 1); } } } private void handle(final CreateVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { setDataVolumeUseVirtIOSCSI(msg.getVmSpec()); startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("start-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } @Transactional private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) { String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)"; TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class); query.setParameter("l3NetworkUuid", l3NetworkUuid); L2NetworkVO l2vo = query.getSingleResult(); return L2NetworkInventory.valueOf(l2vo); } private NicTO completeNicInfo(VmNicInventory nic) { L2NetworkInventory l2inv = getL2NetworkTypeFromL3NetworkUuid(nic.getL3NetworkUuid()); KVMCompleteNicInformationExtensionPoint extp = factory.getCompleteNicInfoExtension(L2NetworkType.valueOf(l2inv.getType())); NicTO to = extp.completeNicInformation(l2inv, nic); if (to.getUseVirtio() == null) { SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.platform); q.add(VmInstanceVO_.uuid, Op.EQ, nic.getVmInstanceUuid()); String platform = q.findValue(); to.setUseVirtio(ImagePlatform.valueOf(platform).isParaVirtualization()); if (!(nic.getIp().isEmpty() || nic.getIp() == null) && VmGlobalConfig.VM_CLEAN_TRAFFIC.value(Boolean.class)) { to.setIp(nic.getIp()); } } return to; } private String getVolumeTOType(VolumeInventory vol) { return vol.getInstallPath().startsWith("iscsi") ? VolumeTO.ISCSI : VolumeTO.FILE; } private void startVm(final VmInstanceSpec spec, final NeedReplyMessage msg, final NoErrorCompletion completion) { checkStateAndStatus(); final StartVmCmd cmd = new StartVmCmd(); boolean virtio; String consoleMode; String nestedVirtualization; String platform = spec.getVmInventory().getPlatform() == null ? spec.getImageSpec().getInventory().getPlatform() : spec.getVmInventory().getPlatform(); if (ImagePlatform.Windows.toString().equals(platform)) { virtio = VmSystemTags.WINDOWS_VOLUME_ON_VIRTIO.hasTag(spec.getVmInventory().getUuid()); } else { virtio = ImagePlatform.valueOf(platform).isParaVirtualization(); } int cpuNum = spec.getVmInventory().getCpuNum(); cmd.setCpuNum(cpuNum); int socket; int cpuOnSocket; //TODO: this is a HACK!!! if (ImagePlatform.Windows.toString().equals(platform) || ImagePlatform.WindowsVirtio.toString().equals(platform)) { if (cpuNum == 1) { socket = 1; cpuOnSocket = 1; } else if (cpuNum % 2 == 0) { socket = 2; cpuOnSocket = cpuNum / 2; } else { socket = cpuNum; cpuOnSocket = 1; } } else { socket = 1; cpuOnSocket = cpuNum; } cmd.setSocketNum(socket); cmd.setCpuOnSocket(cpuOnSocket); cmd.setVmName(spec.getVmInventory().getName()); cmd.setVmInstanceUuid(spec.getVmInventory().getUuid()); cmd.setCpuSpeed(spec.getVmInventory().getCpuSpeed()); cmd.setMemory(spec.getVmInventory().getMemorySize()); cmd.setMaxMemory(self.getCapacity().getTotalPhysicalMemory()); cmd.setUseVirtio(virtio); cmd.setClock(ImagePlatform.isType(platform, ImagePlatform.Windows, ImagePlatform.WindowsVirtio) ? "localtime" : "utc"); cmd.setVideoType(VmGlobalConfig.VM_VIDEO_TYPE.value(String.class)); cmd.setInstanceOfferingOnlineChange(VmSystemTags.INSTANCEOFFERING_ONLIECHANGE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN) != null); cmd.setKvmHiddenState(VmGlobalConfig.KVM_HIDDEN_STATE.value(Boolean.class)); cmd.setSpiceStreamingMode(VmGlobalConfig.VM_SPICE_STREAMING_MODE.value(String.class)); VolumeTO rootVolume = new VolumeTO(); rootVolume.setInstallPath(spec.getDestRootVolume().getInstallPath()); rootVolume.setDeviceId(spec.getDestRootVolume().getDeviceId()); rootVolume.setDeviceType(getVolumeTOType(spec.getDestRootVolume())); rootVolume.setVolumeUuid(spec.getDestRootVolume().getUuid()); rootVolume.setUseVirtio(virtio); rootVolume.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(spec.getDestRootVolume().getUuid())); rootVolume.setWwn(setVolumeWwn(spec.getDestRootVolume().getUuid())); rootVolume.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value()); nestedVirtualization = KVMGlobalConfig.NESTED_VIRTUALIZATION.value(String.class); cmd.setNestedVirtualization(nestedVirtualization); cmd.setRootVolume(rootVolume); cmd.setUseBootMenu(VmGlobalConfig.VM_BOOT_MENU.value(Boolean.class)); List<VolumeTO> dataVolumes = new ArrayList<>(spec.getDestDataVolumes().size()); for (VolumeInventory data : spec.getDestDataVolumes()) { VolumeTO v = new VolumeTO(); v.setInstallPath(data.getInstallPath()); v.setDeviceId(data.getDeviceId()); v.setDeviceType(getVolumeTOType(data)); v.setVolumeUuid(data.getUuid()); // always use virtio driver for data volume v.setUseVirtio(true); v.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(data.getUuid())); v.setWwn(setVolumeWwn(data.getUuid())); v.setShareable(data.isShareable()); v.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value()); dataVolumes.add(v); } dataVolumes.sort(Comparator.comparing(VolumeTO::getDeviceId)); cmd.setDataVolumes(dataVolumes); cmd.setVmInternalId(spec.getVmInventory().getInternalId()); List<NicTO> nics = new ArrayList<>(spec.getDestNics().size()); for (VmNicInventory nic : spec.getDestNics()) { if (!spec.getVmInventory().getType().equals(VmInstanceConstant.USER_VM_TYPE)) { nic.setIp(""); } nics.add(completeNicInfo(nic)); } nics = nics.stream().sorted(Comparator.comparing(NicTO::getDeviceId)).collect(Collectors.toList()); cmd.setNics(nics); for (VmInstanceSpec.IsoSpec isoSpec : spec.getDestIsoList()) { IsoTO bootIso = new IsoTO(); bootIso.setPath(isoSpec.getInstallPath()); bootIso.setImageUuid(isoSpec.getImageUuid()); bootIso.setDeviceId(IsoOperator.getIsoDeviceId(spec.getVmInventory().getUuid(), isoSpec.getImageUuid())); cmd.getBootIso().add(bootIso); } cmd.setBootDev(toKvmBootDev(spec.getBootOrders())); cmd.setHostManagementIp(self.getManagementIp()); cmd.setConsolePassword(spec.getConsolePassword()); cmd.setUsbRedirect(spec.getUsbRedirect()); cmd.setVDIMonitorNumber(Integer.valueOf(spec.getVDIMonitorNumber())); cmd.setUseNuma(VmGlobalConfig.NUMA.value(Boolean.class)); cmd.setVmPortOff(VmGlobalConfig.VM_PORT_OFF.value(Boolean.class)); cmd.setConsoleMode("vnc"); addons(spec, cmd); KVMHostInventory khinv = KVMHostInventory.valueOf(getSelf()); try { extEmitter.beforeStartVmOnKvm(khinv, spec, cmd); } catch (KVMException e) { ErrorCode err = operr("failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", spec.getVmInventory().getUuid(), spec.getVmInventory().getName(), self.getUuid(), self.getManagementIp(), e.getMessage()); throw new OperationFailureException(err); } extEmitter.addOn(khinv, spec, cmd); new Http<>(startVmPath, cmd, StartVmResponse.class).call(new ReturnValueCompletion<StartVmResponse>(msg, completion) { @Override public void success(StartVmResponse ret) { StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply(); if (ret.isSuccess()) { String info = String.format("successfully start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s]", spec.getVmInventory().getUuid(), spec.getVmInventory().getName(), self.getUuid(), self.getManagementIp()); logger.debug(info); extEmitter.startVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), spec); } else { String err = String.format("failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", spec.getVmInventory().getUuid(), spec.getVmInventory().getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR, err)); logger.warn(err); extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, reply.getError()); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply(); reply.setError(err); reply.setSuccess(false); extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, err); bus.reply(msg, reply); completion.done(); } }); } private void addons(final VmInstanceSpec spec, StartVmCmd cmd) { KVMAddons.Channel chan = new KVMAddons.Channel(); chan.setSocketPath(makeChannelSocketPath(spec.getVmInventory().getUuid())); chan.setTargetName("org.qemu.guest_agent.0"); cmd.getAddons().put(KVMAddons.Channel.NAME, chan); logger.debug(String.format("make kvm channel device[path:%s, target:%s]", chan.getSocketPath(), chan.getTargetName())); } private String makeChannelSocketPath(String apvmuuid) { return PathUtil.join(String.format("/var/lib/libvirt/qemu/%s", apvmuuid)); } private void handle(final StartVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("start-vm-on-kvm-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void handle(final CheckNetworkPhysicalInterfaceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { checkPhysicalInterface(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("check-network-physical-interface-on-host-%s", self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void pauseVm(final PauseVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); PauseVmOnHypervisorReply reply = new PauseVmOnHypervisorReply(); PauseVmCmd cmd = new PauseVmCmd(); cmd.setUuid(vminv.getUuid()); cmd.setTimeout(120); new Http<>(pauseVmPath, cmd, PauseVmResponse.class).call(new ReturnValueCompletion<PauseVmResponse>(msg, completion) { @Override public void success(PauseVmResponse ret) { if (!ret.isSuccess()) { String err = String.format("unable to pause vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err)); logger.warn(err); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } }); } private void handle(final PauseVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { pauseVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("pause-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void handle(final ResumeVmOnHypervisorMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return id; } @Override public void run(final SyncTaskChain chain) { resumeVm(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("resume-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()); } @Override protected int getSyncLevel() { return getHostSyncLevel(); } }); } private void resumeVm(final ResumeVmOnHypervisorMsg msg, final NoErrorCompletion completion) { checkStatus(); final VmInstanceInventory vminv = msg.getVmInventory(); ResumeVmOnHypervisorReply reply = new ResumeVmOnHypervisorReply(); ResumeVmCmd cmd = new ResumeVmCmd(); cmd.setUuid(vminv.getUuid()); cmd.setTimeout(120); new Http<>(resumeVmPath, cmd, ResumeVmResponse.class).call(new ReturnValueCompletion<ResumeVmResponse>(msg, completion) { @Override public void success(ResumeVmResponse ret) { if (!ret.isSuccess()) { String err = String.format("unable to resume vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()); reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err)); logger.warn(err); } bus.reply(msg, reply); completion.done(); } @Override public void fail(ErrorCode err) { reply.setError(err); bus.reply(msg, reply); completion.done(); } }); } private void checkPhysicalInterface(CheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) { checkState(); CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd(); cmd.addInterfaceName(msg.getPhysicalInterface()); CheckNetworkPhysicalInterfaceReply reply = new CheckNetworkPhysicalInterfaceReply(); CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class); if (!rsp.isSuccess()) { if (rsp.getFailedInterfaceNames().isEmpty()) { reply.setError(operr("operation error, because:%s", rsp.getError())); } else { reply.setError(operr("%s, failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]", rsp.getError(), msg.getPhysicalInterface(), context.getInventory().getUuid(), context.getInventory().getManagementIp())); } } bus.reply(msg, reply); completion.done(); } @Override public void handleMessage(Message msg) { try { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } catch (Exception e) { bus.logExceptionWithMessageDump(msg, e); bus.replyErrorByMessageType(msg, e); } } @Override public void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next) { } @Override public void deleteHook() { } @Override protected HostInventory getSelfInventory() { return KVMHostInventory.valueOf(getSelf()); } @Override protected void pingHook(final Completion completion) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("ping-kvm-host-%s", self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "ping-host"; @AfterDone List<Runnable> afterDone = new ArrayList<>(); @Override public void run(FlowTrigger trigger, Map data) { PingCmd cmd = new PingCmd(); cmd.hostUuid = self.getUuid(); restf.asyncJsonPost(pingPath, cmd, new JsonAsyncRESTCallback<PingResponse>(trigger) { @Override public void fail(ErrorCode err) { trigger.fail(err); } @Override public void success(PingResponse ret) { if (ret.isSuccess()) { if (!self.getUuid().equals(ret.getHostUuid())) { afterDone.add(() -> { String info = i18n("detected abnormal status[host uuid change, expected: %s but: %s] of kvmagent," + "it's mainly caused by kvmagent restarts behind zstack management server. Report this to ping task, it will issue a reconnect soon", self.getUuid(), ret.getHostUuid()); logger.warn(info); changeConnectionState(HostStatusEvent.disconnected); new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire(); ReconnectHostMsg rmsg = new ReconnectHostMsg(); rmsg.setHostUuid(self.getUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid()); bus.send(rmsg); }); } trigger.next(); } else { trigger.fail(operr(ret.getError())); } } @Override public Class<PingResponse> getReturnClass() { return PingResponse.class; } },TimeUnit.SECONDS, 60); } }); flow(new NoRollbackFlow() { String __name__ = "call-ping-no-failure-plugins"; @Override public void run(FlowTrigger trigger, Map data) { List<KVMPingAgentNoFailureExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentNoFailureExtensionPoint.class); if (exts.isEmpty()) { trigger.next(); return; } AsyncLatch latch = new AsyncLatch(exts.size(), new NoErrorCompletion(trigger) { @Override public void done() { trigger.next(); } }); KVMHostInventory inv = (KVMHostInventory) getSelfInventory(); for (KVMPingAgentNoFailureExtensionPoint ext : exts) { ext.kvmPingAgentNoFailure(inv, new NoErrorCompletion(latch) { @Override public void done() { latch.ack(); } }); } } }); flow(new NoRollbackFlow() { String __name__ = "call-ping-plugins"; @Override public void run(FlowTrigger trigger, Map data) { List<KVMPingAgentExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentExtensionPoint.class); Iterator<KVMPingAgentExtensionPoint> it = exts.iterator(); callPlugin(it, trigger); } private void callPlugin(Iterator<KVMPingAgentExtensionPoint> it, FlowTrigger trigger) { if (!it.hasNext()) { trigger.next(); return; } KVMPingAgentExtensionPoint ext = it.next(); logger.debug(String.format("calling KVMPingAgentExtensionPoint[%s]", ext.getClass())); ext.kvmPingAgent((KVMHostInventory) getSelfInventory(), new Completion(trigger) { @Override public void success() { callPlugin(it, trigger); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } @Override protected int getVmMigrateQuantity() { return KVMGlobalConfig.VM_MIGRATION_QUANTITY.value(Integer.class); } private ErrorCode connectToAgent() { ErrorCode errCode = null; try { ConnectCmd cmd = new ConnectCmd(); cmd.setHostUuid(self.getUuid()); cmd.setSendCommandUrl(restf.getSendCommandUrl()); cmd.setIptablesRules(KVMGlobalProperty.IPTABLES_RULES); ConnectResponse rsp = restf.syncJsonPost(connectPath, cmd, ConnectResponse.class); if (!rsp.isSuccess() || !rsp.isIptablesSucc()) { errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(), connectPath, rsp.getError()); } else { VersionComparator libvirtVersion = new VersionComparator(rsp.getLibvirtVersion()); VersionComparator qemuVersion = new VersionComparator(rsp.getQemuVersion()); boolean liveSnapshot = libvirtVersion.compare(KVMConstant.MIN_LIBVIRT_LIVESNAPSHOT_VERSION) >= 0 && qemuVersion.compare(KVMConstant.MIN_QEMU_LIVESNAPSHOT_VERSION) >= 0; String hostOS = HostSystemTags.OS_DISTRIBUTION.getTokenByResourceUuid(self.getUuid(), HostSystemTags.OS_DISTRIBUTION_TOKEN); //liveSnapshot = liveSnapshot && (!"CentOS".equals(hostOS) || KVMGlobalConfig.ALLOW_LIVE_SNAPSHOT_ON_REDHAT.value(Boolean.class)); if (liveSnapshot) { logger.debug(String.format("kvm host[OS:%s, uuid:%s, name:%s, ip:%s] supports live snapshot with libvirt[version:%s], qemu[version:%s]", hostOS, self.getUuid(), self.getName(), self.getManagementIp(), rsp.getLibvirtVersion(), rsp.getQemuVersion())); SystemTagCreator creator = HostSystemTags.LIVE_SNAPSHOT.newSystemTagCreator(self.getUuid()); creator.recreate = true; creator.create(); } else { HostSystemTags.LIVE_SNAPSHOT.deleteInherentTag(self.getUuid()); } } } catch (RestClientException e) { errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(), connectPath, e.getMessage()); } catch (Throwable t) { logger.warn(t.getMessage(), t); errCode = errf.throwableToInternalError(t); } return errCode; } private KVMHostVO getSelf() { return (KVMHostVO) self; } private void continueConnect(final boolean newAdded, final Completion completion) { ErrorCode errCode = connectToAgent(); if (errCode != null) { throw new OperationFailureException(errCode); } FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("continue-connecting-kvm-host-%s-%s", self.getManagementIp(), self.getUuid())); for (KVMHostConnectExtensionPoint extp : factory.getConnectExtensions()) { KVMHostConnectedContext ctx = new KVMHostConnectedContext(); ctx.setInventory((KVMHostInventory) getSelfInventory()); ctx.setNewAddedHost(newAdded); chain.then(extp.createKvmHostConnectingFlow(ctx)); } chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { if (noStorageAccessible()){ completion.fail(operr("host can not access any primary storage, please check network")); } else { completion.success(); } } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { String err = String.format("connection error for KVM host[uuid:%s, ip:%s]", self.getUuid(), self.getManagementIp()); completion.fail(errf.instantiateErrorCode(HostErrors.CONNECTION_ERROR, err, errCode)); } }).start(); } @Transactional(readOnly = true) private boolean noStorageAccessible(){ // detach ps will delete PrimaryStorageClusterRefVO first. List<String> attachedPsUuids = Q.New(PrimaryStorageClusterRefVO.class) .select(PrimaryStorageClusterRefVO_.primaryStorageUuid) .eq(PrimaryStorageClusterRefVO_.clusterUuid, self.getClusterUuid()) .listValues(); long attachedPsCount = attachedPsUuids.size(); long inaccessiblePsCount = attachedPsCount == 0 ? 0 : Q.New(PrimaryStorageHostRefVO.class) .eq(PrimaryStorageHostRefVO_.hostUuid, self.getUuid()) .eq(PrimaryStorageHostRefVO_.status, PrimaryStorageHostStatus.Disconnected) .in(PrimaryStorageHostRefVO_.primaryStorageUuid, attachedPsUuids) .count(); return inaccessiblePsCount == attachedPsCount && attachedPsCount > 0; } private void createHostVersionSystemTags(String distro, String release, String version) { SystemTagCreator creator = HostSystemTags.OS_DISTRIBUTION.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.recreate = true; creator.setTagByTokens(map(e(HostSystemTags.OS_DISTRIBUTION_TOKEN, distro))); creator.create(); creator = HostSystemTags.OS_RELEASE.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.recreate = true; creator.setTagByTokens(map(e(HostSystemTags.OS_RELEASE_TOKEN, release))); creator.create(); creator = HostSystemTags.OS_VERSION.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.recreate = true; creator.setTagByTokens(map(e(HostSystemTags.OS_VERSION_TOKEN, version))); creator.create(); } @Override public void connectHook(final ConnectHostInfo info, final Completion complete) { if (CoreGlobalProperty.UNIT_TEST_ON) { if (info.isNewAdded()) { SystemTagCreator creator; createHostVersionSystemTags("zstack", "kvmSimulator", "0.1"); if (null == KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN)) { creator = KVMSystemTags.LIBVIRT_VERSION.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.setTagByTokens(map(e(KVMSystemTags.LIBVIRT_VERSION_TOKEN, "1.2.9"))); creator.create(); } if (null == KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN)) { creator = KVMSystemTags.QEMU_IMG_VERSION.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.setTagByTokens(map(e(KVMSystemTags.QEMU_IMG_VERSION_TOKEN, "2.0.0"))); creator.create(); } if (null == KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN)) { creator = KVMSystemTags.CPU_MODEL_NAME.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(KVMSystemTags.CPU_MODEL_NAME_TOKEN, "Broadwell"))); creator.inherent = true; creator.create(); } if (!checkQemuLibvirtVersionOfHost()) { complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match", self.getUuid(), self.getClusterUuid())); return; } if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) { complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match", self.getUuid(), self.getClusterUuid())); return; } } continueConnect(info.isNewAdded(), complete); } else { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("run-ansible-for-kvm-%s", self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { if (info.isNewAdded()) { if ((!AnsibleGlobalProperty.ZSTACK_REPO.contains("zstack-mn")) && (!AnsibleGlobalProperty.ZSTACK_REPO.equals("false"))) { flow(new NoRollbackFlow() { String __name__ = "ping-DNS-check-list"; @Override public void run(FlowTrigger trigger, Map data) { String checkList; if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.ALI_REPO)) { checkList = KVMGlobalConfig.HOST_DNS_CHECK_ALIYUN.value(); } else if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.NETEASE_REPO)) { checkList = KVMGlobalConfig.HOST_DNS_CHECK_163.value(); } else { checkList = KVMGlobalConfig.HOST_DNS_CHECK_LIST.value(); } checkList = checkList.replaceAll(",", " "); SshShell sshShell = new SshShell(); sshShell.setHostname(getSelf().getManagementIp()); sshShell.setUsername(getSelf().getUsername()); sshShell.setPassword(getSelf().getPassword()); sshShell.setPort(getSelf().getPort()); SshResult ret = sshShell.runScriptWithToken("scripts/check-public-dns-name.sh", map(e("dnsCheckList", checkList))); if (ret.isSshFailure()) { trigger.fail(operr("unable to connect to KVM[ip:%s, username:%s, sshPort: %d, ] to do DNS check, please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage())); } else if (ret.getReturnCode() != 0) { trigger.fail(operr("failed to ping all DNS/IP in %s; please check /etc/resolv.conf to make sure your host is able to reach public internet", checkList)); } else { trigger.next(); } } }); } } flow(new NoRollbackFlow() { String __name__ = "check-if-host-can-reach-management-node"; @Override public void run(FlowTrigger trigger, Map data) { SshShell sshShell = new SshShell(); sshShell.setHostname(getSelf().getManagementIp()); sshShell.setUsername(getSelf().getUsername()); sshShell.setPassword(getSelf().getPassword()); sshShell.setPort(getSelf().getPort()); ShellUtils.run(String.format("arp -d %s || true", getSelf().getManagementIp())); SshResult ret = sshShell.runCommand(String.format("curl --connect-timeout 10 %s", restf.getCallbackUrl())); if (ret.isSshFailure()) { throw new OperationFailureException(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d] to check the management node connectivity," + "please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage())); } else if (ret.getReturnCode() != 0) { throw new OperationFailureException(operr("the KVM host[ip:%s] cannot access the management node's callback url. It seems" + " that the KVM host cannot reach the management IP[%s]. %s %s", self.getManagementIp(), Platform.getManagementServerIp(), ret.getStderr(), ret.getExitErrorMessage())); } trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "apply-ansible-playbook"; @Override public void run(final FlowTrigger trigger, Map data) { String srcPath = PathUtil.findFileOnClassPath(String.format("ansible/kvm/%s", agentPackageName), true).getAbsolutePath(); String destPath = String.format("/var/lib/zstack/kvm/package/%s", agentPackageName); SshFileMd5Checker checker = new SshFileMd5Checker(); checker.setUsername(getSelf().getUsername()); checker.setPassword(getSelf().getPassword()); checker.setSshPort(getSelf().getPort()); checker.setTargetIp(getSelf().getManagementIp()); checker.addSrcDestPair(SshFileMd5Checker.ZSTACKLIB_SRC_PATH, String.format("/var/lib/zstack/kvm/package/%s", AnsibleGlobalProperty.ZSTACKLIB_PACKAGE_NAME)); checker.addSrcDestPair(srcPath, destPath); AnsibleRunner runner = new AnsibleRunner(); runner.installChecker(checker); runner.setAgentPort(KVMGlobalProperty.AGENT_PORT); runner.setTargetIp(getSelf().getManagementIp()); runner.setPlayBookName(KVMConstant.ANSIBLE_PLAYBOOK_NAME); runner.setUsername(getSelf().getUsername()); runner.setPassword(getSelf().getPassword()); runner.setSshPort(getSelf().getPort()); if (info.isNewAdded()) { runner.putArgument("init", "true"); runner.setFullDeploy(true); } runner.putArgument("pkg_kvmagent", agentPackageName); runner.putArgument("hostname", String.format("%s.zstack.org", self.getManagementIp().replaceAll("\\.", "-"))); if (CoreGlobalProperty.CHRONY_SERVERS != null && !CoreGlobalProperty.CHRONY_SERVERS.isEmpty()) { runner.putArgument("chrony_servers", String.join(",", CoreGlobalProperty.CHRONY_SERVERS)); } UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl()); ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", self.getUuid()).toString()); String postUrl = ub.build().toString(); runner.putArgument("post_url", postUrl); runner.run(new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); flow(new NoRollbackFlow() { String __name__ = "echo-host"; @Override public void run(final FlowTrigger trigger, Map data) { restf.echo(echoPath, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); flow(new NoRollbackFlow() { String __name__ = "collect-kvm-host-facts"; @Override public void run(final FlowTrigger trigger, Map data) { HostFactCmd cmd = new HostFactCmd(); new Http<>(hostFactPath, cmd, HostFactResponse.class) .call(new ReturnValueCompletion<HostFactResponse>(trigger) { @Override public void success(HostFactResponse ret) { if (!ret.isSuccess()) { trigger.fail(operr("operation error, because:%s", ret.getError())); return; } if (ret.getHvmCpuFlag() == null) { trigger.fail(operr("cannot find either 'vmx' or 'svm' in /proc/cpuinfo, please make sure you have enabled virtualization in your BIOS setting")); return; } // create system tags of os::version etc createHostVersionSystemTags(ret.getOsDistribution(), ret.getOsRelease(), ret.getOsVersion()); SystemTagCreator creator = KVMSystemTags.QEMU_IMG_VERSION.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(KVMSystemTags.QEMU_IMG_VERSION_TOKEN, ret.getQemuImgVersion()))); creator.recreate = true; creator.create(); creator = KVMSystemTags.LIBVIRT_VERSION.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(KVMSystemTags.LIBVIRT_VERSION_TOKEN, ret.getLibvirtVersion()))); creator.recreate = true; creator.create(); creator = KVMSystemTags.HVM_CPU_FLAG.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(KVMSystemTags.HVM_CPU_FLAG_TOKEN, ret.getHvmCpuFlag()))); creator.recreate = true; creator.create(); creator = KVMSystemTags.CPU_MODEL_NAME.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(KVMSystemTags.CPU_MODEL_NAME_TOKEN, ret.getCpuModelName()))); creator.recreate = true; creator.create(); if (ret.getLibvirtVersion().compareTo(KVMConstant.MIN_LIBVIRT_VIRTIO_SCSI_VERSION) >= 0) { creator = KVMSystemTags.VIRTIO_SCSI.newSystemTagCreator(self.getUuid()); creator.recreate = true; creator.create(); } List<String> ips = ret.getIpAddresses(); if (ips != null) { ips.remove(self.getManagementIp()); if (!ips.isEmpty()) { creator = HostSystemTags.EXTRA_IPS.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(HostSystemTags.EXTRA_IPS_TOKEN, StringUtils.join(ips, ",")))); creator.recreate = true; creator.create(); } else { HostSystemTags.EXTRA_IPS.delete(self.getUuid()); } } trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); if (info.isNewAdded()) { flow(new NoRollbackFlow() { String __name__ = "check-qemu-libvirt-version"; @Override public void run(FlowTrigger trigger, Map data) { if (!checkQemuLibvirtVersionOfHost()) { trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match", self.getUuid(), self.getClusterUuid())); return; } if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) { trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match", self.getUuid(), self.getClusterUuid())); return; } trigger.next(); } }); } flow(new NoRollbackFlow() { String __name__ = "prepare-host-env"; @Override public void run(FlowTrigger trigger, Map data) { String script = "which iptables > /dev/null && iptables -C FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 && iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 || true"; runShell(script); trigger.next(); } }); error(new FlowErrorHandler(complete) { @Override public void handle(ErrorCode errCode, Map data) { complete.fail(errCode); } }); done(new FlowDoneHandler(complete) { @Override public void handle(Map data) { continueConnect(info.isNewAdded(), complete); } }); } }).start(); } } private boolean checkCpuModelOfHost() { List<String> hostUuidsInCluster = Q.New(HostVO.class) .select(HostVO_.uuid) .eq(HostVO_.clusterUuid, self.getClusterUuid()) .notEq(HostVO_.uuid, self.getUuid()) .listValues(); if (hostUuidsInCluster.isEmpty()) { return true; } Map<String, List<String>> cpuModelNames = KVMSystemTags.CPU_MODEL_NAME.getTags(hostUuidsInCluster); if (cpuModelNames != null && cpuModelNames.size() != 0) { String clusterCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByTag( cpuModelNames.values().iterator().next().get(0), KVMSystemTags.CPU_MODEL_NAME_TOKEN ); String hostCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid( self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN ); if (clusterCpuModelName != null && !clusterCpuModelName.equals(hostCpuModelName)) { return false; } } return true; } @Override protected void updateOsHook(Completion completion) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("update-operating-system-for-host-%s", self.getUuid())); chain.then(new ShareFlow() { // is the host in maintenance already? HostState oldState = self.getState(); boolean maintenance = oldState == HostState.Maintenance; @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "double-check-host-state-status"; @Override public void run(FlowTrigger trigger, Map data) { if (self.getState() == HostState.PreMaintenance) { trigger.fail(Platform.operr("host is in the premaintenance state, cannot update os")); } else if (self.getStatus() != HostStatus.Connected) { trigger.fail(Platform.operr("host is not in the connected status, cannot update os")); } else { trigger.next(); } } }); flow(new Flow() { String __name__ = "make-host-in-maintenance"; @Override public void run(FlowTrigger trigger, Map data) { if (maintenance) { trigger.next(); return; } // enter maintenance, but donot stop/migrate vm on the host ChangeHostStateMsg cmsg = new ChangeHostStateMsg(); cmsg.setUuid(self.getUuid()); cmsg.setStateEvent(HostStateEvent.preMaintain.toString()); bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getUuid()); bus.send(cmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { trigger.next(); } else { trigger.fail(reply.getError()); } } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (maintenance) { trigger.rollback(); return; } // back to old host state if (oldState == HostState.Disabled) { changeState(HostStateEvent.disable); } else { changeState(HostStateEvent.enable); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "update-host-os"; @Override public void run(FlowTrigger trigger, Map data) { UpdateHostOSCmd cmd = new UpdateHostOSCmd(); cmd.hostUuid = self.getUuid(); new Http<>(updateHostOSPath, cmd, UpdateHostOSRsp.class) .call(new ReturnValueCompletion<UpdateHostOSRsp>(trigger) { @Override public void success(UpdateHostOSRsp ret) { if (ret.isSuccess()) { trigger.next(); } else { trigger.fail(Platform.operr(ret.getError())); } } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); flow(new NoRollbackFlow() { String __name__ = "recover-host-state"; @Override public void run(FlowTrigger trigger, Map data) { if (maintenance) { trigger.next(); return; } // back to old host state if (oldState == HostState.Disabled) { changeState(HostStateEvent.disable); } else { changeState(HostStateEvent.enable); } trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "auto-reconnect-host"; @Override public void run(FlowTrigger trigger, Map data) { ReconnectHostMsg rmsg = new ReconnectHostMsg(); rmsg.setHostUuid(self.getUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid()); bus.send(rmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { logger.info("successfully reconnected host " + self.getUuid()); } else { logger.error("failed to reconnect host " + self.getUuid()); } trigger.next(); } }); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { logger.debug(String.format("successfully updated operating system for host[uuid:%s]", self.getUuid())); completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { logger.warn(String.format("failed to updated operating system for host[uuid:%s] because %s", self.getUuid(), errCode.getDetails())); completion.fail(errCode); } }); } }).start(); } private boolean checkMigrateNetworkCidrOfHost(String cidr) { if (NetworkUtils.isIpv4InCidr(self.getManagementIp(), cidr)) { return true; } final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid( self.getUuid(), HostSystemTags.EXTRA_IPS_TOKEN); if (extraIps == null) { logger.error(String.format("Host[uuid:%s] has no IPs in migrate network", self.getUuid())); return false; } final String[] ips = extraIps.split(","); for (String ip: ips) { if (NetworkUtils.isIpv4InCidr(ip, cidr)) { return true; } } return false; } private boolean checkQemuLibvirtVersionOfHost() { List<String> hostUuidsInCluster = Q.New(HostVO.class) .select(HostVO_.uuid) .eq(HostVO_.clusterUuid, self.getClusterUuid()) .notEq(HostVO_.uuid, self.getUuid()) .listValues(); if (hostUuidsInCluster.isEmpty()) { return true; } Map<String, List<String>> qemuVersions = KVMSystemTags.QEMU_IMG_VERSION.getTags(hostUuidsInCluster); if (qemuVersions != null && qemuVersions.size() != 0) { String clusterQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag( qemuVersions.values().iterator().next().get(0), KVMSystemTags.QEMU_IMG_VERSION_TOKEN ); String hostQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid( self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN ); if (clusterQemuVer != null && !clusterQemuVer.equals(hostQemuVer)) { return false; } } Map<String, List<String>> libvirtVersions = KVMSystemTags.LIBVIRT_VERSION.getTags(hostUuidsInCluster); if (libvirtVersions != null && libvirtVersions.size() != 0) { String clusterLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByTag( libvirtVersions.values().iterator().next().get(0), KVMSystemTags.LIBVIRT_VERSION_TOKEN ); String hostLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid( self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN ); if (clusterLibvirtVer != null && !clusterLibvirtVer.equals(hostLibvirtVer)) { return false; } } return true; } @Override protected int getHostSyncLevel() { return KVMGlobalConfig.HOST_SYNC_LEVEL.value(Integer.class); } @Override protected HostVO updateHost(APIUpdateHostMsg msg) { if (!(msg instanceof APIUpdateKVMHostMsg)) { return super.updateHost(msg); } KVMHostVO vo = (KVMHostVO) super.updateHost(msg); vo = vo == null ? getSelf() : vo; APIUpdateKVMHostMsg umsg = (APIUpdateKVMHostMsg) msg; if (umsg.getUsername() != null) { vo.setUsername(umsg.getUsername()); } if (umsg.getPassword() != null) { vo.setPassword(umsg.getPassword()); } if (umsg.getSshPort() != null && umsg.getSshPort() > 0 && umsg.getSshPort() <= 65535) { vo.setPort(umsg.getSshPort()); } return vo; } }
package gov.nih.nci.calab.ui.workflow; /** * This class prepares the data to show in the page resulting from a workflow actions * * @author pansu */ /* CVS $Id: WorkflowMessageAction.java,v 1.3 2006-12-13 19:33:09 pansu Exp $ */ import gov.nih.nci.calab.ui.core.AbstractBaseAction; import gov.nih.nci.calab.ui.core.InitSessionSetup; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class WorkflowMessageAction extends AbstractBaseAction { public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("Cache-Control", "no-cache"); //fix for IE only InitSessionSetup.getInstance().setCurrentRun(request); ActionForward forward = mapping.findForward("success"); return forward; } public boolean loginRequired() { return true; } }
package ld.ldhomework.crawler; import org.semanticweb.yars.nx.Node; public class Triple { private TripleEntry object; private TripleEntry predicate; private TripleEntry subject; public Triple(Node subject, Node predicate, Node object) { this.subject = new TripleEntry(subject); this.predicate = new TripleEntry(predicate); this.object = new TripleEntry(object); } @Override public boolean equals(Object obj) { boolean result = false; if (obj instanceof Triple) { Triple otherTriple = (Triple) obj; TripleEntry otherSubject = otherTriple.getSubject(); TripleEntry otherPredicate = otherTriple.getPredicate(); TripleEntry otherObject = otherTriple.getObject(); boolean isSameSubject = isSameSubject(otherSubject); boolean isSamePredicate = isSamePredicate(otherPredicate); boolean isSameObject = isSameObject(otherObject); result = isSameSubject && isSamePredicate && isSameObject; } return result; } public TripleEntry getObject() { return object; } public TripleEntry getPredicate() { return predicate; } public TripleEntry getSubject() { return subject; } private boolean isSameObject(TripleEntry otherObject) { boolean result = false; TripleEntry ourObject = this.getObject(); result = isSameTripleEntry(ourObject, otherObject); return result; } private boolean isSamePredicate(TripleEntry otherPredicate) { boolean result = false; TripleEntry ourPredicate = this.getPredicate(); result = isSameTripleEntry(ourPredicate, otherPredicate); return result; } private boolean isSameSubject(TripleEntry otherSubject) { boolean result = false; TripleEntry ourSubject = this.getSubject(); result = isSameTripleEntry(ourSubject, otherSubject); return result; } private boolean isSameTripleEntry(TripleEntry tripleEntry1, TripleEntry tripleEntry2) { boolean result = false; if (tripleEntry1 == null && tripleEntry2 == null) { result = true; } else if (tripleEntry1 != null) { result = tripleEntry1.equals(tripleEntry2); } return result; } @Override public String toString() { return "[" + subject.getValue() + ", " + predicate.getValue() + ", " + object.getValue() + "]"; } public TripleEntry[] toTripleEntryArray() { TripleEntry[] array = { subject, predicate, object }; return array; } }
package com.voxelmodpack.hdskins; import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.mojang.authlib.GameProfile; import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type; import com.mojang.authlib.properties.Property; import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload; import com.mumfrey.liteloader.core.LiteLoader; import com.mumfrey.liteloader.util.log.LiteLoaderLogger; import com.voxelmodpack.hdskins.gui.GuiSkins; import com.voxelmodpack.hdskins.resource.SkinResourceManager; import com.voxelmodpack.hdskins.skins.BethlehemSkinServer; import com.voxelmodpack.hdskins.skins.LegacySkinServer; import com.voxelmodpack.hdskins.skins.ServerType; import com.voxelmodpack.hdskins.skins.SkinServer; import com.voxelmodpack.hdskins.skins.ValhallaSkinServer; import com.voxelmodpack.hdskins.util.ProfileTextureUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.client.resources.SkinManager; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.FileUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Function; import javax.annotation.Nullable; public final class HDSkinManager implements IResourceManagerReloadListener { private static final Logger logger = LogManager.getLogger(); public static final ExecutorService skinUploadExecutor = Executors.newSingleThreadExecutor(); public static final ExecutorService skinDownloadExecutor = Executors.newFixedThreadPool(8); public static final CloseableHttpClient httpClient = HttpClients.createSystem(); public static final HDSkinManager INSTANCE = new HDSkinManager(); private List<ISkinCacheClearListener> clearListeners = Lists.newArrayList(); private BiMap<String, Class<? extends SkinServer>> skinServerTypes = HashBiMap.create(2); private List<SkinServer> skinServers = Lists.newArrayList(); private LoadingCache<GameProfile, CompletableFuture<Map<Type, MinecraftProfileTexture>>> skins = CacheBuilder.newBuilder() .expireAfterAccess(15, TimeUnit.SECONDS) .build(CacheLoader.from(this::loadProfileData)); private List<ISkinModifier> skinModifiers = Lists.newArrayList(); private List<ISkinParser> skinParsers = Lists.newArrayList(); private SkinResourceManager resources = new SkinResourceManager(); // private ExecutorService executor = Executors.newCachedThreadPool(); private Function<List<SkinServer>, GuiSkins> skinsGuiFunc = GuiSkins::new; private HDSkinManager() { // register default skin server types addSkinServerType(LegacySkinServer.class); addSkinServerType(ValhallaSkinServer.class); addSkinServerType(BethlehemSkinServer.class); } public void setSkinsGui(Function<List<SkinServer>, GuiSkins> skinsGuiFunc) { Preconditions.checkNotNull(skinsGuiFunc, "skinsGuiFunc"); this.skinsGuiFunc = skinsGuiFunc; } public GuiSkins createSkinsGui() { return skinsGuiFunc.apply(ImmutableList.copyOf(this.skinServers)); } private CompletableFuture<Map<Type, MinecraftProfileTexture>> loadProfileData(GameProfile profile) { return CompletableFuture.supplyAsync(() -> { Map<Type, MinecraftProfileTexture> textureMap = Maps.newEnumMap(Type.class); for (SkinServer server : skinServers) { try { server.loadProfileData(profile).getTextures().forEach(textureMap::putIfAbsent); if (textureMap.size() == Type.values().length) { break; } } catch (IOException e) { logger.trace(e); } } return textureMap; }, skinDownloadExecutor); } public CompletableFuture<Map<Type, MinecraftProfileTexture>> loadProfileTextures(GameProfile profile) { try { // try to recreate a broken gameprofile // happens when server sends a random profile with skin and displayname Property textures = Iterables.getFirst(profile.getProperties().get("textures"), null); if (textures != null) { String json = new String(Base64.getDecoder().decode(textures.getValue()), StandardCharsets.UTF_8); MinecraftTexturesPayload texturePayload = SkinServer.gson.fromJson(json, MinecraftTexturesPayload.class); if (texturePayload != null) { // name is optional String name = texturePayload.getProfileName(); UUID uuid = texturePayload.getProfileId(); // uuid is required if (uuid != null) { profile = new GameProfile(uuid, name); } // probably uses this texture for a reason. Don't mess with it. if (!texturePayload.getTextures().isEmpty() && texturePayload.getProfileId() == null) { return CompletableFuture.completedFuture(Collections.emptyMap()); } } } } catch (Exception e) { if (profile.getId() == null) { // Something broke server-side probably logger.warn("{} had a null UUID and was unable to recreate it from texture profile.", profile.getName(), e); return CompletableFuture.completedFuture(Collections.emptyMap()); } } return skins.getUnchecked(profile); } public ResourceLocation loadTexture(Type type, MinecraftProfileTexture texture, @Nullable SkinManager.SkinAvailableCallback callback) { String skinDir = type.toString().toLowerCase() + "s/"; final ResourceLocation resource = new ResourceLocation("hdskins", skinDir + texture.getHash()); ITextureObject texObj = Minecraft.getMinecraft().getTextureManager().getTexture(resource); //noinspection ConstantConditions if (texObj != null) { if (callback != null) { callback.skinAvailable(type, resource, texture); } } else { // schedule texture loading on the main thread. TextureLoader.loadTexture(resource, new ThreadDownloadImageETag( new File(LiteLoader.getAssetsDirectory(), "hd/" + skinDir + texture.getHash().substring(0, 2) + "/" + texture.getHash()), texture.getUrl(), DefaultPlayerSkin.getDefaultSkinLegacy(), new ImageBufferDownloadHD(type, () -> { if (callback != null) { callback.skinAvailable(type, resource, texture); } }))); } return resource; } public Map<Type, ResourceLocation> getTextures(GameProfile profile) { Map<Type, ResourceLocation> map = new HashMap<>(); for (Map.Entry<Type, MinecraftProfileTexture> e : loadProfileTextures(profile).getNow(Collections.emptyMap()).entrySet()) { map.put(e.getKey(), loadTexture(e.getKey(), e.getValue(), null)); } return map; } private void addSkinServerType(Class<? extends SkinServer> type) { Preconditions.checkArgument(!type.isInterface(), "type cannot be an interface"); Preconditions.checkArgument(!Modifier.isAbstract(type.getModifiers()), "type cannot be abstract"); ServerType st = type.getAnnotation(ServerType.class); if (st == null) { throw new IllegalArgumentException("class is not annotated with @ServerType"); } this.skinServerTypes.put(st.value(), type); } public Class<? extends SkinServer> getSkinServerClass(String type) { return this.skinServerTypes.get(type); } void addSkinServer(SkinServer skinServer) { this.skinServers.add(skinServer); } public void addClearListener(ISkinCacheClearListener listener) { clearListeners.add(listener); } public void clearSkinCache() { LiteLoaderLogger.info("Clearing local player skin cache"); FileUtils.deleteQuietly(new File(LiteLoader.getAssetsDirectory(), "hd")); skins.invalidateAll(); reloadSkins(); } private void clearNetworkSkin(NetworkPlayerInfo player) { ((INetworkPlayerInfo) player).reloadTextures(); } private boolean onSkinCacheCleared(ISkinCacheClearListener callback) { try { return callback.onSkinCacheCleared(); } catch (Exception e) { logger.warn("Exception encountered calling skin listener '{}'. It will be removed.", callback.getClass().getName(), e); return false; } } public void addSkinModifier(ISkinModifier modifier) { skinModifiers.add(modifier); } public void addSkinParser(ISkinParser parser) { skinParsers.add(parser); } public ResourceLocation getConvertedSkin(ResourceLocation res) { ResourceLocation loc = resources.getConvertedResource(res); return loc == null ? res : loc; } public void convertSkin(BufferedImage image, Graphics dest) { for (ISkinModifier skin : skinModifiers) { skin.convertSkin(image, dest); } } public void reloadSkins() { NetHandlerPlayClient playClient = Minecraft.getMinecraft().getConnection(); if (playClient != null) { playClient.getPlayerInfoMap().forEach(this::clearNetworkSkin); } clearListeners.removeIf(this::onSkinCacheCleared); } public void parseSkin(GameProfile profile, Type type, ResourceLocation resource, MinecraftProfileTexture texture) { // grab the metadata object via reflection. Object is live. Map<String, String> metadata = ProfileTextureUtil.getMetadata(texture); boolean wasNull = metadata == null; if (wasNull) { metadata = new HashMap<>(); } for (ISkinParser parser : skinParsers) { parser.parse(profile, type, resource, metadata); } if (wasNull && !metadata.isEmpty()) { ProfileTextureUtil.setMetadata(texture, metadata); } } @Override public void onResourceManagerReload(IResourceManager resourceManager) { this.resources.onResourceManagerReload(resourceManager); } }
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; 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.Font; import java.awt.FontMetrics; import java.awt.Graphics; 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.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; 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.KeyStroke; import javax.swing.SwingConstants; import javax.swing.plaf.basic.BasicTabbedPaneUI; 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 graph; // The graph menu item 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 Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); /** * 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() { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Creates a new frame frame = new JFrame("BioSim"); // 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 openMenu = new JMenu("Open"); JMenu newMenu = new JMenu("New"); menuBar.add(file); menuBar.add(help); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); graph = new JMenuItem("Graph"); importSbml = new JMenuItem("SBML Model"); importDot = new JMenuItem("Genetic Circuit Model"); exit = new JMenuItem("Exit"); openProj.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); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK)); newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.ALT_MASK)); newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK)); newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK)); about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.ALT_MASK)); graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.ALT_MASK)); importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.ALT_MASK)); importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK)); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); newCircuit.setMnemonic(KeyEvent.VK_C); newCircuit.setDisplayedMnemonicIndex(8); newModel.setMnemonic(KeyEvent.VK_S); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_G); importDot.setMnemonic(KeyEvent.VK_T); importDot.setDisplayedMnemonicIndex(14); importSbml.setMnemonic(KeyEvent.VK_L); importDot.setEnabled(false); importSbml.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); graph.setEnabled(false); file.add(newMenu); newMenu.add(newProj); newMenu.add(newCircuit); newMenu.add(newModel); newMenu.add(graph); file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(importMenu); importMenu.add(importDot); importMenu.add(importSbml); file.addSeparator(); file.add(exit); file.addSeparator(); help.add(manual); 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, ActionEvent.ALT_MASK)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ActionEvent.ALT_MASK)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ActionEvent.ALT_MASK)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ActionEvent.ALT_MASK)); 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; } } // 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(950, 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); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == about) { final JFrame f = new JFrame("About"); JLabel bioSim = new JLabel("BioSim 0.78"); Font font = bioSim.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); bioSim.setFont(font); JLabel uOfU = new JLabel("University of Utah"); 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(); uOfUPanel.add(uOfU); 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); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = "BioSim.html"; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-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) { 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); } // 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")) { 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(); } // 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 + "\n"); // 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(); network.outputSBML(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), "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(); 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 + ".viz " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".viz " + 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("")) { log.addText("Executing:\ndotty " + directory + out + ".viz\n"); exec.exec("dotty " + out + ".viz", 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(); 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 { 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); 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); } } // if the open project menu item is selected 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); } 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 { File f = new File(root + separator + simName); 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(root + separator + simName); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(simName)) { tab.remove(i); } } } else { return; } } 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), "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 { File f = new File(root + separator + simName); 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(root + separator + simName); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(simName)) { tab.remove(i); } } } else { return; } } f.createNewFile(); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(2, 3); Compartment c = document.getModel().createCompartment(); c.setId("default"); 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 (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 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(); 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(". ",".\n"); message += i + ":" + error + "\n"; } if (numErrors > 0) { 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); JOptionPane.showMessageDialog(frame, scroll, "SBML Errors and Warnings", JOptionPane.ERROR_MESSAGE); } 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 { 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 Graph:", "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 = new File(root + separator + graphName); 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(root + separator + graphName); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(graphName)) { tab.remove(i); } } } else { return; } } Graph g = new Graph("amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName.trim(), true); addTab(graphName.trim(), g, "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 { File f = new File(root + separator + lrnName); 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(root + separator + lrnName); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(lrnName)) { tab.remove(i); } } } else { return; } } 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=" + sbmlFile + "\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"); 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("Graph", noData1); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("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"; } } } 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; } boolean write = true; if (new File(root + separator + copy).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) { write = true; File dir = new File(root + separator + copy); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(copy)) { tab.remove(i); } } } else { write = false; } } if (write) { 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.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"))) { 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 { 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 = 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"; } } 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; } boolean write = true; if (new File(root + separator + rename).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) { write = true; File dir = new File(root + separator + rename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(rename)) { tab.remove(i); } } } else { write = false; } } if (write) { 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(); } 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")) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getTabCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponent(j).getName().equals( "Simulate")) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(i)).getComponent(j)) .setSim(rename); } else if (((JTabbedPane) tab.getComponentAt(i)).getComponent(j).getName() .contains("Graph")) { if (((JTabbedPane) tab.getComponentAt(i)).getComponent(j) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponent(j)); g.setDirectory(root + separator + rename); } } } tab.setTitleAt(i, 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) { addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph("amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], true), "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 - 1; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = i; j < numberRecentProj - 1; j++) { String next = recentProjectPaths[j + 1]; recentProjects[j].setText(next.split(separator)[next.split(separator).length - 1]); file.add(recentProjects[j]); recentProjectPaths[j] = next; } break; } } 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(); } /** * 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"))) { 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 (((SBML_Editor) 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) { ((SBML_Editor) tab.getComponentAt(index)).save(false); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } else { return 1; } } else if (tab.getComponentAt(index).getName().contains("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; } } else { return 1; } } else { 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)) .hasChanged()) { 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); } 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().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 { boolean write = true; if (new File(root + separator + filename).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) { write = true; File dir = new File(root + separator + filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(filename)) { tab.remove(i); } } } else { write = false; } } if (write) { 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.getButton() == MouseEvent.BUTTON3 && e.isPopupTrigger()) { 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("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("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.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), "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("amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], true), "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.equals(".sim")) { sim = true; } } if (sim) { openSim(); } else { openLearn(); } } } } } public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3 && e.isPopupTrigger()) { 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("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("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.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(); File f = new File(root + separator + simName); 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(root + separator + simName); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(simName)) { tab.remove(i); } } } else { return; } } 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(); network.outputSBML(root + separator + simName + separator + sbmlFile); try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".pms")); 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", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".pms"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); 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("Graph", noData); simTab.getComponentAt(simTab.getComponents().length - 1).setName("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(); File f = new File(root + separator + simName); 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(root + separator + simName); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(simName)) { tab.remove(i); } } } else { return; } } 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() + ".pms")); 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", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".pms"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); 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("Graph", noData); simTab.getComponentAt(simTab.getComponents().length - 1).setName("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"; Properties load = new Properties(); String learnFile = ""; try { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); } } 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.split(separator)[learnFile.split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } 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("Graph", new Graph("amount", tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true)); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("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("Graph", noData1); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("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()) { 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]; } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; String sbmlLoadFile = null; if (new File(pmsFile).exists()) { try { Scanner s = new Scanner(new File(pmsFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.outputSBML(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; */ } } 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", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); 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() + ".pms"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); if (!graphFile.equals("")) { simTab.addTab("Graph", reb2sac.createGraph(open)); simTab.getComponentAt(simTab.getComponents().length - 1).setName("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("Graph", noData); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Graph"); } 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); } new BioSim(); } 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"))) { 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(); if (ss.substring(ss.length() - 4).equals(".pms")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.outputSBML(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", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".pms"); reb2sac.setSbml(sbml); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); 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("Graph", noData); simTab.getComponentAt(simTab.getComponents().length - 1).setName("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("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("amount", learnName + " data", "tsd.printer", root + separator + learnName, "time", this, null, log, null, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("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("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"); } } } } } } }
package cz.jcu.prf.uai.javamugs.gui; import cz.jcu.prf.uai.javamugs.App; import cz.jcu.prf.uai.javamugs.logic.Game; import cz.jcu.prf.uai.javamugs.logic.Parser; import cz.jcu.prf.uai.javamugs.logic.Press; import cz.jcu.prf.uai.javamugs.logic.PressChart; import javafx.beans.binding.Bindings; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.IOException; public class MenuController { private Stage stage; public Label speedLabel; public Label difficultyLabel; public Slider speedSlider; public Slider difficultySlider; public Button exitButton; public FileChooser fileChooser = new FileChooser(); public VBox rootContainer; public void start() { this.stage = (Stage) rootContainer.getScene().getWindow(); difficultyLabel.textProperty().bind( Bindings.format("%.0f", difficultySlider.valueProperty()) ); speedLabel.textProperty().bind( Bindings.format("%.0f", speedSlider.valueProperty()) ); } public void playButtonAction(ActionEvent event) { openGameWindow(null); //TODO put method under logic return; /*File songFile = fileChooser.showOpenDialog(stage); if (songFile == null) { return; } String songURIstring = songFile.toURI().toString(); File pressChartFile = fileChooser.showOpenDialog(stage); if (pressChartFile == null) { return; } String pressChartPath = pressChartFile.getAbsolutePath(); Parser parser = new Parser(); int timeOffset = (int)speedSlider.getValue(); PressChart pressChart; try { pressChart = parser.parseFile(pressChartPath, timeOffset); } catch(Exception ex) { // TODO change exceptions return; } int difficulty = (int)difficultySlider.getValue(); Game game = new Game(timeOffset, (byte)difficulty, pressChart);*/ } private void openGameWindow(Game game) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/Game.fxml")); Parent root = loader.load(); GameController gameController = (GameController) loader.getController(); gameController.setGame(game); Stage gameStage = new Stage(); gameStage.setTitle("Clone Hero"); gameStage.setScene(new Scene(root)); gameStage.show(); gameController.start(); //((Node)(event.getSource())).getScene().getWindow().hide(); } catch (IOException e) { e.printStackTrace(); } } public void editorButtonAction(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/Editor.fxml")); Parent root = loader.load(); GameController editorController = (EditorController) loader.getController(); Stage editorStage = new Stage(); editorStage.setTitle("Clone Hero Editor"); editorStage.setScene(new Scene(root)); editorStage.show(); editorController.start(); //((Node)(event.getSource())).getScene().getWindow().hide(); } catch (IOException e) { e.printStackTrace(); } } public void exitButtonAction(ActionEvent event) { stage.close(); } }
package example.domain.services; import com.dbdeploy.DbDeploy; import example.domain.services.hibernate.DbDeployer; import org.hibernate.SessionFactory; import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator; import org.springframework.aop.interceptor.PerformanceMonitorInterceptor; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate3.HibernateOperations; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.LocalSessionFactoryBean; import javax.sql.DataSource; import java.util.Properties; import static example.utils.Strings.array; @Configuration public class ServicesConfiguration { @Autowired Environment env; @Value("/WEB-INF/deltas") Resource deltasDir; @Value("/WEB-INF/create_changelog.sql") Resource createSql; @Bean public HibernateOperations hibernateOperations(SessionFactory sessionFactory) throws Exception { return new HibernateTemplate(sessionFactory); } @Bean public FactoryBean<SessionFactory> sessionFactory() { LocalSessionFactoryBean factory = new LocalSessionFactoryBean(); factory.setMappingResources(array("example/domain/services/hibernate/Document.hbm.xml")); factory.setHibernateProperties(hibernateProperties()); factory.setDataSource(dataSource()); return factory; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); properties.setProperty("hibernate.cache.provider_class", env.getProperty("hibernate.cache.provider_class")); return properties; } @Bean public DataSource dataSource() { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName(env.getProperty("database.driver.class")); ds.setUsername(env.getProperty("database.driver.username")); ds.setPassword(env.getProperty("database.driver.password")); ds.setUrl(env.getProperty("database.driver.url")); return ds; } @Bean public JdbcOperations jdbcTemplate() { return new JdbcTemplate(dataSource()); } @Bean public DbDeployer deployer() { return new DbDeployer(jdbcTemplate(), createSql, deltasDir, dbDeploy()); } private DbDeploy dbDeploy() { DbDeploy deploy = new DbDeploy(); deploy.setUrl(env.getProperty("database.driver.url")); deploy.setDriver(env.getProperty("database.driver.class")); deploy.setUserid(env.getProperty("database.driver.username")); deploy.setPassword(env.getProperty("database.driver.password")); return deploy; } @Bean public PerformanceMonitorInterceptor statsInterceptor() { PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(); interceptor.setLoggerName("STATS"); return interceptor; } @Bean public BeanNameAutoProxyCreator repositoryPerformance() { BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator(); creator.setInterceptorNames(array("statsInterceptor")); creator.setBeanNames(array("*Repository")); creator.setProxyTargetClass(false); return creator; } }
package com.cloud.network.resource; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringReader; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.ExternalNetworkResourceUsageAnswer; import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupExternalFirewallCommand; import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand.UsernamePassword; import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.host.Host; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.resource.ServerResource; import com.cloud.utils.NumbersUtil; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; public class JuniperSrxResource implements ServerResource { private String _name; private String _zoneId; private String _physicalNetworkId; private String _ip; private String _username; private String _password; private String _guid; private String _objectNameWordSep; private PrintWriter _toSrx; private BufferedReader _fromSrx; private PrintWriter _UsagetoSrx; private BufferedReader _UsagefromSrx; private static Integer _numRetries; private static Integer _timeoutInSeconds; private static String _publicZone; private static String _privateZone; private static String _publicInterface; private static String _usageInterface; private static String _privateInterface; private static String _ikeProposalName; private static String _ipsecPolicyName; private static String _primaryDnsAddress; private static String _ikeGatewayHostname; private static String _vpnObjectPrefix; private static final Logger s_logger = Logger.getLogger(JuniperSrxResource.class); private enum SrxXml { LOGIN("login.xml"), PRIVATE_INTERFACE_ADD("private-interface-add.xml"), PRIVATE_INTERFACE_WITH_FILTERS_ADD("private-interface-with-filters-add.xml"), PRIVATE_INTERFACE_GETONE("private-interface-getone.xml"), PROXY_ARP_ADD("proxy-arp-add.xml"), PROXY_ARP_GETONE("proxy-arp-getone.xml"), PROXY_ARP_GETALL("proxy-arp-getall.xml"), ZONE_INTERFACE_ADD("zone-interface-add.xml"), ZONE_INTERFACE_GETONE("zone-interface-getone.xml"), SRC_NAT_POOL_ADD("src-nat-pool-add.xml"), SRC_NAT_POOL_GETONE("src-nat-pool-getone.xml"), SRC_NAT_RULE_ADD("src-nat-rule-add.xml"), SRC_NAT_RULE_GETONE("src-nat-rule-getone.xml"), SRC_NAT_RULE_GETALL("src-nat-rule-getall.xml"), DEST_NAT_POOL_ADD("dest-nat-pool-add.xml"), DEST_NAT_POOL_GETONE("dest-nat-pool-getone.xml"), DEST_NAT_POOL_GETALL("dest-nat-pool-getall.xml"), DEST_NAT_RULE_ADD("dest-nat-rule-add.xml"), DEST_NAT_RULE_GETONE("dest-nat-rule-getone.xml"), DEST_NAT_RULE_GETALL("dest-nat-rule-getall.xml"), STATIC_NAT_RULE_ADD("static-nat-rule-add.xml"), STATIC_NAT_RULE_GETONE("static-nat-rule-getone.xml"), STATIC_NAT_RULE_GETALL("static-nat-rule-getall.xml"), ADDRESS_BOOK_ENTRY_ADD("address-book-entry-add.xml"), ADDRESS_BOOK_ENTRY_GETONE("address-book-entry-getone.xml"), ADDRESS_BOOK_ENTRY_GETALL("address-book-entry-getall.xml"), APPLICATION_ADD("application-add.xml"), APPLICATION_GETONE("application-getone.xml"), SECURITY_POLICY_ADD("security-policy-add.xml"), SECURITY_POLICY_GETONE("security-policy-getone.xml"), SECURITY_POLICY_GETALL("security-policy-getall.xml"), SECURITY_POLICY_GROUP("security-policy-group.xml"), GUEST_VLAN_FILTER_TERM_ADD("guest-vlan-filter-term-add.xml"), PUBLIC_IP_FILTER_TERM_ADD("public-ip-filter-term-add.xml"), FILTER_TERM_GETONE("filter-term-getone.xml"), FILTER_GETONE("filter-getone.xml"), FIREWALL_FILTER_BYTES_GETALL("firewall-filter-bytes-getall.xml"), IKE_POLICY_ADD("ike-policy-add.xml"), IKE_POLICY_GETONE("ike-policy-getone.xml"), IKE_POLICY_GETALL("ike-policy-getall.xml"), IKE_GATEWAY_ADD("ike-gateway-add.xml"), IKE_GATEWAY_GETONE("ike-gateway-getone.xml"), IKE_GATEWAY_GETALL("ike-gateway-getall.xml"), IPSEC_VPN_ADD("ipsec-vpn-add.xml"), IPSEC_VPN_GETONE("ipsec-vpn-getone.xml"), IPSEC_VPN_GETALL("ipsec-vpn-getall.xml"), DYNAMIC_VPN_CLIENT_ADD("dynamic-vpn-client-add.xml"), DYNAMIC_VPN_CLIENT_GETONE("dynamic-vpn-client-getone.xml"), DYNAMIC_VPN_CLIENT_GETALL("dynamic-vpn-client-getall.xml"), ADDRESS_POOL_ADD("address-pool-add.xml"), ADDRESS_POOL_GETONE("address-pool-getone.xml"), ADDRESS_POOL_GETALL("address-pool-getall.xml"), ACCESS_PROFILE_ADD("access-profile-add.xml"), ACCESS_PROFILE_GETONE("access-profile-getone.xml"), ACCESS_PROFILE_GETALL("access-profile-getall.xml"), OPEN_CONFIGURATION("open-configuration.xml"), CLOSE_CONFIGURATION("close-configuration.xml"), COMMIT("commit.xml"), ROLLBACK("rollback.xml"), TEST("test.xml"); private String scriptsDir = "scripts/network/juniper"; private String xml; private SrxXml(String filename) { this.xml = getXml(filename); } public String getXml() { return xml; } private String getXml(String filename) { try { String xmlFilePath = Script.findScript(scriptsDir, filename); if (xmlFilePath == null) { throw new Exception("Failed to find Juniper SRX XML file: " + filename); } FileReader fr = new FileReader(xmlFilePath); BufferedReader br = new BufferedReader(fr); String xml = ""; String line; while ((line = br.readLine()) != null) { xml += line.trim(); } return xml; } catch (Exception e) { s_logger.debug(e); return null; } } } public enum UsageFilter { VLAN_INPUT("vlan-input", null, "vlan-input"), VLAN_OUTPUT("vlan-output", null, "vlan-output"), IP_INPUT(_publicZone, "destination-address", "-i"), IP_OUTPUT(_privateZone, "source-address", "-o"); private String name; private String counterIdentifier; private String addressType; private UsageFilter(String name, String addressType, String counterIdentifier) { this.name = name; this.addressType = addressType; if (_usageInterface != null) { counterIdentifier = _usageInterface + counterIdentifier; } this.counterIdentifier = counterIdentifier; } public String getName() { return name; } public String getCounterIdentifier() { return counterIdentifier; } public String getAddressType() { return addressType; } } private enum SrxCommand { LOGIN, OPEN_CONFIGURATION, CLOSE_CONFIGURATION, COMMIT, ROLLBACK, CHECK_IF_EXISTS, CHECK_IF_IN_USE, ADD, DELETE, GET_ALL; } private enum Protocol { tcp, udp, any; } private enum RuleMatchCondition { ALL, PUBLIC_PRIVATE_IPS, PRIVATE_SUBNET; } private enum GuestNetworkType { SOURCE_NAT, INTERFACE_NAT; } private enum SecurityPolicyType { STATIC_NAT("staticnat"), DESTINATION_NAT("destnat"), VPN("vpn"); private String identifier; private SecurityPolicyType(String identifier) { this.identifier = identifier; } private String getIdentifier() { return identifier; } } public Answer executeRequest(Command cmd) { if (cmd instanceof ReadyCommand) { return execute((ReadyCommand) cmd); } else if (cmd instanceof MaintainCommand) { return execute((MaintainCommand) cmd); } else if (cmd instanceof IpAssocCommand) { return execute((IpAssocCommand) cmd); } else if (cmd instanceof SetStaticNatRulesCommand) { return execute((SetStaticNatRulesCommand) cmd); } else if (cmd instanceof SetPortForwardingRulesCommand) { return execute((SetPortForwardingRulesCommand) cmd); } else if (cmd instanceof ExternalNetworkResourceUsageCommand) { return execute((ExternalNetworkResourceUsageCommand) cmd); } else if (cmd instanceof RemoteAccessVpnCfgCommand) { return execute((RemoteAccessVpnCfgCommand) cmd); } else if (cmd instanceof VpnUsersCfgCommand) { return execute((VpnUsersCfgCommand) cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } } public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { try { _name = (String) params.get("name"); if (_name == null) { throw new ConfigurationException("Unable to find name"); } _zoneId = (String) params.get("zoneId"); if (_zoneId == null) { throw new ConfigurationException("Unable to find zone"); } _physicalNetworkId = (String) params.get("physicalNetworkId"); if (_physicalNetworkId == null) { throw new ConfigurationException("Unable to find physical network id in the configuration parameters"); } _ip = (String) params.get("ip"); if (_ip == null) { throw new ConfigurationException("Unable to find IP"); } _username = (String) params.get("username"); if (_username == null) { throw new ConfigurationException("Unable to find username"); } _password = (String) params.get("password"); if (_password == null) { throw new ConfigurationException("Unable to find password"); } _publicInterface = (String) params.get("publicinterface"); if (_publicInterface == null) { throw new ConfigurationException("Unable to find public interface."); } _usageInterface = (String) params.get("usageinterface"); _privateInterface = (String) params.get("privateinterface"); if (_privateInterface == null) { throw new ConfigurationException("Unable to find private interface."); } _publicZone = (String) params.get("publiczone"); if (_publicZone == null) { _publicZone = "untrust"; } _privateZone = (String) params.get("privatezone"); if (_privateZone == null) { _privateZone = "trust"; } _guid = (String)params.get("guid"); if (_guid == null) { throw new ConfigurationException("Unable to find the guid"); } _numRetries = NumbersUtil.parseInt((String) params.get("numretries"), 1); _timeoutInSeconds = NumbersUtil.parseInt((String) params.get("timeout"), 300); _objectNameWordSep = "-"; _ikeProposalName = "cloud-ike-proposal"; _ipsecPolicyName = "cloud-ipsec-policy"; _ikeGatewayHostname = "cloud"; _vpnObjectPrefix = "vpn-a"; _primaryDnsAddress = "4.2.2.2"; // Open a socket and login if (!refreshSrxConnection()) { throw new ConfigurationException("Unable to open a connection to the SRX."); } return true; } catch (Exception e) { throw new ConfigurationException(e.getMessage()); } } public StartupCommand[] initialize() { StartupExternalFirewallCommand cmd = new StartupExternalFirewallCommand(); cmd.setName(_name); cmd.setDataCenter(_zoneId); cmd.setPod(""); cmd.setPrivateIpAddress(_ip); cmd.setStorageIpAddress(""); cmd.setVersion(""); cmd.setGuid(_guid); return new StartupCommand[]{cmd}; } public Host.Type getType() { return Host.Type.ExternalFirewall; } @Override public String getName() { return _name; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public PingCommand getCurrentStatus(final long id) { return new PingCommand(Host.Type.ExternalFirewall, id); } @Override public void disconnected() { closeSocket(); } public IAgentControl getAgentControl() { return null; } public void setAgentControl(IAgentControl agentControl) { return; } private Answer execute(ReadyCommand cmd) { return new ReadyAnswer(cmd); } private Answer execute(MaintainCommand cmd) { return new MaintainAnswer(cmd); } private ExternalNetworkResourceUsageAnswer execute(ExternalNetworkResourceUsageCommand cmd) { try { return getUsageAnswer(cmd); } catch (ExecutionException e) { return new ExternalNetworkResourceUsageAnswer(cmd, e); } } /* * Login */ private boolean refreshSrxConnection() { if (!(closeSocket() && openSocket())) { return false; } try { return login(); } catch (ExecutionException e) { s_logger.error("Failed to login due to " + e.getMessage()); return false; } } private boolean login() throws ExecutionException { String xml = SrxXml.LOGIN.getXml(); xml = replaceXmlValue(xml, "username", _username); xml = replaceXmlValue(xml, "password", _password); return sendRequestAndCheckResponse(SrxCommand.LOGIN, xml); } private boolean openSocket() { try { Socket s = new Socket(_ip, 3221); s.setKeepAlive(true); s.setSoTimeout(_timeoutInSeconds * 1000); _toSrx = new PrintWriter(s.getOutputStream(), true); _fromSrx = new BufferedReader(new InputStreamReader(s.getInputStream())); return true; } catch (IOException e) { s_logger.error(e); return false; } } private boolean closeSocket() { try { if (_toSrx != null) { _toSrx.close(); } if (_fromSrx != null) { _fromSrx.close(); } return true; } catch (IOException e) { s_logger.error(e); return false; } } /* * The usage data will be handled on it's own socket, so usage * commands will use the following methods... */ private boolean usageLogin() throws ExecutionException { String xml = SrxXml.LOGIN.getXml(); xml = replaceXmlValue(xml, "username", _username); xml = replaceXmlValue(xml, "password", _password); return sendUsageRequestAndCheckResponse(SrxCommand.LOGIN, xml); } private boolean openUsageSocket() throws ExecutionException { try { Socket s = new Socket(_ip, 3221); s.setKeepAlive(true); s.setSoTimeout(_timeoutInSeconds * 1000); _UsagetoSrx = new PrintWriter(s.getOutputStream(), true); _UsagefromSrx = new BufferedReader(new InputStreamReader(s.getInputStream())); return usageLogin(); } catch (IOException e) { s_logger.error(e); return false; } } private boolean closeUsageSocket() { try { if (_UsagetoSrx != null) { _UsagetoSrx.close(); } if (_UsagefromSrx != null) { _UsagefromSrx.close(); } return true; } catch (IOException e) { s_logger.error(e); return false; } } /* * Commit/rollback */ private void openConfiguration() throws ExecutionException { String xml = SrxXml.OPEN_CONFIGURATION.getXml(); String successMsg = "Opened a private configuration."; String errorMsg = "Failed to open a private configuration."; if (!sendRequestAndCheckResponse(SrxCommand.OPEN_CONFIGURATION, xml)) { throw new ExecutionException(errorMsg); } else { s_logger.debug(successMsg); } } private void closeConfiguration() { String xml = SrxXml.CLOSE_CONFIGURATION.getXml(); String successMsg = "Closed private configuration."; String errorMsg = "Failed to close private configuration."; try { if (!sendRequestAndCheckResponse(SrxCommand.CLOSE_CONFIGURATION, xml)) { s_logger.error(errorMsg); } } catch (ExecutionException e) { s_logger.error(errorMsg); } s_logger.debug(successMsg); } private void commitConfiguration() throws ExecutionException { String xml = SrxXml.COMMIT.getXml(); String successMsg = "Committed to global configuration."; String errorMsg = "Failed to commit to global configuration."; if (!sendRequestAndCheckResponse(SrxCommand.COMMIT, xml)) { throw new ExecutionException(errorMsg); } else { s_logger.debug(successMsg); closeConfiguration(); } } /* * Guest networks */ private synchronized Answer execute(IpAssocCommand cmd) { refreshSrxConnection(); return execute(cmd, _numRetries); } private Answer execute(IpAssocCommand cmd, int numRetries) { String[] results = new String[cmd.getIpAddresses().length]; int i = 0; try { IpAddressTO ip; if (cmd.getIpAddresses().length != 1) { throw new ExecutionException("Received an invalid number of guest IPs to associate."); } else { ip = cmd.getIpAddresses()[0]; } String sourceNatIpAddress = null; GuestNetworkType type = GuestNetworkType.INTERFACE_NAT; if (ip.isSourceNat()) { type = GuestNetworkType.SOURCE_NAT; if (ip.getPublicIp() == null) { throw new ExecutionException("Source NAT IP address must not be null."); } else { sourceNatIpAddress = ip.getPublicIp(); } } long guestVlanTag = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG)); String guestVlanGateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); String cidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR); long cidrSize = NetUtils.cidrToLong(cidr)[1]; String guestVlanSubnet = NetUtils.getCidrSubNet(guestVlanGateway, cidrSize); Long publicVlanTag = null; if (ip.getVlanId() != null && !ip.getVlanId().equals("untagged")) { try { publicVlanTag = Long.parseLong(ip.getVlanId()); } catch (Exception e) { throw new ExecutionException("Could not parse public VLAN tag: " + ip.getVlanId()); } } openConfiguration(); // Remove the guest network: // Remove source, static, and destination NAT rules // Remove VPN shutdownGuestNetwork(type, ip.getAccountId(), publicVlanTag, sourceNatIpAddress, guestVlanTag, guestVlanGateway, guestVlanSubnet, cidrSize); if (ip.isAdd()) { // Implement the guest network for this VLAN implementGuestNetwork(type, publicVlanTag, sourceNatIpAddress, guestVlanTag, guestVlanGateway, guestVlanSubnet, cidrSize); } commitConfiguration(); results[i++] = ip.getPublicIp() + " - success"; } catch (ExecutionException e) { s_logger.error(e); closeConfiguration(); if (numRetries > 0 && refreshSrxConnection()) { int numRetriesRemaining = numRetries - 1; s_logger.debug("Retrying IPAssocCommand. Number of retries remaining: " + numRetriesRemaining); return execute(cmd, numRetriesRemaining); } else { results[i++] = IpAssocAnswer.errorResult; } } return new IpAssocAnswer(cmd, results); } private void implementGuestNetwork(GuestNetworkType type, Long publicVlanTag, String publicIp, long privateVlanTag, String privateGateway, String privateSubnet, long privateCidrNumber) throws ExecutionException { privateGateway = privateGateway + "/" + privateCidrNumber; privateSubnet = privateSubnet + "/" + privateCidrNumber; managePrivateInterface(SrxCommand.ADD, !type.equals(GuestNetworkType.SOURCE_NAT), privateVlanTag, privateGateway); manageZoneInterface(SrxCommand.ADD, privateVlanTag); if (type.equals(GuestNetworkType.SOURCE_NAT)) { manageSourceNatPool(SrxCommand.ADD, publicIp); manageSourceNatRule(SrxCommand.ADD, publicIp, privateSubnet); manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); manageUsageFilter(SrxCommand.ADD, UsageFilter.IP_OUTPUT, privateSubnet, null, genIpFilterTermName(publicIp)); manageUsageFilter(SrxCommand.ADD, UsageFilter.IP_INPUT, publicIp, null, genIpFilterTermName(publicIp)); } else if (type.equals(GuestNetworkType.INTERFACE_NAT)){ manageUsageFilter(SrxCommand.ADD, UsageFilter.VLAN_OUTPUT, null, privateVlanTag, null); manageUsageFilter(SrxCommand.ADD, UsageFilter.VLAN_INPUT, null, privateVlanTag, null); } String msg = "Implemented guest network with type " + type + ". Guest VLAN tag: " + privateVlanTag + ", guest gateway: " + privateGateway; msg += type.equals(GuestNetworkType.SOURCE_NAT) ? ", source NAT IP: " + publicIp : ""; s_logger.debug(msg); } private void shutdownGuestNetwork(GuestNetworkType type, long accountId, Long publicVlanTag, String sourceNatIpAddress, long privateVlanTag, String privateGateway, String privateSubnet, long privateCidrSize) throws ExecutionException { // Remove static and destination NAT rules for the guest network removeStaticAndDestNatRulesInPrivateVlan(privateVlanTag, privateGateway, privateCidrSize); privateGateway = privateGateway + "/" + privateCidrSize; privateSubnet = privateSubnet + "/" + privateCidrSize; managePrivateInterface(SrxCommand.DELETE, false, privateVlanTag, privateGateway); manageZoneInterface(SrxCommand.DELETE, privateVlanTag); deleteVpnObjectsForAccount(accountId); if (type.equals(GuestNetworkType.SOURCE_NAT)) { manageSourceNatRule(SrxCommand.DELETE, sourceNatIpAddress, privateSubnet); manageSourceNatPool(SrxCommand.DELETE, sourceNatIpAddress); manageProxyArp(SrxCommand.DELETE, publicVlanTag, sourceNatIpAddress); manageUsageFilter(SrxCommand.DELETE, UsageFilter.IP_OUTPUT, privateSubnet, null, genIpFilterTermName(sourceNatIpAddress)); manageUsageFilter(SrxCommand.DELETE, UsageFilter.IP_INPUT, sourceNatIpAddress, null, genIpFilterTermName(sourceNatIpAddress)); } else if (type.equals(GuestNetworkType.INTERFACE_NAT)) { manageUsageFilter(SrxCommand.DELETE, UsageFilter.VLAN_OUTPUT, null, privateVlanTag, null); manageUsageFilter(SrxCommand.DELETE, UsageFilter.VLAN_INPUT, null, privateVlanTag, null); } String msg = "Shut down guest network with type " + type +". Guest VLAN tag: " + privateVlanTag + ", guest gateway: " + privateGateway; msg += type.equals(GuestNetworkType.SOURCE_NAT) ? ", source NAT IP: " + sourceNatIpAddress : ""; s_logger.debug(msg); } /* * Static NAT */ private synchronized Answer execute(SetStaticNatRulesCommand cmd) { refreshSrxConnection(); return execute(cmd, _numRetries); } private Answer execute(SetStaticNatRulesCommand cmd, int numRetries) { StaticNatRuleTO[] allRules = cmd.getRules(); Map<String, ArrayList<FirewallRuleTO>> activeRules = getActiveRules(allRules); Map<String, String> vlanTagMap = getVlanTagMap(allRules); try { openConfiguration(); Set<String> ipPairs = activeRules.keySet(); for (String ipPair : ipPairs) { String[] ipPairComponents = ipPair.split("-"); String publicIp = ipPairComponents[0]; String privateIp = ipPairComponents[1]; List<FirewallRuleTO> activeRulesForIpPair = activeRules.get(ipPair); Long publicVlanTag = getVlanTag(vlanTagMap.get(publicIp)); // Delete the existing static NAT rule for this IP pair removeStaticNatRule(publicVlanTag, publicIp, privateIp); if (activeRulesForIpPair.size() > 0) { // If there are active FirewallRules for this IP pair, add the static NAT rule and open the specified port ranges addStaticNatRule(publicVlanTag, publicIp, privateIp, activeRulesForIpPair); } } commitConfiguration(); return new Answer(cmd); } catch (ExecutionException e) { s_logger.error(e); closeConfiguration(); if (numRetries > 0 && refreshSrxConnection()) { int numRetriesRemaining = numRetries - 1; s_logger.debug("Retrying SetPortForwardingRulesCommand. Number of retries remaining: " + numRetriesRemaining); return execute(cmd, numRetriesRemaining); } else { return new Answer(cmd, e); } } } private void addStaticNatRule(Long publicVlanTag, String publicIp, String privateIp, List<FirewallRuleTO> rules) throws ExecutionException { manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); manageStaticNatRule(SrxCommand.ADD, publicIp, privateIp); manageUsageFilter(SrxCommand.ADD, UsageFilter.IP_INPUT, publicIp, null, genIpFilterTermName(publicIp)); manageAddressBookEntry(SrxCommand.ADD, _privateZone, privateIp, null); // Add a new security policy with the current set of applications addSecurityPolicyAndApplications(SecurityPolicyType.STATIC_NAT, privateIp, extractApplications(rules)); s_logger.debug("Added static NAT rule for public IP " + publicIp + ", and private IP " + privateIp); } private void removeStaticNatRule(Long publicVlanTag, String publicIp, String privateIp) throws ExecutionException { manageStaticNatRule(SrxCommand.DELETE, publicIp, privateIp); manageProxyArp(SrxCommand.DELETE, publicVlanTag, publicIp); manageUsageFilter(SrxCommand.DELETE, UsageFilter.IP_INPUT, publicIp, null, genIpFilterTermName(publicIp)); // Remove any existing security policy and clean up applications removeSecurityPolicyAndApplications(SecurityPolicyType.STATIC_NAT, privateIp); manageAddressBookEntry(SrxCommand.DELETE, _privateZone, privateIp, null); s_logger.debug("Removed static NAT rule for public IP " + publicIp + ", and private IP " + privateIp); } private void removeStaticNatRules(Long privateVlanTag, Map<String, Long> publicVlanTags, List<String[]> staticNatRules) throws ExecutionException { for (String[] staticNatRuleToRemove : staticNatRules) { String staticNatRulePublicIp = staticNatRuleToRemove[0]; String staticNatRulePrivateIp = staticNatRuleToRemove[1]; Long publicVlanTag = null; if (publicVlanTags.containsKey(staticNatRulePublicIp)) { publicVlanTag = publicVlanTags.get(staticNatRulePublicIp); } if (privateVlanTag != null) { s_logger.warn("Found a static NAT rule (" + staticNatRulePublicIp + " <-> " + staticNatRulePrivateIp + ") for guest VLAN with tag " + privateVlanTag + " that is active when the guest network is being removed. Removing rule..."); } removeStaticNatRule(publicVlanTag, staticNatRulePublicIp, staticNatRulePrivateIp); } } /* * VPN */ private synchronized Answer execute(RemoteAccessVpnCfgCommand cmd) { refreshSrxConnection(); return execute(cmd, _numRetries); } private Answer execute(RemoteAccessVpnCfgCommand cmd, int numRetries) { long accountId = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.ACCOUNT_ID)); String guestNetworkCidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR); String preSharedKey = cmd.getPresharedKey(); String[] ipRange = cmd.getIpRange().split("-"); try { openConfiguration(); // Delete existing VPN objects for this account deleteVpnObjectsForAccount(accountId); if (cmd.isCreate()) { // Add IKE policy manageIkePolicy(SrxCommand.ADD, null, accountId, preSharedKey); // Add address pool manageAddressPool(SrxCommand.ADD, null, accountId, guestNetworkCidr, ipRange[0], ipRange[1], _primaryDnsAddress); } commitConfiguration(); return new Answer(cmd); } catch (ExecutionException e) { s_logger.error(e); closeConfiguration(); if (numRetries > 0 && refreshSrxConnection()) { int numRetriesRemaining = numRetries - 1; s_logger.debug("Retrying RemoteAccessVpnCfgCommand. Number of retries remaining: " + numRetriesRemaining); return execute(cmd, numRetriesRemaining); } else { return new Answer(cmd, e); } } } private void deleteVpnObjectsForAccount(long accountId) throws ExecutionException { // Delete all IKE policies for (String ikePolicyName : getVpnObjectNames(SrxXml.IKE_POLICY_GETALL, accountId)) { manageIkePolicy(SrxCommand.DELETE, ikePolicyName, null, null); } // Delete all address pools for (String addressPoolName : getVpnObjectNames(SrxXml.ADDRESS_POOL_GETALL, accountId)) { manageAddressPool(SrxCommand.DELETE, addressPoolName, null, null, null, null, null); } // Delete all IKE gateways for (String ikeGatewayName : getVpnObjectNames(SrxXml.IKE_GATEWAY_GETALL, accountId)) { manageIkeGateway(SrxCommand.DELETE, ikeGatewayName, null, null, null, null); } // Delete all IPsec VPNs for (String ipsecVpnName : getVpnObjectNames(SrxXml.IPSEC_VPN_GETALL, accountId)) { manageIpsecVpn(SrxCommand.DELETE, ipsecVpnName, null, null, null, null); } // Delete all dynamic VPN clients for (String dynamicVpnClientName : getVpnObjectNames(SrxXml.DYNAMIC_VPN_CLIENT_GETALL, accountId)) { manageDynamicVpnClient(SrxCommand.DELETE, dynamicVpnClientName, null, null, null, null); } // Delete all access profiles for (String accessProfileName : getVpnObjectNames(SrxXml.ACCESS_PROFILE_GETALL, accountId)) { manageAccessProfile(SrxCommand.DELETE, accessProfileName, null, null, null, null); } // Delete all security policies for (String securityPolicyName : getVpnObjectNames(SrxXml.SECURITY_POLICY_GETALL, accountId)) { manageSecurityPolicy(SecurityPolicyType.VPN, SrxCommand.DELETE, accountId, null, null, null, securityPolicyName); } // Delete all address book entries for (String addressBookEntryName : getVpnObjectNames(SrxXml.ADDRESS_BOOK_ENTRY_GETALL, accountId)) { manageAddressBookEntry(SrxCommand.DELETE, _privateZone, null, addressBookEntryName); } } public List<String> getVpnObjectNames(SrxXml xmlObj, long accountId) throws ExecutionException { List<String> vpnObjectNames = new ArrayList<String>(); String xmlRequest = xmlObj.getXml(); if (xmlObj.equals(SrxXml.SECURITY_POLICY_GETALL)) { xmlRequest = replaceXmlValue(xmlRequest, "from-zone", _publicZone); xmlRequest = replaceXmlValue(xmlRequest, "to-zone", _privateZone); } else if (xmlObj.equals(SrxXml.ADDRESS_BOOK_ENTRY_GETALL)) { xmlRequest = replaceXmlValue(xmlRequest, "zone", _privateZone); } String xmlResponse = sendRequest(xmlRequest); Document doc = getDocument(xmlResponse); NodeList vpnObjectNameNodes = doc.getElementsByTagName("name"); for (int i = 0; i < vpnObjectNameNodes.getLength(); i++) { NodeList vpnObjectNameEntries = vpnObjectNameNodes.item(i).getChildNodes(); for (int j = 0; j < vpnObjectNameEntries.getLength(); j++) { String vpnObjectName = vpnObjectNameEntries.item(j).getNodeValue(); if (vpnObjectName.startsWith(genObjectName(_vpnObjectPrefix, String.valueOf(accountId)))) { vpnObjectNames.add(vpnObjectName); } } } return vpnObjectNames; } private synchronized Answer execute(VpnUsersCfgCommand cmd) { refreshSrxConnection(); return execute(cmd, _numRetries); } private Answer execute(VpnUsersCfgCommand cmd, int numRetries) { long accountId = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.ACCOUNT_ID)); String guestNetworkCidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR); String ikePolicyName = genIkePolicyName(accountId); UsernamePassword[] users = cmd.getUserpwds(); try { openConfiguration(); for (UsernamePassword user : users) { SrxCommand srxCmd = user.isAdd() ? SrxCommand.ADD : SrxCommand.DELETE; String ipsecVpnName = genIpsecVpnName(accountId, user.getUsername()); // IKE gateway manageIkeGateway(srxCmd, null, accountId, ikePolicyName, _ikeGatewayHostname , user.getUsername()); // IPSec VPN manageIpsecVpn(srxCmd, null, accountId, guestNetworkCidr, user.getUsername(), _ipsecPolicyName); // Dynamic VPN client manageDynamicVpnClient(srxCmd, null, accountId, guestNetworkCidr, ipsecVpnName, user.getUsername()); // Access profile manageAccessProfile(srxCmd, null, accountId, user.getUsername(), user.getPassword(), genAddressPoolName(accountId)); // Address book entry manageAddressBookEntry(srxCmd, _privateZone , guestNetworkCidr, ipsecVpnName); // Security policy manageSecurityPolicy(SecurityPolicyType.VPN, srxCmd, null, null, guestNetworkCidr, null, ipsecVpnName); } commitConfiguration(); return new Answer(cmd); } catch (ExecutionException e) { s_logger.error(e); closeConfiguration(); if (numRetries > 0 && refreshSrxConnection()) { int numRetriesRemaining = numRetries - 1; s_logger.debug("Retrying RemoteAccessVpnCfgCommand. Number of retries remaining: " + numRetriesRemaining); return execute(cmd, numRetriesRemaining); } else { return new Answer(cmd, e); } } } /* * Destination NAT */ private synchronized Answer execute (SetPortForwardingRulesCommand cmd) { refreshSrxConnection(); return execute(cmd, _numRetries); } private Answer execute(SetPortForwardingRulesCommand cmd, int numRetries) { PortForwardingRuleTO[] allRules = cmd.getRules(); Map<String, ArrayList<FirewallRuleTO>> activeRules = getActiveRules(allRules); try { openConfiguration(); Set<String> ipPairs = activeRules.keySet(); for (String ipPair : ipPairs) { String[] ipPairComponents = ipPair.split("-"); String publicIp = ipPairComponents[0]; String privateIp = ipPairComponents[1]; List<FirewallRuleTO> activeRulesForIpPair = activeRules.get(ipPair); // Get a list of all destination NAT rules for the public/private IP address pair List<String[]> destNatRules = getDestNatRules(RuleMatchCondition.PUBLIC_PRIVATE_IPS, publicIp, privateIp, null, null); Map<String, Long> publicVlanTags = getPublicVlanTagsForNatRules(destNatRules); // Delete all of these rules, along with the destination NAT pools and security policies they use removeDestinationNatRules(null, publicVlanTags, destNatRules); // If there are active rules for the public/private IP address pair, add them back for (FirewallRuleTO rule : activeRulesForIpPair) { Long publicVlanTag = getVlanTag(rule.getSrcVlanTag()); PortForwardingRuleTO portForwardingRule = (PortForwardingRuleTO) rule; addDestinationNatRule(getProtocol(rule.getProtocol()), publicVlanTag, portForwardingRule.getSrcIp(), portForwardingRule.getDstIp(), portForwardingRule.getSrcPortRange()[0], portForwardingRule.getSrcPortRange()[1], portForwardingRule.getDstPortRange()[0], portForwardingRule.getDstPortRange()[1]); } } commitConfiguration(); return new Answer(cmd); } catch (ExecutionException e) { s_logger.error(e); closeConfiguration(); if (numRetries > 0 && refreshSrxConnection()) { int numRetriesRemaining = numRetries - 1; s_logger.debug("Retrying SetPortForwardingRulesCommand. Number of retries remaining: " + numRetriesRemaining); return execute(cmd, numRetriesRemaining); } else { return new Answer(cmd, e); } } } private void addDestinationNatRule(Protocol protocol, Long publicVlanTag, String publicIp, String privateIp, int srcPortStart, int srcPortEnd, int destPortStart, int destPortEnd) throws ExecutionException { manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); int offset = 0; for (int srcPort = srcPortStart; srcPort <= srcPortEnd; srcPort++) { int destPort = destPortStart + offset; manageDestinationNatPool(SrxCommand.ADD, privateIp, destPort); manageDestinationNatRule(SrxCommand.ADD, publicIp, privateIp, srcPort, destPort); offset += 1; } manageAddressBookEntry(SrxCommand.ADD, _privateZone, privateIp, null); List<Object[]> applications = new ArrayList<Object[]>(); applications.add(new Object[]{protocol, destPortStart, destPortEnd}); addSecurityPolicyAndApplications(SecurityPolicyType.DESTINATION_NAT, privateIp, applications); String srcPortRange = srcPortStart + "-" + srcPortEnd; String destPortRange = destPortStart + "-" + destPortEnd; s_logger.debug("Added destination NAT rule for protocol " + protocol + ", public IP " + publicIp + ", private IP " + privateIp + ", source port range " + srcPortRange + ", and dest port range " + destPortRange); } private void removeDestinationNatRule(Long publicVlanTag, String publicIp, String privateIp, int srcPort, int destPort) throws ExecutionException { manageDestinationNatRule(SrxCommand.DELETE, publicIp, privateIp, srcPort, destPort); manageDestinationNatPool(SrxCommand.DELETE, privateIp, destPort); manageProxyArp(SrxCommand.DELETE, publicVlanTag, publicIp); removeSecurityPolicyAndApplications(SecurityPolicyType.DESTINATION_NAT, privateIp); manageAddressBookEntry(SrxCommand.DELETE, _privateZone, privateIp, null); s_logger.debug("Removed destination NAT rule for public IP " + publicIp + ", private IP " + privateIp + ", source port " + srcPort + ", and dest port " + destPort); } private void removeDestinationNatRules(Long privateVlanTag, Map<String, Long> publicVlanTags, List<String[]> destNatRules) throws ExecutionException { for (String[] destNatRule : destNatRules) { String publicIp = destNatRule[0]; String privateIp = destNatRule[1]; int srcPort = Integer.valueOf(destNatRule[2]); int destPort = Integer.valueOf(destNatRule[3]); Long publicVlanTag = null; if (publicVlanTags.containsKey(publicIp)) { publicVlanTag = publicVlanTags.get(publicIp); } if (privateVlanTag != null) { s_logger.warn("Found a destination NAT rule (public IP: " + publicIp + ", private IP: " + privateIp + ", public port: " + srcPort + ", private port: " + destPort + ") for guest VLAN with tag " + privateVlanTag + " that is active when the guest network is being removed. Removing rule..."); } removeDestinationNatRule(publicVlanTag, publicIp, privateIp, srcPort, destPort); } } /* * General NAT utils */ private List<String[]> getAllStaticAndDestNatRules() throws ExecutionException { List<String[]> staticAndDestNatRules = new ArrayList<String[]>(); staticAndDestNatRules.addAll(getStaticNatRules(RuleMatchCondition.ALL, null, null)); staticAndDestNatRules.addAll(getDestNatRules(RuleMatchCondition.ALL, null, null, null, null)); return staticAndDestNatRules; } private void removeStaticAndDestNatRulesInPrivateVlan(long privateVlanTag, String privateGateway, long privateCidrSize) throws ExecutionException { List<String[]> staticNatRulesToRemove = getStaticNatRules(RuleMatchCondition.PRIVATE_SUBNET, privateGateway, privateCidrSize); List<String[]> destNatRulesToRemove = getDestNatRules(RuleMatchCondition.PRIVATE_SUBNET, null, null, privateGateway, privateCidrSize); List<String> publicIps = new ArrayList<String>(); addPublicIpsToList(staticNatRulesToRemove, publicIps); addPublicIpsToList(destNatRulesToRemove, publicIps); Map<String, Long> publicVlanTags = getPublicVlanTagsForPublicIps(publicIps); removeStaticNatRules(privateVlanTag, publicVlanTags, staticNatRulesToRemove); removeDestinationNatRules(privateVlanTag, publicVlanTags, destNatRulesToRemove); } private Map<String, ArrayList<FirewallRuleTO>> getActiveRules(FirewallRuleTO[] allRules) { Map<String, ArrayList<FirewallRuleTO>> activeRules = new HashMap<String, ArrayList<FirewallRuleTO>>(); for (FirewallRuleTO rule : allRules) { String ipPair; if (rule.getPurpose().equals(Purpose.StaticNat)) { StaticNatRuleTO staticNatRule = (StaticNatRuleTO) rule; ipPair = staticNatRule.getSrcIp() + "-" + staticNatRule.getDstIp(); } else if (rule.getPurpose().equals(Purpose.PortForwarding)) { PortForwardingRuleTO portForwardingRule = (PortForwardingRuleTO) rule; ipPair = portForwardingRule.getSrcIp() + "-" + portForwardingRule.getDstIp(); } else { continue; } ArrayList<FirewallRuleTO> activeRulesForIpPair = activeRules.get(ipPair); if (activeRulesForIpPair == null) { activeRulesForIpPair = new ArrayList<FirewallRuleTO>(); } if (!rule.revoked() || rule.isAlreadyAdded()) { activeRulesForIpPair.add(rule); } activeRules.put(ipPair, activeRulesForIpPair); } return activeRules; } private Map<String, String> getVlanTagMap(FirewallRuleTO[] allRules) { Map<String, String> vlanTagMap = new HashMap<String, String>(); for (FirewallRuleTO rule : allRules) { vlanTagMap.put(rule.getSrcIp(), rule.getSrcVlanTag()); } return vlanTagMap; } /* * VPN */ private String genIkePolicyName(long accountId) { return genObjectName(_vpnObjectPrefix, String.valueOf(accountId)); } private boolean manageIkePolicy(SrxCommand command, String ikePolicyName, Long accountId, String preSharedKey) throws ExecutionException { if (ikePolicyName == null) { ikePolicyName = genIkePolicyName(accountId); } String xml; switch(command) { case CHECK_IF_EXISTS: xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "policy-name", ikePolicyName); return sendRequestAndCheckResponse(command, xml, "name", ikePolicyName); case ADD: if (manageIkePolicy(SrxCommand.CHECK_IF_EXISTS, ikePolicyName, accountId, preSharedKey)) { return true; } xml = SrxXml.IKE_POLICY_ADD.getXml(); xml = replaceXmlValue(xml, "policy-name", ikePolicyName); xml = replaceXmlValue(xml, "proposal-name", _ikeProposalName); xml = replaceXmlValue(xml, "pre-shared-key", preSharedKey); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add IKE policy: " + ikePolicyName); } else { return true; } case DELETE: if (!manageIkePolicy(SrxCommand.CHECK_IF_EXISTS, ikePolicyName, accountId, preSharedKey)) { return true; } xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "policy-name", ikePolicyName); if (!sendRequestAndCheckResponse(command, xml, "name", ikePolicyName)) { throw new ExecutionException("Failed to delete IKE policy: " + ikePolicyName); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private String genIkeGatewayName(long accountId, String username) { return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); } private boolean manageIkeGateway(SrxCommand command, String ikeGatewayName, Long accountId, String ikePolicyName, String ikeGatewayHostname, String username) throws ExecutionException { if (ikeGatewayName == null) { ikeGatewayName = genIkeGatewayName(accountId, username); } String xml; switch(command) { case CHECK_IF_EXISTS: xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "gateway-name", ikeGatewayName); return sendRequestAndCheckResponse(command, xml, "name", ikeGatewayName); case ADD: if (manageIkeGateway(SrxCommand.CHECK_IF_EXISTS, ikeGatewayName, accountId, ikePolicyName, ikeGatewayHostname, username)) { return true; } xml = SrxXml.IKE_GATEWAY_ADD.getXml(); xml = replaceXmlValue(xml, "gateway-name", ikeGatewayName); xml = replaceXmlValue(xml, "ike-policy-name", ikePolicyName); xml = replaceXmlValue(xml, "ike-gateway-hostname", ikeGatewayHostname); xml = replaceXmlValue(xml, "public-interface-name", _publicInterface); xml = replaceXmlValue(xml, "access-profile-name", genAccessProfileName(accountId, username)); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add IKE gateway: " + ikeGatewayName); } else { return true; } case DELETE: if (!manageIkeGateway(SrxCommand.CHECK_IF_EXISTS, ikeGatewayName, accountId, ikePolicyName, ikeGatewayHostname, username)) { return true; } xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "gateway-name", ikeGatewayName); if (!sendRequestAndCheckResponse(command, xml, "name", ikeGatewayName)) { throw new ExecutionException("Failed to delete IKE gateway: " + ikeGatewayName); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private String genIpsecVpnName(long accountId, String username) { return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); } private boolean manageIpsecVpn(SrxCommand command, String ipsecVpnName, Long accountId, String guestNetworkCidr, String username, String ipsecPolicyName) throws ExecutionException { if (ipsecVpnName == null) { ipsecVpnName = genIpsecVpnName(accountId, username); } String xml; switch(command) { case CHECK_IF_EXISTS: xml = SrxXml.IPSEC_VPN_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); return sendRequestAndCheckResponse(command, xml, "name", ipsecVpnName); case ADD: if (manageIpsecVpn(SrxCommand.CHECK_IF_EXISTS, ipsecVpnName, accountId, guestNetworkCidr, username, ipsecPolicyName)) { return true; } xml = SrxXml.IPSEC_VPN_ADD.getXml(); xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); xml = replaceXmlValue(xml, "ike-gateway", genIkeGatewayName(accountId, username)); xml = replaceXmlValue(xml, "ipsec-policy-name", ipsecPolicyName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add IPSec VPN: " + ipsecVpnName); } else { return true; } case DELETE: if (!manageIpsecVpn(SrxCommand.CHECK_IF_EXISTS, ipsecVpnName, accountId, guestNetworkCidr, username, ipsecPolicyName)) { return true; } xml = SrxXml.IPSEC_VPN_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); if (!sendRequestAndCheckResponse(command, xml, "name", ipsecVpnName)) { throw new ExecutionException("Failed to delete IPSec VPN: " + ipsecVpnName); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private String genDynamicVpnClientName(long accountId, String username) { return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); } private boolean manageDynamicVpnClient(SrxCommand command, String clientName, Long accountId, String guestNetworkCidr, String ipsecVpnName, String username) throws ExecutionException { if (clientName == null) { clientName = genDynamicVpnClientName(accountId, username); } String xml; switch(command) { case CHECK_IF_EXISTS: xml = SrxXml.DYNAMIC_VPN_CLIENT_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "client-name", clientName); return sendRequestAndCheckResponse(command, xml, "name", clientName); case ADD: if (manageDynamicVpnClient(SrxCommand.CHECK_IF_EXISTS, clientName, accountId, guestNetworkCidr, ipsecVpnName, username)) { return true; } xml = SrxXml.DYNAMIC_VPN_CLIENT_ADD.getXml(); xml = replaceXmlValue(xml, "client-name", clientName); xml = replaceXmlValue(xml, "guest-network-cidr", guestNetworkCidr); xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); xml = replaceXmlValue(xml, "username", username); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add dynamic VPN client: " + clientName); } else { return true; } case DELETE: if (!manageDynamicVpnClient(SrxCommand.CHECK_IF_EXISTS, clientName, accountId, guestNetworkCidr, ipsecVpnName, username)) { return true; } xml = SrxXml.DYNAMIC_VPN_CLIENT_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "client-name", clientName); if (!sendRequestAndCheckResponse(command, xml, "name", clientName)) { throw new ExecutionException("Failed to delete dynamic VPN client: " + clientName); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private String genAddressPoolName(long accountId) { return genObjectName(_vpnObjectPrefix, String.valueOf(accountId)); } private boolean manageAddressPool(SrxCommand command, String addressPoolName, Long accountId, String guestNetworkCidr, String lowAddress, String highAddress, String primaryDnsAddress) throws ExecutionException { if (addressPoolName == null) { addressPoolName = genAddressPoolName(accountId); } String xml; switch(command) { case CHECK_IF_EXISTS: xml = SrxXml.ADDRESS_POOL_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); return sendRequestAndCheckResponse(command, xml, "name", addressPoolName); case ADD: if (manageAddressPool(SrxCommand.CHECK_IF_EXISTS, addressPoolName, accountId, guestNetworkCidr, lowAddress, highAddress, primaryDnsAddress)) { return true; } xml = SrxXml.ADDRESS_POOL_ADD.getXml(); xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); xml = replaceXmlValue(xml, "guest-network-cidr", guestNetworkCidr); xml = replaceXmlValue(xml, "address-range-name", "r-" + addressPoolName); xml = replaceXmlValue(xml, "low-address", lowAddress); xml = replaceXmlValue(xml, "high-address", highAddress); xml = replaceXmlValue(xml, "primary-dns-address", primaryDnsAddress); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add address pool: " + addressPoolName); } else { return true; } case DELETE: if (!manageAddressPool(SrxCommand.CHECK_IF_EXISTS, addressPoolName, accountId, guestNetworkCidr, lowAddress, highAddress, primaryDnsAddress)) { return true; } xml = SrxXml.ADDRESS_POOL_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); if (!sendRequestAndCheckResponse(command, xml, "name", addressPoolName)) { throw new ExecutionException("Failed to delete address pool: " + addressPoolName); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private String genAccessProfileName(long accountId, String username) { return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); } private boolean manageAccessProfile(SrxCommand command, String accessProfileName, Long accountId, String username, String password, String addressPoolName) throws ExecutionException { if (accessProfileName == null) { accessProfileName = genAccessProfileName(accountId, username); } String xml; switch(command) { case CHECK_IF_EXISTS: xml = SrxXml.ACCESS_PROFILE_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "access-profile-name", accessProfileName); return sendRequestAndCheckResponse(command, xml, "name", username); case ADD: if (manageAccessProfile(SrxCommand.CHECK_IF_EXISTS, accessProfileName, accountId, username, password, addressPoolName)) { return true; } xml = SrxXml.ACCESS_PROFILE_ADD.getXml(); xml = replaceXmlValue(xml, "access-profile-name", accessProfileName); xml = replaceXmlValue(xml, "username", username); xml = replaceXmlValue(xml, "password", password); xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add access profile: " + accessProfileName); } else { return true; } case DELETE: if (!manageAccessProfile(SrxCommand.CHECK_IF_EXISTS, accessProfileName, accountId, username, password, addressPoolName)) { return true; } xml = SrxXml.ACCESS_PROFILE_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "access-profile-name", accessProfileName); if (!sendRequestAndCheckResponse(command, xml, "name", username)) { throw new ExecutionException("Failed to delete access profile: " + accessProfileName); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } /* * Private interfaces */ private boolean managePrivateInterface(SrxCommand command, boolean addFilters, long vlanTag, String privateInterfaceIp) throws ExecutionException { String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.PRIVATE_INTERFACE_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "private-interface-name", _privateInterface); xml = replaceXmlValue(xml, "vlan-id", String.valueOf(vlanTag)); return sendRequestAndCheckResponse(command, xml, "name", String.valueOf(vlanTag)); case ADD: if (managePrivateInterface(SrxCommand.CHECK_IF_EXISTS, false, vlanTag, privateInterfaceIp)) { return true; } xml = addFilters ? SrxXml.PRIVATE_INTERFACE_WITH_FILTERS_ADD.getXml() : SrxXml.PRIVATE_INTERFACE_ADD.getXml(); xml = replaceXmlValue(xml, "private-interface-name", _privateInterface); xml = replaceXmlValue(xml, "vlan-id", String.valueOf(vlanTag)); xml = replaceXmlValue(xml, "private-interface-ip", privateInterfaceIp); if (addFilters) { xml = replaceXmlValue(xml, "input-filter-name", UsageFilter.VLAN_INPUT.getName() + "-" + vlanTag); xml = replaceXmlValue(xml, "output-filter-name", UsageFilter.VLAN_OUTPUT.getName() + "-" + vlanTag); } if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add private interface for guest VLAN tag " + vlanTag); } else { return true; } case DELETE: if (!managePrivateInterface(SrxCommand.CHECK_IF_EXISTS, false, vlanTag, privateInterfaceIp)) { return true; } xml = SrxXml.PRIVATE_INTERFACE_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "private-interface-name", _privateInterface); xml = replaceXmlValue(xml, "vlan-id", String.valueOf(vlanTag)); if (!sendRequestAndCheckResponse(command, xml, "name", String.valueOf(vlanTag))) { throw new ExecutionException("Failed to delete private interface for guest VLAN tag " + vlanTag); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private Long getVlanTagFromInterfaceName(String interfaceName) throws ExecutionException { Long vlanTag = null; if (interfaceName.contains(".")) { try { String unitNum = interfaceName.split("\\.")[1]; if (!unitNum.equals("0")) { vlanTag = Long.parseLong(unitNum); } } catch (Exception e) { s_logger.error(e); throw new ExecutionException("Unable to parse VLAN tag from interface name: " + interfaceName); } } return vlanTag; } /* * Proxy ARP */ private boolean manageProxyArp(SrxCommand command, Long publicVlanTag, String publicIp) throws ExecutionException { String publicInterface = genPublicInterface(publicVlanTag); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.PROXY_ARP_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "public-interface-name", publicInterface); xml = replaceXmlValue(xml, "public-ip-address", publicIp); return sendRequestAndCheckResponse(command, xml, "name", publicIp + "/32"); case CHECK_IF_IN_USE: // Check if any NAT rules are using this proxy ARP entry String poolName = genSourceNatPoolName(publicIp); String allStaticNatRules = sendRequest(SrxXml.STATIC_NAT_RULE_GETALL.getXml()); String allDestNatRules = sendRequest(replaceXmlValue(SrxXml.DEST_NAT_RULE_GETALL.getXml(), "rule-set", _publicZone)); String allSrcNatRules = sendRequest(SrxXml.SRC_NAT_RULE_GETALL.getXml()); return (allStaticNatRules.contains(publicIp) || allDestNatRules.contains(publicIp) || allSrcNatRules.contains(poolName)); case ADD: if (manageProxyArp(SrxCommand.CHECK_IF_EXISTS, publicVlanTag, publicIp)) { return true; } xml = SrxXml.PROXY_ARP_ADD.getXml(); xml = replaceXmlValue(xml, "public-interface-name", publicInterface); xml = replaceXmlValue(xml, "public-ip-address", publicIp); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add proxy ARP entry for public IP " + publicIp); } else { return true; } case DELETE: if (!manageProxyArp(SrxCommand.CHECK_IF_EXISTS, publicVlanTag, publicIp)) { return true; } if (manageProxyArp(SrxCommand.CHECK_IF_IN_USE, publicVlanTag, publicIp)) { return true; } xml = SrxXml.PROXY_ARP_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "public-interface-name", publicInterface); xml = replaceXmlValue(xml, "public-ip-address", publicIp); if (!sendRequestAndCheckResponse(command, xml, "name", publicIp)) { throw new ExecutionException("Failed to delete proxy ARP entry for public IP " + publicIp); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private Map<String, Long> getPublicVlanTagsForPublicIps(List<String> publicIps) throws ExecutionException { Map<String, Long> publicVlanTags = new HashMap<String, Long>(); List<String> interfaceNames = new ArrayList<String>(); String xmlRequest = SrxXml.PROXY_ARP_GETALL.getXml(); xmlRequest = replaceXmlValue(xmlRequest, "interface-name", ""); String xmlResponse = sendRequest(xmlRequest); Document doc = getDocument(xmlResponse); NodeList interfaces = doc.getElementsByTagName("interface"); for (int i = 0; i < interfaces.getLength(); i++) { String interfaceName = null; NodeList interfaceEntries = interfaces.item(i).getChildNodes(); for (int j = 0; j < interfaceEntries.getLength(); j++) { Node interfaceEntry = interfaceEntries.item(j); if (interfaceEntry.getNodeName().equals("name")) { interfaceName = interfaceEntry.getFirstChild().getNodeValue(); break; } } if (interfaceName != null) { interfaceNames.add(interfaceName); } } if (interfaceNames.size() == 1) { populatePublicVlanTagsMap(xmlResponse, interfaceNames.get(0), publicIps, publicVlanTags); } else if (interfaceNames.size() > 1) { for (String interfaceName : interfaceNames) { xmlRequest = SrxXml.PROXY_ARP_GETALL.getXml(); xmlRequest = replaceXmlValue(xmlRequest, "interface-name", interfaceName); xmlResponse = sendRequest(xmlRequest); populatePublicVlanTagsMap(xmlResponse, interfaceName, publicIps, publicVlanTags); } } return publicVlanTags; } private void populatePublicVlanTagsMap(String xmlResponse, String interfaceName, List<String> publicIps, Map<String, Long> publicVlanTags) throws ExecutionException { Long publicVlanTag = getVlanTagFromInterfaceName(interfaceName); if (publicVlanTag != null) { for (String publicIp : publicIps) { if (xmlResponse.contains(publicIp)) { publicVlanTags.put(publicIp, publicVlanTag); } } } } private Map<String, Long> getPublicVlanTagsForNatRules(List<String[]> natRules) throws ExecutionException { List<String> publicIps = new ArrayList<String>(); addPublicIpsToList(natRules, publicIps); return getPublicVlanTagsForPublicIps(publicIps); } private void addPublicIpsToList(List<String[]> natRules, List<String> publicIps) { for (String[] natRule : natRules) { if (!publicIps.contains(natRule[0])) { publicIps.add(natRule[0]); } } } private String genPublicInterface(Long vlanTag) { String publicInterface = _publicInterface; if (!publicInterface.contains(".")) { if (vlanTag == null) { publicInterface += ".0"; } else { publicInterface += "." + vlanTag; } } return publicInterface; } /* * Zone interfaces */ private String genZoneInterfaceName(long vlanTag) { return _privateInterface + "." + String.valueOf(vlanTag); } private boolean manageZoneInterface(SrxCommand command, long vlanTag) throws ExecutionException { String zoneInterfaceName = genZoneInterfaceName(vlanTag); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.ZONE_INTERFACE_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "private-zone-name", _privateZone); xml = replaceXmlValue(xml, "zone-interface-name", zoneInterfaceName); return sendRequestAndCheckResponse(command, xml, "name", zoneInterfaceName); case ADD: if (manageZoneInterface(SrxCommand.CHECK_IF_EXISTS, vlanTag)) { return true; } xml = SrxXml.ZONE_INTERFACE_ADD.getXml(); xml = replaceXmlValue(xml, "private-zone-name", _privateZone); xml = replaceXmlValue(xml, "zone-interface-name", zoneInterfaceName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add interface " + zoneInterfaceName + " to zone " + _privateZone); } else { return true; } case DELETE: if (!manageZoneInterface(SrxCommand.CHECK_IF_EXISTS, vlanTag)) { return true; } xml = SrxXml.ZONE_INTERFACE_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "private-zone-name", _privateZone); xml = replaceXmlValue(xml, "zone-interface-name", zoneInterfaceName); if (!sendRequestAndCheckResponse(command, xml, "name", zoneInterfaceName)) { throw new ExecutionException("Failed to delete interface " + zoneInterfaceName + " from zone " + _privateZone); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } /* * Static NAT rules */ private String genStaticNatRuleName(String publicIp, String privateIp) { return genObjectName(genIpIdentifier(publicIp), genIpIdentifier(privateIp)); } private boolean manageStaticNatRule(SrxCommand command, String publicIp, String privateIp) throws ExecutionException { String ruleName = genStaticNatRuleName(publicIp, privateIp); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.STATIC_NAT_RULE_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "rule-set", _publicZone); xml = replaceXmlValue(xml, "from-zone", _publicZone); xml = replaceXmlValue(xml, "rule-name", ruleName); return sendRequestAndCheckResponse(command, xml, "name", ruleName); case ADD: if (manageStaticNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp)) { return true; } xml = SrxXml.STATIC_NAT_RULE_ADD.getXml(); xml = replaceXmlValue(xml, "rule-set", _publicZone); xml = replaceXmlValue(xml, "from-zone", _publicZone); xml = replaceXmlValue(xml, "rule-name", ruleName); xml = replaceXmlValue(xml, "original-ip", publicIp); xml = replaceXmlValue(xml, "translated-ip", privateIp); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add static NAT rule from public IP " + publicIp + " to private IP " + privateIp); } else { return true; } case DELETE: if (!manageStaticNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp)) { return true; } xml = SrxXml.STATIC_NAT_RULE_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "rule-set", _publicZone); xml = replaceXmlValue(xml, "from-zone", _publicZone); xml = replaceXmlValue(xml, "rule-name", ruleName); if (!sendRequestAndCheckResponse(command, xml, "name", ruleName)) { throw new ExecutionException("Failed to delete static NAT rule from public IP " + publicIp + " to private IP " + privateIp); } else { return true; } default: throw new ExecutionException("Unrecognized command."); } } private List<String[]> getStaticNatRules(RuleMatchCondition condition, String privateGateway, Long privateCidrSize) throws ExecutionException { List<String[]> staticNatRules = new ArrayList<String[]>(); String xmlRequest = SrxXml.STATIC_NAT_RULE_GETALL.getXml(); String xmlResponse = sendRequest(xmlRequest); Document doc = getDocument(xmlResponse); NodeList rules = doc.getElementsByTagName("rule"); for (int i = 0; i < rules.getLength(); i++) { NodeList ruleEntries = rules.item(i).getChildNodes(); for (int j = 0; j < ruleEntries.getLength(); j++) { Node ruleEntry = ruleEntries.item(j); if (ruleEntry.getNodeName().equals("name")) { String name = ruleEntry.getFirstChild().getNodeValue(); String[] nameContents = name.split("-"); if (nameContents.length != 8) { continue; } String rulePublicIp = nameContents[0] + "." + nameContents[1] + "." + nameContents[2] + "." + nameContents[3]; String rulePrivateIp = nameContents[4] + "." + nameContents[5] + "." + nameContents[6] + "." + nameContents[7]; boolean addToList = false; if (condition.equals(RuleMatchCondition.ALL)) { addToList = true; } else if (condition.equals(RuleMatchCondition.PRIVATE_SUBNET)) { assert (privateGateway != null && privateCidrSize != null); addToList = NetUtils.sameSubnetCIDR(rulePrivateIp, privateGateway, privateCidrSize); } else { s_logger.error("Invalid rule match condition."); assert false; } if (addToList) { staticNatRules.add(new String[]{rulePublicIp, rulePrivateIp}); } } } } return staticNatRules; } /* * Destination NAT pools */ private String genDestinationNatPoolName(String privateIp, long destPort) { return genObjectName(genIpIdentifier(privateIp), String.valueOf(destPort)); } private boolean manageDestinationNatPool(SrxCommand command, String privateIp, long destPort) throws ExecutionException { String poolName = genDestinationNatPoolName(privateIp, destPort); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.DEST_NAT_POOL_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "pool-name", poolName); return sendRequestAndCheckResponse(command, xml, "name", poolName); case CHECK_IF_IN_USE: // Check if any destination nat rules refer to this pool xml = SrxXml.DEST_NAT_RULE_GETALL.getXml(); xml = replaceXmlValue(xml, "rule-set", _publicZone); return sendRequestAndCheckResponse(command, xml, "pool-name", poolName); case ADD: if (manageDestinationNatPool(SrxCommand.CHECK_IF_EXISTS, privateIp, destPort)) { return true; } xml = SrxXml.DEST_NAT_POOL_ADD.getXml(); xml = replaceXmlValue(xml, "pool-name", poolName); xml = replaceXmlValue(xml, "private-address", privateIp + "/32"); xml = replaceXmlValue(xml, "dest-port", String.valueOf(destPort)); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add destination NAT pool for private IP " + privateIp + " and private port " + destPort); } else { return true; } case DELETE: if (!manageDestinationNatPool(SrxCommand.CHECK_IF_EXISTS, privateIp, destPort)) { return true; } if (manageDestinationNatPool(SrxCommand.CHECK_IF_IN_USE, privateIp, destPort)) { return true; } xml = SrxXml.DEST_NAT_POOL_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "pool-name", poolName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to delete destination NAT pool for private IP " + privateIp + " and private port " + destPort); } else { return true; } default: throw new ExecutionException("Unrecognized command."); } } /* * Destination NAT rules */ private String genDestinationNatRuleName(String publicIp, String privateIp, long srcPort, long destPort) { return "destnatrule-" + String.valueOf(genObjectName(publicIp, privateIp, String.valueOf(srcPort), String.valueOf(destPort)).hashCode()).replaceAll("[^a-zA-Z0-9]", ""); } private boolean manageDestinationNatRule(SrxCommand command, String publicIp, String privateIp, long srcPort, long destPort) throws ExecutionException { String ruleName = genDestinationNatRuleName(publicIp, privateIp, srcPort, destPort); String poolName = genDestinationNatPoolName(privateIp, destPort); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.DEST_NAT_RULE_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "rule-set", _publicZone); xml = replaceXmlValue(xml, "from-zone", _publicZone); xml = replaceXmlValue(xml, "rule-name", ruleName); return sendRequestAndCheckResponse(command, xml, "name", ruleName); case ADD: if (manageDestinationNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp, srcPort, destPort)) { return true; } if (!manageDestinationNatPool(SrxCommand.CHECK_IF_EXISTS, privateIp, destPort)) { throw new ExecutionException("The destination NAT pool corresponding to private IP: " + privateIp + " and destination port: " + destPort + " does not exist."); } xml = SrxXml.DEST_NAT_RULE_ADD.getXml(); xml = replaceXmlValue(xml, "rule-set", _publicZone); xml = replaceXmlValue(xml, "from-zone", _publicZone); xml = replaceXmlValue(xml, "rule-name", ruleName); xml = replaceXmlValue(xml, "public-address", publicIp); xml = replaceXmlValue(xml, "src-port", String.valueOf(srcPort)); xml = replaceXmlValue(xml, "pool-name", poolName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add destination NAT rule from public IP " + publicIp + ", public port " + srcPort + ", private IP " + privateIp + ", and private port " + destPort); } else { return true; } case DELETE: if (!manageDestinationNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp, srcPort, destPort)) { return true; } xml = SrxXml.DEST_NAT_RULE_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "rule-set", _publicZone); xml = replaceXmlValue(xml, "from-zone", _publicZone); xml = replaceXmlValue(xml, "rule-name", ruleName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to delete destination NAT rule from public IP " + publicIp + ", public port " + srcPort + ", private IP " + privateIp + ", and private port " + destPort); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private List<String[]> getDestNatRules(RuleMatchCondition condition, String publicIp, String privateIp, String privateGateway, Long privateCidrSize) throws ExecutionException { List<String[]> destNatRules = new ArrayList<String[]>(); String xmlRequest = SrxXml.DEST_NAT_RULE_GETALL.getXml(); xmlRequest = replaceXmlValue(xmlRequest, "rule-set", _publicZone); String xmlResponse = sendRequest(xmlRequest); Document doc = getDocument(xmlResponse); NodeList rules = doc.getElementsByTagName("rule"); for (int ruleIndex = 0; ruleIndex < rules.getLength(); ruleIndex++) { String rulePublicIp = null; String rulePrivateIp = null; String ruleSrcPort = null; String ruleDestPort = null; NodeList ruleEntries = rules.item(ruleIndex).getChildNodes(); for (int ruleEntryIndex = 0; ruleEntryIndex < ruleEntries.getLength(); ruleEntryIndex++) { Node ruleEntry = ruleEntries.item(ruleEntryIndex); if (ruleEntry.getNodeName().equals("dest-nat-rule-match")) { NodeList ruleMatchEntries = ruleEntry.getChildNodes(); for (int ruleMatchIndex = 0; ruleMatchIndex < ruleMatchEntries.getLength(); ruleMatchIndex++) { Node ruleMatchEntry = ruleMatchEntries.item(ruleMatchIndex); if (ruleMatchEntry.getNodeName().equals("destination-address")) { NodeList destAddressEntries = ruleMatchEntry.getChildNodes(); for (int destAddressIndex = 0; destAddressIndex < destAddressEntries.getLength(); destAddressIndex++) { Node destAddressEntry = destAddressEntries.item(destAddressIndex); if (destAddressEntry.getNodeName().equals("dst-addr")) { rulePublicIp = destAddressEntry.getFirstChild().getNodeValue().split("/")[0]; } } } else if (ruleMatchEntry.getNodeName().equals("destination-port")) { NodeList destPortEntries = ruleMatchEntry.getChildNodes(); for (int destPortIndex = 0; destPortIndex < destPortEntries.getLength(); destPortIndex++) { Node destPortEntry = destPortEntries.item(destPortIndex); if (destPortEntry.getNodeName().equals("dst-port")) { ruleSrcPort = destPortEntry.getFirstChild().getNodeValue(); } } } } } else if (ruleEntry.getNodeName().equals("then")) { NodeList ruleThenEntries = ruleEntry.getChildNodes(); for (int ruleThenIndex = 0; ruleThenIndex < ruleThenEntries.getLength(); ruleThenIndex++) { Node ruleThenEntry = ruleThenEntries.item(ruleThenIndex); if (ruleThenEntry.getNodeName().equals("destination-nat")) { NodeList destNatEntries = ruleThenEntry.getChildNodes(); for (int destNatIndex = 0; destNatIndex < destNatEntries.getLength(); destNatIndex++) { Node destNatEntry = destNatEntries.item(destNatIndex); if (destNatEntry.getNodeName().equals("pool")) { NodeList poolEntries = destNatEntry.getChildNodes(); for (int poolIndex = 0; poolIndex < poolEntries.getLength(); poolIndex++) { Node poolEntry = poolEntries.item(poolIndex); if (poolEntry.getNodeName().equals("pool-name")) { String[] poolName = poolEntry.getFirstChild().getNodeValue().split("-"); if (poolName.length == 5) { rulePrivateIp = poolName[0] + "." + poolName[1] + "." + poolName[2] + "." + poolName[3]; ruleDestPort = poolName[4]; } } } } } } } } } if (rulePublicIp == null || rulePrivateIp == null || ruleSrcPort == null || ruleDestPort == null) { continue; } boolean addToList = false; if (condition.equals(RuleMatchCondition.ALL)) { addToList = true; } else if (condition.equals(RuleMatchCondition.PUBLIC_PRIVATE_IPS)) { assert (publicIp != null && privateIp != null); addToList = publicIp.equals(rulePublicIp) && privateIp.equals(rulePrivateIp); } else if (condition.equals(RuleMatchCondition.PRIVATE_SUBNET)) { assert (privateGateway != null && privateCidrSize != null); addToList = NetUtils.sameSubnetCIDR(rulePrivateIp, privateGateway, privateCidrSize); } if (addToList) { destNatRules.add(new String[]{rulePublicIp, rulePrivateIp, ruleSrcPort, ruleDestPort}); } } return destNatRules; } /* * Source NAT pools */ private String genSourceNatPoolName(String publicIp) { return genObjectName(genIpIdentifier(publicIp)); } private boolean manageSourceNatPool(SrxCommand command, String publicIp) throws ExecutionException { String poolName = genSourceNatPoolName(publicIp); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.SRC_NAT_POOL_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "pool-name", poolName); return sendRequestAndCheckResponse(command, xml, "name", poolName); case CHECK_IF_IN_USE: // Check if any source nat rules refer to this pool xml = SrxXml.SRC_NAT_RULE_GETALL.getXml(); return sendRequestAndCheckResponse(command, xml, "pool-name", poolName); case ADD: if (manageSourceNatPool(SrxCommand.CHECK_IF_EXISTS, publicIp)) { return true; } xml = SrxXml.SRC_NAT_POOL_ADD.getXml(); xml = replaceXmlValue(xml, "pool-name", poolName); xml = replaceXmlValue(xml, "address", publicIp + "/32"); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add source NAT pool for public IP " + publicIp); } else { return true; } case DELETE: if (!manageSourceNatPool(SrxCommand.CHECK_IF_EXISTS, publicIp)) { return true; } if (manageSourceNatPool(SrxCommand.CHECK_IF_IN_USE, publicIp)) { return true; } xml = SrxXml.SRC_NAT_POOL_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "pool-name", poolName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to delete source NAT pool for public IP " + publicIp); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } /* * Source NAT rules */ private String genSourceNatRuleName(String publicIp, String privateSubnet) { return genObjectName(genIpIdentifier(publicIp), genIpIdentifier(privateSubnet)); } private boolean manageSourceNatRule(SrxCommand command, String publicIp, String privateSubnet) throws ExecutionException { String ruleName = genSourceNatRuleName(publicIp, privateSubnet); String poolName = genSourceNatPoolName(publicIp); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.SRC_NAT_RULE_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "rule-set", _privateZone); xml = replaceXmlValue(xml, "from-zone", _privateZone); xml = replaceXmlValue(xml, "rule-name", ruleName); return sendRequestAndCheckResponse(command, xml, "name", ruleName); case ADD: if (manageSourceNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateSubnet)) { return true; } if (!manageSourceNatPool(SrxCommand.CHECK_IF_EXISTS, publicIp)) { throw new ExecutionException("The source NAT pool corresponding to " + publicIp + " does not exist."); } xml = SrxXml.SRC_NAT_RULE_ADD.getXml(); xml = replaceXmlValue(xml, "rule-set", _privateZone); xml = replaceXmlValue(xml, "from-zone", _privateZone); xml = replaceXmlValue(xml, "to-zone", _publicZone); xml = replaceXmlValue(xml, "rule-name", ruleName); xml = replaceXmlValue(xml, "private-subnet", privateSubnet); xml = replaceXmlValue(xml, "pool-name", poolName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add source NAT rule for public IP " + publicIp + " and private subnet " + privateSubnet); } else { return true; } case DELETE: if (!manageSourceNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateSubnet)) { return true; } xml = SrxXml.SRC_NAT_RULE_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "rule-set", _privateZone); xml = replaceXmlValue(xml, "from-zone", _privateZone); xml = replaceXmlValue(xml, "rule-name", ruleName); if (!sendRequestAndCheckResponse(command, xml, "name", ruleName)) { throw new ExecutionException("Failed to delete source NAT rule for public IP " + publicIp + " and private subnet " + privateSubnet); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } /* * Address book entries */ private String genAddressBookEntryName(String ip) { if (ip == null) { return "any"; } else { return genIpIdentifier(ip); } } private boolean manageAddressBookEntry(SrxCommand command, String zone, String ip, String entryName) throws ExecutionException { if (!zone.equals(_publicZone) && !zone.equals(_privateZone)) { throw new ExecutionException("Invalid zone."); } if (entryName == null) { entryName = genAddressBookEntryName(ip); } String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.ADDRESS_BOOK_ENTRY_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "zone", zone); xml = replaceXmlValue(xml, "entry-name", entryName); return sendRequestAndCheckResponse(command, xml, "name", entryName); case CHECK_IF_IN_USE: // Check if any security policies refer to this address book entry xml = SrxXml.SECURITY_POLICY_GETALL.getXml(); String fromZone = zone.equals(_publicZone) ? _privateZone : _publicZone; xml = replaceXmlValue(xml, "from-zone", fromZone); xml = replaceXmlValue(xml, "to-zone", zone); return sendRequestAndCheckResponse(command, xml, "destination-address", entryName); case ADD: if (manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, zone, ip, entryName)) { return true; } xml = SrxXml.ADDRESS_BOOK_ENTRY_ADD.getXml(); xml = replaceXmlValue(xml, "zone", zone); xml = replaceXmlValue(xml, "entry-name", entryName); xml = replaceXmlValue(xml, "ip", ip); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add address book entry for IP " + ip + " in zone " + zone); } else { return true; } case DELETE: if (!manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, zone, ip, entryName)) { return true; } if (manageAddressBookEntry(SrxCommand.CHECK_IF_IN_USE, zone, ip, entryName)) { return true; } xml = SrxXml.ADDRESS_BOOK_ENTRY_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "zone", zone); xml = replaceXmlValue(xml, "entry-name", entryName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to delete address book entry for IP " + ip + " in zone " + zone); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } /* * Applications */ private String genApplicationName(Protocol protocol, int startPort, int endPort) { if (protocol.equals(Protocol.any)) { return Protocol.any.toString(); } else { return genObjectName(protocol.toString(), String.valueOf(startPort), String.valueOf(endPort)); } } private Object[] parseApplicationName(String applicationName) throws ExecutionException { String errorMsg = "Invalid application: " + applicationName; String[] applicationComponents = applicationName.split("-"); Protocol protocol; Integer startPort; Integer endPort; try { protocol = getProtocol(applicationComponents[0]); startPort = Integer.parseInt(applicationComponents[1]); endPort = Integer.parseInt(applicationComponents[2]); } catch (Exception e) { throw new ExecutionException(errorMsg); } return new Object[]{protocol, startPort, endPort}; } private boolean manageApplication(SrxCommand command, Protocol protocol, int startPort, int endPort) throws ExecutionException { if (protocol.equals(Protocol.any)) { return true; } String applicationName = genApplicationName(protocol, startPort, endPort); String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.APPLICATION_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "name", applicationName); return sendRequestAndCheckResponse(command, xml, "name", applicationName); case ADD: if (manageApplication(SrxCommand.CHECK_IF_EXISTS, protocol, startPort, endPort)) { return true; } xml = SrxXml.APPLICATION_ADD.getXml(); xml = replaceXmlValue(xml, "name", applicationName); xml = replaceXmlValue(xml, "protocol", protocol.toString()); String destPort; if (startPort == endPort) { destPort = String.valueOf(startPort); } else { destPort = startPort + "-" + endPort; } xml = replaceXmlValue(xml, "dest-port", destPort); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add application " + applicationName); } else { return true; } case DELETE: if (!manageApplication(SrxCommand.CHECK_IF_EXISTS, protocol, startPort, endPort)) { return true; } xml = SrxXml.APPLICATION_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "name", applicationName); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to delete application " + applicationName); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } private List<String> getUnusedApplications(List<String> applications) throws ExecutionException { List<String> unusedApplications = new ArrayList<String>(); // Check if any of the applications are unused by existing security policies String xml = SrxXml.SECURITY_POLICY_GETALL.getXml(); xml = replaceXmlValue(xml, "from-zone", _publicZone); xml = replaceXmlValue(xml, "to-zone", _privateZone); String allPolicies = sendRequest(xml); for (String application : applications) { if (!application.equals(Protocol.any.toString()) && !allPolicies.contains(application)) { unusedApplications.add(application); } } return unusedApplications; } private List<String> getApplicationsForSecurityPolicy(SecurityPolicyType type, String privateIp) throws ExecutionException { String fromZone = _publicZone; String toZone = _privateZone; String policyName = genSecurityPolicyName(type, null, null, fromZone, toZone, privateIp); String xml = SrxXml.SECURITY_POLICY_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "from-zone", fromZone); xml = replaceXmlValue(xml, "to-zone", toZone); xml = replaceXmlValue(xml, "policy-name", policyName); String policy = sendRequest(xml); Document doc = getDocument(policy); List<String> policyApplications = new ArrayList<String>(); NodeList applicationNodes = doc.getElementsByTagName("application"); for (int i = 0; i < applicationNodes.getLength(); i++) { Node applicationNode = applicationNodes.item(i); policyApplications.add(applicationNode.getFirstChild().getNodeValue()); } return policyApplications; } private List<Object[]> extractApplications(List<FirewallRuleTO> rules) throws ExecutionException { List<Object[]> applications = new ArrayList<Object[]>(); for (FirewallRuleTO rule : rules) { Object[] application = new Object[3]; application[0] = getProtocol(rule.getProtocol()); application[1] = rule.getSrcPortRange()[0]; application[2] = rule.getSrcPortRange()[1]; applications.add(application); } return applications; } /* * Security policies */ private String genSecurityPolicyName(SecurityPolicyType type, Long accountId, String username, String fromZone, String toZone, String translatedIp) { if (type.equals(SecurityPolicyType.VPN)) { return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); } else { return genObjectName(type.getIdentifier(), fromZone, toZone, genIpIdentifier(translatedIp)); } } private boolean manageSecurityPolicy(SecurityPolicyType type, SrxCommand command, Long accountId, String username, String privateIp, List<String> applicationNames, String ipsecVpnName) throws ExecutionException { String fromZone = _publicZone; String toZone = _privateZone; String securityPolicyName; String addressBookEntryName; if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) { securityPolicyName = ipsecVpnName; addressBookEntryName = ipsecVpnName; } else { securityPolicyName = genSecurityPolicyName(type, accountId, username, fromZone, toZone, privateIp); addressBookEntryName = genAddressBookEntryName(privateIp); } String xml; switch (command) { case CHECK_IF_EXISTS: xml = SrxXml.SECURITY_POLICY_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "from-zone", fromZone); xml = replaceXmlValue(xml, "to-zone", toZone); xml = replaceXmlValue(xml, "policy-name", securityPolicyName); return sendRequestAndCheckResponse(command, xml, "name", securityPolicyName); case CHECK_IF_IN_USE: List<String[]> rulesToCheck = null; if (type.equals(SecurityPolicyType.STATIC_NAT)) { // Check if any static NAT rules rely on this security policy rulesToCheck = getStaticNatRules(RuleMatchCondition.ALL, null, null); } else if (type.equals(SecurityPolicyType.DESTINATION_NAT)) { // Check if any destination NAT rules rely on this security policy rulesToCheck = getDestNatRules(RuleMatchCondition.ALL, null, null, null, null); } else { return false; } for (String[] rule : rulesToCheck) { String rulePrivateIp = rule[1]; if (privateIp.equals(rulePrivateIp)) { return true; } } return false; case ADD: if (!manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, toZone, privateIp, ipsecVpnName)) { throw new ExecutionException("No address book entry for policy: " + securityPolicyName); } xml = SrxXml.SECURITY_POLICY_ADD.getXml(); xml = replaceXmlValue(xml, "from-zone", fromZone); xml = replaceXmlValue(xml, "to-zone", toZone); xml = replaceXmlValue(xml, "policy-name", securityPolicyName); xml = replaceXmlValue(xml, "src-address", "any"); xml = replaceXmlValue(xml, "dest-address", addressBookEntryName); if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) { xml = replaceXmlValue(xml, "tunnel", "<tunnel><ipsec-vpn>" + ipsecVpnName + "</ipsec-vpn></tunnel>"); } else { xml = replaceXmlValue(xml, "tunnel", ""); } String applications; if (applicationNames == null) { applications = "<application>any</application>"; } else { applications = ""; for (String applicationName : applicationNames) { applications += "<application>" + applicationName + "</application>"; } } xml = replaceXmlValue(xml, "applications", applications); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add security policy for privateIp " + privateIp + " and applications " + applicationNames); } else { return true; } case DELETE: if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, applicationNames, ipsecVpnName)) { return true; } if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, applicationNames, ipsecVpnName)) { return true; } xml = SrxXml.SECURITY_POLICY_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "from-zone", fromZone); xml = replaceXmlValue(xml, "to-zone", toZone); xml = replaceXmlValue(xml, "policy-name", securityPolicyName); boolean success = sendRequestAndCheckResponse(command, xml); if (success) { xml = SrxXml.SECURITY_POLICY_GETALL.getXml(); xml = replaceXmlValue(xml, "from-zone", fromZone); xml = replaceXmlValue(xml, "to-zone", toZone); String getAllResponseXml = sendRequest(xml); if (getAllResponseXml == null) { throw new ExecutionException("Deleted security policy, but failed to delete security policy group."); } if (!getAllResponseXml.contains(fromZone) || !getAllResponseXml.contains(toZone)) { return true; } else if (!getAllResponseXml.contains("match") && !getAllResponseXml.contains("then")) { xml = SrxXml.SECURITY_POLICY_GROUP.getXml(); xml = replaceXmlValue(xml, "from-zone", fromZone); xml = replaceXmlValue(xml, "to-zone", toZone); xml = setDelete(xml, true); if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Deleted security policy, but failed to delete security policy group."); } else { return true; } } else { return true; } } else { throw new ExecutionException("Failed to delete security policy for privateIp " + privateIp + " and applications " + applicationNames); } default: s_logger.debug("Unrecognized command."); return false; } } private boolean addSecurityPolicyAndApplications(SecurityPolicyType type, String privateIp, List<Object[]> applications) throws ExecutionException { // Add all necessary applications List<String> applicationNames = new ArrayList<String>(); for (Object[] application : applications) { Protocol protocol = (Protocol) application[0]; int startPort = application[1] != null ? ((Integer) application[1]) : -1; int endPort = application[2] != null ? ((Integer) application[2]) : -1; String applicationName = genApplicationName(protocol, startPort, endPort); if (!applicationNames.contains(applicationName)) { applicationNames.add(applicationName); } manageApplication(SrxCommand.ADD, protocol, startPort, endPort); } // Add a new security policy manageSecurityPolicy(type, SrxCommand.ADD, null, null, privateIp, applicationNames, null); return true; } private boolean removeSecurityPolicyAndApplications(SecurityPolicyType type, String privateIp) throws ExecutionException { if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, null, null)) { return true; } if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, null, null)) { return true; } // Get a list of applications for this security policy List<String> applications = getApplicationsForSecurityPolicy(type, privateIp); // Remove the security policy manageSecurityPolicy(type, SrxCommand.DELETE, null, null, privateIp, null, null); // Remove any applications for the removed security policy that are no longer in use List<String> unusedApplications = getUnusedApplications(applications); for (String application : unusedApplications) { Object[] applicationComponents; try { applicationComponents = parseApplicationName(application); } catch (ExecutionException e) { s_logger.error("Found an invalid application: " + application + ". Not attempting to clean up."); continue; } Protocol protocol = (Protocol) applicationComponents[0]; Integer startPort = (Integer) applicationComponents[1]; Integer endPort = (Integer) applicationComponents[2]; manageApplication(SrxCommand.DELETE, protocol, startPort, endPort); } return true; } /* * Filter terms */ private String genIpFilterTermName(String ipAddress) { return genIpIdentifier(ipAddress); } private boolean manageUsageFilter(SrxCommand command, UsageFilter filter, String ip, Long guestVlanTag, String filterTermName) throws ExecutionException { String filterName; String filterDescription; String xml; if (filter.equals(UsageFilter.IP_INPUT) || filter.equals(UsageFilter.IP_OUTPUT)) { assert (ip != null && guestVlanTag == null); filterName = filter.getName(); filterDescription = filter.toString() + ", public IP = " + ip; xml = SrxXml.PUBLIC_IP_FILTER_TERM_ADD.getXml(); } else if (filter.equals(UsageFilter.VLAN_INPUT) || filter.equals(UsageFilter.VLAN_OUTPUT)) { assert (ip == null && guestVlanTag != null); filterName = filter.getName() + "-" + guestVlanTag; filterDescription = filter.toString() + ", guest VLAN tag = " + guestVlanTag; filterTermName = filterName; xml = SrxXml.GUEST_VLAN_FILTER_TERM_ADD.getXml(); } else { return false; } switch(command) { case CHECK_IF_EXISTS: xml = SrxXml.FILTER_TERM_GETONE.getXml(); xml = setDelete(xml, false); xml = replaceXmlValue(xml, "filter-name", filterName); xml = replaceXmlValue(xml, "term-name", filterTermName); return sendRequestAndCheckResponse(command, xml, "name", filterTermName); case ADD: if (manageUsageFilter(SrxCommand.CHECK_IF_EXISTS, filter, ip, guestVlanTag, filterTermName)) { return true; } xml = replaceXmlValue(xml, "filter-name", filterName); xml = replaceXmlValue(xml, "term-name", filterTermName); if (filter.equals(UsageFilter.IP_INPUT) || filter.equals(UsageFilter.IP_OUTPUT)) { xml = replaceXmlValue(xml, "ip-address", ip); xml = replaceXmlValue(xml, "address-type", filter.getAddressType()); } if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to add usage filter: " + filterDescription); } else { return true; } case DELETE: if (!manageUsageFilter(SrxCommand.CHECK_IF_EXISTS, filter, ip, guestVlanTag, filterTermName)) { return true; } boolean deleteFilter = filter.equals(UsageFilter.VLAN_INPUT) || filter.equals(UsageFilter.VLAN_OUTPUT); xml = deleteFilter ? SrxXml.FILTER_GETONE.getXml() : SrxXml.FILTER_TERM_GETONE.getXml(); xml = setDelete(xml, true); xml = replaceXmlValue(xml, "filter-name", filterName); xml = !deleteFilter ? replaceXmlValue(xml, "term-name", filterTermName) : xml; if (!sendRequestAndCheckResponse(command, xml)) { throw new ExecutionException("Failed to delete usage filter: " + filterDescription); } else { return true; } default: s_logger.debug("Unrecognized command."); return false; } } /* * Usage */ private ExternalNetworkResourceUsageAnswer getUsageAnswer(ExternalNetworkResourceUsageCommand cmd) throws ExecutionException { try { String socOpenException = "Failed to open a connection for Usage data."; String socCloseException = "Unable to close connection for Usage data."; if (!openUsageSocket()) { throw new ExecutionException(socOpenException); } ExternalNetworkResourceUsageAnswer answer = new ExternalNetworkResourceUsageAnswer(cmd); String xml = SrxXml.FIREWALL_FILTER_BYTES_GETALL.getXml(); String rawUsageData = sendUsageRequest(xml); Document doc = getDocument(rawUsageData); NodeList counters = doc.getElementsByTagName("counter"); for (int i = 0; i < counters.getLength(); i++) { Node n = counters.item(i); if (n.getNodeName().equals("counter")) { NodeList counterInfoList = n.getChildNodes(); String counterName = null; long byteCount = 0; for (int j = 0; j < counterInfoList.getLength(); j++) { Node counterInfo = counterInfoList.item(j); if (counterInfo.getNodeName().equals("counter-name")) { counterName = counterInfo.getFirstChild().getNodeValue(); } else if (counterInfo.getNodeName().equals("byte-count")) { try { byteCount = Long.parseLong(counterInfo.getFirstChild().getNodeValue()); } catch (Exception e) { s_logger.debug(e); byteCount = 0; } } } if (byteCount >= 0) { updateUsageAnswer(answer, counterName, byteCount); } } } if (!closeUsageSocket()) { throw new ExecutionException(socCloseException); } return answer; } catch (Exception e) { closeUsageSocket(); throw new ExecutionException(e.getMessage()); } } private void updateBytesMap(Map<String, long[]> bytesMap, UsageFilter filter, String usageAnswerKey, long additionalBytes) { long[] bytesSentAndReceived = bytesMap.get(usageAnswerKey); if (bytesSentAndReceived == null) { bytesSentAndReceived = new long[]{0,0}; } int index = 0; if (filter.equals(UsageFilter.VLAN_OUTPUT) || filter.equals(UsageFilter.IP_INPUT)) { index = 1; } bytesSentAndReceived[index] += additionalBytes; bytesMap.put(usageAnswerKey, bytesSentAndReceived); } private String getIpAddress(String counterName) { String[] counterNameArray = counterName.split("-"); if (counterNameArray.length < 4) { return null; } else { return counterNameArray[0] + "." + counterNameArray[1] + "." + counterNameArray[2] + "." + counterNameArray[3]; } } private String getGuestVlanTag(String counterName) { String[] counterNameArray = counterName.split("-"); if (counterNameArray.length != 3) { return null; } else { return counterNameArray[2]; } } private UsageFilter getUsageFilter(String counterName) { for (UsageFilter filter : UsageFilter.values()) { if (counterName.contains(filter.getCounterIdentifier())) { return filter; } } return null; } private String getUsageAnswerKey(UsageFilter filter, String counterName) { if (filter.equals(UsageFilter.VLAN_INPUT) || filter.equals(UsageFilter.VLAN_OUTPUT)) { return getGuestVlanTag(counterName); } else if (filter.equals(UsageFilter.IP_INPUT) || filter.equals(UsageFilter.IP_OUTPUT)) { return getIpAddress(counterName); } else { return null; } } private Map<String, long[]> getBytesMap(ExternalNetworkResourceUsageAnswer answer, UsageFilter filter, String usageAnswerKey) { if (filter.equals(UsageFilter.VLAN_INPUT) || filter.equals(UsageFilter.VLAN_OUTPUT)) { return answer.guestVlanBytes; } else if (filter.equals(UsageFilter.IP_INPUT) || filter.equals(UsageFilter.IP_OUTPUT)) { return answer.ipBytes; } else { return null; } } private void updateUsageAnswer(ExternalNetworkResourceUsageAnswer answer, String counterName, long byteCount) { if (counterName == null || byteCount <= 0) { return; } UsageFilter filter = getUsageFilter(counterName); String usageAnswerKey = getUsageAnswerKey(filter, counterName); Map<String, long[]> bytesMap = getBytesMap(answer, filter, usageAnswerKey); updateBytesMap(bytesMap, filter, usageAnswerKey, byteCount); } /* * XML API commands */ private String sendRequestPrim(PrintWriter sendStream, BufferedReader recvStream, String xmlRequest) throws ExecutionException { if (!xmlRequest.contains("request-login")) { s_logger.debug("Sending request: " + xmlRequest); } else { s_logger.debug("Sending login request"); } boolean timedOut = false; StringBuffer xmlResponseBuffer = new StringBuffer(""); try { sendStream.write(xmlRequest); sendStream.flush(); String line = ""; while ((line = recvStream.readLine()) != null) { xmlResponseBuffer.append(line); if (line.contains("</rpc-reply>")) { break; } } } catch (SocketTimeoutException e) { s_logger.debug(e); timedOut = true; } catch (IOException e) { s_logger.debug(e); return null; } String xmlResponse = xmlResponseBuffer.toString(); String errorMsg = null; if (timedOut) { errorMsg = "Timed out on XML request: " + xmlRequest; } else if (xmlResponse.isEmpty()) { errorMsg = "Received an empty XML response."; } else if (xmlResponse.contains("Unexpected XML tag type")) { errorMsg = "Sent a command without being logged in."; } else if (!xmlResponse.contains("</rpc-reply>")) { errorMsg = "Didn't find the rpc-reply tag in the XML response."; } if (errorMsg == null) { return xmlResponse; } else { s_logger.error(errorMsg); throw new ExecutionException(errorMsg); } } private String sendRequest(String xmlRequest) throws ExecutionException { return sendRequestPrim(_toSrx, _fromSrx, xmlRequest); } private String sendUsageRequest(String xmlRequest) throws ExecutionException { return sendRequestPrim(_UsagetoSrx, _UsagefromSrx, xmlRequest); } private boolean checkResponse(String xmlResponse, boolean errorKeyAndValue, String key, String value) { if (!xmlResponse.contains("authentication-response")) { s_logger.debug("Checking response: " + xmlResponse); } else { s_logger.debug("Checking login response"); } String textToSearchFor = key; if (value != null) { textToSearchFor = "<" + key + ">" + value + "</" + key + ">"; } if ((errorKeyAndValue && !xmlResponse.contains(textToSearchFor)) || (!errorKeyAndValue && xmlResponse.contains(textToSearchFor))) { return true; } String responseMessage = extractXml(xmlResponse, "message"); if (responseMessage != null) { s_logger.error("Request failed due to: " + responseMessage); } else { if (errorKeyAndValue) { s_logger.error("Found error (" + textToSearchFor + ") in response."); } else { s_logger.debug("Didn't find " + textToSearchFor + " in response."); } } return false; } private boolean sendRequestAndCheckResponse(SrxCommand command, String xmlRequest, String... keyAndValue) throws ExecutionException { boolean errorKeyAndValue = false; String key; String value; switch (command) { case LOGIN: key = "status"; value = "success"; break; case OPEN_CONFIGURATION: case CLOSE_CONFIGURATION: errorKeyAndValue = true; key = "error"; value = null; break; case COMMIT: key = "commit-success"; value = null; break; case CHECK_IF_EXISTS: case CHECK_IF_IN_USE: assert (keyAndValue != null && keyAndValue.length == 2) : "If the SrxCommand is " + command + ", both a key and value must be specified."; key = keyAndValue[0]; value = keyAndValue[1]; break; default: key = "load-success"; value = null; break; } String xmlResponse = sendRequest(xmlRequest); return checkResponse(xmlResponse, errorKeyAndValue, key, value); } private boolean sendUsageRequestAndCheckResponse(SrxCommand command, String xmlRequest, String... keyAndValue) throws ExecutionException { boolean errorKeyAndValue = false; String key; String value; switch (command) { case LOGIN: key = "status"; value = "success"; break; case OPEN_CONFIGURATION: case CLOSE_CONFIGURATION: errorKeyAndValue = true; key = "error"; value = null; break; case COMMIT: key = "commit-success"; value = null; break; case CHECK_IF_EXISTS: case CHECK_IF_IN_USE: assert (keyAndValue != null && keyAndValue.length == 2) : "If the SrxCommand is " + command + ", both a key and value must be specified."; key = keyAndValue[0]; value = keyAndValue[1]; break; default: key = "load-success"; value = null; break; } String xmlResponse = sendUsageRequest(xmlRequest); return checkResponse(xmlResponse, errorKeyAndValue, key, value); } /* * XML utils */ private String replaceXmlTag(String xml, String oldTag, String newTag) { return xml.replaceAll(oldTag, newTag); } private String replaceXmlValue(String xml, String marker, String value) { marker = "\\s*%" + marker + "%\\s*"; if (value == null) { value = ""; } return xml.replaceAll(marker, value); } private String extractXml(String xml, String marker) { String startMarker = "<" + marker + ">"; String endMarker = "</" + marker + ">"; if (xml.contains(startMarker) && xml.contains(endMarker)) { return xml.substring(xml.indexOf(startMarker) + startMarker.length(), xml.indexOf(endMarker)); } else { return null; } } private String setDelete(String xml, boolean delete) { if (delete) { String deleteMarker = " delete=\"delete\""; xml = replaceXmlTag(xml, "get-configuration", "load-configuration"); xml = replaceXmlValue(xml, "delete", deleteMarker); } else { xml = replaceXmlTag(xml, "load-configuration", "get-configuration"); xml = replaceXmlValue(xml, "delete", ""); } return xml; } /* * Misc */ private Long getVlanTag(String vlan) throws ExecutionException { Long publicVlanTag = null; if (!vlan.equals("untagged")) { try { publicVlanTag = Long.parseLong(vlan); } catch (Exception e) { throw new ExecutionException("Unable to parse VLAN tag: " + vlan); } } return publicVlanTag; } private String genObjectName(String... args) { String objectName = ""; for (int i = 0; i < args.length; i++) { objectName += args[i]; if (i != args.length -1) { objectName += _objectNameWordSep; } } return objectName; } private String genIpIdentifier(String ip) { return ip.replace('.', '-').replace('/', '-'); } private Protocol getProtocol(String protocolName) throws ExecutionException { protocolName = protocolName.toLowerCase(); try { return Protocol.valueOf(protocolName); } catch (Exception e) { throw new ExecutionException("Invalid protocol: " + protocolName); } } private Document getDocument(String xml) throws ExecutionException { StringReader srcNatRuleReader = new StringReader(xml); InputSource srcNatRuleSource = new InputSource(srcNatRuleReader); Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(srcNatRuleSource); } catch (Exception e) { s_logger.error(e); throw new ExecutionException(e.getMessage()); } if (doc == null) { throw new ExecutionException("Failed to parse xml " + xml); } else { return doc; } } }
package com.freetymekiyan.algorithms.level.medium; /** * A message containing letters from A-Z is being encoded to numbers using the following mapping: * <p> * 'A' -> 1 * 'B' -> 2 * ... * 'Z' -> 26 * Given an encoded message containing digits, determine the total number of ways to decode it. * <p> * For example, * Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). * <p> * The number of ways decoding "12" is 2. * <p> * Company Tags: Microsoft, Uber, Facebook * Tags: Dynamic Programming, String */ class DecodeWays { public static void main(String[] args) { DecodeWays d = new DecodeWays(); System.out.println(d.numDecodings("1029")); } /** * DP. O(n) Time, O(n) Space. * Suppose the length of the String is n. * Recurrence relation: * number of decode ways at length n related to number of decode ways at previous lengths. * If we can decode the last digit, then ways[n] += ways[n-1]. * If we can decode the last two digits, then ways[n] += ways[n-2]. * Base case: * ways[0] = 1, means only one way when string length is zero. * ways[1] = 0 or 1, depending on the only digit is 0 or non-zero. */ public static int numDecodings(String s) { if (s == null || s.length() == 0) { return 0; } int len = s.length(); int[] ways = new int[len + 1]; // Base cases ways[0] = 1; ways[1] = s.charAt(0) == '0' ? 0 : 1; for (int i = 2; i <= len; i++) { int code1 = Integer.valueOf(s.substring(i - 1, i)); int code2 = Integer.valueOf(s.substring(i - 2, i)); // System.out.println(code2); ways[i] = (code1 != 0 ? ways[i - 1] : 0) + (code2 <= 26 && code2 > 9 ? ways[i - 2] : 0); } return ways[len]; } /** * DP. O(n) Time, O(1) Space. * Don't need an array since we only need previous two results. * Remember to update those results. */ public int numDecodingsB(String s) { if (s == null || s.length() == 0) { return 0; } int len = s.length(); int prev1 = 1; int prev2 = s.charAt(0) == '0' ? 0 : 1; for (int i = 2; i <= len; i++) { int code1 = Integer.valueOf(s.substring(i - 1, i)); // 1 digit int code2 = Integer.valueOf(s.substring(i - 2, i)); // 2 digits int temp = prev2; prev2 = (code1 != 0 ? prev2 : 0) + (code2 <= 26 && code2 > 9 ? prev1 : 0); prev1 = temp; } return prev2; } }
package com.valkryst; import com.valkryst.AsciiPanel.AsciiCharacter; import javafx.scene.paint.Color; import org.junit.Assert; import org.junit.Test; public class AsciiCharacterTest { @Test public void AsciiCharacter() { for (char c = 0 ; c < Character.MAX_VALUE ; c++) { final AsciiCharacter character = new AsciiCharacter(c); boolean passed = character.getCharacter() == c; passed &= character.getBackgroundColor().equals(Color.BLACK); passed &= character.getForegroundColor().equals(Color.WHITE); if (passed == false) { System.out.println("Other Character: '" + c + "'"); System.out.println(character); } Assert.assertTrue(passed); } } @Test public void equals() { final AsciiCharacter characterA = new AsciiCharacter('a'); final AsciiCharacter characterB = new AsciiCharacter('a'); Assert.assertTrue(characterA.equals(characterB)); } @Test public void invertColors() { final AsciiCharacter character = new AsciiCharacter('a'); character.setBackgroundColor(Color.BLACK); character.setForegroundColor(Color.WHITE); character.invertColors(); boolean inversionSuccessful = character.getBackgroundColor().equals(Color.WHITE); inversionSuccessful &= character.getForegroundColor().equals(Color.BLACK); Assert.assertTrue(inversionSuccessful); } @Test public void setBackgroundColorA() { final AsciiCharacter character = new AsciiCharacter('a'); character.setBackgroundColor(Color.RED); Assert.assertTrue(character.getBackgroundColor().equals(Color.RED)); } @Test public void setBackgroundColorB() { final AsciiCharacter character = new AsciiCharacter('a'); character.setBackgroundColor(null); Assert.assertTrue(character.getBackgroundColor().equals(Color.BLACK)); } @Test public void setForegroundColorA() { final AsciiCharacter character = new AsciiCharacter('a'); character.setForegroundColor(Color.RED); Assert.assertTrue(character.getForegroundColor().equals(Color.RED)); } @Test public void setForegroundColorB() { final AsciiCharacter character = new AsciiCharacter('a'); character.setBackgroundColor(null); Assert.assertTrue(character.getForegroundColor().equals(Color.WHITE)); } }
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 lhpn2sbml.parser.LHPNFile; import lhpn2sbml.gui.*; import graph.Graph; 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.FocusEvent; //import java.awt.event.FocusListener; 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.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.SwingUtilities; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JViewport; 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.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; //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 { 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 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, 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 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 Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean lema; private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml, saveAsTemplate, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules, viewTrace, viewLog, saveParam, saveSbml, saveTemp, viewModGraph, viewModBrowser, createAnal, createLearn, createSbml, createSynth, createVer, close, closeAll; 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(); // Sets up the Tool Bar toolbar = new JToolBar(); String imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "save.png"; saveButton = makeToolButton(imgName, "save", "Save", "Save"); // toolButton = new JButton("Save"); toolbar.add(saveButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "saveas.png"; saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As"); toolbar.add(saveasButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "run-icon.jpg"; runButton = makeToolButton(imgName, "run", "Save and Run", "Run"); // toolButton = new JButton("Run"); toolbar.add(runButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "refresh.jpg"; refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh"); toolbar.add(refreshButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "savecheck.png"; checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check"); toolbar.add(checkButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.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"); 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("Histogram"); 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"); 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"); 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"); saveAsLhpn = new JMenuItem("LHPN"); 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("Rules"); viewTrace = new JMenuItem("Trace"); viewLog = new JMenuItem("Log"); viewModGraph = new JMenuItem("Using GraphViz"); viewModBrowser = new JMenuItem("Using Browser"); 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); 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); 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); run.addActionListener(this); check.addActionListener(this); saveSbml.addActionListener(this); saveTemp.addActionListener(this); saveParam.addActionListener(this); export.addActionListener(this); viewCircuit.addActionListener(this); viewRules.addActionListener(this); viewTrace.addActionListener(this); viewLog.addActionListener(this); viewModGraph.addActionListener(this); viewModBrowser.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 (lema) { viewModGraph.setActionCommand("viewModel"); } else { viewModGraph.setActionCommand("graph"); } viewModBrowser.setActionCommand("browse"); createLearn.setActionCommand("createLearn"); createSbml.setActionCommand("createSBML"); createSynth.setActionCommand("openSynth"); createVer.setActionCommand("openVerify"); 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)); viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 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); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_H); if (!lema) { importDot.setMnemonic(KeyEvent.VK_G); } else { importLhpn.setMnemonic(KeyEvent.VK_L); } importSbml.setMnemonic(KeyEvent.VK_S); importVhdl.setMnemonic(KeyEvent.VK_V); 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); importVhdl.setEnabled(false); importLhpn.setEnabled(false); importCsp.setEnabled(false); importHse.setEnabled(false); importUnc.setEnabled(false); importRsg.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); newLhpn.setEnabled(false); newCsp.setEnabled(false); newHse.setEnabled(false); newUnc.setEnabled(false); newRsg.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); save.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.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); viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.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 (!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(close); file.add(closeAll); file.addSeparator(); file.add(save); // file.add(saveAsMenu); if (!lema) { saveAsMenu.add(saveAsGcm); saveAsMenu.add(saveAsGraph); saveAsMenu.add(saveAsSbml); saveAsMenu.add(saveAsTemplate); } else { saveAsMenu.add(saveAsLhpn); saveAsMenu.add(saveAsGraph); } file.add(saveAs); file.add(saveAsSbml); file.add(saveAsTemplate); file.add(saveParam); file.add(run); if (!lema) { file.add(check); } 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.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); } view.add(viewCircuit); view.add(viewLog); if (lema) { view.addSeparator(); view.add(viewRules); view.add(viewTrace); } view.addSeparator(); view.add(viewModel); viewModel.add(viewModGraph); viewModel.add(viewModBrowser); view.addSeparator(); view.add(refresh); tools.add(createAnal); tools.add(createLearn); if (lema) { tools.add(createSynth); 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); 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 (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.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 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; } 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); } } }); JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", "")); JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", "")); 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", "Number Of Steps" }; JComboBox useInterval = new JComboBox(choices); useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", "")); 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(useInterval); 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.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 { JPanel prefPanel = new JPanel(new GridLayout(0,2)); JLabel viewerLabel = new JLabel("External Editor for non-LHPN files:"); viewerField = new JTextField(""); viewerCheck = new JCheckBox("Use External Viewer"); prefPanel.add(viewerLabel); prefPanel.add(viewerField); prefPanel.add(viewerCheck); // 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, prefPanel, "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() == 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 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 (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Verification) { ((Verification) array[0]).viewLog(); } else 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() == 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(2)).save(); } } } 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() == 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 JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewTrace(); } else { ((Verification) array[0]).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 = "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")) { if (lema) { openLearnLHPN(); } else { 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(); 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) != 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.addMouseListener(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, "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[] 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(); SBML_Editor sbml = new SBML_Editor(root + separator + sbmlFile, null, log, this, null, null); // sbml.addMouseListener(this); addTab(sbmlFile, sbml, "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); GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false); // 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); } } // 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, "Print Interval", 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, "Print Interval", 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 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 JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); int index = ((JTabbedPane) comp).getSelectedIndex(); if (component instanceof Graph) { ((Graph) component).save(); } else if (component instanceof Learn) { ((Learn) component).saveGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).saveLhpn(); } 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 Reb2Sac) { ((Reb2Sac) component).save(); } } if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).save(); } else 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); } 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 LHPN name:", "LHPN Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".g")) { newName = newName + ".g"; } ((LHPNEditor) comp).saveAs(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 JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).saveAs(); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).saveAs(); } else 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(".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(); ((Learn) component).run(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); ((LearnLHPN) component).run(); } 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 JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).save(); ((Verification) array[0]).run(); } else if (comp.getName().equals("Synthesis")) { Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).save(); ((Synthesis) array[0]).run(); } } } 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 (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) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } String filename = Buttons.browse(frame, null, null, JFileChooser.DIRECTORIES_ONLY, "New", -1); 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", -1); } 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); } GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f .getName(), this, log, false); // 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(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); 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() > 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 { if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.delete(); f.createNewFile(); new LHPNFile().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), "LHPN Editor"); refreshTree(); } if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.createNewFile(); new LHPNFile().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(); 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", -1); 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", -1); 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", -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("")) { 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", -1); 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", -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("")) { 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", -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("")) { 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", -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("")) { 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", -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("")) { 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(); if (lema) { DataManager data = new DataManager(root + separator + lrnName, this, lema); lrnTab.addTab("Data Manager", data); } else { DataManager data = new DataManager(root + separator + lrnName, this, lema); // data.addMouseListener(this); 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; if (lema) { tsdGraph = new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator + lrnName, "time", this, null, log, null, true, false); } else { tsdGraph = new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator + lrnName, "time", this, null, log, null, true, true); } // 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("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 += ".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( ".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") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { 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 += ".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() >= 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) { // 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 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]); 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); 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); // 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) { 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); } } /** * 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)) { 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 LHPN.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * 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())); } } else { if (e.isPopupTrigger() && tree.getFile() != null) { 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.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) { 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); // 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 (viewerCheck.isSelected()) { String command = viewerField.getText() + " " + 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(".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); } 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) { 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); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (viewerCheck.isSelected()) { String command = viewerField.getText() + " " + 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 (viewerCheck.isSelected()) { String command = viewerField.getText() + " " + 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 (viewerCheck.isSelected()) { String command = viewerField.getText() + " " + 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 (viewerCheck.isSelected()) { String command = viewerField.getText() + " " + 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(".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 { if (lema) { openLearnLHPN(); } else { openLearn(); } } } } } } } 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); if (e != null) { 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()); } } catch (Exception e1) { } } } else { if (tree.getFile() != null) { if (e.isPopupTrigger() && tree.getFile() != null) { 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.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()); } } else if (!popup.isVisible()) { frame.getGlassPane().setVisible(true); } } } } 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())); } } 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())); } } 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); // 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(""); 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 { 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); // 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(""); 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(); // 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("")) { 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, "amount", 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(); // 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("")) { 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, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, false); // 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) != 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("")) { 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(); // 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("")) { Verification ver = new Verification(tree.getFile(), "flag", log, this); // ver.addMouseListener(this); verPanel.add(ver); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], verPanel, "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 = ""; 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); // 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); } } } } } private class NewAction extends AbstractAction { NewAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(newProj); if (!lema) { popup.add(newCircuit); popup.add(newModel); } else { popup.add(newVhdl); popup.add(newLhpn); popup.add(newCsp); popup.add(newHse); popup.add(newUnc); popup.add(newRsg); } 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); } else { popup.add(importVhdl); popup.add(importLhpn); popup.add(importCsp); popup.add(importHse); popup.add(importUnc); popup.add(importRsg); } 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()); } } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } 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 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") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { 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); // 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, "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 { 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 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)); 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("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); } } } } } private void enableTabMenu(int selectedTab) { // 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); 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); } 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.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); 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); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); Boolean learn = false; 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); } else { run.setEnabled(true); } saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.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); 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(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.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); saveParam.setEnabled(true); 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(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.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); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { if (((Learn) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } saveButton.setEnabled(((Learn) component).getSaveGcmEnabled()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((Learn) component).getSaveGcmEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((Learn) component).getViewLogEnabled()); saveParam.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()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.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()); saveParam.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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); 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(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.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); saveParam.setEnabled(true); 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(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.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); saveParam.setEnabled(true); 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewRules.setEnabled(false); // viewTrace.setEnabled(((Verification) // comp).getViewTraceEnabled()); viewTrace.setEnabled(true); viewCircuit.setEnabled(true); // viewLog.setEnabled(((Verification) // comp).getViewLogEnabled()); viewLog.setEnabled(true); saveParam.setEnabled(true); } 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); // viewRules.setEnabled(((Synthesis) // comp).getViewRulesEnabled()); // viewTrace.setEnabled(((Synthesis) // comp).getViewTraceEnabled()); // viewCircuit.setEnabled(((Synthesis) // comp).getViewCircuitEnabled()); // viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewRules.setEnabled(true); viewTrace.setEnabled(true); viewCircuit.setEnabled(true); viewLog.setEnabled(true); saveParam.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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); } private void enableTreeMenu() { // 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); 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); saveParam.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); saveParam.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); saveParam.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); saveParam.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); viewLog.setEnabled(false); saveParam.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); saveParam.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); saveParam.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); saveParam.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); saveParam.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); saveParam.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); saveParam.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()) { 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) { } } } } } 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; } }
package fi.csc.chipster.rest.token; import java.io.IOException; import java.time.LocalDateTime; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javax.annotation.Priority; import javax.ws.rs.ForbiddenException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotFoundException; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.ext.Provider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import fi.csc.chipster.auth.AuthenticationClient; import fi.csc.chipster.auth.model.Role; import fi.csc.chipster.auth.model.Token; import fi.csc.chipster.auth.resource.AuthPrincipal; import fi.csc.chipster.auth.resource.AuthSecurityContext; import fi.csc.chipster.rest.exception.NotAuthorizedException; @Provider @Priority(Priorities.AUTHENTICATION) // execute this filter before others public class TokenRequestFilter implements ContainerRequestFilter { @SuppressWarnings("unused") private static final Logger logger = LogManager.getLogger(); public static final String QUERY_PARAMETER_TOKEN = "token"; public static final String HEADER_AUTHORIZATION = "authorization"; public static final String TOKEN_USER = "token"; private static final int TOKEN_CACHE_LIFETIME = 10000; private Map<String, Token> tokenCache = new HashMap<>(); private boolean authenticationRequired = true; private AuthenticationClient authService; private boolean passwordRequired = true; private Timer tokenCacheTimer = new Timer(); public TokenRequestFilter(AuthenticationClient authService) { this.authService = authService; } @Override public void filter(ContainerRequestContext requestContext) throws IOException { if ("OPTIONS".equals(requestContext.getMethod())) { // CORS preflight checks require unauthenticated OPTIONS return; } String authHeader = requestContext.getHeaderString(HEADER_AUTHORIZATION); // allow token to be sent also as a query parameter, because JS EventSource doesn't allow setting headers String authParameter = requestContext.getUriInfo().getQueryParameters().getFirst(QUERY_PARAMETER_TOKEN); String password = getToken(authHeader, authParameter); if (password == null) { if (passwordRequired) { throw new NotAuthorizedException("password or token required"); } else if (!authenticationRequired) { // this filter is configured to pass non-authenticated users through requestContext.setSecurityContext(new AuthSecurityContext(new AuthPrincipal(null, Role.UNAUTHENTICATED), requestContext.getSecurityContext())); return; } } try { // throws an exception if fails AuthPrincipal principal = tokenAuthentication(password); // login ok requestContext.setSecurityContext( new AuthSecurityContext(principal, requestContext.getSecurityContext())); } catch (ForbiddenException e) { // unable to check the user's token because auth didn't accept our own token throw new InternalServerErrorException("failed to check the token", e); } catch (NotFoundException e) { if (authenticationRequired) { throw new ForbiddenException(e); } else { // DatasetTokens have to be passed through requestContext.setSecurityContext(new AuthSecurityContext( new AuthPrincipal(null, password, new HashSet<String>()), requestContext.getSecurityContext())); return; } } } public static String getToken(String authHeader, String authParameter) { if (authHeader != null) { BasicAuthParser parser = new BasicAuthParser(authHeader); if (!TOKEN_USER.equals(parser.getUsername())) { throw new NotAuthorizedException("only tokens allowed"); } return parser.getPassword(); } else { return authParameter; } } public AuthPrincipal tokenAuthentication(String clientTokenKey) { if (clientTokenKey == null) { throw new NotAuthorizedException("no authorization header"); } Token dbClientToken = null; synchronized (tokenCache) { // optimize reads to non-blocking if (tokenCache.containsKey(clientTokenKey)) { dbClientToken = tokenCache.get(clientTokenKey); } else { dbClientToken = authService.getDbToken(clientTokenKey); if (dbClientToken == null) { // auth responds with NotFoundException throw new NotFoundException("token not found"); } tokenCache.put(clientTokenKey, dbClientToken); tokenCacheTimer.schedule(new TimerTask() { @Override public void run() { synchronized (tokenCache) { tokenCache.remove(clientTokenKey); // clientTokeyKey is effectively final } } }, TOKEN_CACHE_LIFETIME); } } if (dbClientToken.getValid().isBefore(LocalDateTime.now())) { // auth respods with NotFoundException throw new NotFoundException("token expired"); } return new AuthPrincipal(dbClientToken.getUsername(), clientTokenKey, dbClientToken.getRoles()); } public void authenticationRequired(boolean authenticationRequired, boolean passwordRequired) { this.authenticationRequired = authenticationRequired; this.passwordRequired = passwordRequired; } }
package fi.csc.microarray.client; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.swing.Icon; import javax.swing.Timer; import org.apache.log4j.Logger; import org.mortbay.util.IO; import fi.csc.microarray.client.dataimport.ImportItem; import fi.csc.microarray.client.dataimport.ImportSession; import fi.csc.microarray.client.dataimport.ImportUtils; import fi.csc.microarray.client.dialog.ChipsterDialog.DetailsVisibility; import fi.csc.microarray.client.dialog.DialogInfo.Severity; import fi.csc.microarray.client.operation.Operation; import fi.csc.microarray.client.operation.OperationCategory; import fi.csc.microarray.client.operation.OperationDefinition; import fi.csc.microarray.client.operation.Operation.DataBinding; import fi.csc.microarray.client.operation.Operation.ResultListener; import fi.csc.microarray.client.selection.DataSelectionManager; import fi.csc.microarray.client.tasks.Task; import fi.csc.microarray.client.tasks.TaskEventListener; import fi.csc.microarray.client.tasks.TaskException; import fi.csc.microarray.client.tasks.TaskExecutor; import fi.csc.microarray.client.tasks.Task.State; import fi.csc.microarray.client.visualisation.VisualisationFrameManager; import fi.csc.microarray.client.visualisation.VisualisationMethod; import fi.csc.microarray.client.visualisation.VisualisationMethodChangedEvent; import fi.csc.microarray.client.visualisation.Visualisation.Variable; import fi.csc.microarray.client.visualisation.VisualisationFrameManager.FrameType; import fi.csc.microarray.client.visualisation.methods.PhenodataEditor; import fi.csc.microarray.client.workflow.WorkflowManager; import fi.csc.microarray.config.Configuration; import fi.csc.microarray.config.DirectoryLayout; import fi.csc.microarray.databeans.DataBean; import fi.csc.microarray.databeans.DataFolder; import fi.csc.microarray.databeans.DataItem; import fi.csc.microarray.databeans.DataManager; import fi.csc.microarray.databeans.DataBean.Link; import fi.csc.microarray.databeans.features.table.EditableTable; import fi.csc.microarray.databeans.features.table.TableBeanEditor; import fi.csc.microarray.exception.MicroarrayException; import fi.csc.microarray.messaging.SourceMessageListener; import fi.csc.microarray.messaging.auth.AuthenticationRequestListener; import fi.csc.microarray.messaging.auth.ClientLoginListener; import fi.csc.microarray.module.DefaultModules; import fi.csc.microarray.module.Modules; import fi.csc.microarray.util.Files; import fi.csc.microarray.util.Strings; /** * This is the logical essence of Chipster client application. It does * not tell how client should look or react, but what and how it should * do. * * @author Aleksi Kallio * */ public abstract class ClientApplication { private static final int HEARTBEAT_DELAY = 2*1000; // Logger for this class private static Logger logger; public static File SNAPSHOT_DIR = null; public static File OLD_SNAPSHOT_DIR = null; // Module names (see ToolRepository) public static final String MODULE_MICROARRAY = "microarray"; public static final String MODULE_SEQUENCE = "sequence"; // ABSTRACT INTERFACE protected abstract void initialiseGUI() throws MicroarrayException, IOException; protected abstract void taskCountChanged(int newTaskCount, boolean attractAttention); public abstract void reportException(Exception e); public abstract void reportTaskError(Task job) throws MicroarrayException; public abstract void importGroup(Collection<ImportItem> datas, String folderName); public abstract void showSourceFor(String operationName) throws TaskException; public abstract void showHistoryScreenFor(DataBean data); public abstract void showDetailsFor(DataBean data); public abstract void showPopupMenuFor(MouseEvent e, DataItem data); public abstract void showPopupMenuFor(MouseEvent e, List<DataItem> datas); public abstract void showImportToolFor(File file, String destinationFolder, boolean skipActionChooser); public abstract void visualiseWithBestMethod(FrameType target); public abstract void reportInitialisation(String report, boolean newline); public abstract Icon getIconFor(DataItem data); public abstract void viewHelp(String id); public abstract void viewHelpFor(OperationDefinition operationDefinition); public abstract void showDialog(String title, String message, String details, Severity severity, boolean modal); public abstract void showDialog(String title, String message, String details, Severity severity, boolean modal, DetailsVisibility detailsVisibility); public abstract void deleteDatas(DataItem... datas); public abstract void createLink(DataBean source, DataBean target, Link type); public abstract void removeLink(DataBean source, DataBean target, Link type); public abstract File saveWorkflow(); public abstract File openWorkflow(); public abstract void loadSession(); public abstract void loadSessionFrom(URL url); public abstract void saveSession(); public abstract void runWorkflow(URL workflowScript); public abstract void runWorkflow(URL workflowScript, AtEndListener atEndListener); public abstract void flipTaskListVisibility(boolean closeIfVisible); // TODO should not be here (GUI related) public abstract void setMaximisedVisualisationMode(boolean maximisedVisualisationMode); public abstract VisualisationFrameManager getVisualisationFrameManager(); public abstract void runBlockingTask(String taskName, final Runnable runnable); public abstract DataManager getDataManager(); /** * Method is called periodically to maintain state that cannot be maintained * in realtime. */ public abstract void heartBeat(); // CONCRETE IMPLEMENTATIONS (SOME PARTIAL) /** * Listens to jobExecutor's state in general. */ private PropertyChangeListener jobExecutorChangeListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { taskCountChanged((Integer)evt.getNewValue(), true); logger.debug("JobExecutor property changed event: " + evt.getPropertyName() + ": " + (Integer)evt.getNewValue()); } }; protected String metadata; protected CountDownLatch definitionsInitialisedLatch = new CountDownLatch(1); private boolean eventsEnabled = false; private PropertyChangeSupport eventSupport = new PropertyChangeSupport(this); private String requestedModule; // TODO wrap these to some kind of repository protected Collection<OperationCategory> visibleCategories; protected Map<String, OperationDefinition> operationDefinitions; protected Map<String, OperationDefinition> internalOperationDefinitions; protected WorkflowManager workflowManager; protected DataManager manager; protected DataSelectionManager selectionManager; protected ServiceAccessor serviceAccessor; protected TaskExecutor taskExecutor; protected boolean isStandalone; private AuthenticationRequestListener overridingARL; protected ClientConstants clientConstants; protected Configuration configuration; public ClientApplication() { this(false, null); } public ClientApplication(boolean isStandalone, AuthenticationRequestListener overridingARL) { this.configuration = DirectoryLayout.getInstance().getConfiguration(); this.clientConstants = new ClientConstants(); this.serviceAccessor = isStandalone ? new LocalServiceAccessor() : new RemoteServiceAccessor(); this.isStandalone = isStandalone; this.overridingARL = overridingARL; } protected void initialiseApplication() throws MicroarrayException, IOException { // these had to be delayed as they are not available before loading configuration logger = Logger.getLogger(ClientApplication.class); SNAPSHOT_DIR = new File(DirectoryLayout.getInstance().getUserDataDir().getAbsolutePath(), "session-snapshot.zip"); OLD_SNAPSHOT_DIR = new File(DirectoryLayout.getInstance().getUserDataDir().getAbsolutePath(), "workspace-snapshot"); // initialise modules Modules modules = DefaultModules.getDefaultModules(); Session.getSession().setModules(modules); // initialise workflows this.workflowManager = new WorkflowManager(this); // initialise data management this.manager = new DataManager(); Session.getSession().setDataManager(manager); modules.plugFeatures(this.manager); this.selectionManager = new DataSelectionManager(this); Session.getSession().setClientApplication(this); try { // try to initialise JMS connection (or standalone services) logger.debug("Initialise JMS connection."); reportInitialisation("Connecting to broker at " + configuration.getString("messaging", "broker-host") + "...", true); serviceAccessor.initialise(manager, getAuthenticationRequestListener()); this.taskExecutor = serviceAccessor.getTaskExecutor(); Session.getSession().setServiceAccessor(serviceAccessor); reportInitialisation(" connected", false); // check services reportInitialisation("Checking remote services...", true); String status = serviceAccessor.checkRemoveServices(); if (!ServiceAccessor.ALL_SERVICES_OK.equals(status)) { throw new Exception(status); } reportInitialisation(" all are available", false); // Fetch descriptions from compute server reportInitialisation("Fetching analysis descriptions...", true); serviceAccessor.fetchDescriptions(getRequestedModule()); this.visibleCategories = serviceAccessor.getVisibleCategories(); // create GUI elements from descriptions this.operationDefinitions = new HashMap<String, OperationDefinition>(); for (OperationCategory category: visibleCategories) { for (OperationDefinition operationDefinition: category.getOperationList()) { operationDefinitions.put(operationDefinition.getID(), operationDefinition); } } logger.debug("created " + visibleCategories.size() + " operation categories"); reportInitialisation(" received and processed", false); // load internal operation definitions internalOperationDefinitions = new HashMap<String, OperationDefinition>(); internalOperationDefinitions.put(OperationDefinition.IMPORT_DEFINITION.getID(), OperationDefinition.IMPORT_DEFINITION); internalOperationDefinitions.put(OperationDefinition.CREATE_DEFINITION.getID(), OperationDefinition.CREATE_DEFINITION); for (OperationCategory category : serviceAccessor.getHiddenCategories()) { for (OperationDefinition operationDefinition : category.getOperationList()) { internalOperationDefinitions.put(operationDefinition.getID(), operationDefinition); } } // start listening to job events taskExecutor.addChangeListener(jobExecutorChangeListener); // client is now initialised definitionsInitialisedLatch.countDown(); initialiseGUI(); // start heartbeat final Timer timer = new Timer(HEARTBEAT_DELAY, new ActionListener() { public void actionPerformed(ActionEvent e) { ClientApplication.this.heartBeat(); } }); timer.setCoalesce(true); timer.setRepeats(true); timer.setInitialDelay(0); timer.start(); } catch (Exception e) { showDialog("Starting Chipster failed.", "There could be a problem with the network connection, or the remote services could be down. " + "Please see the details below for more information about the problem.\n\n" + "Chipster also fails to start if there has been a version update with a change in configurations. In such case please delete Chipster application settings directory.", e.toString(), Severity.ERROR, false); throw new MicroarrayException(e); } } /** * @return a name of the module that user wants to be loaded. */ public String getRequestedModule() { return requestedModule; } /** * Set module that user wants loaded. * * @param requestedModule */ public void setRequestedModule(String requestedModule) { this.requestedModule = requestedModule; } /** * Add listener for applications state changes. */ public void addPropertyChangeListener(PropertyChangeListener listener) { eventSupport.addPropertyChangeListener(listener); } /** * @see #addPropertyChangeListener(PropertyChangeListener) */ public void removePropertyChangeListener(PropertyChangeListener listener) { eventSupport.removePropertyChangeListener(listener); } public List<DataBean> getAllDataBeans(){ List<DataBean> datas = new ArrayList<DataBean>(); // The depth of the file structure is max 2, so we don't need recursion // Iterate the folders for (DataItem item1 : this.manager.getRootFolder().getChildren()) { if(item1 instanceof DataFolder){ DataFolder folder = (DataFolder)item1; // Iterate the datas for(DataItem item2 : folder.getChildren()){ if(item2 instanceof DataBean){ DataBean bean = (DataBean)item2; datas.add(bean); } } } } return datas; } public DataSelectionManager getSelectionManager() { return selectionManager; } public void selectAllItems(){ List<DataBean> datas = getAllDataBeans(); for (DataBean data : datas) { selectionManager.selectMultiple(data, this); } } public void setVisualisationMethod(VisualisationMethod method, List<Variable> variables, List<DataBean> datas, FrameType target ) { dispatchVisualisationEvent(new VisualisationMethodChangedEvent(this, method, variables, datas, target)); } public void setVisualisationMethod(VisualisationMethodChangedEvent e){ dispatchEvent(e); } public void setEventsEnabled(boolean eventsEnabled) { this.eventsEnabled = eventsEnabled; taskExecutor.setEventsEnabled(eventsEnabled); } /** * Renames the given dataset with the given name and updates the change * on screen. * * @param data Dataset to rename. * @param newName The new name. Must contain at least one character. */ public void renameDataItem(DataItem data, String newName) { data.setName(newName); } public void executeOperation(final OperationDefinition operationDefinition, ResultListener resultListener) { try { Operation operation = new Operation(operationDefinition, getSelectionManager().getSelectedDatasAsArray()); operation.setResultListener(resultListener); executeOperation(operation); } catch (MicroarrayException e) { reportException(e); } } public void executeOperation(final Operation operation) { // check operation (relevant only for workflows) if (operation.getBindings() == null) { throw new RuntimeException("Attempted to run " + operation.getDefinition().getFullName() + " with input datasets that were not compatitible with the operation."); } // check job count if (taskExecutor.getRunningTaskCount() >= clientConstants.MAX_JOBS) { showDialog("Task not started as there are maximum number of tasks already running.", "You can only run " + clientConstants.MAX_JOBS + " tasks at the same time. Please wait for one of the currently running tasks to finish and try again.", null, Severity.INFO, false); return; } // check job size long bytes = 0; for (DataBinding binding : operation.getBindings()) { bytes += binding.getData().getContentLength(); } int megabytes = (int)(bytes/1000000L); if (megabytes > clientConstants.MAX_JOB_SIZE_MB) { showDialog("Task not started since input datasets are too large.", "Maximum size for input datasets is " + clientConstants.MAX_JOB_SIZE_MB + " megabytes.", "Input datasets size: " + megabytes, Severity.INFO, false); return; } // start executing the task Task task = taskExecutor.createTask(operation); task.addTaskEventListener(new TaskEventListener() { public void onStateChange(Task job, State oldState, State newState) { if (newState.isFinished()) { try { // FIXME there should be no need to pass the operation as it goes within the task onFinishedTask(job, operation); } catch (Exception e) { reportException(e); } } } }); try { taskExecutor.startExecuting(task); } catch (TaskException te) { reportException(te); } } /** * When a job finishes, this is called by the JobEventListener that * monitors the execution. This creates a new dataset out of the * results and inserts it to the data set views. * * @param job The finished job. * @param oper The finished operation, which in fact is the GUI's * abstraction of the concrete executed job. Operation * has a decisively longer life span than its * corresponding job entity. * @throws MicroarrayException * @throws IOException */ public void onFinishedTask(Task job, Operation oper) throws MicroarrayException, IOException { LinkedList<DataBean> newBeans = new LinkedList<DataBean>(); try { logger.debug("operation finished, state is " + job.getState()); // for canceled tasks, do nothing if (job.getState() == State.CANCELLED) { } // for unsuccessful tasks, report failing else if (!job.getState().finishedSuccesfully()) { reportTaskError(job); } // for completed tasks, create datasets etc. else { newBeans = new LinkedList<DataBean>(); // read operated datas LinkedList<DataBean> sources = new LinkedList<DataBean>(); for (DataBinding binding : oper.getBindings()) { // remove derivation links that start from phenodata if (!binding.getData().queryFeatures("/phenodata").exists()) { sources.add(binding.getData()); } } // decide output folder DataFolder folder; if (oper.getOutputFolder() != null) { folder = oper.getOutputFolder(); } else if (sources.size() > 0) { folder = sources.get(0).getParent(); } else { folder = manager.getRootFolder(); } DataBean phenodata = null; for (String outputName : job.outputNames()) { DataBean result = job.getOutput(outputName); result.setOperation(oper); // check if this is phenodata if (result.queryFeatures("/phenodata").exists()) { phenodata = job.getOutput(outputName); } // set sources for (DataBean source : sources) { result.addLink(Link.DERIVATION, source); } // initialise cache try { result.initialiseStreamStartCache(); } catch (IOException e) { throw new MicroarrayException(e); } // connect data (events are generated and it becomes visible) folder.addChild(result); newBeans.add(result); } if (phenodata != null) { // link phenodata to other datasets for (DataBean bean : newBeans) { if (bean != phenodata) { phenodata.addLink(Link.ANNOTATION, bean); } } // if original names are not already contained in the phenodata if (!phenodata.queryFeatures("/column/" + PhenodataEditor.PHENODATA_NAME_COLUMN).exists()) { // augment phenodata with original dataset names (using parameter bindings) HashSet<String> insertedNames = new HashSet<String>(); TableBeanEditor tableEditor = new TableBeanEditor(phenodata); EditableTable editableTable = tableEditor.getEditable(); LinkedList<String> newColumn = new LinkedList<String>(); newColumn.addAll(Arrays.asList(Strings.repeatToArray("", editableTable.getRowCount()))); editableTable.addColumn(PhenodataEditor.PHENODATA_NAME_COLUMN, 1, newColumn); // add after sample column for (int ri = 0; ri < editableTable.getRowCount(); ri++) { String sample = editableTable.getValue(PhenodataEditor.PHENODATA_SAMPLE_COLUMN, ri); boolean correctRowFound = false; String originalName = null; for (DataBinding binding : oper.getBindings()) { if (binding.getName().equals(sample)) { System.out.println("binding: " + binding.getName() + "sample: " + sample); originalName = binding.getData().getName(); correctRowFound = true; break; } } if (!correctRowFound) { originalName = sample; // just duplicate the sample name if proper is not found } // check that original names are unique if (insertedNames.contains(originalName)) { final String separator = "/"; int i = 2; while (insertedNames.contains(originalName + separator + i)) { i++; } originalName = originalName + separator + i; } editableTable.setValue(PhenodataEditor.PHENODATA_NAME_COLUMN, ri, originalName); insertedNames.add(originalName); } tableEditor.write(); } // if chip descriptions (visualisation view names) aren't there already if (!phenodata.queryFeatures("/column/" + PhenodataEditor.PHENODATA_DESCRIPTION_COLUMN).exists()) { // copy original dataset names TableBeanEditor tableEditor = new TableBeanEditor(phenodata); EditableTable editableTable = tableEditor.getEditable(); LinkedList<String> newColumn = new LinkedList<String>(); newColumn.addAll(Arrays.asList(Strings.repeatToArray("", editableTable.getRowCount()))); editableTable.addColumn(PhenodataEditor.PHENODATA_DESCRIPTION_COLUMN, newColumn); for (int ri = 0; ri < editableTable.getRowCount(); ri++) { String sample = editableTable.getValue(PhenodataEditor.PHENODATA_NAME_COLUMN, ri); editableTable.setValue(PhenodataEditor.PHENODATA_DESCRIPTION_COLUMN, ri, sample); } tableEditor.write(); } } } } finally { if (oper.getResultListener() != null) { if (job.getState().finishedSuccesfully()) { oper.getResultListener().resultData(newBeans); } else { oper.getResultListener().noResults(); } } } } protected void quit() { logger.debug("quitting client"); try { serviceAccessor.close(); } catch (Exception e) { // do nothing } } public void dispatchVisualisationEvent(VisualisationMethodChangedEvent event) { logger.debug("VisualisationEvent dispatched: " + event.getNewMethod()); this.dispatchEvent(event); } public void dispatchEvent(PropertyChangeEvent event) { logger.debug("dispatching event: " + event); if (eventsEnabled) { eventSupport.firePropertyChange(event); } } public List<File> getWorkflows() { return workflowManager.getWorkflows(); } public interface SourceCodeListener { public void updateSourceCodeAt(int index, String sourceCode); } public void fetchSourceFor(String[] operationIDs, final SourceCodeListener listener) throws MicroarrayException { int i = -1; for (String id : operationIDs) { i++; logger.debug("describe operation " + id); if (id == null) { listener.updateSourceCodeAt(i, null); continue; } SourceMessageListener sourceListener = null; try { sourceListener = serviceAccessor.retrieveSourceCode(id); String source = sourceListener.waitForResponse(60, TimeUnit.SECONDS); listener.updateSourceCodeAt(i, source); // source can be null } catch (Exception e) { throw new MicroarrayException(e); } finally { if (sourceListener != null) { sourceListener.cleanUp(); } } } } public void importWholeDirectory(File root) { List<File> onlyFiles = new LinkedList<File>(); for (File file : root.listFiles()) { if (file.isFile()) { //not a folder onlyFiles.add(file); } } ImportSession importSession = new ImportSession(ImportSession.Source.CLIPBOARD, onlyFiles, root.getName(), true); ImportUtils.executeImport(importSession); } /** * * @param operationDefinitionID * @return null if operation definition is not found */ public OperationDefinition getOperationDefinition(String operationDefinitionID) { OperationDefinition definition = operationDefinitions.get(operationDefinitionID); if (definition == null) { definition = internalOperationDefinitions.get(operationDefinitionID); } return definition; } /** * FIXME Better handling for existing file * * @param data * @param selectedFile */ protected void exportToFile(final DataBean data, final File selectedFile) { runBlockingTask("exporting file", new Runnable() { public void run() { try { File newFile = selectedFile; int i = 1; while (newFile.exists()) { i++; String[] parts = Files.parseFilename(selectedFile); newFile = new File(parts[0] + File.separator + parts[1] + "_" + i + "." + parts[2]); } newFile.createNewFile(); FileOutputStream out = new FileOutputStream(newFile); IO.copy(data.getContentByteStream(), out); out.close(); } catch (Exception e) { throw new RuntimeException(e); } } }); } public TaskExecutor getTaskExecutor() { return this.taskExecutor; } protected AuthenticationRequestListener getAuthenticationRequestListener() { AuthenticationRequestListener authenticator; if (overridingARL != null) { authenticator = overridingARL; } else { authenticator = new Authenticator(); } authenticator.setLoginListener(new ClientLoginListener() { public void firstLogin() { } public void loginCancelled() { System.exit(1); } }); return authenticator; } }
package fr.insalyon.citi.golo.runtime; import java.lang.invoke.*; import static java.lang.invoke.MethodHandles.guardWithTest; import static java.lang.invoke.MethodHandles.insertArguments; import static java.lang.invoke.MethodType.methodType; public class OperatorSupport { static class InlineCache extends MutableCallSite { final MethodHandles.Lookup callerLookup; final String name; InlineCache(MethodHandles.Lookup callerLookup, String name, MethodType type) { super(type); this.callerLookup = callerLookup; this.name = name; } } private static final MethodHandle GUARD_2; private static final MethodHandle FALLBACK_2; static { try { MethodHandles.Lookup lookup = MethodHandles.lookup(); GUARD_2 = lookup.findStatic( OperatorSupport.class, "guard_2", methodType(boolean.class, Class.class, Class.class, Object.class, Object.class)); FALLBACK_2 = lookup.findStatic( OperatorSupport.class, "fallback_2", methodType(Object.class, InlineCache.class, Object[].class)); } catch (NoSuchMethodException | IllegalAccessException e) { throw new Error("Could not bootstrap the required method handles", e); } } public static boolean guard_2(Class<?> expected1, Class<?> expected2, Object receiver1, Object receiver2) { Class<?> t1 = (receiver1 == null) ? Object.class : receiver1.getClass(); Class<?> t2 = (receiver2 == null) ? Object.class : receiver2.getClass(); return (t1 == expected1) && (t2 == expected2); } public static Object fallback_2(InlineCache inlineCache, Object[] args) throws Throwable { Class<?> receiverClass1 = (args[0] == null) ? Object.class : args[0].getClass(); Class<?> receiverClass2 = (args[1] == null) ? Object.class : args[1].getClass(); MethodHandle target; try { target = inlineCache.callerLookup.findStatic( OperatorSupport.class, inlineCache.name, methodType(Object.class, receiverClass1, receiverClass2)); } catch (Throwable t1) { try { target = inlineCache.callerLookup.findStatic( OperatorSupport.class, inlineCache.name + "_fallback", methodType(Object.class, Object.class, Object.class)); } catch (Throwable t2) { return reject(args[0], args[1], inlineCache.name); } } target = target.asType(methodType(Object.class, Object.class, Object.class)); MethodHandle guard = insertArguments(GUARD_2, 0, receiverClass1, receiverClass2); MethodHandle guardedTarget = guardWithTest(guard, target, inlineCache.getTarget()); inlineCache.setTarget(guardedTarget); return target.invokeWithArguments(args); } public static CallSite bootstrap(MethodHandles.Lookup caller, String name, MethodType type, int arity) throws NoSuchMethodException, IllegalAccessException { InlineCache callSite = new InlineCache(caller, name, type); MethodHandle fallbackHandle; if (arity == 2) { fallbackHandle = FALLBACK_2 .bindTo(callSite) .asCollector(Object[].class, type.parameterCount()) .asType(type); } else { throw new UnsupportedOperationException("no fallback for unary operators yet"); } callSite.setTarget(fallbackHandle); return callSite; } // plus ............................................................................................................. public static Object plus(Integer a, Integer b) { return a + b; } public static Object plus(Long a, Long b) { return a + b; } public static Object plus(Integer a, Long b) { return ((long) a) + b; } public static Object plus(Long a, Integer b) { return a + ((long) b); } public static Object plus(String a, String b) { return a + b; } public static Object plus_fallback(Object a, Object b) { if (isNotNullAndString(a) || isNotNullAndString(b)) { return new StringBuilder().append(a).append(b).toString(); } return reject(a, b, "plus"); } // divide ........................................................................................................... public static Object divide(Integer a, Integer b) { return a / b; } public static Object divide(Long a, Long b) { return a / b; } public static Object divide(Long a, Integer b) { return ((long) a) / b; } public static Object divide(Integer a, Long b) { return a / ((long) b); } // comparisons ...................................................................................................... public static Object equals_fallback(Object a, Object b) { return (a == b) || ((a != null) && a.equals(b)); } public static Object notequals_fallback(Object a, Object b) { return (a != b) && (((a != null) && !a.equals(b)) || ((b != null) && !b.equals(a))); } @SuppressWarnings("unchecked") public static Object less_fallback(Object a, Object b) { if (bothNotNull(a, b) && isComparable(a) && isComparable(b)) { return ((Comparable) a).compareTo(b) < 0; } return reject(a, b, "less"); } @SuppressWarnings("unchecked") public static Object lessorequals_fallback(Object a, Object b) { if (bothNotNull(a, b) && isComparable(a) && isComparable(b)) { return ((Comparable) a).compareTo(b) <= 0; } return reject(a, b, "lessorequals"); } @SuppressWarnings("unchecked") public static Object more_fallback(Object a, Object b) { if (bothNotNull(a, b) && isComparable(a) && isComparable(b)) { return ((Comparable) a).compareTo(b) > 0; } return reject(a, b, "more"); } @SuppressWarnings("unchecked") public static Object moreorequals_fallback(Object a, Object b) { if (bothNotNull(a, b) && isComparable(a) && isComparable(b)) { return ((Comparable) a).compareTo(b) >= 0; } return reject(a, b, "moreorequals"); } // minus ............................................................................................................ public static Object minus(Integer a, Integer b) { return a - b; } public static Object minus(Long a, Long b) { return a - b; } public static Object minus(Integer a, Long b) { return ((long) a) - b; } public static Object minus(Long a, Integer b) { return a - ((long) b); } // times ............................................................................................................ public static Object times (Integer a, Integer b) { return a * b; } public static Object times (Long a, Long b) { return a * b; } public static Object times (Long a, Integer b) { return a * ((long) b); } public static Object times (Integer a, Long b) { return ((long) a) * b; } public static Object times_fallback(Object a, Object b) { if (isInteger(a) && isString(b)) { return repeat((String) b, (Integer) a); } if (isString(a) && isInteger(b)) { return repeat((String) a, (Integer) b); } return reject(a, b, "times"); } private static String repeat(String string, int n) { StringBuilder builder = new StringBuilder(string); for (int i = 1; i < n; i++) { builder.append(string); } return builder.toString(); } // logic ............................................................................................................ public static Object and(Boolean a, Boolean b) { return a && b; } public static Object or(Boolean a, Boolean b) { return a || b; } private static boolean bothNotNull(Object a, Object b) { return (a != null) && (b != null); } private static boolean isNotNullAndString(Object obj) { return (obj != null) && (obj.getClass() == String.class); } private static boolean isString(Object obj) { return obj.getClass() == String.class; } private static boolean isInteger(Object obj) { return obj.getClass() == Integer.class; } private static boolean isLong(Object obj) { return obj.getClass() == Long.class; } private static boolean isComparable(Object obj) { return obj instanceof Comparable<?>; } private static boolean isBoolean(Object obj) { return obj.getClass() == Boolean.class; } private static boolean isClass(Object obj) { return (obj != null) && (obj.getClass() == Class.class); } public static Object not(Object a) { if (a != null && isBoolean(a)) { return !((Boolean) a); } return reject(a, "not"); } public static Object oftype(Object a, Object b) { if (isClass(b)) { return ((Class<?>) b).isInstance(a); } return reject(a, b, "oftype"); } private static Object reject(Object a, String symbol) throws IllegalArgumentException { throw new IllegalArgumentException(String.format("Operator %s is not supported for type %s", symbol, a.getClass())); } private static Object reject(Object a, Object b, String symbol) throws IllegalArgumentException { throw new IllegalArgumentException(String.format("Operator %s is not supported for types %s and %s", symbol, a.getClass(), b.getClass())); } public static Object is(Object a, Object b) { return a == b; } public static Object isnt(Object a, Object b) { return a != b; } }
package com.jwetherell.algorithms.mathematics; import com.jwetherell.algorithms.numbers.Complex; import java.util.ArrayList; import java.util.Collections; public class Multiplication { public static final long multiplication(int a, int b) { long result = ((long) a) * ((long) b); return result; } public static final long multiplyUsingLoop(int a, int b) { int absB = Math.abs(b); long result = a; for (int i = 1; i < absB; i++) { result += a; } return (b < 0) ? -result : result; } public static final long multiplyUsingRecursion(int a, int b) { int absB = Math.abs(b); long result = a; if (absB == 1) return result; result += multiplyUsingRecursion(a, absB - 1); return (b < 0) ? -result : result; } public static final long multiplyUsingShift(int a, int b) { int absA = Math.abs(a); int absB = Math.abs(b); long result = 0L; while (absA > 0) { if ((absA & 1) > 0) result += absB; // Is odd absA >>= 1; absB <<= 1; } return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result; } public static final long multiplyUsingLogs(int a, int b) { long absA = Math.abs(a); long absB = Math.abs(b); long result = Math.round(Math.pow(10, (Math.log10(absA) + Math.log10(absB)))); return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result; } public static String multiplyUsingFFT(String a, String b) { if(a.equals("0") || b.equals("0")){ return "0"; } boolean negative = false; if( (a.charAt(0) == '-' && b.charAt(0) != '-') || (a.charAt(0) != '-' && b.charAt(0) == '-')){ negative = true; } if(a.charAt(0) == '-'){ a = a.substring(1); } if(b.charAt(0) == '-'){ b = b.substring(1); } int size = 1; while (size < (a.length()+b.length())){ size *= 2; } Complex[] aCoefficients = new Complex[size]; Complex[] bCoefficients = new Complex[size]; for(int i = 0; i<size; i++){ aCoefficients[i] = new Complex(); bCoefficients[i] = new Complex(); } for(int i = 0; i<a.length(); i++){ aCoefficients[i] = new Complex((double)(Character.getNumericValue(a.charAt(a.length()-i-1))), 0.0); } for(int i = 0; i<b.length(); i++){ bCoefficients[i] = new Complex((double)(Character.getNumericValue(b.charAt(b.length()-i-1))), 0.0); } FFT.FFT(aCoefficients); FFT.FFT(bCoefficients); for(int i = 0; i< size; i++){ aCoefficients[i] = aCoefficients[i].multiply(bCoefficients[i]); } for(int i = 0; i<size/2; i++){ Complex temp = aCoefficients[i]; aCoefficients[i] = aCoefficients[size-i-1]; aCoefficients[size-i-1] = temp; } FFT.FFT(aCoefficients); ArrayList<Integer> res = new ArrayList<Integer>(); int pass = 0; for(int i = 0; i<size; i++){ res.add((int) (pass + Math.floor( (aCoefficients[i].abs() + 1) / size) ) ); if(res.get(i) >= 10){ pass = res.get(i)/10; res.set(i, res.get(i) % 10); } else { pass = 0; } } Collections.reverse(res); StringBuilder result = new StringBuilder(); if(negative){ result.append('-'); } boolean startPrinting = false; for(Integer x : res){ if(x != 0) { startPrinting = true; } if(startPrinting) { result.append(x); } } return result.toString(); } }
package co.epitre.aelf_lectures.data; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public final class AelfRssParser { // Entry-Point public static List<LectureItem> parse(InputStream in) throws IOException, XmlPullParserException { return readFeed(in); } // Low level RSS Parser private static List<LectureItem> readFeed(InputStream in) throws XmlPullParserException, IOException { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(in, null); parser.nextTag(); List<LectureItem> lectures = new ArrayList<>(); parser.require(XmlPullParser.START_TAG, null, "rss"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); // Starts by looking for the entry tag if (name.equals("channel")) { readChannel(parser, lectures); } else { skip(parser); } } return lectures; } private static void readChannel (XmlPullParser parser, List<LectureItem> lectures) throws XmlPullParserException, IOException { parser.require(XmlPullParser.START_TAG, null, "channel"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); // Starts by looking for the entry tag if (name.equals("item")) { lectures.add(readEntry(parser)); } else { skip(parser); } } } // item parser private static LectureItem readEntry(XmlPullParser parser) throws XmlPullParserException, IOException { parser.require(XmlPullParser.START_TAG, null, "item"); String key = null; String title = null; String description = null; String reference = null; while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); switch (name) { case "title": parser.require(XmlPullParser.START_TAG, null, name); title = readText(parser); parser.require(XmlPullParser.END_TAG, null, name); break; case "description": parser.require(XmlPullParser.START_TAG, null, name); description = readText(parser); parser.require(XmlPullParser.END_TAG, null, name); break; case "key": parser.require(XmlPullParser.START_TAG, null, name); key = readText(parser).replace("\n", "").trim(); parser.require(XmlPullParser.END_TAG, null, name); break; case "reference": parser.require(XmlPullParser.START_TAG, null, name); reference = readText(parser); parser.require(XmlPullParser.END_TAG, null, name); break; default: skip(parser); break; } } return new LectureItem(key, title, description, reference); } // Extract text from the feed private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException { String result = ""; if (parser.next() == XmlPullParser.TEXT) { result = parser.getText(); result = result.replace("\n", "").trim(); parser.nextTag(); } return result; } // skip tags I do not need private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException { if (parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while (depth != 0) { switch (parser.next()) { case XmlPullParser.END_TAG: depth break; case XmlPullParser.START_TAG: depth++; break; } } } }
package com.ning.phatamorgana.models; import java.io.File; import java.util.Map; import org.jruby.embed.LocalVariableBehavior; import org.jruby.embed.PathType; import org.jruby.embed.ScriptingContainer; public class JRubyScriptLoader { /** Hooks into the application. */ private Map<String, Object> context; /** * Creates the JRuby loader. * @param context hooks into the application */ public JRubyScriptLoader(Map<String, Object> context) { this.context = context; } /** * Loads the JRuby scripts in the given path and its subdirectories. * @param directory the path to the scripts */ public void loadScripts(File directory) { try { ScriptingContainer container = new ScriptingContainer(LocalVariableBehavior.PERSISTENT); container.put("$context", context); container.runScriptlet("require 'java'"); container.runScriptlet("java_import 'com.ning.phatamorgana.models.UnitTest'"); container.runScriptlet("java_import 'com.ning.phatamorgana.models.Documentation'"); container.runScriptlet("java_import 'com.ning.phatamorgana.models.ChangeSet'"); for (File f : directory.listFiles()) { if (f.isDirectory()) { loadScripts(f); } else if (f.isFile() && f.getName().endsWith(".rb")) { container.runScriptlet(PathType.ABSOLUTE, f.getAbsolutePath()); } } } catch (Exception e) { throw new RuntimeException(e); } } }
package harmony.mastermind.logic.commands; import java.util.ArrayList; import harmony.mastermind.commons.core.EventsCenter; import harmony.mastermind.commons.events.ui.ShowHelpRequestEvent; import harmony.mastermind.logic.HelpPopupEntry; /**@@author A0139194X * Format full help instructions for every command for display. */ public class HelpCommand extends Command { public static final String COMMAND_WORD = "help"; public static final String COMMAND_DESCRIPTION = "Shows program usage instructions"; public static final String COMMAND_SUMMARY = "Getting help:" + "\n" + COMMAND_WORD; private ArrayList<String> commandList; private ArrayList<String> formatList; private ArrayList<String> descriptionList; private ArrayList<HelpPopupEntry> helpEntries; public static final String SUCCESSFULLY_SHOWN = "Command summary displayed."; public HelpCommand() { initInfo(); } private void initInfo() { if (helpEntries == null) { initCommandWords(); initFormat(); initDescription(); initEntries(); } } private void initEntries() { helpEntries = new ArrayList<HelpPopupEntry>(); for (int i = 0; i < commandList.size(); i++) { helpEntries.add(new HelpPopupEntry(commandList.get(i), formatList.get(i), descriptionList.get(i))); } } private void initCommandWords() { commandList = new ArrayList<String>(); commandList.add(HelpCommand.COMMAND_WORD); commandList.add(AddCommand.COMMAND_KEYWORD_ADD + ", " + AddCommand.COMMAND_KEYWORD_DO); commandList.add(EditCommand.COMMAND_KEYWORD_EDIT + ", " + EditCommand.COMMAND_KEYWORD_UPDATE + ", " + EditCommand.COMMAND_KEYWORD_CHANGE); commandList.add(MarkCommand.COMMAND_WORD); commandList.add(UnmarkCommand.COMMAND_WORD); commandList.add(DeleteCommand.COMMAND_WORD); commandList.add(UndoCommand.COMMAND_WORD); commandList.add(RedoCommand.COMMAND_WORD); commandList.add(ListCommand.COMMAND_WORD); commandList.add(FindCommand.COMMAND_WORD); commandList.add(UpcomingCommand.COMMAND_WORD); commandList.add(RelocateCommand.COMMAND_WORD); commandList.add(ImportCommand.COMMAND_WORD); commandList.add(ExportCommand.COMMAND_KEYWORD_EXPORT); commandList.add(HistoryCommand.COMMAND_KEYWORD_ACTIONHISTORY); commandList.add(ClearCommand.COMMAND_WORD); commandList.add(ExitCommand.COMMAND_WORD); } private void initFormat() { formatList = new ArrayList<String>(); formatList.add(HelpCommand.COMMAND_WORD); formatList.add(AddCommand.COMMAND_FORMAT); formatList.add(EditCommand.COMMAND_FORMAT); formatList.add(MarkCommand.COMMAND_FORMAT); formatList.add(UnmarkCommand.COMMAND_FORMAT); formatList.add(DeleteCommand.COMMAND_FORMAT); formatList.add(UndoCommand.COMMAND_WORD); formatList.add(RedoCommand.COMMAND_WORD); formatList.add(ListCommand.COMMAND_FORMAT); formatList.add(FindCommand.COMMAND_FORMAT); formatList.add(UpcomingCommand.COMMAND_FORMAT); formatList.add(RelocateCommand.COMMAND_FORMAT); formatList.add(ImportCommand.COMMAND_FORMAT); formatList.add(ExportCommand.COMMAND_FORMAT); formatList.add(HistoryCommand.COMMAND_KEYWORD_ACTIONHISTORY); formatList.add(ClearCommand.COMMAND_WORD); formatList.add(ExitCommand.COMMAND_WORD); } private void initDescription() { descriptionList = new ArrayList<String>(); descriptionList.add(HelpCommand.COMMAND_DESCRIPTION); descriptionList.add(AddCommand.COMMAND_DESCRIPTION); descriptionList.add(EditCommand.COMMAND_DESCRIPTION); descriptionList.add(MarkCommand.COMMAND_DESCRIPTION); descriptionList.add(UnmarkCommand.COMMAND_DESCRIPTION); descriptionList.add(DeleteCommand.COMMAND_DESCRIPTION); descriptionList.add(UndoCommand.COMMAND_DESCRIPTION); descriptionList.add(RedoCommand.COMMAND_DESCRIPTION); descriptionList.add(ListCommand.COMMAND_DESCRIPTION); descriptionList.add(FindCommand.COMMAND_DESCRIPTION); descriptionList.add(UpcomingCommand.COMMAND_DESCRIPTION); descriptionList.add(RelocateCommand.COMMAND_DESCRIPTION); descriptionList.add(ImportCommand.COMMAND_DESCRIPTION); descriptionList.add(ExportCommand.COMMAND_DESCRIPTION); descriptionList.add(HistoryCommand.COMMAND_DESCRIPTION); descriptionList.add(ClearCommand.COMMAND_DESCRIPTION); descriptionList.add(ExitCommand.COMMAND_DESCRIPTION); } //@@author A0139194X @Override public CommandResult execute() { EventsCenter.getInstance().post(new ShowHelpRequestEvent(helpEntries)); return new CommandResult(COMMAND_WORD, SUCCESSFULLY_SHOWN); } }
package com.twitter.intellij.pants.index; import com.intellij.openapi.fileTypes.UnknownFileType; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.util.indexing.DataIndexer; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.FileContent; import com.intellij.util.indexing.ID; import com.intellij.util.indexing.ScalarIndexExtension; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import com.twitter.intellij.pants.model.PantsTargetAddress; import com.twitter.intellij.pants.util.PantsPsiUtil; import com.twitter.intellij.pants.util.PantsUtil; import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class PantsAddressesIndex extends ScalarIndexExtension<String> { public static final ID<String, Void> NAME = ID.create("PantsAddressesIndex"); public static Collection<String> getAddresses(@NotNull PsiFile file) { // We need to make sure that the files really belong to the project. // As stated in http://www.jetbrains.org/intellij/sdk/docs/basics/indexing_and_psi_stubs/file_based_indexes.html#accessing-a-file-based-index // it "may also contain additional keys not currently found in the project." return PantsUtil.findBuildRoot(file) .map(root -> FileBasedIndex.getInstance().getAllKeys(NAME, file.getProject()).stream() .filter(key -> { Optional<String> relativePath = PantsTargetAddress.extractPath(key); if (!relativePath.isPresent()) return false; String absolutePath = root.getPath() + File.separatorChar + relativePath.get() + File.separatorChar + "BUILD"; return root.getFileSystem().findFileByPath(absolutePath) != null; })) .orElse(Stream.empty()) .collect(Collectors.toList()); } @NotNull @Override public ID<String, Void> getName() { return NAME; } @NotNull @Override public DataIndexer<String, Void, FileContent> getIndexer() { return indexer; } @NotNull @Override public KeyDescriptor<String> getKeyDescriptor() { return new EnumeratorStringDescriptor(); } @NotNull @Override public FileBasedIndex.InputFilter getInputFilter() { return file -> PantsUtil.isBUILDFileName(file.getName()); } @Override public boolean dependsOnFileContent() { return true; } @Override public int getVersion() { return 0; } private static DataIndexer<String, Void, FileContent> indexer = inputData -> { if (!PantsUtil.isPantsProject(inputData.getProject())) { return Collections.emptyMap(); } final VirtualFile file = inputData.getFile(); Optional<VirtualFile> buildRoot = PantsUtil.findBuildRoot(file); if (!buildRoot.isPresent()) { return Collections.emptyMap(); } String relative = FileUtil.getRelativePath(buildRoot.get().getPath(), file.getParent().getPath(), File.separatorChar); FileType fileType = inputData.getFileType(); if (relative == null || relative.isEmpty() || fileType == UnknownFileType.INSTANCE || !(fileType instanceof LanguageFileType)) { return Collections.emptyMap(); } else { PsiFile psiFile = inputData.getPsiFile(); Set<String> targetNames = PantsPsiUtil.findTargets(psiFile).keySet(); Map<String, Void> result = new HashMap<>(); targetNames.forEach(name -> result.put(toAddress(relative, name), null)); result.put(toAddress(relative, new File(relative).getName()), null); return result; } }; private static String toAddress(String relative, String name) { return new PantsTargetAddress(relative, name).toString(); } }
package cis234a.nsort.model; import java.util.ArrayList; import java.util.HashMap; /** * This a ItemList class represents a list of items. * * @author (Chris.Stultz, John.Loranger, Ryan.Reams, Josh.Eads) * @version (4/11/2015) */ public class ItemList { private ArrayList<Item> items; /** * Constructor for the class. */ public ItemList() { items = new ArrayList<Item>(); //initialize empty } /** * Add a new item to the nsort.test. * * @param item to be added to the nsort.test. */ public void addItem(Item item) { items.add(item); } /** * Remove an item from the nsort.test based on its value. * * @return if the item was removed from the nsort.test. * @param value of the item to be removed from the nsort.test. */ public boolean removeItem(String value) { for (int i = 0; i < items.size(); i++) { if (items.get(i).getValue().equalsIgnoreCase(value)) { items.remove(i); return true; } } return false; } /** * Get an item in the nsort.test based on its index. * * @param index of the item in the nsort.test * @return the item in the nsort.test at the index position provided. */ public Item getItem(int index) { if (index >= 0 && index <= items.size()) { return items.get(index); } else return null; } /** * Get an item in the nsort.test based on its value. * If it can't find the item with the value it returns null. * * @param value of the item in the nsort.test * @return the item in the nsort.test with the value provided. * @override */ public Item getItem(String value) { for (Item item : items) { if (item.getValue().equalsIgnoreCase(value)) { return item; } } return null; } /** * Get the size of the nsort.test * * @return the size of the nsort.test */ public int getSize() { return items.size(); } }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.miso.client; import java.util.HashMap; import java.awt.event.ActionEvent; import javax.swing.Icon; import com.google.common.collect.Maps; import com.samskivert.util.StringUtil; import com.samskivert.swing.RadialMenu; import static com.threerings.miso.Log.log; /** * Objects in scenes can be configured to generate action events. Those events are grouped into * types and an object action handler can be registered to handle all actions of a particular * type. */ public class ObjectActionHandler { /** * Returns true if we should allow this object action, false if we should not. */ public boolean actionAllowed (String action) { return true; } /** * Returns true if we should display the text for the action. By default this returns whether * the action is allowed or not, but can be overridden by subclasses. This is used to * completely hide actions that should not be visible without the proper privileges. */ public boolean isVisible (String action) { return actionAllowed(action); } /** * Get the human readable object tip for the specified action. */ public String getTipText (String action) { return action; } /** * Returns the tooltip icon for the specified action or null if the action has no tooltip * icon. */ public Icon getTipIcon (String action) { return null; } /** * Return a {@link RadialMenu} or null if no menu needed. */ public RadialMenu handlePressed (SceneObject sourceObject) { return null; } /** * Called when an action is generated for an object. */ public void handleAction (SceneObject scobj, ActionEvent event) { log.warning("Unknown object action", "scobj", scobj, "action", event); } /** * Returns the type associated with this action command (which is mapped to a registered * object action handler) or the empty string if it has no type. */ public static String getType (String command) { int cidx = StringUtil.isBlank(command) ? -1 : command.indexOf(':'); return (cidx == -1) ? "" : command.substring(0, cidx); } /** * Returns the unqualified object action (minus the type, see {@link #getType}). */ public static String getAction (String command) { int cidx = StringUtil.isBlank(command) ? -1 : command.indexOf(':'); return (cidx == -1) ? command : command.substring(cidx+1); } /** * Creates an indicator for this type of object action. */ public SceneObjectIndicator createIndicator (MisoScenePanel panel, String text, Icon icon) { return new SceneObjectTip(text, icon); } /** * Looks up the object action handler associated with the specified command. */ public static ObjectActionHandler lookup (String command) { return _oahandlers.get(getType(command)); } /** * Registers an object action handler which will be called when a user clicks on an object in * a scene that has an associated action. */ public static void register (String prefix, ObjectActionHandler handler) { // make sure we know about potential funny business if (_oahandlers.containsKey(prefix)) { log.warning("Warning! Overwriting previous object action handler registration, all " + "hell could shortly break loose", "prefix", prefix, "handler", handler); } _oahandlers.put(prefix, handler); } /** * Removes an object action handler registration. */ public static void unregister (String prefix) { _oahandlers.remove(prefix); } /** Our registered object action handlers. */ protected static HashMap<String, ObjectActionHandler> _oahandlers = Maps.newHashMap(); }
package goldenapple.rfdrills.config; public enum EnumEnergyUnit { //i don't want energy conversion so this is pretty much useless RF(1.0F), EU(0.25F), //4 RF = 1 EU J(2.5F), //1 RF = 2.5 J gJ(1.6F); //1 RF = 1.6 GalactiCraft J private float conversionRateFromRF; private EnumEnergyUnit(float concersionRateFromRF){ this.conversionRateFromRF = concersionRateFromRF; } public static float convert(float energy, EnumEnergyUnit energyUnitFrom, EnumEnergyUnit energyUnitTo){ float energyRF = energy * 1 / energyUnitFrom.conversionRateFromRF; return energyRF * energyUnitTo.conversionRateFromRF; } }
package hudson.plugins.warnings; import hudson.FilePath.FileCallable; import hudson.plugins.warnings.util.ContextHashCode; import hudson.plugins.warnings.util.ModuleDetector; import hudson.plugins.warnings.util.ParserResult; import hudson.plugins.warnings.util.model.FileAnnotation; import hudson.remoting.VirtualChannel; import java.io.File; import java.io.IOException; /** * Scans the workspace for maven pom.xml files and ant build.xml files and maps * all annotations to corresponding modules. Additionally, the content of each * file with warnings is read and a hash code of the warning is created to * enable a more flexible new and fixed warnings detection. * * @author Ulli Hafner */ public class AnnotationsClassifier implements FileCallable<ParserResult> { /** Generated ID. */ private static final long serialVersionUID = 5152042155205600031L; /** All annotations. */ private final ParserResult result; /** The default encoding to be used when reading and parsing files. */ private final String defaultEncoding; /** * Creates a new instance of {@link AnnotationsClassifier}. * * @param result * the annotations to assign a module for * @param defaultEncoding * the default encoding to be used when reading and parsing files */ public AnnotationsClassifier(final ParserResult result, final String defaultEncoding) { this.result = result; this.defaultEncoding = defaultEncoding; } /** {@inheritDoc} */ public ParserResult invoke(final File workspace, final VirtualChannel channel) throws IOException { ModuleDetector detector = new ModuleDetector(workspace); ContextHashCode contextHashCode = new ContextHashCode(); for (FileAnnotation annotation : result.getAnnotations()) { try { annotation.setModuleName(detector.guessModuleName(annotation.getFileName())); annotation.setContextHashCode(contextHashCode.create( annotation.getFileName(), annotation.getPrimaryLineNumber(), defaultEncoding)); } catch (IOException exception) { // ignore and continue } } return result; } }
package com.untamedears.JukeAlert.listener; import static com.untamedears.JukeAlert.util.Utility.doesSnitchExist; import static com.untamedears.JukeAlert.util.Utility.isDebugging; import static com.untamedears.JukeAlert.util.Utility.isOnSnitch; import static com.untamedears.JukeAlert.util.Utility.isPartialOwnerOfSnitch; import static com.untamedears.JukeAlert.util.Utility.notifyGroup; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.UUID; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.DoubleChest; import org.bukkit.entity.LivingEntity; 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.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.material.Lever; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; import vg.civcraft.mc.citadel.Citadel; import vg.civcraft.mc.citadel.ReinforcementManager; import vg.civcraft.mc.citadel.events.ReinforcementCreationEvent; import vg.civcraft.mc.citadel.reinforcement.PlayerReinforcement; import vg.civcraft.mc.citadel.reinforcement.Reinforcement; import vg.civcraft.mc.namelayer.events.GroupDeleteEvent; import vg.civcraft.mc.namelayer.group.Group; import com.untamedears.JukeAlert.JukeAlert; import com.untamedears.JukeAlert.external.VanishNoPacket; import com.untamedears.JukeAlert.manager.PlayerManager; import com.untamedears.JukeAlert.manager.SnitchManager; import com.untamedears.JukeAlert.model.Snitch; public class JukeAlertListener implements Listener { private ReinforcementManager rm = Citadel.getReinforcementManager(); private final JukeAlert plugin = JukeAlert.getInstance(); SnitchManager snitchManager = plugin.getSnitchManager(); PlayerManager playerManager = plugin.getPlayerManager(); private final Map<UUID, Set<Snitch>> playersInSnitches = new TreeMap<UUID, Set<Snitch>>(); private final ArrayList<Location> previousLocations = new ArrayList<Location>(); private final VanishNoPacket vanishNoPacket = new VanishNoPacket(); private boolean checkProximity(Snitch snitch, UUID accountId) { Set<Snitch> inList = playersInSnitches.get(accountId); if (inList == null) { inList = new TreeSet<Snitch>(); playersInSnitches.put(accountId, inList); } return inList.contains(snitch); } @EventHandler(priority = EventPriority.HIGHEST) public void playerJoinEvent(PlayerJoinEvent event) { Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } UUID accountId = player.getUniqueId(); Set<Snitch> inList = new TreeSet<Snitch>(); playersInSnitches.put(accountId, inList); Location location = player.getLocation(); World world = location.getWorld(); Set<Snitch> snitches = snitchManager.findSnitches(world, location); for (Snitch snitch : snitches) { if (!isOnSnitch(snitch, accountId)) { snitch.imposeSnitchTax(); inList.add(snitch); notifyGroup( snitch, ChatColor.AQUA + " * " + player.getDisplayName() + " logged in to snitch at " + snitch.getName() + " [" + snitch.getLoc().getWorld().getName() + " " + snitch.getX() + " " + snitch.getY() + " " + snitch.getZ() + "]"); if (snitch.shouldLog()) { plugin.getJaLogger().logSnitchLogin(snitch, location, player); Location north = new Location(world, snitch.getX(), snitch.getY(), snitch.getZ()-1); toggleLeverIfApplicable(snitch, north, true); } } } } public void handlePlayerExit(PlayerEvent event) { Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } UUID accountId = player.getUniqueId(); playersInSnitches.remove(accountId); Location location = player.getLocation(); World world = location.getWorld(); Set<Snitch> snitches = snitchManager.findSnitches(world, location); for (Snitch snitch : snitches) { if (!isOnSnitch(snitch, accountId)) { snitch.imposeSnitchTax(); notifyGroup( snitch, ChatColor.AQUA + " * " + player.getDisplayName() + " logged out in snitch at " + snitch.getName() + " [" + snitch.getLoc().getWorld().getName() + " " + snitch.getX() + " " + snitch.getY() + " " + snitch.getZ() + "]"); if (snitch.shouldLog()) { plugin.getJaLogger().logSnitchLogout(snitch, location, player); } } } } @EventHandler(ignoreCancelled = true) public void playerKickEvent(PlayerKickEvent event) { handlePlayerExit(event); } @EventHandler(ignoreCancelled = true) public void playerQuitEvent(PlayerQuitEvent event) { handlePlayerExit(event); } @EventHandler(priority = EventPriority.HIGHEST) public void placeSnitchBlock(BlockPlaceEvent event) { if (event.isCancelled()) { return; } Block block = event.getBlock(); Player player = event.getPlayer(); Location loc = block.getLocation(); if (block.getType().equals(Material.JUKEBOX)) { if (!rm.isReinforced(loc)) { player.sendMessage(ChatColor.YELLOW + "You've placed a jukebox; reinforce it to register it as a snitch."); } } else if (block.getType().equals(Material.NOTE_BLOCK)) { if (!rm.isReinforced(loc)) { player.sendMessage(ChatColor.YELLOW + "You've placed a noteblock; reinforce it to register it as an entry snitch."); } } } @EventHandler(priority = EventPriority.HIGHEST) public void reinforceSnitchBlock(ReinforcementCreationEvent event) { if (event.isCancelled()) { return; } Block block = event.getBlock(); if (block.getType().equals(Material.JUKEBOX)) { Player player = event.getPlayer(); Location loc = block.getLocation(); Reinforcement rei = event.getReinforcement(); if (rei instanceof PlayerReinforcement) { PlayerReinforcement reinforcement = (PlayerReinforcement) rei; Group owner = reinforcement.getGroup(); if (owner == null) { JukeAlert.getInstance().log(String.format( "No group on rein (%s)", reinforcement.getLocation().toString())); } Snitch snitch; if (snitchManager.getSnitch(loc.getWorld(), loc) != null) { snitch = snitchManager.getSnitch(loc.getWorld(), loc); plugin.getJaLogger().updateSnitchGroup(snitchManager.getSnitch(loc.getWorld(), loc), owner.getName()); snitchManager.removeSnitch(snitch); snitch.setGroup(owner); } else { snitch = new Snitch(loc, owner, true, false); plugin.getJaLogger().logSnitchPlace(player.getWorld().getName(), owner.getName(), "", loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), true); snitch.setId(plugin.getJaLogger().getLastSnitchID()); plugin.getJaLogger().increaseLastSnitchID(); } snitchManager.addSnitch(snitch); player.sendMessage(ChatColor.AQUA + "You've created a snitch block registered to the group " + owner.getName() + ". To name your snitch, type /janame."); } } else if (block.getType().equals(Material.NOTE_BLOCK)) { Player player = event.getPlayer(); Location loc = block.getLocation(); Reinforcement rei = event.getReinforcement(); if (rei instanceof PlayerReinforcement) { PlayerReinforcement reinforcement = (PlayerReinforcement) rei; Group owner = reinforcement.getGroup(); if (owner == null) { JukeAlert.getInstance().log(String.format( "No group on rein (%s)", reinforcement.getLocation().toString())); } Snitch snitch; if (snitchManager.getSnitch(loc.getWorld(), loc) != null) { snitch = snitchManager.getSnitch(loc.getWorld(), loc); plugin.getJaLogger().updateSnitchGroup(snitchManager.getSnitch(loc.getWorld(), loc), owner.getName()); snitchManager.removeSnitch(snitch); snitch.setGroup(owner); } else { snitch = new Snitch(loc, owner, false, false); plugin.getJaLogger().logSnitchPlace(player.getWorld().getName(), owner.getName(), "", loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), false); snitch.setId(plugin.getJaLogger().getLastSnitchID()); plugin.getJaLogger().increaseLastSnitchID(); } snitchManager.addSnitch(snitch); player.sendMessage(ChatColor.AQUA + "You've created an entry snitch registered to the group " + owner.getName() + ". To name your entry snitch, type /janame."); } } } @EventHandler(ignoreCancelled = true) public void onGroupDeletion(GroupDeleteEvent event) { String groupName = event.getGroup().getName(); Set<Snitch> removeSet = new TreeSet<Snitch>(); for (Snitch snitch : snitchManager.getAllSnitches()) { final Group snitchGroup = snitch.getGroup(); String snitchGroupName = null; if (snitchGroup != null) { snitchGroupName = snitchGroup.getName(); } if (snitchGroupName != null && snitchGroupName.equalsIgnoreCase(groupName)) { removeSet.add(snitch); } } for (Snitch snitch : removeSet) { final Location loc = snitch.getLoc(); if (snitch.shouldLog()) { plugin.getJaLogger().logSnitchBreak(loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } snitchManager.removeSnitch(snitch); } } @EventHandler(priority = EventPriority.HIGHEST) public void breakSnitchBlock(BlockBreakEvent event) { if (event.isCancelled()) { return; } Block block = event.getBlock(); if (!block.getType().equals(Material.JUKEBOX)) { return; } if (vanishNoPacket.isPlayerInvisible(event.getPlayer())) { return; } Location loc = block.getLocation(); if (snitchManager.getSnitch(loc.getWorld(), loc) != null) { Snitch snitch = snitchManager.getSnitch(loc.getWorld(), loc); if (snitch.shouldLog()) { plugin.getJaLogger().logSnitchBreak(loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } snitchManager.removeSnitch(snitch); } } @EventHandler(priority = EventPriority.HIGH) public void enterSnitchProximity(PlayerMoveEvent event) { Location from = event.getFrom(); Location to = event.getTo(); if (from.getBlockX() == to.getBlockX() && from.getBlockY() == to.getBlockY() && from.getBlockZ() == to.getBlockZ() && from.getWorld().equals(to.getWorld())) { // Player didn't move by at least one block. return; } Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } UUID accountId = player.getUniqueId(); Location location = player.getLocation(); World world = location.getWorld(); Set<Snitch> inList = playersInSnitches.get(accountId); if (inList == null) { inList = new TreeSet<Snitch>(); playersInSnitches.put(accountId, inList); } Set<Snitch> snitches = snitchManager.findSnitches(world, location); for (Snitch snitch : snitches) { if (doesSnitchExist(snitch, true)) { if (isPartialOwnerOfSnitch(snitch, accountId)) { if (!inList.contains(snitch)) { inList.add(snitch); plugin.getJaLogger().logSnitchVisit(snitch); } } if ((!isOnSnitch(snitch, accountId) || isDebugging())) { if (!inList.contains(snitch)) { snitch.imposeSnitchTax(); inList.add(snitch); if ((plugin.getConfigManager().getInvisibilityEnabled() && player.hasPotionEffect(PotionEffectType.INVISIBILITY)) && !snitch.shouldLog()) continue; else{ notifyGroup( snitch, ChatColor.AQUA + " * " + player.getDisplayName() + " entered snitch at " + snitch.getName() + " [" + snitch.getLoc().getWorld().getName() + " " + snitch.getX() + " " + snitch.getY() + " " + snitch.getZ() + "]"); } if (snitch.shouldLog()){ plugin.getJaLogger().logSnitchEntry(snitch, location, player); Location north = new Location(world, snitch.getX(), snitch.getY(), snitch.getZ()-1); toggleLeverIfApplicable(snitch, north, true); } } } } } snitches = snitchManager.findSnitches(world, location, true); Set<Snitch> rmList = new TreeSet<Snitch>(); for (Snitch snitch : inList) { if (snitches.contains(snitch)) { continue; } rmList.add(snitch); } inList.removeAll(rmList); } // Exceptions: No exceptions must be raised from this for any reason. private void toggleLeverIfApplicable(final Snitch snitch, final Location blockToPossiblyToggle, final Boolean leverShouldEnable) { try { if(!JukeAlert.getInstance().getConfigManager().getAllowTriggeringLevers()) return; if (null == snitch) return; World world = snitch.getLoc().getWorld(); if(snitch.shouldToggleLevers()) { if (world.getBlockAt(blockToPossiblyToggle).getType() == Material.LEVER) { BlockState leverState = world.getBlockAt(blockToPossiblyToggle).getState(); Lever lever = ((Lever)leverState.getData()); if(leverShouldEnable && !lever.isPowered()) { lever.setPowered(true); leverState.setData(lever); leverState.update(); } else if (!leverShouldEnable && lever.isPowered()) { lever.setPowered(false); leverState.setData(lever); leverState.update(); } if (leverShouldEnable) { BukkitScheduler scheduler = plugin.getServer().getScheduler(); scheduler.scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { toggleLeverIfApplicable(snitch, blockToPossiblyToggle, false); } }, 15L); } } } } catch(Exception ex) { // eat. return; } } @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryOpenEvent(InventoryOpenEvent e) { Player player = (Player) e.getPlayer(); if (e.isCancelled()) { return; } if (vanishNoPacket.isPlayerInvisible(player)) { return; } Block block; if (e.getInventory().getHolder() instanceof Chest) { Chest chest = (Chest) e.getInventory().getHolder(); block = chest.getBlock(); } else if (e.getInventory().getHolder() instanceof DoubleChest) { DoubleChest chest = (DoubleChest) e.getInventory().getHolder(); block = chest.getLocation().getBlock(); } else { return; } UUID accountId = player.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(player.getWorld(), player.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId)) { plugin.getJaLogger().logUsed(snitch, player, block); Location south = new Location(block.getWorld(), snitch.getX(), snitch.getY(), snitch.getZ()+1); toggleLeverIfApplicable(snitch, south, true); } } } } @EventHandler(priority = EventPriority.HIGH) public void playerKillEntity(EntityDeathEvent event) { LivingEntity entity = event.getEntity(); LivingEntity killer = entity.getKiller(); // TODO: This should never be true, bug? if (entity instanceof Player) { return; } if (!(killer instanceof Player)) { return; } if (vanishNoPacket.isPlayerInvisible((Player) killer)) { return; } Player player = (Player) killer; UUID accountId = player.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(player.getWorld(), player.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId)) { plugin.getJaLogger().logSnitchEntityKill(snitch, player, entity); } } } } @EventHandler(priority = EventPriority.HIGH) public void playerKillPlayer(PlayerDeathEvent event) { if (!(event.getEntity().getKiller() instanceof Player)) { return; } Player killed = event.getEntity(); Player killer = killed.getKiller(); if (vanishNoPacket.isPlayerInvisible(killer)) { return; } UUID accountId = killer.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(killed.getWorld(), killed.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId) || checkProximity(snitch, accountId)) { plugin.getJaLogger().logSnitchPlayerKill(snitch, killer, killed); } } } } @EventHandler(priority = EventPriority.HIGH) public void onBlockIgniteEvent(BlockIgniteEvent event) { if (event.isCancelled()) { return; } if (event.getPlayer() == null) { return; } Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } Block block = event.getBlock(); UUID accountId = player.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(block.getWorld(), block.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId)) { plugin.getJaLogger().logSnitchIgnite(snitch, player, block); } } } } @EventHandler(priority = EventPriority.HIGH) public void onBlockBurnEvent(BlockBurnEvent event) { if (event.isCancelled()) { return; } Block block = event.getBlock(); Set<Snitch> snitches = snitchManager.findSnitches(block.getWorld(), block.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (snitch.getGroup() != null) { continue; } plugin.getJaLogger().logSnitchBlockBurn(snitch, block); } } @EventHandler(priority = EventPriority.HIGH) public void playerBreakBlock(BlockBreakEvent event) { if (event.isCancelled()) { return; } Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } Block block = event.getBlock(); UUID accountId = player.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(block.getWorld(), block.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId)) { plugin.getJaLogger().logSnitchBlockBreak(snitch, player, block); Location west = new Location(block.getWorld(), snitch.getX()-1, snitch.getY(), snitch.getZ()); toggleLeverIfApplicable(snitch, west, true); } } } } @EventHandler(priority = EventPriority.HIGH) public void playerPlaceBlock(BlockPlaceEvent event) { if (event.isCancelled()) { return; } Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } Block block = event.getBlock(); UUID accountId = player.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(block.getWorld(), block.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId)) { plugin.getJaLogger().logSnitchBlockPlace(snitch, player, block); Location east = new Location(block.getWorld(), snitch.getX()+1, snitch.getY(), snitch.getZ()); toggleLeverIfApplicable(snitch, east, true); } } } } @EventHandler(priority = EventPriority.HIGH) public void playerFillBucket(PlayerBucketFillEvent event) { if (event.isCancelled()) { return; } Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } Block block = event.getBlockClicked(); UUID accountId = player.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(block.getWorld(), block.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId)) { plugin.getJaLogger().logSnitchBucketFill(snitch, player, block); } } } } @EventHandler(priority = EventPriority.HIGH) public void playerEmptyBucket(PlayerBucketEmptyEvent event) { if (event.isCancelled()) { return; } Player player = event.getPlayer(); if (vanishNoPacket.isPlayerInvisible(player)) { return; } Block block = event.getBlockClicked(); UUID accountId = player.getUniqueId(); Set<Snitch> snitches = snitchManager.findSnitches(block.getWorld(), block.getLocation()); for (Snitch snitch : snitches) { if (!snitch.shouldLog()) { continue; } if (!isOnSnitch(snitch, accountId) || isDebugging()) { if (checkProximity(snitch, accountId)) { plugin.getJaLogger().logSnitchBucketEmpty(snitch, player, block.getLocation(), player.getItemInHand()); } } } } }
package scalac.util; import java.util.HashMap; import java.lang.reflect.Modifier; import java.lang.reflect.Method; import java.lang.reflect.Field; import scalac.Global; import scalac.ApplicationError; import scalac.symtab.Type; import scalac.symtab.Symbol; import scalac.symtab.Scope; /** * Debugging class, used e.g. to obtain string representations of * compiler data structures that are not "pretty-printed" and thus * easier to relate to the source code. * * All methods are static to be easily useable in any context. * * @author Michel Schinz * @version 1.0 */ public abstract class Debug { // // Debug interface - abort public static Error abort() { return new ApplicationError(); } public static Error abort(String message) { return new ApplicationError(message); } public static Error abort(Object object) { return new ApplicationError(object); } public static Error abort(Throwable cause) { return new ApplicationError(cause); } public static Error abort(String message, Object object) { return new ApplicationError(message, object); } public static Error abort(String message, Throwable cause) { return new ApplicationError(message, cause); } public static Error abort(Object object, Throwable cause) { return new ApplicationError(object, cause); } public static Error abort(String message, Object object, Throwable cause) { return new ApplicationError(message, object, cause); } // // Debug interface - log public static boolean log(Object a) { return logAll(new Object[] {a}); } public static boolean log(Object a, Object b) { return logAll(new Object[] {a, b}); } public static boolean log(Object a, Object b, Object c) { return logAll(new Object[] {a, b, c}); } public static boolean log(Object a, Object b, Object c, Object d) { return logAll(new Object[] {a, b, c, d}); } public static boolean logAll(Object[] args) { return Global.instance.log(showAll(args)); } // // Debug interface - handlers public static final HashMap/*<Class,DebugHandler>*/ handlers; static { handlers = new HashMap(); handlers.put(String.class, DebugToStringHandler.instance); handlers.put(Type.class, DebugType.instance); handlers.put(Symbol.class, DebugSymbol.instance); handlers.put(Scope.class, DebugScope.instance); } public static DebugHandler getHandler(Object that) { if (that == null) return DebugDefaultHandler.instance; return getHandler(that.getClass()); } public static DebugHandler getHandler(Class clasz) { if (clasz == null) return DebugDefaultHandler.instance; Object handler = handlers.get(clasz); if (handler != null) return (DebugHandler)handler; return getHandler(clasz.getSuperclass()); } // // Debug interface - toString public static String toString(Object that) { return show(that); } // // Debug interface - show public static String show(Object a) { return showAll(new Object[] {a}); } public static String show(Object a, Object b) { return showAll(new Object[] {a, b}); } public static String show(Object a, Object b, Object c) { return showAll(new Object[] {a, b, c}); } public static String show(Object a, Object b, Object c, Object d) { return showAll(new Object[] {a, b, c, d}); } public static String show(Object a, Object b, Object c, Object d, Object e) { return showAll(new Object[] {a, b, c, d, e}); } public static String show(Object a, Object b, Object c, Object d, Object e, Object f) { return showAll(new Object[] {a, b, c, d, e, f}); } public static String show(Object a, Object b, Object c, Object d, Object e, Object f, Object g) { return showAll(new Object[] {a, b, c, d, e, f, g}); } public static String show(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h) { return showAll(new Object[] {a, b, c, d, e, f, g, h}); } public static String show(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i) { return showAll(new Object[] {a, b, c, d, e, f, g, h, i}); } public static String show(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j) { return showAll(new Object[] {a, b, c, d, e, f, g, h, i, j}); } public static String show(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k) { return showAll(new Object[] {a, b, c, d, e, f, g, h, i, j, k}); } public static String show(Object a, Object b, Object c, Object d, Object e, Object f, Object g, Object h, Object i, Object j, Object k, Object l) { return showAll(new Object[] {a, b, c, d, e, f, g, h, i, j, k, l}); } public static String showAll(Object[] args) { if (args == null) return "null"; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < args.length; i++) append(buffer, args[i]); return buffer.toString(); } // // Debug interface - append public static void append(StringBuffer buffer, Object that) { getHandler(that).append0(buffer, that); } public static void appendDefault(StringBuffer buffer, Object that) { if (that == null) { buffer.append("null"); return; } if (!that.getClass().isArray()) { appendObject(buffer, that); } else { appendArray(buffer, (Object[])that); } } public static void appendObject(StringBuffer buffer, Object that) { if (that == null) { buffer.append("null"); return; } buffer.append(getClassName(that)); Class owner = null; if (hasToString(that.getClass())) { buffer.append('('); buffer.append(that); buffer.append(')'); } else { int code = System.identityHashCode(that); buffer.append('@'); buffer.append(Integer.toHexString(code)); } } public static void appendArray(StringBuffer buffer, Object[] that) { if (that == null) { buffer.append("null"); return; } buffer.append('['); for (int i = 0; i < that.length; i++) { if (i > 0) buffer.append(','); append(buffer, that[i]); } buffer.append(']'); } // // Debug interface - utils public static final Class OBJECT_CLASS = Object.class; public static boolean hasToString(Class clasz) { try { Method toString = clasz.getMethod("toString", new Class[0]); return toString.getDeclaringClass() != OBJECT_CLASS; } catch (NoSuchMethodException excpetion) { return false; } catch (SecurityException excpetion) { return false; } } public static String getClassName(Object object) { if (object == null) return "null"; Class clasz = object.getClass(); String name = clasz.getName(); if (!name.endsWith("$$Var")) return name; Class superclass = clasz.getSuperclass(); Field[] fields = superclass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { Field field = fields[i]; if (field.getType() != clasz) continue; if (!Modifier.isStatic(field.getModifiers())) continue; Object value = field.get(null); if (value != object) continue; return name + "[" + field.getName() + "]"; } catch (IllegalAccessException exception) { // continue } } return name; } // } public interface DebugHandler { // // DebugHandler interface public void append0(StringBuffer buffer, Object that); // } public abstract class DebugAbstractHandler implements DebugHandler { // // DebugAbstractHandler interface public String show(Object that) { return Debug.show(that, this); } // } public class DebugDefaultHandler extends DebugAbstractHandler { // // DebugDefaultHandler interface public static DebugDefaultHandler instance = new DebugDefaultHandler(); // // DebugHandler interface public void append0(StringBuffer buffer, Object that) { Debug.appendDefault(buffer, that); } // } public class DebugToStringHandler extends DebugAbstractHandler { // // DebugToStringHandler interface public static DebugToStringHandler instance = new DebugToStringHandler(); // // DebugHandler interface public void append0(StringBuffer buffer, Object that) { buffer.append(that); } // } public class DebugObject extends DebugAbstractHandler { // // DebugObject interface public static DebugObject instance = new DebugObject(); public void append1(StringBuffer buffer, Object that) { Debug.appendObject(buffer, that); } // // DebugHandler interface public void append0(StringBuffer buffer, Object that) { append1(buffer, (Object)that); } // } public class DebugArray extends DebugAbstractHandler { // // DebugArray interface public static DebugArray instance = new DebugArray(); public void append1(StringBuffer buffer, Object[] that) { Debug.appendArray(buffer, that); } // // DebugHandler interface public void append0(StringBuffer buffer, Object that) { append1(buffer, (Object[])that); } // } public class DebugType extends DebugAbstractHandler { // // DebugType interface public static DebugType instance = new DebugType(); public void append1(StringBuffer buffer, Type that) { switch (that) { case ErrorType: buffer.append("ErrorType"); return; case AnyType: buffer.append("AnyType"); return; case NoType: buffer.append("NoType"); return; case ThisType(Symbol symbol): buffer.append("ThisType("); Debug.append(buffer, symbol); buffer.append(')'); return; case TypeRef(Type prefix, Symbol symbol, Type[] args) : buffer.append("TypeRef("); Debug.append(buffer, prefix); buffer.append(','); Debug.append(buffer, symbol); buffer.append(','); Debug.append(buffer, args); buffer.append(')'); return; case SingleType(Type prefix, Symbol symbol): buffer.append("SingleType("); Debug.append(buffer, prefix); buffer.append(','); Debug.append(buffer, symbol); buffer.append(')'); return; case CompoundType(Type[] basetypes, Scope members): buffer.append("CompoundType("); Debug.append(buffer, basetypes); buffer.append(','); Debug.append(buffer, members); buffer.append(','); Debug.append(buffer, that.symbol()); buffer.append(')'); return; case MethodType(Symbol[] vparams, Type result): buffer.append("MethodType("); Debug.append(buffer, vparams); buffer.append(','); Debug.append(buffer, result); buffer.append(')'); return; case PolyType(Symbol[] tparams, Type result): buffer.append("PolyType("); Debug.append(buffer, tparams); buffer.append(','); Debug.append(buffer, result); buffer.append(')'); return; case OverloadedType(Symbol[] alts, Type[] alttypes): buffer.append("OverloadedType("); Debug.append(buffer, alts); buffer.append(','); Debug.append(buffer, alttypes); buffer.append(')'); return; case LazyType(): buffer.append("LazyType()"); return; case TypeVar(Type origin, Type.Constraint constr): buffer.append("TypeVar("); Debug.append(buffer, origin); buffer.append(','); Debug.append(buffer, constr); buffer.append(')'); return; case UnboxedType(int tag): buffer.append("UnboxedType("); buffer.append(tag); buffer.append(')'); return; case UnboxedArrayType(Type elemtp): buffer.append("UnboxedArrayType("); Debug.append(buffer, elemtp); buffer.append(')'); return; default: Debug.appendDefault(buffer, that); return; } } // // DebugHandler interface public void append0(StringBuffer buffer, Object that) { append1(buffer, (Type)that); } // } public class DebugSymbol extends DebugAbstractHandler { // // DebugSymbol interface public static DebugSymbol instance = new DebugSymbol(); public void append1(StringBuffer buffer, Symbol that) { if (that != Symbol.NONE && that != Symbol.ERROR) { if (that.owner() != Global.instance.definitions.ROOT_CLASS) { Debug.append(buffer, that.owner()); buffer.append("."); } } buffer.append(that.name); if (Global.instance.uniqid) { buffer.append(' buffer.append(Global.instance.uniqueID.id(that)); } } // // DebugHandler interface public void append0(StringBuffer buffer, Object that) { append1(buffer, (Symbol)that); } // } public class DebugScope extends DebugAbstractHandler { // // DebugScope interface public static DebugScope instance = new DebugScope(); public void append1(StringBuffer buffer, Scope that) { buffer.append('{'); for (Scope.SymbolIterator i = that.iterator(); i.hasNext();) { Debug.append(buffer, i.next()); if (i.hasNext()) buffer.append(','); } buffer.append('}'); } // // DebugHandler interface public void append0(StringBuffer buffer, Object that) { append1(buffer, (Scope)that); } // }
package com.ashish.cop290assign0.utils; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.util.Base64; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.ashish.cop290assign0.R; import com.ashish.cop290assign0.data.FormData; import com.ashish.cop290assign0.data.Member; import com.github.siyamed.shapeimageview.CircularImageView; /** * Collection of static methods to manipulate objects on the screen / display. * @author Abhishek Kedia */ public class ScreenUtils { public static String getStringFromTextView(View v, int id) { try { return ((TextView) v.findViewById(id)).getText().toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } public static void setTextInTextView(View v, int id, CharSequence text) { try { ((TextView) v.findViewById(id)).setText(text); } catch (Exception e) { e.printStackTrace(); } } public static void setErrorInEditText(View v, int id, CharSequence error) { try { ((EditText) v.findViewById(id)).setError(error); } catch (Exception e) { e.printStackTrace(); } } public static void removeErrorFromEditText(View v, int id) { setErrorInEditText(v, id, null); } public static void setMemberImageInCircularImageView(View view, int id, Bitmap memberImage) { try { CircularImageView memberImageView = (CircularImageView) view.findViewById(id); if (memberImage != null) memberImageView.setImageBitmap(memberImage); else memberImageView.setImageResource(R.mipmap.ic_launcher); } catch (Exception e) { e.printStackTrace(); } } public static void setImageBorderInCircularImageView(View view, int id, int color) { try { ((CircularImageView) view.findViewById(id)).setBorderColor(color); } catch (Exception e) { e.printStackTrace(); } } public static void setMemberImageAndBorderInCircularImageView(View view, int id, Bitmap memberImage) { setMemberImageInCircularImageView(view, id, memberImage); if(memberImage == null) setImageBorderInCircularImageView(view,id,Color.parseColor("#ffffff")); else setImageBorderInCircularImageView(view,id,Color.parseColor("#ff3C16")); } public static void hideKeyboard(View v) { try { InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } catch (Exception e) { e.printStackTrace(); } } public static byte[] base64StringToByteArray(String base64String) { try { return Base64.decode(base64String, Base64.DEFAULT); } catch (Exception e) { e.printStackTrace(); return null; } } public static Bitmap base64StringToBitmap(String base64String) { byte[] b = base64StringToByteArray(base64String); return BitmapFactory.decodeByteArray(b, 0, b.length); } //Adds asterisk to editTexts using SpannableString(used for selective formatting of strings ex. color,on click url). public static void addRedAsteriskToEditText(EditText editText) { try { String text = editText.getHint().toString(); String asterisk = " *"; SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(text); int start = builder.length(); builder.append(asterisk); int end = builder.length(); builder.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); editText.setHint(builder); } catch (Exception e) { e.printStackTrace(); } } public static void addRedAsteriskToEditText(View v, int id) { addRedAsteriskToEditText((EditText) v.findViewById(id)); } //Creates a progressDialog public static ProgressDialog createProgressDialog(View view, String title, String description){ ProgressDialog progressDialog = new ProgressDialog(view.getContext()); progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); progressDialog.setCancelable(false); progressDialog.setTitle(title); progressDialog.setMessage(description); progressDialog.show(); return progressDialog; } //creates and shows a custom dialog //TODO make the header of dialog colored according to success or failure. RED if failed, green if success. public static void makeDialog(View view, String title, String msg, String buttonText,boolean success){ final Dialog dialog = new Dialog(view.getContext()); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //ask why?? dialog.setContentView(R.layout.error_dialog_layout); dialog.setCancelable(false); if(success) { dialog.findViewById(R.id.dialog_title_bar).setBackgroundColor(Color.parseColor("#12B42C")); ((Button)dialog.findViewById(R.id.error_button)).setTextColor(Color.parseColor("#12B42C")); } ((TextView)dialog.findViewById(R.id.title_text)).setText(title); ((TextView)dialog.findViewById(R.id.error_text)).setText(msg); ((Button)dialog.findViewById(R.id.error_button)).setText(buttonText); (dialog.findViewById(R.id.error_button)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); layoutParams.copyFrom(dialog.getWindow().getAttributes()); layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; dialog.show(); dialog.getWindow().setAttributes(layoutParams); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } public static void setTextInTextView(Dialog v, int id, CharSequence text) { try { ((TextView) v.findViewById(id)).setText(text); } catch (Exception e) { e.printStackTrace(); } } public static void setMemberImageInCircularImageView(Dialog view, int id, Bitmap memberImage) { try { CircularImageView memberImageView = (CircularImageView) view.findViewById(id); if (memberImage != null) memberImageView.setImageBitmap(memberImage); else memberImageView.setImageResource(R.mipmap.ic_launcher); } catch (Exception e) { e.printStackTrace(); } } public static void setImageBorderInCircularImageView(Dialog view, int id, int color) { try { ((CircularImageView) view.findViewById(id)).setBorderColor(color); } catch (Exception e) { e.printStackTrace(); } } public static void setMemberImageAndBorderInCircularImageView(Dialog view, int id, Bitmap memberImage) { setMemberImageInCircularImageView(view,id,memberImage); // if(memberImage == null) // //setImageBorderInCircularImageView(view,id,Color.parseColor("#ffffff")); // else // if(memberImage != null) //setImageBorderInCircularImageView(view,id,Color.parseColor("#ff3C16")); } //TODO move to a new class //TODO show team name in confirmation dialog public static void makeConfirmationDialog(View view, FormData formData, final View.OnClickListener submitClickHandler) { final Dialog dialog = new Dialog(view.getContext(),R.style.DialogSlideAnim); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.confirm_dialog_layout); dialog.setCancelable(false); // dialog.show(); // view = dialog.getCurrentFocus(); //TODO improve this setTextInTextView(dialog,R.id.team_name,formData.getTeamName()); setTextInTextView(dialog, R.id.detail1, formData.getMember(1).toFormattedString()); setMemberImageAndBorderInCircularImageView(dialog, R.id.img1, formData.getMember(1).getImageBitmap()); setTextInTextView(dialog, R.id.detail2, formData.getMember(2).toFormattedString()); setMemberImageAndBorderInCircularImageView(dialog, R.id.img2, formData.getMember(2).getImageBitmap()); if(formData.getIsFilled(3)) { setTextInTextView(dialog,R.id.detail3,formData.getMember(3).toFormattedString()); setMemberImageAndBorderInCircularImageView(dialog, R.id.img3, formData.getMember(3).getImageBitmap()); } else { dialog.findViewById(R.id.student3_layout).setVisibility(View.GONE); } //set button listener //cancel button (dialog.findViewById(R.id.cancel)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); (dialog.findViewById(R.id.submit)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); submitClickHandler.onClick(v); //TODO improve } }); WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); layoutParams.copyFrom(dialog.getWindow().getAttributes()); layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; dialog.show(); dialog.getWindow().setAttributes(layoutParams); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.server; import java.util.List; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import com.samskivert.util.Invoker; import com.samskivert.util.Lifecycle; import com.threerings.presents.server.PresentsDObjectMgr.LongRunnable; import static com.threerings.presents.Log.log; /** * Extends the generic {@link Invoker} and integrates it a bit more into the Presents system. */ @Singleton public class PresentsInvoker extends ReportingInvoker implements Lifecycle.ShutdownComponent { @Inject public PresentsInvoker (PresentsDObjectMgr omgr, Lifecycle cycle, ReportManager repmgr) { super("presents.Invoker", omgr, repmgr); cycle.addComponent(this); _omgr = omgr; } /** * Adds an invoker that may post to the PresentsInvoker and the DObjectManager and may be * posted to by the PresentsInvoker and DObjectManager. This invoker will be taken into * consideration by {@link #postRunnableWhenEmpty(Runnable)} and in waiting for invokers to * empty out on shutdown. */ public void addInterdependentInvoker (Invoker invoker) { _interdependentInvokers.add(invoker); } /** * Posts the given runnable to this invoker when it, the DObjectManager and any interdependent * invokers are all empty. */ public void postRunnableWhenEmpty (Runnable onEmpty) { postUnit(new EmptyingUnit(onEmpty)); } @Override // from Invoker, Lifecycle.ShutdownComponent public void shutdown () { // this will do a sophisticated shutdown of both ourself and the dobjmgr; note: we // specifically avoid setting _shutdownRequested as it's OK for units to be posted to the // PresentsInvoker during the shutdown phase, we just delay shutdown until we're able to // make it to the shutdown unit without queueing up more units for processing postRunnableWhenEmpty(new Runnable() { public void run () { _omgr.harshShutdown(); // end the dobj thread // Now that things have emptied out, set _shutdownRequested and commit suicide PresentsInvoker.super.shutdown(); }}); } @Override // from Invoker protected void didShutdown () { _server.invokerDidShutdown(); } /** * This gets posted to this invoker over and over again until it, any interdependent invokers * and the DObjectManager are all empty. */ protected class EmptyingUnit extends Unit { public EmptyingUnit (Runnable onEmpty) { _onEmpty = onEmpty; } @Override public boolean invoke () { if (_loopCount > MAX_LOOPS) { log.warning("Emptying waiter looped on invoker 10000 times without finishing, " + "running onEmpty while items remain in the queue."); _onEmpty.run(); return false; // if the invoker queue is not empty, we put ourselves back on it } else if (!isEmpty()) { _loopCount++; postUnit(this); return false; } else if (++_passCount >= MAX_PASSES) { log.warning("Emptying waiter passed 50 times without finishing, running onEmpty " + "while items remain in queue."); _onEmpty.run(); return false; } else { _loopCount = 0; // The invoker is empty and running this. Check if everything else is empty. List<BlockingUnit> checkers = Lists.newArrayListWithCapacity(_interdependentInvokers.size() + 1); for (Invoker invoker : _interdependentInvokers) { checkers.add(new BlockingUnit(invoker)); } checkers.add(new BlockingUnit()); long checkStart = System.currentTimeMillis(); while (true) { synchronized (_checkMonitor) { boolean unchecked = false; for (BlockingUnit checker : checkers) { if (!checker.run) { unchecked = true; break; } } if (unchecked) { long timeChecking = System.currentTimeMillis() - checkStart; if (timeChecking >= FIVE_MINUTES) { log.warning("Waited 5 minutes for the all the blocking units to " + "no avail. Running onEmpty while items may remain in " + "the queue."); releaseCheckers(checkers); _onEmpty.run(); return false; } // At least one checker hasn't started running yet. We need to wait // till they're all in place before looking at emptiness. try { _checkMonitor.wait(FIVE_MINUTES - timeChecking); } catch (InterruptedException e) { // Not a problem, we'll just check on the checkers again } } else { // All the checkers are blocking their respective threads. That means // if their queues are empty, nothing else is running. for (BlockingUnit checker : checkers) { if (!checker.isEmpty()) { // Balls, we found an invoker with items in its queue. Let // everybody get back to work. releaseCheckers(checkers); // Post on the busy unit, so when it clears we'll post back // here checker.post(new Runnable() { public void run () { PresentsInvoker.this.postUnit(EmptyingUnit.this); } }); return false; } } // Everything is gloriously clean. Stop blocking all the threads and // shut down this invoker and the DObjectManager releaseCheckers(checkers); _onEmpty.run(); return false; } } } } } @Override public long getLongThreshold () { return 60 * 1000; } protected void releaseCheckers (List<BlockingUnit> checkers) { for (BlockingUnit checker : checkers) { synchronized (checker) { checker.released = true; checker.notify(); } } } /** The runnable to execute when all associated queues are empty or we've given up. */ protected Runnable _onEmpty; /** The number of times we've been passed to the object manager. */ protected int _passCount; /** How many times we've looped on the thread we're currently on. */ protected int _loopCount; /** The maximum number of passes we allow before just ending things. */ protected static final int MAX_PASSES = 50; /** The maximum number of loops we allow before just ending things. */ protected static final int MAX_LOOPS = 10000; protected static final long FIVE_MINUTES = 5 * 60 * 1000L; } /** * Runs in an Invoker or the DObjectManager and blocks it until released by EmptyingUnit. */ protected class BlockingUnit extends Unit implements LongRunnable { /** * If the run method of this checker has been entered. If this is true while released is * false, this checker is blocking its thread. */ public boolean run; /** If this checker no longer needs to block its thread. */ public boolean released; public BlockingUnit () { _omgr.postRunnable(this); } public BlockingUnit (Invoker invoker) { _invoker = invoker; _invoker.postUnit(this); } public boolean isEmpty () { return _invoker == null ? _omgr.queueIsEmpty() : _invoker.isEmpty(); } public void post (Runnable runnable) { if (_invoker != null) { _invoker.postRunnable(runnable); } else { _omgr.postRunnable(runnable); } } @Override public void run() { // Override Invoker.Unit's run altogether to allow this to be posted as a Runnable to // the DObjectMgr as well. run = true; synchronized (_checkMonitor) { _checkMonitor.notify(); } synchronized (this) { while (!released) { try { wait(); } catch (InterruptedException e) { // Not a problem, we'll check our invariant } } } } @Override public boolean invoke () { run(); return false; } @Override public long getLongThreshold () { // Don't bitch about being a long invoker unless this has been blocking for longer than // the EmptyingUnit timeout return EmptyingUnit.FIVE_MINUTES; } protected Invoker _invoker; } /** * Synchronizes between EmptyingUnit and its BlockingUnits when checking that all * interdependent invokers are blocked. */ protected Object _checkMonitor = new Object(); /** Invokers that may post to Presents and may be posted to by Presents. */ protected List<Invoker> _interdependentInvokers = Lists.newArrayList(); /** The distributed object manager with which we interoperate. */ protected PresentsDObjectMgr _omgr; /** The server we're working for. */ @Inject protected PresentsServer _server; }
package com.coolweather.android; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.coolweather.android.db.City; import com.coolweather.android.db.County; import com.coolweather.android.db.Province; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); private List<Province> provinceList; private List<City> cityList; private List<County> countyList; private int currentLevel; private Province selectedProvince; private City selectedCity; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area, container, false); titleText = view.findViewById(R.id.title_text); backButton = view.findViewById(R.id.back_button); listView = view.findViewById(R.id.list_view); adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); queryCounties(); } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY) { queryProvinces(); } } }); queryProvinces(); } private void queryProvinces() { titleText.setText(""); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; } else { String address = "http://guolin.tech/api/china"; queryFromServer(address, "province"); } } private void queryCities() { titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList = DataSupport.where("provinceId = ?", String.valueOf(selectedProvince.getId())) .find(City.class); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; } else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/" + provinceCode; queryFromServer(address, "city"); } } private void queryCounties() { titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityId = ?", String.valueOf(selectedCity.getId())) .find(County.class); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; } else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/" + provinceCode +"/" + cityCode; queryFromServer(address, "county"); } } private void queryFromServer(String address, final String type) { showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onFailure(Call call, IOException e) { // runOnUiThread getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(), "", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); boolean result = false; if ("province".equals(type)) { result = Utility.handlerProvinceResponse(responseText); } else if ("city".equals(type)) { result = Utility.handlerCityResponse(responseText, selectedProvince.getId()); } else if ("county".equals(type)) { result = Utility.handlerCountyResponse(responseText, selectedCity.getId()); } if (result) { // runOnUiThread getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)) { queryCities(); } else if ("county".equals(type)) { queryCounties(); } } }); } } }); } private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } }
package info.faceland.strife.listeners; import com.google.common.base.CharMatcher; import info.faceland.beast.BeastData; import info.faceland.strife.StrifePlugin; import info.faceland.strife.attributes.StrifeAttribute; import info.faceland.strife.data.Champion; import info.faceland.utils.StringConverter; import org.bukkit.ChatColor; import org.bukkit.Sound; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import java.util.Map; import java.util.Random; public class CombatListener implements Listener { private final StrifePlugin plugin; private final Random random; public CombatListener(StrifePlugin plugin) { this.plugin = plugin; random = new Random(System.currentTimeMillis()); } @EventHandler(priority = EventPriority.HIGHEST) public void onProjectileLaunch(ProjectileLaunchEvent event) { if (event.getEntity().getShooter() instanceof Entity) { event.getEntity().setVelocity(event.getEntity().getVelocity().add(((Entity) event.getEntity().getShooter()).getVelocity())); } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { LivingEntity a; if (event.isCancelled() || !(event.getEntity() instanceof LivingEntity)) { return; } // LET THE DATA GATHERING COMMENCE boolean melee = true; if (event.getDamager() instanceof LivingEntity) { a = (LivingEntity) event.getDamager(); } else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) { a = (LivingEntity) ((Projectile) event.getDamager()).getShooter(); melee = false; } else { return; } LivingEntity b = (LivingEntity) event.getEntity(); if (b instanceof Player) { double chance = plugin.getChampionManager().getChampion(b.getUniqueId()).getAttributeValues().get(StrifeAttribute.EVASION); if (random.nextDouble() < chance) { event.setCancelled(true); b.getWorld().playSound(a.getEyeLocation(), Sound.IRONGOLEM_THROW, 1f, 2f); return; } } double damage; double meleeDamageA = StrifeAttribute.MELEE_DAMAGE.getBaseValue(), attackSpeedA; double criticalDamageA = StrifeAttribute.CRITICAL_DAMAGE.getBaseValue(), armorPenA = StrifeAttribute.ARMOR_PENETRATION.getBaseValue(); double lifeStealA = StrifeAttribute.LIFE_STEAL.getBaseValue(), lifeStolenA = 0D, playerHealthA = b.getHealth(); double rangedDamageA = StrifeAttribute.RANGED_DAMAGE.getBaseValue(), criticalRateA = StrifeAttribute.CRITICAL_RATE.getBaseValue(); double attackSpeedMultA = 1D, fireDamageA = StrifeAttribute.FIRE_DAMAGE.getBaseValue(); double armorB = StrifeAttribute.ARMOR.getBaseValue(), reflectDamageB = StrifeAttribute.DAMAGE_REFLECT.getBaseValue(); double parryB, blockB = StrifeAttribute.BLOCK.getBaseValue(); boolean blocking = false; boolean parried = false; if (a instanceof Player) { for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) { if (event.isApplicable(modifier)) { event.setDamage(modifier, 0D); } } Player p = (Player) a; Champion champ = plugin.getChampionManager().getChampion(p.getUniqueId()); Map<StrifeAttribute, Double> vals = champ.getAttributeValues(); meleeDamageA = vals.get(StrifeAttribute.MELEE_DAMAGE); attackSpeedA = (StrifeAttribute.ATTACK_SPEED.getBaseValue() * (1 / (1 + vals.get(StrifeAttribute.ATTACK_SPEED)))); criticalDamageA = vals.get(StrifeAttribute.CRITICAL_DAMAGE); armorPenA = vals.get(StrifeAttribute.ARMOR_PENETRATION); lifeStealA = vals.get(StrifeAttribute.LIFE_STEAL); playerHealthA = a.getHealth(); rangedDamageA = vals.get(StrifeAttribute.RANGED_DAMAGE); criticalRateA = vals.get(StrifeAttribute.CRITICAL_RATE); fireDamageA = vals.get(StrifeAttribute.FIRE_DAMAGE); long timeLeft = plugin.getAttackSpeedTask().getTimeLeft(a.getUniqueId()); long timeToSet = Math.round(Math.max(4.0 * attackSpeedA, 0.0)); if (timeLeft > 0) { attackSpeedMultA = Math.max(1.0 - 1.0 * timeLeft / timeToSet, 0.0); } plugin.getAttackSpeedTask().setTimeLeft(a.getUniqueId(), timeToSet); } else { BeastData data = plugin.getBeastPlugin().getData(a.getType()); if (data != null && a.getCustomName() != null) { int level = StringConverter.toInt(CharMatcher.DIGIT.retainFrom(ChatColor.stripColor(a.getCustomName()))); meleeDamageA = data.getDamageExpression().setVariable("LEVEL", level).evaluate(); rangedDamageA = meleeDamageA; } } if (b instanceof Player) { Player p = (Player) b; Champion champ = plugin.getChampionManager().getChampion(p.getUniqueId()); Map<StrifeAttribute, Double> vals = champ.getAttributeValues(); armorB = vals.get(StrifeAttribute.ARMOR); reflectDamageB = vals.get(StrifeAttribute.DAMAGE_REFLECT); parryB = vals.get(StrifeAttribute.PARRY); blockB = vals.get(StrifeAttribute.BLOCK); if (((Player) b).isBlocking()) { blocking = true; if (random.nextDouble() < parryB) { parried = true; } } } // LET THE DAMAGE CALCULATION COMMENCE if (melee) { if (blocking) { if (parried) { damage = meleeDamageA * attackSpeedMultA; a.damage(damage * 0.25); event.setCancelled(true); b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return; } damage = meleeDamageA * attackSpeedMultA; if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); double blockReducer = (1 - blockB); if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) { damage += damage / (a.getLocation().distanceSquared(b.getLocation()) / 2); } event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage * damageReducer * blockReducer); lifeStolenA = event.getFinalDamage() * lifeStealA; a.setHealth(Math.min(playerHealthA + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); return; } damage = meleeDamageA * attackSpeedMultA; if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) { damage += damage / (a.getLocation().distanceSquared(b.getLocation()) / 2); } event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage * damageReducer); lifeStolenA = event.getFinalDamage() * lifeStealA; a.setHealth(Math.min(playerHealthA + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); return; } if (blocking) { if (parried) { event.setCancelled(true); b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return; } damage = rangedDamageA * (a instanceof Player ? (event.getDamager().getVelocity().lengthSquared() / Math.pow(3, 2)) : 0); if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); double blockReducer = (1 - blockB); if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) { damage += damage / (a.getLocation().distanceSquared(b.getLocation()) / 2); } event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage * damageReducer * blockReducer); lifeStolenA = event.getFinalDamage() * lifeStealA; a.setHealth(Math.min(a.getHealth() + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); return; } damage = rangedDamageA * (a instanceof Player ? (event.getDamager().getVelocity().lengthSquared() / Math.pow(3, 2)) : 0); if (random.nextDouble() < criticalRateA) { damage = damage * criticalDamageA; b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f); } double damageReducer = (1 - (armorB * (1 - armorPenA))); if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) { damage += damage / (a.getLocation().distanceSquared(b.getLocation()) / 2); } event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage * damageReducer); lifeStolenA = event.getFinalDamage() * lifeStealA; a.setHealth(Math.min(a.getHealth() + lifeStolenA, a.getMaxHealth())); if (reflectDamageB > 0) { a.damage(damage * reflectDamageB); a.getWorld().playSound(a.getEyeLocation(), Sound.GLASS, 1f, 2f); } b.setFireTicks((int) Math.round(fireDamageA * 20)); } }
package com.versionone.integration.teamcity; import com.intellij.openapi.diagnostic.Logger; import com.versionone.integration.ciCommon.BuildInfo; import com.versionone.integration.ciCommon.V1Worker; import jetbrains.buildServer.messages.Status; import jetbrains.buildServer.serverSide.BuildServerAdapter; import jetbrains.buildServer.serverSide.SBuildServer; import jetbrains.buildServer.serverSide.SRunningBuild; import jetbrains.buildServer.serverSide.WebLinks; import jetbrains.buildServer.vcs.SVcsModification; import jetbrains.buildServer.vcs.SelectPrevBuildPolicy; import org.jetbrains.annotations.NotNull; import java.util.Date; import java.util.List; /** * This class is registered in TeamCity and receives all necessary events. */ public class V1ServerListener extends BuildServerAdapter { private static final Logger LOG = Logger.getInstance(V1ServerListener.class.getName()); public static final String PLUGIN_NAME = "TeamCityNotificator"; private final SBuildServer myBuildServer; private final V1Worker myWorker; private final WebLinks weblinks; private final FileConfig myConfig; public V1ServerListener(SBuildServer server, WebLinks links) { myBuildServer = server; weblinks = links; myConfig = new FileConfig(server.getConfigDir()); myWorker = new V1Worker(myConfig); } public void register() { LOG.info("V1ServerListener.register()"); myBuildServer.addListener(this); } @Override public void buildFinished(SRunningBuild runningBuild) { LOG.info("V1ServerListener.buildFinished(): " + runningBuild); LOG.info("url=" + myConfig.getUrl() + " user=" + myConfig.getUserName() + " password="+myConfig.getPassword()); final TCBuildInfo buildInfo = new TCBuildInfo(runningBuild, weblinks, myConfig); if (buildInfo.isCorrect()) { int result = myWorker.submitBuildRun(buildInfo); LOG.info("V1ServerListener submitBuildRun result=" + result); } else LOG.error("BuildInfo was not correct"); } public FileConfig getConfig() { return myConfig; } /** * This class is a adapter of TeamCity {@link jetbrains.buildServer.serverSide.SRunningBuild} to {@link BuildInfo}. */ static class TCBuildInfo implements BuildInfo { private final SRunningBuild build; private final WebLinks weblinks; private final FileConfig myConfig; TCBuildInfo(SRunningBuild build, WebLinks weblinks, FileConfig myConfig) { this.build = build; this.weblinks = weblinks; this.myConfig = myConfig; } @SuppressWarnings({"ConstantConditions"}) public String getProjectName() { if (myConfig.isFullyQualifiedBuildName()) { return build.getBuildType().getFullName(); } else { return build.getBuildType().getProjectName(); } } public long getBuildId() { return build.getBuildId(); } public Date getStartTime() { return build.getStartDate(); } public long getElapsedTime() { return build.getElapsedTime() * 1000; } public boolean isSuccessful() { return build.getBuildStatus().isSuccessful(); } public boolean isForced() { return build.getTriggeredBy().isTriggeredByUser(); } public List<SVcsModification> getChanges() { build.getChanges(SelectPrevBuildPolicy.SINCE_LAST_BUILD, true); return build.getContainingChanges(); } /** * Return URL to the current build results. * * @return url to the TeamCity with info about build */ @NotNull public String getUrl() { return weblinks.getViewResultsUrl(build); } public String getBuildName() { return build.getBuildNumber(); } public boolean isCorrect() { return build.getBuildStatus() != Status.UNKNOWN && build.getBuildType() != null; } } }
package org.jaxen.function; import java.util.List; import org.jaxen.Context; import org.jaxen.Function; import org.jaxen.FunctionCallException; import org.jaxen.Navigator; public class NormalizeSpaceFunction implements Function { public Object call(Context context, List args) throws FunctionCallException { if (args.size() >= 1) { return evaluate( args.get(0), context.getNavigator() ); } throw new FunctionCallException( "normalize-space() requires one argument" ); } public static String evaluate(Object strArg, Navigator nav) { String str = StringFunction.evaluate( strArg, nav ); char[] buffer = str.toCharArray(); int write = 0; int lastWrite = 0; boolean wroteOne = false; int read = 0; while (read < buffer.length) { if (Character.isWhitespace(buffer[read])) { if (wroteOne) { buffer[write++] = ' '; } do { read++; } while(read < buffer.length && Character.isWhitespace(buffer[read])); } else { buffer[write++] = buffer[read++]; wroteOne = true; lastWrite = write; } } return new String(buffer, 0, lastWrite); } }
package com.fisheradelakin.floridaman; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends Activity { public static final String URL = "http: private static final String TAG_TITLE = "title"; private static final String TAG_URL = "url"; ListView listView; ArrayList<HashMap<String,String>> newsList = new ArrayList<HashMap<String, String>>(); TextView title; TextView desc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button newStoryButton = (Button) findViewById(R.id.showAnotherStoryButton); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { if (isNetworkAvailable()) { new JSONParse().execute(); } } }; newStoryButton.setOnClickListener(listener); } private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); boolean isAvailable = false; if(networkInfo != null && networkInfo.isConnected()) { isAvailable = true; } else { Toast.makeText(this, "No network. Sorry, jokes are not available.", Toast.LENGTH_SHORT).show(); } return isAvailable; } private class JSONParse extends AsyncTask<String, String, JSONObject> { private ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); title = (TextView)findViewById(R.id.title); desc = (TextView)findViewById(R.id.desc); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Getting New Stories ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected JSONObject doInBackground(String... args) { JSONParser jParser = new JSONParser(); // Getting JSON from URL JSONObject json = jParser.getJsonFromUrl(URL); return json; } @Override protected void onPostExecute(JSONObject json) { pDialog.dismiss(); try { JSONObject response = json.getJSONObject("data"); System.out.println(response); //JSONObject data = response.getJSONObject("data"); JSONArray hotTopics = response.getJSONArray("children"); for(int i=0; i<hotTopics.length(); i++) { JSONObject topic = hotTopics.getJSONObject(i).getJSONObject("data"); String title = topic.getString(TAG_TITLE); String url = topic.getString(TAG_URL); HashMap<String, String> map = new HashMap<String, String>(); map.put(TAG_TITLE, title); map.put(TAG_URL, url); newsList.add(map); listView=(ListView)findViewById(R.id.list); ListAdapter adapter = new SimpleAdapter(MainActivity.this, newsList, R.layout.list_item, new String[] { TAG_TITLE,TAG_URL}, new int[] { R.id.title, R.id.desc}); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(desc.getText().toString())); startActivity(i); } }); System.out.println(title); System.out.println(url); } } catch (Exception e) { e.printStackTrace(); } } } }
package dyvil.tools.compiler.ast.access; import dyvil.reflect.Modifiers; import dyvil.tools.compiler.ast.classes.IClass; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.expression.IValue; import dyvil.tools.compiler.ast.field.IDataMember; import dyvil.tools.compiler.ast.generic.ITypeContext; import dyvil.tools.compiler.ast.method.IMethod; import dyvil.tools.compiler.ast.parameter.EmptyArguments; import dyvil.tools.compiler.ast.structure.IClassCompilableList; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.IType.TypePosition; import dyvil.tools.compiler.backend.MethodWriter; import dyvil.tools.compiler.backend.exception.BytecodeException; import dyvil.tools.compiler.util.Markers; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.ast.IASTNode; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.position.ICodePosition; public final class ClassAccess implements IValue { protected ICodePosition position; protected IType type; public ClassAccess(IType type) { this.type = type; } public ClassAccess(ICodePosition position, IType type) { this.position = position; this.type = type; } @Override public ICodePosition getPosition() { return this.position; } @Override public void setPosition(ICodePosition position) { this.position = position; } @Override public boolean isConstant() { return true; } @Override public int valueTag() { return CLASS_ACCESS; } @Override public boolean isPrimitive() { return false; } @Override public boolean isResolved() { return this.type.isResolved(); } @Override public IType getType() { return this.type; } @Override public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context) { if (type.isSuperTypeOf(this.type)) { return this; } return null; } @Override public boolean isType(IType type) { return type.isSuperTypeOf(this.type); } @Override public void resolveTypes(MarkerList markers, IContext context) { this.type = this.type.resolveType(null, context); } @Override public IValue resolve(MarkerList markers, IContext context) { this.type.resolve(markers, context); final Name name = this.type.getName(); final IDataMember field = context.resolveField(name); if (field != null) { final FieldAccess fieldAccess = new FieldAccess(this.position); fieldAccess.name = name; fieldAccess.field = field; return fieldAccess; } final IMethod method = IContext.resolveMethod(context, null, name, EmptyArguments.INSTANCE); if (method != null) { final MethodCall methodCall = new MethodCall(this.position); methodCall.name = name; methodCall.method = method; methodCall.dotless = true; methodCall.arguments = EmptyArguments.INSTANCE; return methodCall; } return this; } @Override public void checkTypes(MarkerList markers, IContext context) { this.type.checkType(markers, context, TypePosition.TYPE); if (!this.type.isResolved()) { markers.add(Markers.semantic(this.position, this.type.isArrayType() ? "resolve.type" : "resolve.any", this.type.toString())); } } @Override public void check(MarkerList markers, IContext context) { this.type.check(markers, context); if (!this.type.isResolved()) { // Already reported this in CHECK_TYPES return; } final IClass iclass = this.type.getTheClass(); if (iclass != null && iclass.hasModifier(Modifiers.OBJECT_CLASS)) { // Object type, we can safely use it's instance field. return; } markers.add(Markers.semantic(this.position, "type.access.invalid", this.type.toString())); } @Override public IValue foldConstants() { return this; } @Override public IValue cleanup(IContext context, IClassCompilableList compilableList) { return this; } @Override public void writeExpression(MethodWriter writer, IType type) throws BytecodeException { IClass iclass = this.type.getTheClass(); if (iclass != null) { IDataMember field = iclass.getMetadata().getInstanceField(); if (field != null) { field.writeGet(writer, null, this.getLineNumber()); return; } } throw new BytecodeException("Object access was not compiled correctly"); } @Override public String toString() { return IASTNode.toString(this); } @Override public void toString(String prefix, StringBuilder buffer) { this.type.toString(prefix, buffer); } }
package io.ebean.docker.commands; import io.ebean.docker.commands.process.ProcessHandler; import io.ebean.docker.container.Container; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class PostgresContainer extends DbContainer implements Container { /** * Create Postgres container with configuration from properties. */ public static PostgresContainer create(String pgVersion, Properties properties) { return new PostgresContainer(new PostgresConfig(pgVersion, properties)); } private static final Logger log = LoggerFactory.getLogger(Commands.class); /** * Create with configuration. */ public PostgresContainer(PostgresConfig config) { super(config); } /** * Start the container and wait for it to be ready. * <p> * This checks if the container is already running. * </p> * <p> * Returns false if the wait for ready was unsuccessful. * </p> */ @Override public boolean startWithCreate() { startMode = Mode.Create; if (startIfNeeded() && fastStart()) { // container was running, fast start enabled and passed // so skip the usual checks for user, extensions and connectivity return true; } if (!waitForDatabaseReady()) { log.warn("Failed waitForDatabaseReady for container {}", config.containerName()); return false; } createUser(true); createDatabase(true); createDatabaseExtensions(); if (!waitForConnectivity()) { log.warn("Failed waiting for connectivity"); return false; } return true; } /** * Start with a drop and create of the database and user. */ @Override public boolean startWithDropCreate() { startMode = Mode.DropCreate; startIfNeeded(); if (!waitForDatabaseReady()) { log.warn("Failed waitForDatabaseReady for container {}", config.containerName()); return false; } if (!dropDatabaseIfExists() || !dropUserIfExists()) { // failed to drop existing db or user return false; } if (!createUser(false) || !createDatabase(false)) { // failed to create the db or user return false; } createDatabaseExtensions(); if (!waitForConnectivity()) { log.warn("Failed waiting for connectivity"); return false; } return true; } @Override protected boolean isDatabaseAdminReady() { return execute("datname", showDatabases()); } @Override protected boolean isFastStartDatabaseExists() { return databaseExists(dbConfig.getDbName()); } /** * Return true if the database exists. */ public boolean databaseExists(String dbName) { return !hasZeroRows(databaseExistsFor(dbName)); } /** * Return true if the database user exists. */ public boolean userExists(String dbUser) { return !hasZeroRows(roleExistsFor(dbUser)); } /** * Create the database user. */ public boolean createUser(boolean checkExists) { String extraDbUser = getExtraDbUser(); if (defined(extraDbUser) && (!checkExists || !userExists(extraDbUser))) { if (!createUser(extraDbUser, getWithDefault(dbConfig.getExtraDbPassword(), dbConfig.getPassword()))) { log.error("Failed to create extra database user " + extraDbUser); } } if (checkExists && userExists(dbConfig.getUsername())) { return true; } return createUser(dbConfig.getUsername(), dbConfig.getPassword()); } /** * Maybe return an extra user to create. * <p> * The extra user will default to be the same as the extraDB if that is defined. * Additionally we don't create an extra user IF it is the same as the main db user. */ private String getExtraDbUser() { String extraUser = getWithDefault(dbConfig.getExtraDbUser(), dbConfig.getExtraDb()); return extraUser != null && !extraUser.equals(dbConfig.getUsername()) ? extraUser : null; } private boolean createUser(String user, String pwd) { ProcessBuilder pb = createRole(user, pwd); return execute("CREATE ROLE", pb, "Failed to create database user"); } /** * Create the database with the option of checking if if already exists. * * @param checkExists When true check the database doesn't already exists */ public boolean createDatabase(boolean checkExists) { String extraDb = dbConfig.getExtraDb(); if (defined(extraDb) && (!checkExists || !databaseExists(extraDb))) { String extraUser = getWithDefault(getExtraDbUser(), dbConfig.getUsername()); if (!createDatabase(extraDb, extraUser, dbConfig.getExtraDbInitSqlFile(), dbConfig.getExtraDbSeedSqlFile())) { log.error("Failed to create extra database " + extraDb); } } if (checkExists && databaseExists(dbConfig.getDbName())) { return true; } return createDatabase(dbConfig.getDbName(), dbConfig.getUsername(), dbConfig.getInitSqlFile(), dbConfig.getSeedSqlFile()); } @Override protected void executeSqlFile(String dbUser, String dbName, String containerFilePath) { ProcessBuilder pb = sqlFileProcess(dbUser, dbName, containerFilePath); executeWithout("ERROR", pb, "Error executing init sql file: " + containerFilePath); } private ProcessBuilder sqlFileProcess(String dbUser, String dbName, String containerFilePath) { List<String> args = new ArrayList<>(); args.add(config.docker); args.add("exec"); args.add("-i"); args.add(config.containerName()); args.add("psql"); args.add("-U"); args.add(dbUser); args.add("-d"); args.add(dbName); args.add("-f"); args.add(containerFilePath); return createProcessBuilder(args); } private boolean createDatabase(String dbName, String dbUser, String initSqlFile, String seedSqlFile) { ProcessBuilder pb = createDb(dbName, dbUser); if (execute("CREATE DATABASE", pb, "Failed to create database with owner")) { runDbSqlFile(dbName, dbUser, initSqlFile); runDbSqlFile(dbName, dbUser, seedSqlFile); return true; } return false; } private String getWithDefault(String value, String defaultValue) { return value == null ? defaultValue : value; } /** * Create the database extensions if defined. */ public void createDatabaseExtensions() { String dbExtn = dbConfig.getExtensions(); if (defined(dbExtn)) { if (defined(dbConfig.getExtraDb())) { createDatabaseExtensionsFor(dbExtn, dbConfig.getExtraDb()); } createDatabaseExtensionsFor(dbExtn, dbConfig.getDbName()); } } private void createDatabaseExtensionsFor(String dbExtn, String dbName) { List<String> extensions = new ArrayList<>(); for (String extension : dbExtn.split(",")) { extension = extension.trim(); if (!extension.isEmpty()) { extensions.add(extension); } } if (!extensions.isEmpty()) { ProcessHandler.process(createDatabaseExtension(extensions, dbName)); } } private ProcessBuilder createDatabaseExtension(List<String> extensions, String dbName) { //docker exec -i ut_postgres psql -U postgres -d test_db -c "create extension if not exists pgcrypto"; List<String> args = new ArrayList<>(); args.add(config.docker); args.add("exec"); args.add("-i"); args.add(config.containerName()); args.add("psql"); args.add("-U"); args.add("postgres"); args.add("-d"); args.add(dbName); for (String extension : extensions) { args.add("-c"); args.add("create extension if not exists " + extension); } return createProcessBuilder(args); } /** * Drop the database if it exists. */ public boolean dropDatabaseIfExists() { String extraDb = dbConfig.getExtraDb(); if (defined(extraDb) && !dropDatabaseIfExists(extraDb)) { log.error("Failed to drop extra database " + extraDb); } return dropDatabaseIfExists(dbConfig.getDbName()); } private boolean dropDatabaseIfExists(String dbName) { if (databaseExists(dbName)) { ProcessBuilder pb = dropDatabase(dbName); return execute("DROP DATABASE", pb, "Failed to drop database"); } return true; } /** * Drop the database user if it exists. */ public boolean dropUserIfExists() { String extraDbUser = getExtraDbUser(); if (defined(extraDbUser) && !dropUserIfExists(extraDbUser)) { log.error("Failed to drop extra database user " + extraDbUser); } return dropUserIfExists(dbConfig.getUsername()); } private boolean dropUserIfExists(String dbUser) { if (!userExists(dbUser)) { return true; } ProcessBuilder pb = dropUser(dbUser); return execute("DROP ROLE", pb, "Failed to drop database user"); } /** * Wait for the 'database system is ready' using pg_isready. * <p> * This means the DB is ready to take server side commands but TCP connectivity may still not be available yet. * </p> * * @return True when we detect the database is ready (to create user and database etc). */ public boolean isDatabaseReady() { try { return ProcessHandler.process(pgIsReady()).success(); } catch (RuntimeException e) { return false; } } private boolean hasZeroRows(ProcessBuilder pb) { return hasZeroRows(ProcessHandler.process(pb).getOutLines()); } private ProcessBuilder dropDatabase(String dbName) { return sqlProcess("drop database if exists " + dbName); } private ProcessBuilder dropUser(String dbUser) { return sqlProcess("drop role if exists " + dbUser); } private ProcessBuilder createDb(String dbName, String roleName) { return sqlProcess("create database " + dbName + " with owner " + roleName); } private ProcessBuilder createRole(String roleName, String pass) { return sqlProcess("create role " + roleName + " password '" + pass + "' login createrole"); } private ProcessBuilder roleExistsFor(String roleName) { return sqlProcess("select rolname from pg_roles where rolname = '" + roleName + "'"); } private ProcessBuilder databaseExistsFor(String dbName) { return sqlProcess("select 1 from pg_database where datname = '" + dbName + "'"); } private ProcessBuilder showDatabases() { return sqlProcess("select datname from pg_database"); } private ProcessBuilder sqlProcess(String sql) { List<String> args = new ArrayList<>(); args.add(config.docker); args.add("exec"); args.add("-i"); args.add(config.containerName()); args.add("psql"); args.add("-U"); args.add("postgres"); args.add("-c"); args.add(sql); return createProcessBuilder(args); } @Override protected ProcessBuilder runProcess() { List<String> args = new ArrayList<>(); args.add(config.docker); args.add("run"); args.add("-d"); args.add("--name"); args.add(config.containerName()); args.add("-p"); args.add(config.getPort() + ":" + config.getInternalPort()); if (dbConfig.isInMemory() && dbConfig.getTmpfs() != null) { args.add("--tmpfs"); args.add(dbConfig.getTmpfs()); } args.add("-e"); args.add(dbConfig.getAdminPassword()); args.add(config.getImage()); return createProcessBuilder(args); } private ProcessBuilder pgIsReady() { List<String> args = new ArrayList<>(); args.add(config.docker); args.add("exec"); args.add("-i"); args.add(config.containerName()); args.add("pg_isready"); args.add("-h"); args.add("localhost"); args.add("-p"); args.add(config.getInternalPort()); return createProcessBuilder(args); } private boolean hasZeroRows(List<String> stdOutLines) { return stdoutContains(stdOutLines, "(0 rows)"); } }
package com.getirkit.example.activity; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; //import com.getirkit.example.adapter.TriggerListAdapter; import com.getirkit.example.Settings.GrobalSettings; import com.getirkit.example.activity.DBManager.IRkitDBManager; import com.getirkit.example.activity.datatable.DTableINFRARED; import com.getirkit.example.adapter.TriggerListAdapter; import com.getirkit.example.fragment.TriggersFragment; import com.getirkit.irkit.IRKit; import com.getirkit.irkit.IRKitEventListener; import com.getirkit.irkit.IRPeripheral; import com.getirkit.irkit.IRPeripherals; import com.getirkit.irkit.IRSignal; import com.getirkit.irkit.activity.DeviceActivity; import com.getirkit.irkit.activity.IRKitSetupActivity; import com.getirkit.irkit.activity.SignalActivity; import com.getirkit.irkit.activity.WaitSignalActivity; import com.getirkit.example.R; import com.getirkit.example.adapter.DeviceListAdapter; import com.getirkit.example.adapter.SignalListAdapter; import com.getirkit.example.fragment.DevicesFragment; import com.getirkit.example.fragment.NavigationDrawerFragment; import com.getirkit.example.fragment.SelectSignalActionDialogFragment; import com.getirkit.example.fragment.SignalsFragment; import com.getirkit.irkit.net.IRAPIError; import com.getirkit.irkit.net.IRAPIResult; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, IRKitEventListener, TriggersFragment.TriggersFragmentListener,DevicesFragment.DevicesFragmentListener, SelectSignalActionDialogFragment.SelectSignalActionDialogFragmentListener, SignalsFragment.SignalsFragmentListener { public static final String TAG = MainActivity.class.getSimpleName(); // Activity request codesa private static final int REQUEST_IRKIT_SETUP = 1; private static final int REQUEST_SIGNAL_DETAIL = 2; private static final int REQUEST_WAIT_SIGNAL = 3; private static final int REQUEST_DEVICE_DETAIL = 4; private static final int REQUEST_TRIGGER_SETUP =5; private int currentSection; private int editingPeripheralPosition = -1; private int selectedSignalPosition = -1; private SignalListAdapter signalListAdapter; private DeviceListAdapter deviceListAdapter; private TriggerListAdapter triggerListAdapter; /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IRkitDBManager manager = new IRkitDBManager(getApplicationContext()); //manager.ALLDeleteINFRARED(); ArrayList<DTableINFRARED> lst = new ArrayList<DTableINFRARED>(); lst = manager.selectAllINFRARED(); for (DTableINFRARED infra: lst ) { Log.d(TAG,"MainActivity:90 "+infra.getREDID()); Log.d(TAG,infra.getREDPATTERN()); } //Intent intent = new Intent(this, WifiConf.class); //startActivity(intent); mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); if (mTitle == null) { mTitle = getTitle(); } // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); if (savedInstanceState != null) { editingPeripheralPosition = savedInstanceState.getInt("editingPeripheralPosition"); selectedSignalPosition = savedInstanceState.getInt("selectedSignalPosition"); } IRKit irkit = IRKit.sharedInstance(); irkit.setIRKitEventListener(this); // Set context, then initialize if not initialized yet. // context // contextOK irkit.init(getApplicationContext()); // Show dialog after orientation change (support library bug?) showSelectSignalActionDialogIfNeeded(); } /** * Show SelectSignalActionDialog if the dialog exists in fragment manager. */ private void showSelectSignalActionDialogIfNeeded() { final SelectSignalActionDialogFragment dialog = (SelectSignalActionDialogFragment) getSupportFragmentManager().findFragmentByTag("SelectSignalActionDialogFragment"); if (dialog != null) { new Handler().post(new Runnable() { @Override public void run() { dialog.show(getSupportFragmentManager(), "SelectSignalActionDialogFragment"); } }); } } /** * Save UI state * * @param outState */ @Override protected void onSaveInstanceState(Bundle outState) { // Save UI state changes to the outState. // This bundle will be passed to onCreate if the process is // killed and restarted. outState.putInt("editingPeripheralPosition", editingPeripheralPosition); outState.putInt("selectedSignalPosition", selectedSignalPosition); super.onSaveInstanceState(outState); } @Override protected void onResume() { super.onResume(); IRKit irkit = IRKit.sharedInstance(); irkit.setIRKitEventListener(this); // Start Bonjour discovery // Bonjour irkit.startServiceDiscovery(); // Watch Wi-Fi state change // Wi-Fi irkit.registerWifiStateChangeListener(); // Get clientkey if we have not received it yet // clientkey irkit.registerClient(); } @Override protected void onPause() { super.onPause(); IRKit irkit = IRKit.sharedInstance(); // Stop Bonjour discovery // Bonjour irkit.stopServiceDiscovery(); // Unset listener irkit.setIRKitEventListener(null); // Unwatch Wi-Fi state change // Wi-Fi irkit.unregisterWifiStateChangeListener(); } @Override public void onNavigationDrawerItemSelected(int position) { String tag = String.valueOf(position + 1); Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag); if (fragment == null) { if (position == 0) { // Signals (Buttons) fragment = SignalsFragment.newInstance(position + 1); } else if (position == 1) { // Devices fragment = DevicesFragment.newInstance(position + 1); } else if (position == 2) { //trigger fragment = TriggersFragment.newInstance(position + 1); }else{ throw new IllegalStateException("Unknown drawer item position: " + position); } } // update the main content by replacing fragments FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, fragment, tag) .commit(); } public void onSectionAttached(int number) { currentSection = number; switch (number) { case 1: mTitle = getString(R.string.title_signals); break; case 2: mTitle = getString(R.string.title_devices); break; case 3: mTitle = "Trigger"; break; } } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. if (currentSection == 1) { // Signals (Buttons) getMenuInflater().inflate(R.menu.signals, menu); } else if (currentSection == 2) { // Devices getMenuInflater().inflate(R.menu.devices, menu); }else if (currentSection == 3){ //triggers getMenuInflater().inflate(R.menu.triger, menu); } restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @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.menu_signals__add) { // Start WaitSignalActivity Intent intent = new Intent(this, WaitSignalActivity.class); startActivityForResult(intent, REQUEST_WAIT_SIGNAL); return true; } else if (id == R.id.menu_devices__add) { // Start IRKitSetupActivity Intent intent = new Intent(this, IRKitSetupActivity.class); startActivityForResult(intent, REQUEST_IRKIT_SETUP); return true; }else if (id == R.id.triggers__listview){ Intent intent = new Intent(this, TriggersFragment.class); startActivity(intent); //startActivityForResult } return super.onOptionsItemSelected(item); } //VoiceConf public void VoiceIntent(){ Intent intent = new Intent(this, VoiceConf.class); startActivity(intent); } //wifiConf public void WifiIntent(){ Intent intent = new Intent(this,WifiConf.class); startActivity(intent); } //WeatherConf public void WeatherIntent(){ Intent intent = new Intent(this,WeatherConf.class); startActivity(intent); } //CallConf public void CallIntent(){ Intent intent = new Intent(this,CallConf.class); startActivity(intent); } //TimerConf public void TimerIntent(){ Intent intent = new Intent(this,TimerConf.class); startActivity(intent); } @Override public void onActivityResult(int requestCode, int resultCode ,Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IRKIT_SETUP) { // Returned from IRKitSetupActivity if (resultCode == RESULT_OK) { if (deviceListAdapter != null) { deviceListAdapter.notifyDataSetChanged(); } } } else if (requestCode == REQUEST_WAIT_SIGNAL) { // Returned from WaitSignalActivity if (resultCode == RESULT_OK) { Log.d(TAG,""+data.getExtras()); Bundle args = data.getExtras(); IRSignal signal = args.getParcelable("signal"); IRkitDBManager manager = new IRkitDBManager(this); manager.insertINFRARED(signal.toString()); if (signal == null) { Log.e(TAG, "failed to receive signal"); return; } Log.d(TAG, "received signal: " + signal); IRKit irkit = IRKit.sharedInstance(); signal.setId(irkit.signals.getNewId()); if (signal.hasBitmapImage()) { // Do not call renameToSuggestedImageFilename before // assigning an ID to the signal. if (!signal.renameToSuggestedImageFilename(this)) { Log.e(TAG, "Failed to rename bitmap file"); } } // Add and save the signal irkit.signals.add(signal); irkit.signals.save(); if (signalListAdapter != null) { signalListAdapter.notifyDataSetChanged(); } } } else if (requestCode == REQUEST_DEVICE_DETAIL) { // Returned from DeviceActivity if (resultCode == RESULT_OK) { Bundle args = data.getExtras(); String action = args.getString("action"); IRPeripheral peripheral = args.getParcelable("peripheral"); switch (action) { case "save": saveEditingPeripheral(peripheral); break; case "delete": deleteEditingPeripheral(); break; default: Log.e(TAG, "unknown action: " + action); break; } } editingPeripheralPosition = -1; } else if (requestCode == REQUEST_SIGNAL_DETAIL) { if (resultCode == RESULT_OK) { Bundle args = data.getExtras(); String action = args.getString("action"); IRSignal signal = args.getParcelable("signal"); IRKit irkit = IRKit.sharedInstance(); switch (action) { case "save": if (selectedSignalPosition != -1) { IRSignal signalToEdit = irkit.signals.get(selectedSignalPosition); if (signalToEdit != null) { signalToEdit.copyFrom(signal, this); } irkit.signals.save(); if (signalListAdapter != null) { signalListAdapter.notifyDataSetChanged(); } } break; case "delete": if (selectedSignalPosition != -1) { irkit.signals.remove(selectedSignalPosition); irkit.signals.save(); if (signalListAdapter != null) { signalListAdapter.notifyDataSetChanged(); } } break; default: Log.e(TAG, "unknown action: " + action); break; } } selectedSignalPosition = -1; } else { } Log.e(TAG, "unknown requestCode: " + requestCode); } private void saveEditingPeripheral(IRPeripheral peripheral) { if (editingPeripheralPosition == -1) { Log.e(TAG, "invalid editingPeripheral"); return; } IRPeripherals peripherals = IRKit.sharedInstance().peripherals; IRPeripheral editingPeripheral = peripherals.get(editingPeripheralPosition); if (editingPeripheral == null) { Log.e(TAG, "editingPeripheral is null"); return; } editingPeripheral.setCustomizedName(peripheral.getCustomizedName()); peripherals.save(); if (deviceListAdapter != null) { deviceListAdapter.notifyDataSetChanged(); } } private void deleteEditingPeripheral() { if (editingPeripheralPosition == -1) { Log.e(TAG, "Invalid editingPeripheral"); return; } IRPeripheral peripheral = IRKit.sharedInstance().peripherals.get(editingPeripheralPosition); if (peripheral == null) { Log.e(TAG, "editingPeripheral is null"); return; } // Remove device and also signals tied to the device IRKit irkit = IRKit.sharedInstance(); IRPeripheral removedPeripheral = irkit.peripherals.remove(editingPeripheralPosition); irkit.peripherals.save(); irkit.signals.removeIRSignalsForDeviceId(removedPeripheral.getDeviceId()); irkit.signals.save(); if (deviceListAdapter != null) { deviceListAdapter.notifyDataSetChanged(); } } /** * Called when a new IRKit is found. * IRKit * * @param peripheral */ @Override public void onNewIRKitFound(IRPeripheral peripheral) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, R.string.new_irkit_found, Toast.LENGTH_SHORT).show(); if (deviceListAdapter != null) { deviceListAdapter.notifyDataSetChanged(); } } }); } /** * Called when an existing IRKit is found. * IRKit * * @param peripheral */ @Override public void onExistingIRKitFound(IRPeripheral peripheral) { } @Override public void onDeviceClick(int position) { final IRPeripheral peripheral = IRKit.sharedInstance().peripherals.get(position); // Start DeviceActivity Bundle args = new Bundle(); args.putParcelable("peripheral", peripheral); editingPeripheralPosition = position; Intent intent = new Intent(this, DeviceActivity.class); intent.putExtras(args); startActivityForResult(intent, MainActivity.REQUEST_DEVICE_DETAIL); } @Override public void onSelectSignalActionSend() { /* if (selectedSignalPosition == -1) { return; }*/ //final IRSignal signal = IRKit.sharedInstance().signals.get(selectedSignalPosition); final IRSignal signal = IRKit.sharedInstance().signals.get(1); Log.d(TAG, "MainActivity:499"+signal); if (signal != null) { IRKit.sharedInstance().sendSignal(signal, new IRAPIResult() { @Override public void onSuccess() { } @Override public void onError(IRAPIError error) { String msg = "Error sending " + signal.getName() + ": " + error.message; Log.e(TAG, msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } @Override public void onTimeout() { String msg = "Error sending " + signal.getName() + ": timeout"; Log.e(TAG, msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); } } @Override public void onSelectSignalActionEdit() { if (selectedSignalPosition == -1) { return; } final IRSignal signal = IRKit.sharedInstance().signals.get(selectedSignalPosition); if (signal != null) { // Start SignalActivity Bundle args = new Bundle(); args.putInt("mode", SignalActivity.MODE_EDIT); args.putParcelable("signal", signal); Intent intent = new Intent(this, SignalActivity.class); intent.putExtras(args); startActivityForResult(intent, REQUEST_SIGNAL_DETAIL); } } @Override public void onSignalClick(int position) { selectedSignalPosition = position; SelectSignalActionDialogFragment dialog = new SelectSignalActionDialogFragment(); dialog.show(getSupportFragmentManager(), "SelectSignalActionDialogFragment"); } public SignalListAdapter getSignalListAdapter() { return signalListAdapter; } public void setSignalListAdapter(SignalListAdapter signalListAdapter) { this.signalListAdapter = signalListAdapter; } public DeviceListAdapter getDeviceListAdapter() { return deviceListAdapter; } public void setDeviceListAdapter(DeviceListAdapter deviceListAdapter) { this.deviceListAdapter = deviceListAdapter; } public TriggerListAdapter getTriggerListAdapter() { return triggerListAdapter; } public void setTriggerListAdapter(TriggerListAdapter triggerListAdapter) { this.triggerListAdapter = triggerListAdapter; } @Override public void onTriggerClick(int position) { } }
package io.github.classgraph; import java.lang.reflect.Array; import java.util.Objects; import java.util.Set; /** A wrapper used to pair annotation parameter names with annotation parameter values. */ public class AnnotationParameterValue extends ScanResultObject implements Comparable<AnnotationParameterValue> { private String name; private ObjectTypedValueWrapper value; /** Default constructor for deserialization. */ AnnotationParameterValue() { } /** * @param name * The annotation paramater name. * @param value * The annotation parameter value. */ AnnotationParameterValue(final String name, final Object value) { this.name = name; this.value = new ObjectTypedValueWrapper(value); } /** @return The annotation parameter name. */ public String getName() { return name; } /** * @return The annotation parameter value. May be one of the following types: * <ul> * <li>String for string constants * <li>String[] for arrays of strings * <li>A boxed type, e.g. Integer or Character, for primitive-typed constants * <li>A 1-dimensional primitive-typed array (i.e. int[], long[], short[], char[], byte[], boolean[], * float[], or double[]), for arrays of primitives * <li>A 1-dimensional {@link Object}[] array for array types (and then the array element type may be * one of the types in this list) * <li>{@link AnnotationEnumValue}, for enum constants (this wraps the enum class and the string name of * the constant) * <li>{@link AnnotationClassRef}, for Class references within annotations (this wraps the name of the * referenced class) * <li>{@link AnnotationInfo}, for nested annotations * </ul> */ public Object getValue() { return value == null ? null : value.get(); } /** * Set (update) the value of the annotation parameter. Used to replace Object[] arrays containing boxed types * into primitive arrays. */ void setValue(final Object newValue) { this.value = new ObjectTypedValueWrapper(newValue); } @Override protected String getClassName() { // getClassInfo() is not valid for this type, so getClassName() does not need to be implemented throw new IllegalArgumentException("getClassName() cannot be called here"); } @Override protected ClassInfo getClassInfo() { throw new IllegalArgumentException("getClassInfo() cannot be called here"); } @Override void setScanResult(final ScanResult scanResult) { super.setScanResult(scanResult); if (value != null) { value.setScanResult(scanResult); } } /** Get the names of any classes referenced in the annotation parameters. */ @Override void getClassNamesFromTypeDescriptors(final Set<String> referencedClassNames) { if (value != null) { value.getClassNamesFromTypeDescriptors(referencedClassNames); } } /** * For primitive array type params, replace Object[] arrays containing boxed types with primitive arrays (need * to check the type of each method of the annotation class to determine if it is a primitive array type). */ void convertWrapperArraysToPrimitiveArrays(final ClassInfo annotationClassInfo) { if (value != null) { value.convertWrapperArraysToPrimitiveArrays(annotationClassInfo, name); } } /** Instantiate an annotation parameter value. */ Object instantiate(final ClassInfo annotationClassInfo) { return value.instantiateOrGet(annotationClassInfo, name); } @Override public String toString() { final StringBuilder buf = new StringBuilder(); toString(buf); return buf.toString(); } void toString(final StringBuilder buf) { buf.append(name); buf.append(" = "); toStringParamValueOnly(buf); } void toStringParamValueOnly(final StringBuilder buf) { if (value == null) { buf.append("null"); } else { final Object paramVal = value.get(); final Class<?> valClass = paramVal.getClass(); if (valClass.isArray()) { buf.append('{'); for (int j = 0, n = Array.getLength(paramVal); j < n; j++) { if (j > 0) { buf.append(", "); } final Object elt = Array.get(paramVal, j); buf.append(elt == null ? "null" : elt.toString()); } buf.append('}'); } else if (paramVal instanceof String) { buf.append('"'); buf.append(paramVal.toString().replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r")); buf.append('"'); } else if (paramVal instanceof Character) { buf.append('\''); buf.append(paramVal.toString().replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r")); buf.append('\''); } else { buf.append(paramVal.toString()); } } } @Override public int compareTo(final AnnotationParameterValue o) { final int diff = name.compareTo(o.getName()); if (diff != 0) { return diff; } // Use toString() order and get() (which can be slow) as a last-ditch effort -- only happens // if the annotation has multiple parameters of the same name but different value. final Object p0 = getValue(); final Object p1 = o.getValue(); if (p0 == null && p1 == null) { return 0; } else if (p0 == null && p1 != null) { return -1; } else if (p0 != null && p1 == null) { return 1; } return p0.toString().compareTo(p1.toString()); } @Override public boolean equals(final Object obj) { if (!(obj instanceof AnnotationParameterValue)) { return false; } final AnnotationParameterValue o = (AnnotationParameterValue) obj; return this.compareTo(o) == 0 && (value == null) == (o.value == null) && (value == null || value.equals(o.value)); } @Override public int hashCode() { return Objects.hash(name, value); } }
package uk.org.ulcompsoc.ld32.systems; import uk.org.ulcompsoc.ld32.components.Wallet; import uk.org.ulcompsoc.ld32.util.Mappers; import uk.org.ulcompsoc.ld32.util.TextureManager; import uk.org.ulcompsoc.ld32.util.TextureName; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector3; public class GUIRenderSystem extends IteratingSystem { final Batch batch; final TextureManager textureManager; private OrthographicCamera camera; //different textures private TextureRegion frame = null; private TextureRegion redBallIcon = null; private TextureRegion blueBallIcon = null; private TextureRegion greenBallIcon = null; private TextureRegion zero = null; private TextureRegion one = null; private TextureRegion two = null; private TextureRegion three = null; private TextureRegion four = null; private TextureRegion five = null; private TextureRegion six = null; private TextureRegion seven = null; private TextureRegion eight = null; private TextureRegion nine = null; // Default coordinates for drawing elements in predefined positions private final Vector3 DFLT_POSITION_OF_THE_FRAME = new Vector3(0.0f, 0.0f, 0.0f); private final Vector3 DFLT_POSITION_OF_THE_RED_BALL = new Vector3(120.0f, 150.0f, 0.0f); private final Vector3 DFLT_POSITION_OF_THE_BLUE_BALL = new Vector3(120.0f, 250.0f, 0.0f); private final Vector3 DFLT_POSITION_OF_THE_GREEN_BALL = new Vector3(120.0f, 350.f, 0.0f); private final Vector3 DFLT_RED_1_DIGIT_POSITION = new Vector3(120.0f, 72.0f, 0.0f); private final Vector3 DFLT_RED_2_DIGIT_POSITION = new Vector3(155.0f, 72.0f, 0.0f); private final Vector3 DFLT_BLUE_1_DIGIT_POSITION= null; private final Vector3 DFLT_BLUE_2_DIGIT_POSITION= null; private final Vector3 DFLT_GREEN_1_DIGIT_POSITION = null; private final Vector3 DFLT_GREEN_2_DIGIT_POSITION = null; private Vector3 temp; @SuppressWarnings("unchecked") public GUIRenderSystem(final Batch batch, final TextureManager textureManager, final OrthographicCamera cam, int priority) { super(Family.all(Wallet.class).get(), priority); this.batch = batch; this.textureManager = textureManager; this.camera = cam; this.frame = new TextureRegion(textureManager.nameMap.get(TextureName.FRAME_1)); this.redBallIcon = new TextureRegion(textureManager.nameMap.get(TextureName.BALL_R)); this.blueBallIcon = new TextureRegion(textureManager.nameMap.get(TextureName.BALL_B)); this.greenBallIcon = new TextureRegion(textureManager.nameMap.get(TextureName.BALL_G)); this.zero = new TextureRegion(textureManager.nameMap.get(TextureName.ZERO)); this.one = new TextureRegion(textureManager.nameMap.get(TextureName.ONE)); this.two = new TextureRegion(textureManager.nameMap.get(TextureName.TWO)); this.three = new TextureRegion(textureManager.nameMap.get(TextureName.THREE)); this.four = new TextureRegion(textureManager.nameMap.get(TextureName.FOUR)); this.five = new TextureRegion(textureManager.nameMap.get(TextureName.FIVE)); this.six = new TextureRegion(textureManager.nameMap.get(TextureName.SIX)); this.seven = new TextureRegion(textureManager.nameMap.get(TextureName.SEVEN)); this.eight = new TextureRegion(textureManager.nameMap.get(TextureName.EIGHT)); this.nine = new TextureRegion(textureManager.nameMap.get(TextureName.NINE)); } @Override protected void processEntity(Entity entity, float deltaTime) { Wallet wallet = Mappers.walletMapper.get(entity); camera.update(); temp = camera.unproject(DFLT_POSITION_OF_THE_FRAME.cpy()); batch.setProjectionMatrix(camera.combined); int redcount = wallet.red; int bluecount = wallet.blue; int greencount = wallet.green; final float scale = 0.68f; final float w = frame.getRegionWidth() * scale; final float h = frame.getRegionHeight() * scale; batch.begin(); batch.draw(frame, temp.x, temp.y - h, w, h); temp = camera.unproject(DFLT_POSITION_OF_THE_RED_BALL.cpy()); batch.draw(redBallIcon, temp.x, temp.y); temp = camera.unproject(DFLT_POSITION_OF_THE_BLUE_BALL.cpy()); batch.draw(blueBallIcon, temp.x, temp.y); temp = camera.unproject(DFLT_POSITION_OF_THE_GREEN_BALL.cpy()); batch.draw(greenBallIcon, temp.x, temp.y); this.handleRedCounter(redcount, batch); batch.end(); // batch.draw(textureManager., x, y, originX, originY, width, height, // scaleX, scaleY, rotation); } protected void handleRedCounter(int counter, Batch batch) { float scalefactor = 0.5f; float newWidth = zero.getRegionWidth()*scalefactor; float newHeight = zero.getRegionHeight()*scalefactor; String toBreakDown; if(counter>9){ if(counter>99){ toBreakDown = "99"; } else { toBreakDown = counter+""; } temp = camera.unproject(DFLT_RED_1_DIGIT_POSITION.cpy()); batch.draw(this.getNumber(Integer.parseInt(toBreakDown.substring(0, 1))), temp.x, (temp.y-newWidth), newWidth, newHeight); temp = camera.unproject(DFLT_RED_2_DIGIT_POSITION.cpy()); batch.draw(this.getNumber(Integer.parseInt(toBreakDown.substring(1))), temp.x, (temp.y-newWidth) ,newWidth, newHeight); } else { temp = camera.unproject(DFLT_RED_2_DIGIT_POSITION.cpy()); batch.draw(this.getNumber(counter), temp.x, (temp.y-newWidth),newWidth, newHeight); } } private TextureRegion getNumber(int number){ switch(number){ case 0: return this.zero; case 1: return this.one; case 2: return this.two; case 3: return this.three; case 4: return this.four; case 5: return this.five; case 6: return this.six; case 7: return this.seven; case 8: return this.eight; case 9: return this.nine; default: return null; } } }
package io.loli.sc.server.action; import io.loli.sc.server.entity.ClientToken; import io.loli.sc.server.entity.UploadedImage; import io.loli.sc.server.entity.User; import io.loli.sc.server.service.BucketService; import io.loli.sc.server.service.ClientTokenService; import io.loli.sc.server.service.FileFetchService; import io.loli.sc.server.service.UploadedImageService; import io.loli.sc.server.service.UserService; import io.loli.sc.server.storage.StorageUploader; import io.loli.util.string.MD5Util; import io.loli.util.string.ShortUrl; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Date; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; /** * * * @author choco * */ @Named @RequestMapping(value = { "/api" }) public class ImageClientUpload { @Inject private ClientTokenService cts; @Inject @Named("userService") private UserService us; @Inject private UploadedImageService uic; @Inject @Named("fileFetchService") private FileFetchService ffs; private Logger LOGGER = Logger.getLogger(ImageClientUpload.class); private static final String LOCAL_HOST = "127.0.0.1"; @RequestMapping(value = { "/token" }, method = { RequestMethod.GET, RequestMethod.POST }) @ResponseStatus(HttpStatus.OK) public @ResponseBody ClientToken requestToken( @RequestParam(required = true) String email, @RequestParam(required = true) String password) { User trueUser = us.findByEmail(email); String token = null; ClientToken ct = null; if (trueUser != null && trueUser.getPassword().equalsIgnoreCase(password)) { ct = cts.findByEmail(email); if (ct != null) { // emailtokentoken token = ct.getToken(); LOGGER.info(email + "tokentoken"); } else { // emailtokentoken ct = new ClientToken(); // md5 String word = trueUser.getEmail() + new java.util.Date().getTime(); try { token = MD5Util.hash(word); } catch (NoSuchAlgorithmException e) { LOGGER.error(e); } ct.setToken(token); ct.setUser(trueUser); cts.save(ct); LOGGER.info(email + "token"); } return ct; } return new ClientToken(); } @Inject private BucketService bucketService; @Inject private UserService userService; @RequestMapping(value = { "/upload" }, method = { RequestMethod.POST }) @ResponseStatus(HttpStatus.OK) public @ResponseBody UploadedImage upload( @RequestParam(value = "token", required = false) String token, @RequestParam(value = "email", required = false) String email, @RequestParam(value = "desc", required = false) String desc, @RequestParam(value = "image", required = true) MultipartFile imageFile, HttpServletRequest request) { UploadedImage imageObj = new UploadedImage(); imageObj.setDate(new Date()); if (email == null && desc == null && token == null) { imageObj.setDesc(imageFile.getOriginalFilename()); } else { if (!cts.checkTokenBelongToUser(token, email)) { LOGGER.info(email + "token"); return new UploadedImage(); } else { imageObj.setUser(userService.findByEmail(email)); } imageObj.setOriginName(desc); } User user = null; if ((user = (User) request.getSession().getAttribute("user")) != null) { imageObj.setUser(user); } String ip = request.getRemoteAddr(); if (ip != null && LOCAL_HOST.equals(ip)) { ip = request.getHeader("X-Real-IP"); } imageObj.setIp(ip); imageObj.setUa(request.getHeader("user-agent")); String fileName = ""; if (imageFile.getOriginalFilename().contains(".")) { fileName = ShortUrl.shortText(new Date().getTime() + imageFile.getOriginalFilename())[0]; } else { fileName = ShortUrl.shortText(new Date().getTime() + imageFile.getOriginalFilename())[0].toLowerCase(); } imageObj.setRedirectCode(fileName); File file = saveImage(imageFile, fileName); String ref = null; if ((ref = request.getHeader("REFERER")) != null) { if (ref.contains("file")) { imageObj.setStorageBucket(bucketService.randomFileBucket()); } else { imageObj.setStorageBucket(bucketService.randomImageBucket()); } } else { imageObj.setStorageBucket(bucketService.randomImageBucket()); } StorageUploader uploader = StorageUploader.newInstance(imageObj .getStorageBucket()); imageObj.setPath(uploader.upload(file)); imageObj.setOriginName(imageFile.getOriginalFilename()); uic.save(imageObj); if (imageObj.getUser() == null) { LOGGER.info(":" + imageObj.getOriginName() + ", " + imageObj.getPath()); } else { LOGGER.info(imageObj.getUser().getEmail() + ":" + imageObj.getOriginName() + ", " + imageObj.getPath()); } return imageObj; } @ResponseBody @RequestMapping(value = { "/fetch" }, method = { RequestMethod.POST }) public UploadedImage fetch(String path, HttpServletRequest request) { File imageFile = ffs.fetch(path); if (imageFile == null) { return new UploadedImage(); } User user = null; UploadedImage imageObj = new UploadedImage(); if ((user = (User) request.getSession().getAttribute("user")) != null) { imageObj.setUser(user); } String ip = request.getRemoteAddr(); if (ip != null && ip.equals("127.0.0.1")) { ip = request.getHeader("X-Real-IP"); } imageObj.setIp(ip); imageObj.setUa(request.getHeader("user-agent")); String ref = null; if ((ref = request.getHeader("REFERER")) != null) { if (ref.contains("file")) { imageObj.setStorageBucket(bucketService.randomFileBucket()); } else { imageObj.setStorageBucket(bucketService.randomImageBucket()); } } else { imageObj.setStorageBucket(bucketService.randomImageBucket()); } StorageUploader uploader = StorageUploader.newInstance(imageObj .getStorageBucket()); imageObj.setPath(uploader.upload(imageFile)); imageObj.setOriginName(imageFile.getName()); uic.save(imageObj); if (imageObj.getUser() == null) { LOGGER.info(":" + imageObj.getOriginName() + ", " + imageObj.getPath()); } else { LOGGER.info(imageObj.getUser().getEmail() + ":" + imageObj.getOriginName() + ", " + imageObj.getPath()); } return imageObj; } /** * * * @param image * @return File */ private File saveImage(MultipartFile image, String fileName) { if (image.getOriginalFilename().contains(".")) { fileName += "." // jpg,png + image.getOriginalFilename() .substring( image.getOriginalFilename() .lastIndexOf(".") + 1) .toLowerCase(); } File file = new File(System.getProperty("java.io.tmpdir"), fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdir(); } try { FileUtils.writeByteArrayToFile(file, image.getBytes()); } catch (IOException e) { LOGGER.error(e); } return file; } }
package me.nallar.modpatcher; import javassist.ClassLoaderPool; import me.nallar.javapatcher.patcher.Patcher; import me.nallar.javapatcher.patcher.Patches; import me.nallar.mixin.internal.MixinApplicator; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.LaunchClassLoader; import java.io.*; import java.nio.file.*; class ModPatcherTransformer { public static final ClassLoaderPool pool; private static final String MOD_PATCHES_DIRECTORY = "./ModPatches/"; private static final Patcher patcher; private static final String ALREADY_LOADED_PROPERTY_NAME = "nallar.ModPatcher.alreadyLoaded"; private static final String DUMP_PROPERTY_NAME = "nallar.ModPatcher.dump"; private static final boolean DUMP = !System.getProperty(DUMP_PROPERTY_NAME, "").isEmpty(); private static boolean classLoaderInitialised = false; private static MixinApplicator mixinApplicator; static { PatcherLog.info("ModPatcher running under classloader " + ModPatcherTransformer.class.getClassLoader().getClass().getName()); checkForMultipleClassLoads(); try { patcher = new Patcher(pool = new ClassLoaderPool(), Patches.class, new MCPMappings()); // TODO - issue #2. Determine layout/config file structure recursivelyAddXmlFiles(new File(MOD_PATCHES_DIRECTORY), patcher); } catch (Throwable t) { throw logError("Failed to create Patcher", t); } } private static Error logError(String message, Throwable t) { PatcherLog.error(message, t); return new Error(message, t); } private static void checkForMultipleClassLoads() { if (System.getProperty(ALREADY_LOADED_PROPERTY_NAME) != null) { Error e = logError("Detected multiple classloads of ModPatcher - classloading issue?", new Throwable()); if (!System.getProperty(ALREADY_LOADED_PROPERTY_NAME).equals("breakEverything")) throw e; } else { System.setProperty(ALREADY_LOADED_PROPERTY_NAME, "true"); } } static Patcher getPatcher() { return patcher; } @SuppressWarnings("deprecation") private static void recursivelyAddXmlFiles(File directory, Patcher patcher) { File[] files = directory.listFiles(); if (files == null) return; try { for (File f : files) { if (f.isDirectory()) { recursivelyAddXmlFiles(f, patcher); } else if (f.getName().endsWith(".xml")) { patcher.readPatchesFromXmlInputStream(new FileInputStream(f)); } else if (f.getName().endsWith(".json")) { patcher.readPatchesFromJsonInputStream(new FileInputStream(f)); } } } catch (IOException e) { PatcherLog.warn("Failed to load patch", e); } } static IClassTransformer getInstance() { return ClassTransformer.INSTANCE; } static void initialiseClassLoader(LaunchClassLoader classLoader) { if (classLoaderInitialised) return; classLoaderInitialised = true; classLoader.addTransformerExclusion("me.nallar.whocalled."); classLoader.addTransformerExclusion("me.nallar.javatransformer."); classLoader.addTransformerExclusion("me.nallar.javapatcher."); classLoader.addTransformerExclusion("me.nallar.mixin."); classLoader.addTransformerExclusion("javassist."); classLoader.addTransformerExclusion("com.github.javaparser."); LaunchClassLoaderUtil.instance = classLoader; ModPatcherTweaker.add(); LaunchClassLoaderUtil.addTransformer(ModPatcherTransformer.getInstance()); LaunchClassLoaderUtil.dumpTransformersIfEnabled(); LaunchClassLoaderUtil.removeRedundantExclusions(); } static String getDefaultPatchesDirectory() { return MOD_PATCHES_DIRECTORY; } static MixinApplicator getMixinApplicator() { MixinApplicator mixinApplicator = ModPatcherTransformer.mixinApplicator; if (mixinApplicator == null) { ModPatcherTransformer.mixinApplicator = mixinApplicator = new MixinApplicator(); mixinApplicator.setMakeAccessible(false); mixinApplicator.setNoMixinIsError(true); mixinApplicator.setLog(PatcherLog::info); } return mixinApplicator; } private static class ClassTransformer implements IClassTransformer { static IClassTransformer INSTANCE = new ClassTransformer(); private boolean init; private static void dumpIfEnabled(String name, byte[] data) { if (!DUMP || !name.contains("net.minecraft")) return; Path path = Paths.get("./DUMP/" + name + ".class"); try { Files.createDirectories(path.getParent()); Files.write(path, data); } catch (IOException e) { PatcherLog.error("Failed to dump class " + name, e); } } @Override public byte[] transform(String name, String transformedName, byte[] bytes) { if (!init) { init = true; patcher.logDebugInfo(); } dumpIfEnabled(transformedName + "_unpatched", bytes); final byte[] originalBytes = bytes; if (mixinApplicator != null) { bytes = getMixinApplicator().getMixinTransformer().transformClass(() -> originalBytes, transformedName).get(); } LaunchClassLoaderUtil.cacheSrgBytes(transformedName, bytes); try { bytes = patcher.patch(transformedName, bytes); } catch (Throwable t) { PatcherLog.error("Failed to patch " + transformedName, t); } finally { LaunchClassLoaderUtil.releaseSrgBytes(transformedName); } if (originalBytes != bytes) dumpIfEnabled(transformedName, bytes); return bytes; } } }
package jp.ac.nii.prl.mape.kb.controller; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import jp.ac.nii.prl.mape.kb.bx.BXRunner; import jp.ac.nii.prl.mape.kb.properties.HaskellProperties; @RestController @Component @RequestMapping("/kb") public class KBController { private final HaskellProperties haskellProperties; private final BXRunner bxRunner; private static final Logger logger = LoggerFactory.getLogger(KBController.class); @Autowired public KBController(HaskellProperties haskellProperties, BXRunner bxRunner) { this.haskellProperties = haskellProperties; this.bxRunner = bxRunner; } @RequestMapping(value="get/{bx}", method=RequestMethod.GET) public String getNoParam(@PathVariable String bx) { logger.info("Got GET request for BX " + bx); return get(bx, "nothing"); } @RequestMapping(value="get/{bx}/{param}", method=RequestMethod.GET) public String get(@PathVariable String bx, @PathVariable String param) { String view = ""; switch(bx) { case "failure": bxGet("autoscalingFailure", param); view = bxGet(bx, param); break; case "autoScaling": view = bxGet(bx, param); break; case "firewall": view = bxGet(bx, param); break; case "execution": view = bxGet(bx, param); break; default: throw new TransformationException(String.format("Cannot run transformation %s", bx)); } return view; } public String bxGet(String bx, String param) { logger.info(String.format("Running GET transformation %s with param %s", bx, param)); String view; try { view = bxRunner.get(bx, param, haskellProperties.getExecutable(), haskellProperties.getJsonPath()); } catch (IOException | InterruptedException e) { logger.error("Error in GET transformation " + bx); throw new TransformationException("Error in GET transformation"); } return view; } @RequestMapping(value="put/{bx}", method=RequestMethod.POST) public ResponseEntity<?> putNoParam(@PathVariable String bx, @RequestBody String view) { return put(bx, "nothing", view); } @RequestMapping(value="put/{bx}/{param}", method=RequestMethod.POST) public ResponseEntity<?> put(@PathVariable String bx, @PathVariable String param, @RequestBody String view) { boolean res = false; switch(bx) { case "failure": res = bxPut(bx, param, view); break; case "autoScaling": res = bxPut(bx, param, view); if (!res) break; res = bxPut("autoscalingFailure", param, ""); break; case "firewall": res = bxPut(bx, param, view); break; case "execution": res = bxPut(bx, param, view); break; default: logger.error(String.format("Can't perform put transformation %s", bx)); res = false; break; } if (!res) { HttpHeaders httpHeaders = new HttpHeaders(); return new ResponseEntity<>(null, httpHeaders, HttpStatus.INTERNAL_SERVER_ERROR); } // create response HttpHeaders httpHeaders = new HttpHeaders(); return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED); } public boolean bxPut(String bx, String param, String view) { logger.info(String.format("Running PUT transformation %s with param %s", bx, param)); if (bx == "autoscalingFailure") { } if (!bxRunner.put(bx, view, param, haskellProperties.getExecutable(), haskellProperties.getJsonPath())) { return false; } logger.info(String.format("PUT transformation %s completed", bx)); return true; } @RequestMapping(value="source", method=RequestMethod.POST) public ResponseEntity<?> updateSource(@RequestBody String source) { logger.info("Updating source"); Path path = Paths.get(haskellProperties.getJsonPath() + "source.json"); try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write(source); } catch (IOException ex) { logger.error(ex.getMessage()); logger.trace(ex.getStackTrace().toString()); HttpHeaders httpHeaders = new HttpHeaders(); return new ResponseEntity<>(null, httpHeaders, HttpStatus.FORBIDDEN); } logger.info("Source updated"); // create response HttpHeaders httpHeaders = new HttpHeaders(); return new ResponseEntity<>(null, httpHeaders, HttpStatus.OK); } }
package com.iuridiniz.checkmyecg; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Color; import android.net.Uri; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.support.v7.widget.ShareActionProvider; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import com.androidplot.xy.BoundaryMode; import com.androidplot.xy.LineAndPointFormatter; import com.androidplot.xy.PointLabelFormatter; import com.androidplot.xy.SimpleXYSeries; import com.androidplot.xy.XYPlot; import com.androidplot.xy.XYSeries; import com.androidplot.xy.XYStepMode; import com.iuridiniz.checkmyecg.filter.GraphFilter2; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.calib3d.Calib3d; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfDMatch; import org.opencv.core.MatOfKeyPoint; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.features2d.DMatch; import org.opencv.features2d.DescriptorExtractor; import org.opencv.features2d.DescriptorMatcher; import org.opencv.features2d.FeatureDetector; import org.opencv.features2d.KeyPoint; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Vector; public class ResultEkgActivity extends ActionBarActivity { public static final String EXTRA_PHOTO_URI = "com.iuridiniz.checkmyecg.ResultEkgActivity.extra.PHOTO_URI;"; public static final String EXTRA_PHOTO_DATA_PATH = "com.iuridiniz.checkmyecg.ResultEkgActivity.extra.DATA_PATH;"; public static final String EXTRA_SERIES_X = "com.iuridiniz.checkmyecg.ResultEkgActivity.extra.SERIES_X;"; public static final String EXTRA_SERIES_Y = "com.iuridiniz.checkmyecg.ResultEkgActivity.extra.SERIES_Y;"; static final String TAG = "ResultEkg"; private ShareActionProvider mShareActionProvider; private Uri mImageUri; private String mImageDataPath; private ImageView mImageContent; private TextView mTextContent; private boolean mOpenCvLoaded = false; private XYPlot mPlot; private double[] mSeriesX; private double[] mSeriesY; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result_ekg); final Intent intent = getIntent(); mSeriesX = intent.getDoubleArrayExtra(EXTRA_SERIES_X); mSeriesY = intent.getDoubleArrayExtra(EXTRA_SERIES_Y); mPlot = (XYPlot) findViewById(R.id.result_plot); mPlot.setVisibility(View.INVISIBLE); mTextContent = (TextView) findViewById(R.id.result_text); mTextContent.setText(""); /* init openCV */ if (OpenCVLoader.initDebug()) { Log.i(TAG, "OpenCV loaded successfully (static initialization)"); mOpenCvLoaded = true; onReady(savedInstanceState); return; } /* binaries not included, use OpenCV manager */ Log.i(TAG, "OpenCV libs not included on APK, trying async initialization"); OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_10, this, new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case BaseLoaderCallback.SUCCESS: Log.i(TAG, "OpenCV loaded successfully (async initialization)"); runOnUiThread(new Runnable() { @Override public void run() { mOpenCvLoaded = true; onReady(savedInstanceState); } }); break; default: super.onManagerConnected(status); break; } } }); } private void onReady(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.pick_derivation) .setItems(R.array.derivations_array, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, final int which) { // The 'which' argument contains the index position // of the selected item runOnUiThread(new Runnable() { @Override public void run() { ResultEkgActivity.this.compareWithDerivation(which); ResultEkgActivity.this.showEKG(); } }); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ResultEkgActivity.this.finish(); } }); Dialog d = builder.create(); d.show(); } private void showEKG() { // Create a couple arrays of y-values to plot: Number[] seriesX = {0, 1, 2, 3, 4, 5}; /* sample data */ Number[] seriesY = {1, 8, -5, 2, 7, 4}; /* sample data */ if (mSeriesX != null && mSeriesY != null) { seriesX = convertDoubleArrayToNumberArray(mSeriesX); seriesY = convertDoubleArrayToNumberArray(mSeriesY); } // Turn the above arrays into XYSeries': XYSeries series1 = new SimpleXYSeries( Arrays.asList(seriesX), Arrays.asList(seriesY), "EKG"); // Create a formatter to use for drawing a series using LineAndPointRenderer // and configure it from xml: LineAndPointFormatter series1Format = new LineAndPointFormatter(Color.BLACK, null, null, null); // add a new series' to the xyplot: mPlot.addSeries(series1, series1Format); mPlot.setVisibility(View.VISIBLE); mPlot.invalidate(); } private void compareWithDerivation(int derivationIndex) { String[] derivations = getResources().getStringArray(R.array.derivations_array); String derivation = derivations[derivationIndex]; Log.i(TAG, String.format("Comparing the ekg derivation '%s' with pathological base", derivation)); } @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_result_ekg, menu); // Set up ShareActionProvider's default share intent MenuItem shareItem = menu.findItem(R.id.action_share); mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, mTextContent.getText()); mShareActionProvider.setShareIntent(intent); return super.onCreateOptionsMenu(menu); } @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(); return super.onOptionsItemSelected(item); } public static Number[] convertDoubleArrayToNumberArray(double[] a) { Number[] r = new Number[a.length]; for (int i=0; i<a.length; i++) { r[i] = a[i]; } return r; } public static double[] convertNumberListToDoubleArray(List<Number> l) { double[] r = new double[l.size()]; for (int i=0; i<r.length; i++) { r[i] = (double) l.get(i); } return r; } }
package kalang.compiler.dependency; import org.apache.ivy.Ivy; import org.apache.ivy.core.cache.ArtifactOrigin; import org.apache.ivy.core.event.EventManager; import org.apache.ivy.core.event.download.StartArtifactDownloadEvent; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.report.ArtifactDownloadReport; import org.apache.ivy.core.report.ResolveReport; import org.apache.ivy.core.resolve.IvyNode; import org.apache.ivy.core.resolve.ResolveOptions; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.plugins.resolver.AbstractResolver; import org.apache.ivy.plugins.resolver.IBiblioResolver; import org.apache.ivy.util.Message; import org.apache.ivy.util.filter.FilterHelper; import org.apache.ivy.util.url.URLHandlerRegistry; import java.io.IOException; import java.text.ParseException; import java.util.*; public class DependencyResolver { private final List<String> repositories; public DependencyResolver() { this.repositories = Collections.EMPTY_LIST; } public DependencyResolver(Set<String> repositories){ this.repositories = new LinkedList<>(repositories); } /** * Resolve dependencies * @param artifacts * @return the result of resolution * @throws ResolveException if failed to resolve */ public ResolveResult resolve(Artifact[] artifacts){ try { return doResolve(artifacts); } catch (IOException | ParseException e) { throw new RuntimeException(e); } } private ResolveResult doResolve(Artifact[] artifacts) throws IOException, ParseException { Message.setDefaultLogger(new NoMessageLogger()); URLHandlerRegistry.setDefault(new ExtendURLHandler()); IvySettings settings = new IvySettings(); if (!this.repositories.isEmpty()) { int repoSize = repositories.size(); for(int i=0;i<repoSize;i++) { IBiblioResolver dr = new IBiblioResolver(); dr.setName("user-repo" + (i+1)); dr.setM2compatible(true); dr.setRoot(repositories.get(i)); settings.addResolver(dr); } } settings.loadDefault(); if (!this.repositories.isEmpty()) { settings.setDefaultResolver("user-repo1"); } EventManager eventManager = new EventManager(); eventManager.addIvyListener(event -> { if (event instanceof StartArtifactDownloadEvent) { ArtifactOrigin origin = ((StartArtifactDownloadEvent) event).getOrigin(); System.err.println("Downloading:" +origin.getLocation()); } }); Collection<org.apache.ivy.plugins.resolver.DependencyResolver> resolvers = settings.getResolvers(); for(org.apache.ivy.plugins.resolver.DependencyResolver r:resolvers) { if (r instanceof AbstractResolver) { ((AbstractResolver) r).setEventManager(eventManager); } } Ivy ivy = Ivy.newInstance(settings); ResolveOptions ops = new ResolveOptions(); //confs: [default, master, compile, provided, runtime, test, system, sources, javadoc, optional] ops.setConfs(new String[]{"default"}); ops.setArtifactFilter(FilterHelper.getArtifactTypeFilter("jar,bundle")); ModuleRevisionId[] mrids = new ModuleRevisionId[artifacts.length]; for(int i=0;i<artifacts.length;i++){ Artifact art = artifacts[i]; mrids[i] = ModuleRevisionId.newInstance(art.getGroup(),art.getName(),art.getVersion()); } DefaultModuleDescriptor moduleDescriptor = DefaultModuleDescriptor.newCallerInstance(mrids, true, false); ResolveReport res = ivy.resolve(moduleDescriptor, ops); ResolveResult result = new ResolveResult(); ArtifactDownloadReport[] reports = res.getAllArtifactsReports(); for(ArtifactDownloadReport r:reports) { result.addLocalFile(r.getLocalFile()); } IvyNode[] uds = res.getUnresolvedDependencies(); if (uds!=null && uds.length>0) { throw new ResolveException("failed to resolve artifact:" + uds[0].getId().toString()); } return result; } }