answer
stringlengths
17
10.2M
/* * $Id: TestPluginManager.java,v 1.26 2003-12-23 00:37:32 tlipkis Exp $ */ package org.lockss.plugin; import java.io.*; import java.net.*; import java.util.*; import junit.framework.*; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.poller.*; import org.lockss.util.*; import org.lockss.test.*; import org.lockss.repository.*; import org.lockss.poller.PollSpec; /** * Test class for org.lockss.plugin.PluginManager */ public class TestPluginManager extends LockssTestCase { private MockLockssDaemon theDaemon; static String mockPlugKey = "org|lockss|test|MockPlugin"; static Properties props1 = new Properties(); static Properties props2 = new Properties(); static { props1.setProperty(MockPlugin.CONFIG_PROP_1, "val1"); props1.setProperty(MockPlugin.CONFIG_PROP_2, "val2"); props2.setProperty(MockPlugin.CONFIG_PROP_1, "val1"); props2.setProperty(MockPlugin.CONFIG_PROP_2, "va.l3");//auid contains a dot } static String mauauidKey1 = PropUtil.propsToCanonicalEncodedString(props1); static String mauauid1 = mockPlugKey+"&"+ mauauidKey1; // static String m static String mauauidKey2 = PropUtil.propsToCanonicalEncodedString(props2); static String mauauid2 = mockPlugKey+"&"+mauauidKey2; static String p1param = PluginManager.PARAM_AU_TREE + "." + mockPlugKey + "."; static String p1a1param = p1param + mauauidKey1 + "."; static String p1a2param = p1param + mauauidKey2 + "."; static String configStr = p1a1param + MockPlugin.CONFIG_PROP_1 + "=val1\n" + p1a1param + MockPlugin.CONFIG_PROP_2 + "=val2\n" + p1a2param + MockPlugin.CONFIG_PROP_1 + "=val1\n" + p1a2param + MockPlugin.CONFIG_PROP_2 + "=va.l3\n" + // value contains a dot // needed to allow PluginManager to register AUs // leave value blank to allow 'doConfig()' to fill it in dynamically LockssRepositoryImpl.PARAM_CACHE_LOCATION + "="; PluginManager mgr; public TestPluginManager(String msg) { super(msg); } public void setUp() throws Exception { super.setUp(); theDaemon = new MockLockssDaemon(); mgr = new PluginManager(); theDaemon.setPluginManager(mgr); theDaemon.setDaemonInited(true); mgr.initService(theDaemon); } public void tearDown() throws Exception { mgr.stopService(); theDaemon.stopDaemon(); super.tearDown(); } private void doConfig() throws Exception { mgr.startService(); String localConfig = configStr + getTempDir().getAbsolutePath() + File.separator; ConfigurationUtil.setCurrentConfigFromString(localConfig); } private void minimalConfig() throws Exception { mgr.startService(); ConfigurationUtil.setFromArgs(LockssRepositoryImpl.PARAM_CACHE_LOCATION, getTempDir().getAbsolutePath() + File.separator); } public void testNameFromKey() { assertEquals("org.lockss.Foo", PluginManager.pluginNameFromKey("org|lockss|Foo")); } public void testKeyFromName() { assertEquals("org|lockss|Foo", PluginManager.pluginKeyFromName("org.lockss.Foo")); } public void testKeyFromId() { assertEquals("org|lockss|Foo", PluginManager.pluginKeyFromId("org.lockss.Foo")); } public void testEnsurePluginLoaded() throws Exception { // non-existent class shouldn't load String key = "org|lockss|NoSuchClass"; assertFalse(mgr.ensurePluginLoaded(key)); assertNull(mgr.getPlugin(key)); // MockPlugin should load assertTrue(mgr.ensurePluginLoaded(mockPlugKey)); Plugin p = mgr.getPlugin(mockPlugKey); assertTrue(p.toString(), p instanceof MockPlugin); MockPlugin mpi = (MockPlugin)mgr.getPlugin(mockPlugKey); assertNotNull(mpi); assertEquals(1, mpi.getInitCtr()); // should have been inited once // second time shouldn't reload, reinstantiate, or reinitialize plugin assertTrue(mgr.ensurePluginLoaded(mockPlugKey)); MockPlugin mpi2 = (MockPlugin)mgr.getPlugin(mockPlugKey); assertSame(mpi, mpi2); assertEquals(1, mpi.getInitCtr()); } public void testInitPluginRegistry() { String n1 = "org.lockss.test.MockPlugin"; String n2 = ThrowingMockPlugin.class.getName(); assertEmpty(mgr.getRegisteredPlugins()); ConfigurationUtil.setFromArgs(PluginManager.PARAM_PLUGIN_REGISTRY, n1 + ";" + n2); Plugin p1 = mgr.getPlugin(mgr.pluginKeyFromName(n1)); assertNotNull(p1); assertTrue(p1.toString(), p1 instanceof MockPlugin); Plugin p2 = mgr.getPlugin(mgr.pluginKeyFromName(n2)); assertNotNull(p2); assertTrue(p2.toString(), p2 instanceof ThrowingMockPlugin); assertEquals(2, mgr.getRegisteredPlugins().size()); ConfigurationUtil.setFromArgs(PluginManager.PARAM_PLUGIN_REGISTRY, n1); assertEquals(1, mgr.getRegisteredPlugins().size()); assertNull(mgr.getPlugin(mgr.pluginKeyFromName(n2))); assertNotNull(mgr.getPlugin(mgr.pluginKeyFromName(n1))); assertTrue(mgr.getPlugin(mgr.pluginKeyFromName(n1)) instanceof MockPlugin); } public void testInitTitleDB() { Properties p = new Properties(); p.put("org.lockss.title.1.foo", "foo1"); p.put("org.lockss.title.1.bar", "bar1"); p.put("org.lockss.title.2.bar", "bar2"); ConfigurationUtil.setCurrentConfigFromProps(p); } public void testStop() throws Exception { doConfig(); MockPlugin mpi = (MockPlugin)mgr.getPlugin(mockPlugKey); assertEquals(0, mpi.getStopCtr()); mgr.stopService(); assertEquals(1, mpi.getStopCtr()); } public void testAuConfig() throws Exception { doConfig(); MockPlugin mpi = (MockPlugin)mgr.getPlugin(mockPlugKey); // plugin should be registered assertNotNull(mpi); // should have been inited once assertEquals(1, mpi.getInitCtr()); // get the two archival units ArchivalUnit au1 = mgr.getAuFromId(mauauid1); ArchivalUnit au2 = mgr.getAuFromId(mauauid2); // verify the plugin's set of all AUs is {au1, au2} Collection aus = mpi.getAllAus(); assertEquals(SetUtil.set(au1, au2), new HashSet(mgr.getAllAus())); // verify au1's configuration assertEquals(mauauid1, au1.getAuId()); MockArchivalUnit mau1 = (MockArchivalUnit)au1; Configuration c1 = mau1.getConfiguration(); assertEquals("val1", c1.get(MockPlugin.CONFIG_PROP_1)); assertEquals("val2", c1.get(MockPlugin.CONFIG_PROP_2)); // verify au1's configuration assertEquals(mauauid2, au2.getAuId()); MockArchivalUnit mau2 = (MockArchivalUnit)au2; Configuration c2 = mau2.getConfiguration(); assertEquals("val1", c2.get(MockPlugin.CONFIG_PROP_1)); assertEquals("va.l3", c2.get(MockPlugin.CONFIG_PROP_2)); assertEquals(au1, mgr.getAuFromId(mauauid1)); } public void testCreateAu() throws Exception { minimalConfig(); String pid = new ThrowingMockPlugin().getPluginId(); String key = PluginManager.pluginKeyFromId(pid); assertTrue(mgr.ensurePluginLoaded(key)); ThrowingMockPlugin mpi = (ThrowingMockPlugin)mgr.getPlugin(key); assertNotNull(mpi); Configuration config = ConfigurationUtil.fromArgs("a", "b"); ArchivalUnit au = mgr.createAu(mpi, config); // verify put in PluginManager map String auid = au.getAuId(); ArchivalUnit aux = mgr.getAuFromId(auid); assertSame(au, aux); // verify got right config Configuration auConfig = au.getConfiguration(); assertEquals("b", auConfig.get("a")); assertEquals(1, auConfig.keySet().size()); assertEquals(mpi, au.getPlugin()); // verify turns RuntimeException into ArchivalUnit.ConfigurationException mpi.setCfgEx(new ArchivalUnit.ConfigurationException("should be thrown")); try { ArchivalUnit au2 = mgr.createAu(mpi, config); fail("createAU should have thrown ArchivalUnit.ConfigurationException"); } catch (ArchivalUnit.ConfigurationException e) { } mpi.setRtEx(new ExpectedRuntimeException("Ok if in log")); try { ArchivalUnit au2 = mgr.createAu(mpi, config); fail("createAU should have thrown ArchivalUnit.ConfigurationException"); } catch (ArchivalUnit.ConfigurationException e) { // this is what's expected } catch (RuntimeException e) { fail("createAU threw RuntimeException"); } } public void testConfigureAu() throws Exception { minimalConfig(); String pid = new ThrowingMockPlugin().getPluginId(); String key = PluginManager.pluginKeyFromId(pid); assertTrue(mgr.ensurePluginLoaded(key)); ThrowingMockPlugin mpi = (ThrowingMockPlugin)mgr.getPlugin(key); assertNotNull(mpi); Configuration config = ConfigurationUtil.fromArgs("a", "b"); ArchivalUnit au = mgr.createAu(mpi, config); String auid = au.getAuId(); ArchivalUnit aux = mgr.getAuFromId(auid); assertSame(au, aux); // verify can reconfig mgr.configureAu(mpi, ConfigurationUtil.fromArgs("a", "c"), auid); Configuration auConfig = au.getConfiguration(); assertEquals("c", auConfig.get("a")); assertEquals(1, auConfig.keySet().size()); // verify turns RuntimeException into ArchivalUnit.ConfigurationException mpi.setCfgEx(new ArchivalUnit.ConfigurationException("should be thrown")); try { mgr.configureAu(mpi, config, auid); fail("configureAU should have thrown ArchivalUnit.ConfigurationException"); } catch (ArchivalUnit.ConfigurationException e) { } mpi.setRtEx(new ExpectedRuntimeException("Ok if in log")); try { mgr.configureAu(mpi, config, auid); fail("configureAU should have thrown ArchivalUnit.ConfigurationException"); } catch (ArchivalUnit.ConfigurationException e) { // this is what's expected } catch (RuntimeException e) { fail("createAU threw RuntimeException"); } } static class ThrowingMockPlugin extends MockPlugin { RuntimeException rtEx; ArchivalUnit.ConfigurationException cfgEx;; public void setRtEx(RuntimeException rtEx) { this.rtEx = rtEx; } public void setCfgEx(ArchivalUnit.ConfigurationException cfgEx) { this.cfgEx = cfgEx; } public ArchivalUnit createAu(Configuration config) throws ArchivalUnit.ConfigurationException { if (rtEx != null) { throw rtEx; } else if (cfgEx != null) { throw cfgEx; } else { return super.createAu(config); } } public ArchivalUnit configureAu(Configuration config, ArchivalUnit au) throws ArchivalUnit.ConfigurationException { if (rtEx != null) { throw rtEx; } else if (cfgEx != null) { throw cfgEx; } else { return super.configureAu(config, au); } } } public void testFindCus() throws Exception { String url = "http://foo.bar/"; String lower = "abc"; String upper = "xyz"; doConfig(); MockPlugin mpi = (MockPlugin)mgr.getPlugin(mockPlugKey); // make a PollSpec with info from a manually created CUS, which should // match one of the registered AUs CachedUrlSet protoCus = makeCus(mpi, mauauid1, url, lower, upper); PollSpec ps1 = new PollSpec(protoCus); // verify PluginManager can make a CUS for the PollSpec CachedUrlSet cus = mgr.findCachedUrlSet(ps1); assertNotNull(cus); // verify the CUS's CUSS CachedUrlSetSpec cuss = cus.getSpec(); assertEquals(url, cuss.getUrl()); RangeCachedUrlSetSpec rcuss = (RangeCachedUrlSetSpec)cuss; assertEquals(lower, rcuss.getLowerBound()); assertEquals(upper, rcuss.getUpperBound()); assertEquals(mauauid1, cus.getArchivalUnit().getAuId()); // can't test protoCus.getArchivalUnit() .equals( cus.getArchivalUnit() ) // as we made a fake mock one to build PollSpec, and PluginManager will // have created & configured a real mock one. CachedUrlSet protoAuCus = makeAuCus(mpi, mauauid1); PollSpec ps2 = new PollSpec(protoAuCus); CachedUrlSet aucus = mgr.findCachedUrlSet(ps2); assertNotNull(aucus); CachedUrlSetSpec aucuss = aucus.getSpec(); assertTrue(aucuss instanceof AuCachedUrlSetSpec); } public void testFindSingleNodeCus() throws Exception { String url = "http://foo.bar/"; String lower = PollSpec.SINGLE_NODE_LWRBOUND; doConfig(); MockPlugin mpi = (MockPlugin)mgr.getPlugin(mockPlugKey); // make a PollSpec with info from a manually created CUS, which should // match one of the registered AUs CachedUrlSet protoCus = makeCus(mpi, mauauid1, url, lower, null); PollSpec ps1 = new PollSpec(protoCus); // verify PluginManager can make a CUS for the PollSpec CachedUrlSet cus = mgr.findCachedUrlSet(ps1); assertNotNull(cus); // verify the CUS's CUSS CachedUrlSetSpec cuss = cus.getSpec(); assertTrue(cuss instanceof SingleNodeCachedUrlSetSpec); assertEquals(url, cuss.getUrl()); } public void testFindMostRecentCachedUrl() throws Exception { String prefix = "http://foo.bar/"; String url1 = "http://foo.bar/baz"; String url2 = "http://foo.bar/not"; doConfig(); MockPlugin mpi = (MockPlugin)mgr.getPlugin(mockPlugKey); // get the two archival units MockArchivalUnit au1 = (MockArchivalUnit)mgr.getAuFromId(mauauid1); ArchivalUnit au2 = mgr.getAuFromId(mauauid2); assertNull(mgr.findMostRecentCachedUrl(url1)); CachedUrlSetSpec cuss = new MockCachedUrlSetSpec(prefix, null); MockCachedUrlSet mcuss = new MockCachedUrlSet(au1, cuss); mcuss.addUrl("foo", url1, true, true, null); au1.setAuCachedUrlSet(mcuss); CachedUrl cu = mgr.findMostRecentCachedUrl(url1); assertNotNull(cu); assertEquals(url1, cu.getUrl()); assertNull(mgr.findMostRecentCachedUrl(url2)); } public void testGenerateAuId() { Properties props = new Properties(); props.setProperty("key&1", "val=1"); props.setProperty("key2", "val 2"); props.setProperty("key.3", "val:3"); props.setProperty("key4", "val.4"); String pluginId = "org|lockss|plugin|Blah"; String actual = PluginManager.generateAuId(pluginId, props); String expected = pluginId+"&"+ "key%261~val%3D1&"+ "key%2E3~val%3A3&"+ "key2~val+2&"+ "key4~val%2E4"; assertEquals(expected, actual); } public void testConfigKeyFromAuId() { String pluginId = "org|lockss|plugin|Blah"; String auId = "base_url~foo&volume~123"; String totalId = PluginManager.generateAuId(pluginId, auId); String expectedStr = pluginId + "." + auId; assertEquals(expectedStr, PluginManager.configKeyFromAuId(totalId)); } public CachedUrlSet makeCus(Plugin plugin, String auid, String url, String lower, String upper) { MockArchivalUnit au = new MockArchivalUnit(); au.setAuId(auid); au.setPlugin(plugin); au.setPluginId(plugin.getPluginId()); CachedUrlSet cus = new MockCachedUrlSet(au, new RangeCachedUrlSetSpec(url, lower, upper)); return cus; } public CachedUrlSet makeAuCus(Plugin plugin, String auid) { MockArchivalUnit au = new MockArchivalUnit(); au.setAuId(auid); au.setPlugin(plugin); au.setPluginId(plugin.getPluginId()); CachedUrlSet cus = new MockCachedUrlSet(au, new AuCachedUrlSetSpec()); return cus; } private static String wkey = "org|lockss|plugin|wrapper|WrappedPlugin"; public void testWrappedAu() { if (WrapperState.isUsingWrapping()) { try { mgr.startService(); String localConfig = p1a1param + MockPlugin.CONFIG_PROP_1 + "=val1\n" + p1a1param + MockPlugin.CONFIG_PROP_2 + "=val2\n" + p1a1param + "reserved.wrapper=true\n" + LockssRepositoryImpl.PARAM_CACHE_LOCATION + "=" + getTempDir().getAbsolutePath() + File.separator + "\n"; ConfigurationUtil.setCurrentConfigFromString(localConfig); ArchivalUnit wau = (ArchivalUnit) mgr.getAuFromId( mauauid1); Plugin wplug = (Plugin) wau.getPlugin(); MockPlugin mock = (MockPlugin) WrapperState.getOriginal(wplug); assertSame(mock,wplug); MockArchivalUnit mau = (MockArchivalUnit) WrapperState.getOriginal(wau); assertSame(mock, mau.getPlugin()); assertSame(mau,wau); } catch (IOException e) { fail(e.getMessage()); } catch (ClassCastException e) { fail("WrappedArchivalUnit not found."); } } } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(TestPluginManager.class); return suite; } }
package de.zib.gndms.model.gorfx; import de.zib.gndms.model.common.PermissionInfo; import de.zib.gndms.model.common.PersistentContract; import de.zib.gndms.model.common.TimedGridResource; import de.zib.gndms.model.gorfx.types.TaskState; import de.zib.gndms.stuff.copy.Copier; import de.zib.gndms.stuff.copy.CopyMode; import de.zib.gndms.stuff.copy.Copyable; import de.zib.gndms.stuff.mold.Mold; import de.zib.gndms.stuff.mold.Molder; import org.jetbrains.annotations.NotNull; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @MappedSuperclass @Copyable(CopyMode.MOLD) public abstract class AbstractTask extends TimedGridResource { private OfferType offerType; private String description; private byte[] serializedCredential; private PersistentContract contract; private boolean broken = false; private TaskState state = TaskState.CREATED; private boolean done = false; private int progress = 0; private int maxProgress = 100; @Basic private Serializable orq; @Basic private String faultString; /** * Payload depending on state, either task results or a detailed task failure **/ @Basic private Serializable data; @Basic private String wid; private PermissionInfo permissions; List<SubTask> subTasks = new ArrayList<SubTask>(); public void transit(final TaskState newState) { final @NotNull TaskState goalState = newState == null ? getState() : newState; final @NotNull TaskState transitState = getState().transit(goalState); assert transitState != null; setState(transitState); } public void fail (final @NotNull Exception e) { setState(getState().transit(TaskState.FAILED)); setFaultString(e.getMessage()); setData(e); setProgress(0); } public void finish(final Serializable result) { setState(getState().transit(TaskState.FINISHED)); setFaultString(""); setData(result); setProgress(maxProgress); } public void add ( SubTask st ) { if( subTasks == null ); subTasks = new LinkedList<SubTask>( ); subTasks.add( st ); } // TODO veryify "(D) this" @SuppressWarnings({"unchecked"}) public <D> Molder<D> molder(@NotNull final Class<D> moldedClazz) { return Mold.newMolderProxy( (Class<D>) getClass(), (D) this, moldedClazz); } public void mold(final @NotNull AbstractTask instance) { instance.setId( getId() ); instance.setTerminationTime( getTerminationTime() ); instance.description = description; instance.wid = wid; instance.faultString = faultString; instance.done = done; instance.state = state; instance.broken = broken; instance.progress = progress; instance.maxProgress = maxProgress; instance.contract = Copier.copy(false, contract); /* shallow therefore needs refresh */ instance.offerType = offerType; instance.orq = Copier.copySerializable(orq); instance.data = Copier.copySerializable(data); instance.permissions = Copier.copyViaConstructor( permissions ); if (subTasks == null) instance.subTasks = null; else { instance.subTasks = new LinkedList<SubTask>(); instance.subTasks.addAll(subTasks); } } public void refresh(final @NotNull EntityManager em) { if (offerType != null) offerType = em.find(OfferType.class, offerType.getOfferTypeKey()); } /* Nullable for testing purposes */ @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="offerTypeKey", nullable=false, updatable=false, columnDefinition="VARCHAR") public OfferType getOfferType() { return offerType; } @Column(name="descr", nullable=false, updatable=false, columnDefinition="VARCHAR") public String getDescription() { return description; } @Column(name="cred", nullable=true, updatable=true, columnDefinition="BLOB") @Lob public byte[] getSerializedCredential() { return serializedCredential; } /* always this.tod >= this.validity */ @Embedded @AttributeOverrides({ @AttributeOverride(name="accepted", column=@Column(name="accepted", nullable=false, updatable=false)), @AttributeOverride(name="deadline", column=@Column(name="deadline", nullable=true, updatable=false)), @AttributeOverride(name="resultValidity", column=@Column(name="validity", nullable=true, updatable=false)) }) public PersistentContract getContract() { return contract; } @Column(name="broken", updatable=true) public boolean isBroken() { return broken; } @Enumerated(EnumType.STRING) @Column(name="state", nullable=false, updatable=true) public TaskState getState() { return state; } @Column(name = "done", nullable=false, updatable=true) public boolean isDone() { return done; } @Column(name = "done", nullable=false, updatable=true) public int getProgress() { return progress; } @Column(name="max_progress", nullable=false, updatable=false) public int getMaxProgress() { return maxProgress; } @Column(name="orq", nullable=false, updatable=true) public Serializable getOrq() { return orq; } @Column(name="fault", nullable=true, updatable=true, columnDefinition="VARCHAR", length=5000 ) public String getFaultString() { return faultString; } @Column(name="data", nullable=true, updatable=true) public Serializable getData() { return data; } @Column(name="wid", nullable=true, updatable=false) public String getWid() { return wid; } @Embedded public PermissionInfo getPermissions() { return permissions; } @OneToMany( targetEntity=SubTask.class, cascade={CascadeType.REMOVE}, fetch=FetchType.EAGER ) public List<SubTask> getSubTasks() { return subTasks; } public void setOfferType( OfferType offerType ) { this.offerType = offerType; } public void setDescription( String description ) { this.description = description; } public void setSerializedCredential( byte[] serializedCredential ) { this.serializedCredential = serializedCredential; } public void setContract( PersistentContract contract ) { this.contract = contract; } public void setBroken( boolean broken ) { this.broken = broken; } public void setState( TaskState state ) { this.state = state; } public void setDone( boolean done ) { this.done = done; } public void setProgress( int progress ) { this.progress = progress; } public void setMaxProgress( int maxProgress ) { this.maxProgress = maxProgress; } public void setOrq( Serializable orq ) { this.orq = orq; } public void setFaultString( String faultString ) { this.faultString = faultString; } public void setData( Serializable data ) { this.data = data; } public void setWid( String wid ) { this.wid = wid; } public void setPermissions( PermissionInfo permissions ) { this.permissions = permissions; } public void setSubTasks( List<SubTask> subTasks ) { this.subTasks = subTasks; } }
package jme3test.network; import com.jme3.network.Client; import com.jme3.network.Message; import com.jme3.network.MessageConnection; import com.jme3.network.MessageListener; import com.jme3.network.Network; import com.jme3.network.Server; import com.jme3.network.serializing.Serializable; import com.jme3.network.serializing.Serializer; import java.io.IOException; public class TestThroughput implements MessageListener<MessageConnection> { //extends MessageAdapter { private static long lastTime = -1; private static long counter = 0; private static long total = 0; private static Client client; // Change this flag to test UDP instead of TCP private static boolean testReliable = true; private boolean isOnServer; public TestThroughput( boolean isOnServer ) { this.isOnServer = isOnServer; } @Override public void messageReceived( MessageConnection source, Message msg){ if( !isOnServer ) { // It's local to the client so we got it back counter++; total++; long time = System.currentTimeMillis(); //System.out.println( "total:" + total + " counter:" + counter + " lastTime:" + lastTime + " time:" + time ); if( lastTime < 0 ) { lastTime = time; } else if( time - lastTime > 1000 ) { long delta = time - lastTime; double scale = delta / 1000.0; double pps = counter / scale; System.out.println( "messages per second:" + pps + " total messages:" + total ); counter = 0; lastTime = time; } } else { if( source == null ) { System.out.println( "Received a message from a not fully connected source, msg:"+ msg ); } else { //System.out.println( "sending:" + msg + " back to client:" + source ); // The 'reliable' flag is transient and the server doesn't // (yet) reset this value for us. ((com.jme3.network.message.Message)msg).setReliable(testReliable); source.send(msg); } } } public static void main(String[] args) throws IOException, InterruptedException{ Serializer.registerClass(TestMessage.class); Server server = Network.createServer( 5110 ); server.start(); Client client = Network.connectToServer( "localhost", 5110, 5000 ); client.start(); client.addMessageListener(new TestThroughput(false), TestMessage.class); server.addMessageListener(new TestThroughput(true), TestMessage.class); Thread.sleep(1); TestMessage test = new TestMessage(); // for( int i = 0; i < 10; i++ ) { while( true ) { //System.out.println( "sending." ); client.send(test); } //Thread.sleep(5000); } @Serializable public static class TestMessage extends com.jme3.network.message.Message { public TestMessage(){ setReliable(testReliable); } } }
package org.neo4j.helpers; /** * Utility to handle pairs of objects. */ public final class Pair<T1, T2> { private final T1 first; private final T2 other; public Pair( T1 first, T2 other ) { this.first = first; this.other = other; } public T1 first() { return first; } public T2 other() { return other; } @Override public String toString() { return "(" + first + ", " + other + ")"; } @Override public int hashCode() { return ( 31 * hashCode( first ) ) | hashCode( other ); } @SuppressWarnings( "unchecked" ) @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj instanceof Pair ) { Pair that = (Pair) obj; return equals( this.first, that.first ) && equals( this.other, that.other ); } return false; } private static int hashCode( Object obj ) { return obj == null ? 0 : obj.hashCode(); } private static boolean equals( Object obj1, Object obj2 ) { return ( obj1 == obj2 ) || ( obj1 != null && obj1.equals( obj2 ) ); } }
package org.pcap4j.util; import static java.nio.ByteOrder.*; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteOrder; import java.util.regex.Pattern; /** * @author Kaito Yamada * @since pcap4j 0.9.1 */ public final class ByteArrays { public static final int BYTE_SIZE_IN_BYTES = 1; public static final int SHORT_SIZE_IN_BYTES = 2; public static final int INT_SIZE_IN_BYTES = 4; public static final int LONG_SIZE_IN_BYTES = 8; public static final int INET4_ADDRESS_SIZE_IN_BYTES = 4; public static final int INET6_ADDRESS_SIZE_IN_BYTES = 16; public static final int BYTE_SIZE_IN_BITS = 8; private static final Pattern NO_SEPARATOR_HEX_STRING_PATTERN = Pattern.compile("\\A([0-9a-fA-F][0-9a-fA-F])+\\z"); private ByteArrays() { throw new AssertionError(); } /** * * @param array * @return a new array containing specified array's elements in reverse order. */ public static byte[] reverse(byte[] array) { byte[] rarray = new byte[array.length]; for (int i = 0; i < array.length; i++) { rarray[i] = array[array.length - i - 1]; } return rarray; } /** * * @param array * @param offset * @return byte value. */ public static byte getByte(byte[] array, int offset) { validateBounds(array, offset, BYTE_SIZE_IN_BYTES); return array[offset]; } /** * * @param value * @return byte array */ public static byte[] toByteArray(byte value) { return new byte[] { value }; } /** * * @param value * @param separator * @return hex string */ public static String toHexString(byte value, String separator) { return toHexString(toByteArray(value), separator); } /** * * @param array * @param offset * @return short value */ public static short getShort(byte[] array, int offset) { return getShort(array, offset, ByteOrder.BIG_ENDIAN); } /** * * @param array * @param offset * @param bo * @return short value */ public static short getShort(byte[] array, int offset, ByteOrder bo) { validateBounds(array, offset, SHORT_SIZE_IN_BYTES); if (bo == null) { throw new NullPointerException(" bo: " + bo); } if (bo.equals(LITTLE_ENDIAN)) { return (short)( (( array[offset + 1]) << (BYTE_SIZE_IN_BITS * 1)) | ((0xFF & array[offset ]) ) ); } else { return (short)( (( array[offset ]) << (BYTE_SIZE_IN_BITS * 1)) | ((0xFF & array[offset + 1]) ) ); } } /** * * @param value * @return byte array */ public static byte[] toByteArray(short value) { return toByteArray(value, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param bo * @return byte array */ public static byte[] toByteArray(short value, ByteOrder bo) { if (bo.equals(LITTLE_ENDIAN)) { return new byte[] { (byte)(value ), (byte)(value >> BYTE_SIZE_IN_BITS * 1) }; } else { return new byte[] { (byte)(value >> BYTE_SIZE_IN_BITS * 1), (byte)(value ) }; } } /** * * @param value * @param separator * @return hex string */ public static String toHexString(short value, String separator) { return toHexString(value, separator, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param separator * @param bo * @return hex string */ public static String toHexString(short value, String separator, ByteOrder bo) { return toHexString(toByteArray(value, bo), separator); } /** * * @param array * @param offset * @return int value. */ public static int getInt(byte[] array, int offset) { return getInt(array, offset, ByteOrder.BIG_ENDIAN); } /** * * @param array * @param offset * @param bo * @return int value. */ public static int getInt(byte[] array, int offset, ByteOrder bo) { validateBounds(array, offset, INT_SIZE_IN_BYTES); if (bo == null) { throw new NullPointerException(" bo: " + bo); } if (bo.equals(LITTLE_ENDIAN)) { return (( array[offset + 3]) << (BYTE_SIZE_IN_BITS * 3)) | ((0xFF & array[offset + 2]) << (BYTE_SIZE_IN_BITS * 2)) | ((0xFF & array[offset + 1]) << (BYTE_SIZE_IN_BITS * 1)) | ((0xFF & array[offset ]) ); } else { return (( array[offset ]) << (BYTE_SIZE_IN_BITS * 3)) | ((0xFF & array[offset + 1]) << (BYTE_SIZE_IN_BITS * 2)) | ((0xFF & array[offset + 2]) << (BYTE_SIZE_IN_BITS * 1)) | ((0xFF & array[offset + 3]) ); } } /** * @param array * @param offset * @param length * @return int value. */ public static int getInt(byte[] array, int offset, int length) { return getInt(array, offset, length, ByteOrder.BIG_ENDIAN); } /** * @param array * @param offset * @param length * @param bo * @return int value. */ public static int getInt(byte[] array, int offset, int length, ByteOrder bo) { validateBounds(array, offset, length); if (length > INT_SIZE_IN_BYTES) { StringBuilder sb = new StringBuilder(30) .append("length must be equal or less than ") .append(INT_SIZE_IN_BYTES) .append(", but is: ") .append(length); throw new IllegalArgumentException(sb.toString()); } if (bo == null) { throw new NullPointerException(" bo: " + bo); } int value = 0; if (bo.equals(LITTLE_ENDIAN)) { for (int i = offset + length - 1; i >= offset; i value <<= BYTE_SIZE_IN_BITS; value |= 0xFF & array[i]; } } else { for (int i = offset; i < offset + length; i++) { value <<= BYTE_SIZE_IN_BITS; value |= 0xFF & array[i]; } } return value; } /** * * @param value * @return byte array */ public static byte[] toByteArray(int value) { return toByteArray(value, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param bo * @return byte array */ public static byte[] toByteArray(int value, ByteOrder bo) { if (bo.equals(LITTLE_ENDIAN)) { return new byte[] { (byte)(value ), (byte)(value >> BYTE_SIZE_IN_BITS * 1), (byte)(value >> BYTE_SIZE_IN_BITS * 2), (byte)(value >> BYTE_SIZE_IN_BITS * 3), }; } else { return new byte[] { (byte)(value >> BYTE_SIZE_IN_BITS * 3), (byte)(value >> BYTE_SIZE_IN_BITS * 2), (byte)(value >> BYTE_SIZE_IN_BITS * 1), (byte)(value ) }; } } /** * @param value * @param length * @return byte array */ public static byte[] toByteArray(int value, int length) { return toByteArray(value, length, ByteOrder.BIG_ENDIAN); } /** * @param value * @param length * @param bo * @return byte array */ public static byte[] toByteArray(int value, int length, ByteOrder bo) { if (length > INT_SIZE_IN_BYTES) { StringBuilder sb = new StringBuilder(30) .append("length must be equal or less than ") .append(INT_SIZE_IN_BYTES) .append(", but is: ") .append(length); throw new IllegalArgumentException(sb.toString()); } byte[] arr = new byte[length]; if (bo.equals(LITTLE_ENDIAN)) { for (int i = 0; i < length; i++) { arr[length - i - 1] = (byte)(value >> BYTE_SIZE_IN_BITS * i); } } else { for (int i = 0; i < length; i++) { arr[i] = (byte)(value >> BYTE_SIZE_IN_BITS * i); } } return arr; } /** * * @param value * @param separator * @return hex string */ public static String toHexString(int value, String separator) { return toHexString(value, separator, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param separator * @param bo * @return hex string */ public static String toHexString(int value, String separator, ByteOrder bo) { return toHexString(toByteArray(value, bo), separator); } /** * * @param array * @param offset * @return long value */ public static long getLong(byte[] array, int offset) { return getLong(array, offset, ByteOrder.BIG_ENDIAN); } /** * * @param array * @param offset * @param bo * @return long value */ public static long getLong(byte[] array, int offset, ByteOrder bo) { validateBounds(array, offset, LONG_SIZE_IN_BYTES); if (bo == null) { throw new NullPointerException(" bo: " + bo); } if (bo.equals(LITTLE_ENDIAN)) { return (( (long)array[offset + 7]) << (BYTE_SIZE_IN_BITS * 7)) | ((0xFFL & array[offset + 6]) << (BYTE_SIZE_IN_BITS * 6)) | ((0xFFL & array[offset + 5]) << (BYTE_SIZE_IN_BITS * 5)) | ((0xFFL & array[offset + 4]) << (BYTE_SIZE_IN_BITS * 4)) | ((0xFFL & array[offset + 3]) << (BYTE_SIZE_IN_BITS * 3)) | ((0xFFL & array[offset + 2]) << (BYTE_SIZE_IN_BITS * 2)) | ((0xFFL & array[offset + 1]) << (BYTE_SIZE_IN_BITS * 1)) | ((0xFFL & array[offset ]) ); } else { return (( (long)array[offset ]) << (BYTE_SIZE_IN_BITS * 7)) | ((0xFFL & array[offset + 1]) << (BYTE_SIZE_IN_BITS * 6)) | ((0xFFL & array[offset + 2]) << (BYTE_SIZE_IN_BITS * 5)) | ((0xFFL & array[offset + 3]) << (BYTE_SIZE_IN_BITS * 4)) | ((0xFFL & array[offset + 4]) << (BYTE_SIZE_IN_BITS * 3)) | ((0xFFL & array[offset + 5]) << (BYTE_SIZE_IN_BITS * 2)) | ((0xFFL & array[offset + 6]) << (BYTE_SIZE_IN_BITS * 1)) | ((0xFFL & array[offset + 7]) ); } } /** * * @param value * @return byte array */ public static byte[] toByteArray(long value) { return toByteArray(value, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param bo * @return byte array */ public static byte[] toByteArray(long value, ByteOrder bo) { if (bo.equals(LITTLE_ENDIAN)) { return new byte[] { (byte)(value ), (byte)(value >> BYTE_SIZE_IN_BITS * 1), (byte)(value >> BYTE_SIZE_IN_BITS * 2), (byte)(value >> BYTE_SIZE_IN_BITS * 3), (byte)(value >> BYTE_SIZE_IN_BITS * 4), (byte)(value >> BYTE_SIZE_IN_BITS * 5), (byte)(value >> BYTE_SIZE_IN_BITS * 6), (byte)(value >> BYTE_SIZE_IN_BITS * 7) }; } else { return new byte[] { (byte)(value >> BYTE_SIZE_IN_BITS * 7), (byte)(value >> BYTE_SIZE_IN_BITS * 6), (byte)(value >> BYTE_SIZE_IN_BITS * 5), (byte)(value >> BYTE_SIZE_IN_BITS * 4), (byte)(value >> BYTE_SIZE_IN_BITS * 3), (byte)(value >> BYTE_SIZE_IN_BITS * 2), (byte)(value >> BYTE_SIZE_IN_BITS * 1), (byte)(value ) }; } } /** * * @param value * @param separator * @return hex string */ public static String toHexString(long value, String separator) { return toHexString(value, separator, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param separator * @param bo * @return hex string */ public static String toHexString(long value, String separator, ByteOrder bo) { return toHexString(toByteArray(value, bo), separator); } /** * * @param array * @param offset * @return a new MacAddress object. */ public static MacAddress getMacAddress(byte[] array, int offset) { return getMacAddress(array, offset, ByteOrder.BIG_ENDIAN); } /** * * @param array * @param offset * @param bo * @return a new MacAddress object. */ public static MacAddress getMacAddress( byte[] array, int offset, ByteOrder bo ) { validateBounds(array, offset, MacAddress.SIZE_IN_BYTES); if (bo == null) { throw new NullPointerException(" bo: " + bo); } if (bo.equals(LITTLE_ENDIAN)) { return MacAddress.getByAddress( reverse(getSubArray(array, offset, MacAddress.SIZE_IN_BYTES)) ); } else { return MacAddress.getByAddress( getSubArray(array, offset, MacAddress.SIZE_IN_BYTES) ); } } /** * * @param value * @return byte array */ public static byte[] toByteArray(MacAddress value) { return toByteArray(value, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param bo * @return byte array */ public static byte[] toByteArray(MacAddress value, ByteOrder bo) { if (bo.equals(LITTLE_ENDIAN)) { return reverse(value.getAddress()); } else { return value.getAddress(); } } /** * * @param array * @param offset * @param length * @return a new LinkLayerAddress object. */ public static LinkLayerAddress getLinkLayerAddress(byte[] array, int offset, int length) { return getLinkLayerAddress(array, offset, length, ByteOrder.BIG_ENDIAN); } /** * * @param array * @param offset * @param length * @param bo * @return a new LinkLayerAddress object. */ public static LinkLayerAddress getLinkLayerAddress( byte[] array, int offset, int length, ByteOrder bo ) { validateBounds(array, offset, length); if (bo == null) { throw new NullPointerException(" bo: " + bo); } if (bo.equals(LITTLE_ENDIAN)) { return LinkLayerAddress.getByAddress( reverse(getSubArray(array, offset, length)) ); } else { return LinkLayerAddress.getByAddress( getSubArray(array, offset, length) ); } } /** * * @param value * @return byte array */ public static byte[] toByteArray(LinkLayerAddress value) { return toByteArray(value, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param bo * @return byte array */ public static byte[] toByteArray(LinkLayerAddress value, ByteOrder bo) { if (bo.equals(LITTLE_ENDIAN)) { return reverse(value.getAddress()); } else { return value.getAddress(); } } /** * * @param array * @param offset * @return a new Inet4Address object. */ public static Inet4Address getInet4Address(byte[] array, int offset) { return getInet4Address(array, offset, ByteOrder.BIG_ENDIAN); } /** * * @param array * @param offset * @param bo * @return a new Inet4Address object. */ public static Inet4Address getInet4Address( byte[] array, int offset, ByteOrder bo ) { validateBounds(array, offset, INET4_ADDRESS_SIZE_IN_BYTES); if (bo == null) { throw new NullPointerException(" bo: " + bo); } try { if (bo.equals(LITTLE_ENDIAN)) { return (Inet4Address)InetAddress.getByAddress( reverse( getSubArray( array, offset, INET4_ADDRESS_SIZE_IN_BYTES ) ) ); } else { return (Inet4Address)InetAddress.getByAddress( getSubArray( array, offset, INET4_ADDRESS_SIZE_IN_BYTES ) ); } } catch (UnknownHostException e) { throw new AssertionError(e); } } /** * * @param array * @param offset * @return a new Inet6Address object. */ public static Inet6Address getInet6Address(byte[] array, int offset) { return getInet6Address(array, offset, ByteOrder.BIG_ENDIAN); } /** * * @param array * @param offset * @param bo * @return a new Inet6Address object. */ public static Inet6Address getInet6Address( byte[] array, int offset, ByteOrder bo ) { validateBounds(array, offset, INET6_ADDRESS_SIZE_IN_BYTES); if (bo == null) { throw new NullPointerException(" bo: " + bo); } try { if (bo.equals(LITTLE_ENDIAN)) { return (Inet6Address)InetAddress.getByAddress( reverse( getSubArray( array, offset, INET6_ADDRESS_SIZE_IN_BYTES ) ) ); } else { return (Inet6Address)InetAddress.getByAddress( getSubArray( array, offset, INET6_ADDRESS_SIZE_IN_BYTES ) ); } } catch (UnknownHostException e) { throw new AssertionError(e); } } /** * * @param value * @return byte array */ public static byte[] toByteArray(InetAddress value) { return toByteArray(value, ByteOrder.BIG_ENDIAN); } /** * * @param value * @param bo * @return byte array */ public static byte[] toByteArray(InetAddress value, ByteOrder bo) { if (bo.equals(LITTLE_ENDIAN)) { return reverse(value.getAddress()); } else { return value.getAddress(); } } /** * * @param array * @param offset * @param length * @return sub array */ public static byte[] getSubArray(byte[] array, int offset, int length) { validateBounds(array, offset, length); byte[] subArray = new byte[length]; System.arraycopy(array, offset, subArray, 0, length); return subArray; } /** * * @param array * @param offset * @return sub array */ public static byte[] getSubArray(byte[] array, int offset) { return getSubArray(array, offset, array.length - offset); } /** * * @param array * @param separator * @return hex string */ public static String toHexString(byte[] array, String separator) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < array.length; i++) { buf.append(String.format("%02x", array[i])); buf.append(separator); } if (separator.length() != 0 && array.length > 0) { buf.delete(buf.lastIndexOf(separator), buf.length()); } return buf.toString(); } /** * * @param array * @param separator * @param offset * @param length * @return hex string */ public static String toHexString( byte[] array, String separator, int offset, int length ) { validateBounds(array, offset, length); StringBuffer buf = new StringBuffer(); for (int i = offset; i < offset + length; i++) { buf.append(String.format("%02x", array[i])); buf.append(separator); } if (separator.length() != 0 && length > 0) { buf.delete(buf.lastIndexOf(separator), buf.length()); } return buf.toString(); } /** * * @param data * @return checksum */ public static short calcChecksum(byte[] data) { int sum = 0; for (int i = 0; i < data.length; i += SHORT_SIZE_IN_BYTES) { sum += (0xFFFF) & getShort(data, i); } sum = (0xFFFF & sum) + ((0xFFFF0000 & sum) >> (BYTE_SIZE_IN_BITS * SHORT_SIZE_IN_BYTES)); sum = (0xFFFF & sum) + ((0xFFFF0000 & sum) >> (BYTE_SIZE_IN_BITS * SHORT_SIZE_IN_BYTES)); return (short)(0xFFFF & ~sum); } /** * * @param hexString * @param separator * @return a new byte array. */ public static byte[] parseByteArray(String hexString, String separator) { if ( hexString == null || separator == null ) { StringBuilder sb = new StringBuilder(); sb.append("hexString: ") .append(hexString) .append(" separator: ") .append(separator); throw new NullPointerException(sb.toString()); } if (hexString.startsWith("0x")) { hexString = hexString.substring(2); } String noSeparatorHexString; if (separator.length() == 0) { if ( !NO_SEPARATOR_HEX_STRING_PATTERN.matcher(hexString).matches() ) { StringBuilder sb = new StringBuilder(100); sb.append("invalid hex string(") .append(hexString) .append("), not match pattern(") .append(NO_SEPARATOR_HEX_STRING_PATTERN.pattern()) .append(")"); throw new IllegalArgumentException(sb.toString()); } noSeparatorHexString = hexString; } else { StringBuilder patternSb = new StringBuilder(60); patternSb.append("\\A[0-9a-fA-F][0-9a-fA-F](") .append(Pattern.quote(separator)) .append("[0-9a-fA-F][0-9a-fA-F])*\\z"); String patternString = patternSb.toString(); Pattern pattern = Pattern.compile(patternString); if (!pattern.matcher(hexString).matches()) { StringBuilder sb = new StringBuilder(150); sb.append("invalid hex string(") .append(hexString) .append("), not match pattern(") .append(patternString) .append(")"); throw new IllegalArgumentException(sb.toString()); } noSeparatorHexString = hexString.replaceAll(Pattern.quote(separator), ""); } int arrayLength = noSeparatorHexString.length() / 2; byte[] array = new byte[arrayLength]; for (int i = 0; i < arrayLength; i++) { array[i] = (byte)Integer.parseInt( noSeparatorHexString.substring(i * 2, i * 2 + 2), 16 ); } return array; } /** * * @param array * @return a clone of array */ public static byte[] clone(byte[] array) { byte[] clone = new byte[array.length]; System.arraycopy(array, 0, clone, 0, array.length); return clone; } public static void validateBounds(byte[] arr, int offset, int len) { if (arr == null) { throw new NullPointerException("arr must not be null."); } if (arr.length == 0) { throw new IllegalArgumentException("arr is empty."); } if (len == 0) { throw new IllegalArgumentException("length is zero."); } if (offset < 0 || len < 0 || offset + len > arr.length) { StringBuilder sb = new StringBuilder(100); sb.append("arr.length: ") .append(arr.length) .append(", offset: ") .append(offset) .append(", len: ") .append(len); throw new ArrayIndexOutOfBoundsException(sb.toString()); } } }
/** * @author cdr */ package com.intellij.unscramble; import com.intellij.execution.ExecutionManager; import com.intellij.execution.ExecutionRegistry; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.runners.JavaProgramRunner; import com.intellij.execution.ui.*; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.ui.TextFieldWithHistory; import com.intellij.util.ArrayUtil; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class UnscrambleDialog extends DialogWrapper{ private static final String PROPERTY_LOG_FILE_HISTORY_URLS = "UNSCRAMBLE_LOG_FILE_URL"; private static final String PROPERTY_LOG_FILE_LAST_URL = "UNSCRAMBLE_LOG_FILE_LAST_URL"; private static final String PROPERTY_UNSCRAMBLER_NAME_USED = "UNSCRAMBLER_NAME_USED"; private final Project myProject; private JPanel myEditorPanel; private JPanel myLogFileChooserPanel; private JComboBox myUnscrambleChooser; private JPanel myPanel; private Editor myEditor; private TextFieldWithHistory myLogFile; private JCheckBox myUseUnscrambler; private JPanel myUnscramblePanel; public UnscrambleDialog(Project project) { super(false); myProject = project; populateRegisteredUnscramblerList(); myUnscrambleChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { UnscrambleSupport unscrambleSupport = getSelectedUnscrambler(); GuiUtils.enableChildren(myLogFileChooserPanel, unscrambleSupport != null, null); } }); myUseUnscrambler.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { useUnscramblerChanged(); } }); createLogFileChooser(); createEditor(); reset(); setTitle("Analyze Stacktrace"); init(); } private void useUnscramblerChanged() { boolean selected = myUseUnscrambler.isSelected(); GuiUtils.enableChildren(myUnscramblePanel, selected, new JComponent[]{myUseUnscrambler}); } private void reset() { final List<String> savedUrls = getSavedLogFileUrls(); myLogFile.setHistory(savedUrls); String lastUrl = getLastUsedLogUrl(); if (lastUrl == null && savedUrls.size() != 0) { lastUrl = savedUrls.get(savedUrls.size() - 1); } if (lastUrl != null) { myLogFile.setText(lastUrl); myLogFile.setSelectedItem(lastUrl); } final UnscrambleSupport selectedUnscrambler = getSavedUnscrambler(); final int count = myUnscrambleChooser.getItemCount(); int index = 0; if (selectedUnscrambler != null) { for (int i = 0; i < count; i++) { final UnscrambleSupport unscrambleSupport = (UnscrambleSupport)myUnscrambleChooser.getItemAt(i); if (unscrambleSupport != null && Comparing.strEqual(unscrambleSupport.getPresentableName(), selectedUnscrambler.getPresentableName())) { index = i; break; } } } if (count > 0) { myUseUnscrambler.setEnabled(true); myUnscrambleChooser.setSelectedIndex(index); myUseUnscrambler.setSelected(selectedUnscrambler != null); } else { myUseUnscrambler.setEnabled(false); } useUnscramblerChanged(); pasteTextFromClipboard(); } public static String getLastUsedLogUrl() { String lastUrl = PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_LAST_URL); return lastUrl; } public static UnscrambleSupport getSavedUnscrambler() { final List<UnscrambleSupport> registeredUnscramblers = getRegisteredUnscramblers(); final String savedUnscramblerName = PropertiesComponent.getInstance().getValue(PROPERTY_UNSCRAMBLER_NAME_USED); UnscrambleSupport selectedUnscrambler = null; for (int i = 0; i < registeredUnscramblers.size(); i++) { final UnscrambleSupport unscrambleSupport = registeredUnscramblers.get(i); if (Comparing.strEqual(unscrambleSupport.getPresentableName(), savedUnscramblerName)) { selectedUnscrambler = unscrambleSupport; } } return selectedUnscrambler; } public static List<String> getSavedLogFileUrls() { final List<String> res = new ArrayList<String>(); final String savedUrl = PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_HISTORY_URLS); final String[] strings = savedUrl == null ? ArrayUtil.EMPTY_STRING_ARRAY : savedUrl.split(":::"); for (int i = 0; i != strings.length; ++i) { res.add(strings[i]); } return res; } private void pasteTextFromClipboard() { String text = getTextInClipboard(); if (text != null) { final String text1 = text; Runnable runnable = new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myEditor.getDocument().insertString(0, StringUtil.convertLineSeparators(text1)); } }); } }; CommandProcessor.getInstance().executeCommand(myProject, runnable, "", this); } } public static String getTextInClipboard() { String text = null; try { Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(UnscrambleDialog.class); if (contents != null) { text = (String)contents.getTransferData(DataFlavor.stringFlavor); } } catch (Exception ex) { } return text; } private UnscrambleSupport getSelectedUnscrambler() { if (!myUseUnscrambler.isSelected()) return null; return (UnscrambleSupport)myUnscrambleChooser.getSelectedItem(); } private void createEditor() { EditorFactory editorFactory = EditorFactory.getInstance(); Document document = editorFactory.createDocument(""); myEditor = editorFactory.createEditor(document); EditorSettings settings = myEditor.getSettings(); settings.setFoldingOutlineShown(false); settings.setLineMarkerAreaShown(false); settings.setLineNumbersShown(false); settings.setRightMarginShown(false); EditorPanel editorPanel = new EditorPanel(myEditor); editorPanel.setPreferredSize(new Dimension(600, 400)); myEditorPanel.setLayout(new BorderLayout()); myEditorPanel.add(editorPanel, BorderLayout.CENTER); } protected Action[] createActions(){ return new Action[]{new SplitAction(), getOKAction(), getCancelAction()}; } private void createLogFileChooser() { myLogFile = new TextFieldWithHistory(); JPanel panel = GuiUtils.constructFieldWithBrowseButton(myLogFile, new ActionListener() { public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); VirtualFile[] files = FileChooser.chooseFiles(myLogFile, descriptor); if (files.length != 0) { myLogFile.setText(FileUtil.toSystemDependentName(files[files.length-1].getPath())); } } }); myLogFileChooserPanel.setLayout(new BorderLayout()); myLogFileChooserPanel.add(panel, BorderLayout.CENTER); } private void populateRegisteredUnscramblerList() { List<UnscrambleSupport> unscrambleComponents = getRegisteredUnscramblers(); //myUnscrambleChooser.addItem(null); for (int i = 0; i < unscrambleComponents.size(); i++) { final UnscrambleSupport unscrambleSupport = unscrambleComponents.get(i); myUnscrambleChooser.addItem(unscrambleSupport); } myUnscrambleChooser.setRenderer(new DefaultListCellRenderer() { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); UnscrambleSupport unscrambleSupport = (UnscrambleSupport)value; setText(unscrambleSupport == null ? "<Do not unscramble>" : unscrambleSupport.getPresentableName()); return this; } }); } private static List<UnscrambleSupport> getRegisteredUnscramblers() { List<UnscrambleSupport> unscrambleComponents = new ArrayList<UnscrambleSupport>(); Class[] interfaces = ApplicationManager.getApplication().getComponentInterfaces(); for (final Class anInterface : interfaces) { Object component = ApplicationManager.getApplication().getComponent(anInterface); if (component instanceof UnscrambleSupport) { unscrambleComponents.add((UnscrambleSupport)component); } } return unscrambleComponents; } protected JComponent createCenterPanel() { return myPanel; } public void dispose() { EditorFactory editorFactory = EditorFactory.getInstance(); editorFactory.releaseEditor(myEditor); if (isOK()){ final List list = myLogFile.getHistory(); String res = null; for (int i = 0; i < list.size(); i++) { final String s = (String)list.get(i); if (res == null) { res = s; } else { res = res + ":::" + s; } } PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_HISTORY_URLS, res); UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); PropertiesComponent.getInstance().setValue(PROPERTY_UNSCRAMBLER_NAME_USED, selectedUnscrambler == null ? null : selectedUnscrambler.getPresentableName()); PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_LAST_URL, myLogFile.getText()); } super.dispose(); } private final class SplitAction extends AbstractAction { public SplitAction(){ putValue(Action.NAME, "&Normalize"); putValue(DEFAULT_ACTION, Boolean.FALSE); } public void actionPerformed(ActionEvent e){ String text = myEditor.getDocument().getText(); // move 'at' to the line start text = text.replaceAll("(\\S)[\\s&&[^\\n]]*at ", "$1\n at "); text = text.replaceAll("(\\S)\\nat ", "$1\n at "); // merge (inadvertently) splitted lines text = text.replaceAll("\\s*\\n\\s*(([\\S&&[^a]])([\\S&&[^t]])?)", "$1"); final String newText = text; CommandProcessor.getInstance().executeCommand( myProject, new Runnable() { public void run(){ ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run(){ myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), newText); } }); } }, "", null ); } } private static final class EditorPanel extends JPanel implements DataProvider{ private final Editor myEditor; public EditorPanel(Editor editor) { super(new BorderLayout()); myEditor = editor; add(myEditor.getComponent()); } public Object getData(String dataId) { if (DataConstants.EDITOR.equals(dataId)) { return myEditor; } return null; } } protected void doOKAction() { if (performUnscramble()) { myLogFile.addCurrentTextToHistory(); close(OK_EXIT_CODE); } } private boolean performUnscramble() { UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); return showUnscrambledText(selectedUnscrambler, myLogFile.getText(), myProject, myEditor.getDocument().getText()); } static boolean showUnscrambledText(UnscrambleSupport unscrambleSupport, String logName, Project project, String textToUnscramble) { String unscrambledTrace = unscrambleSupport == null ? textToUnscramble : unscrambleSupport.unscramble(project,textToUnscramble, logName); if (unscrambledTrace == null) return false; final ConsoleView consoleView = addConsole(project); consoleView.print(unscrambledTrace+"\n", ConsoleViewContentType.ERROR_OUTPUT); consoleView.performWhenNoDeferredOutput( new Runnable() { public void run() { consoleView.scrollTo(0); } } ); return true; } private static ConsoleView addConsole(final Project project){ final ConsoleView consoleView = new ConsoleViewImpl(project); final JavaProgramRunner defaultRunner = ExecutionRegistry.getInstance().getDefaultRunner(); final DefaultActionGroup toolbarActions = new DefaultActionGroup(); final RunContentDescriptor descriptor = new RunContentDescriptor(consoleView, null, new MyConsolePanel(consoleView, toolbarActions), "<Unscrambled Stacktrace>") { public boolean isContentReuseProhibited() { return true; } }; toolbarActions.add(new CloseAction(defaultRunner, descriptor, project)); ExecutionManager.getInstance(project).getContentManager().showRunContent(defaultRunner, descriptor); return consoleView; } private static final class MyConsolePanel extends JPanel { public MyConsolePanel(ExecutionConsole consoleView, ActionGroup toolbarActions) { super(new BorderLayout()); JPanel toolbarPanel = new JPanel(new BorderLayout()); toolbarPanel.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions,false).getComponent()); add(toolbarPanel, BorderLayout.WEST); add(consoleView.getComponent(), BorderLayout.CENTER); } } protected String getDimensionServiceKey(){ return "#com.intellij.unscramble.UnscrambleDialog"; } public JComponent getPreferredFocusedComponent() { return myEditor.getContentComponent(); } }
package net.malisis.core.client.gui.icon; import java.util.Arrays; import net.malisis.core.renderer.icon.MalisisIcon; /** * @author Ordinastie * */ public class GuiIcon extends MalisisIcon { protected MalisisIcon[] icons; public GuiIcon(MalisisIcon icon) { this.icons = new MalisisIcon[] { icon }; } public GuiIcon(MalisisIcon[] icons) { this.icons = icons; } public MalisisIcon getIcon(int index) { if (icons == null || icons.length == 0) return null; return icons[index % icons.length]; } @Override public MalisisIcon flip(boolean horizontal, boolean vertical) { for (MalisisIcon icon : icons) icon.flip(horizontal, vertical); return super.flip(horizontal, vertical); } @Override public void setRotation(int rotation) { for (MalisisIcon icon : icons) icon.setRotation(rotation); super.setRotation(rotation); } @Override public MalisisIcon clip(float offsetXFactor, float offsetYFactor, float widthFactor, float heightFactor) { for (MalisisIcon icon : icons) icon.clip(offsetXFactor, offsetYFactor, widthFactor, heightFactor); return super.clip(offsetXFactor, offsetYFactor, widthFactor, heightFactor); } @Override public MalisisIcon clip(int offsetX, int offsetY, int width, int height) { for (MalisisIcon icon : icons) icon.clip(offsetX, offsetY, width, height); return super.clip(offsetX, offsetY, width, height); } @Override public String toString() { return Arrays.toString(icons); } }
package me.buildcarter8.iBukkit.utils; import java.util.Arrays; import java.util.List; import java.util.Random; import org.bukkit.ChatColor; public class Colors { private static final Random RANDOM = new Random(); public static final List<ChatColor> CHAT_COLOR_POOL = Arrays.asList( ChatColor.DARK_BLUE, ChatColor.DARK_GREEN, ChatColor.DARK_AQUA, ChatColor.DARK_RED, ChatColor.DARK_PURPLE, ChatColor.GOLD, ChatColor.BLUE, ChatColor.GREEN, ChatColor.AQUA, ChatColor.RED, ChatColor.LIGHT_PURPLE, ChatColor.YELLOW); //Allows random chat colors public static ChatColor randChatColor() { return CHAT_COLOR_POOL.get(RANDOM.nextInt(CHAT_COLOR_POOL.size())); } }
package net.jforum.drivers.generic; import java.security.NoSuchAlgorithmException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.jforum.JForum; import net.jforum.drivers.external.LoginAuthenticator; import net.jforum.entities.Group; import net.jforum.entities.KarmaStatus; import net.jforum.entities.User; import net.jforum.model.DataAccessDriver; import net.jforum.util.preferences.ConfigKeys; import net.jforum.util.preferences.SystemGlobals; /** * @author Rafael Steil * @version $Id: UserModel.java,v 1.29 2005/02/07 10:56:29 andowson Exp $ */ public class UserModel extends AutoKeys implements net.jforum.model.UserModel { private static LoginAuthenticator loginAuthenticator; public UserModel() { String className = SystemGlobals.getValue(ConfigKeys.LOGIN_AUTHENTICATOR); try { loginAuthenticator = (LoginAuthenticator)Class.forName(className).newInstance(); loginAuthenticator.setUserModel(this); } catch (Exception e) { throw new RuntimeException("Error while trying to instantiate a " + "login.authenticator instance (" + className + "): " + e); } } /** * @see net.jforum.model.UserModel#selectById(int) */ public User selectById(int userId) throws Exception { String q = SystemGlobals.getSql("UserModel.selectById"); PreparedStatement p = JForum.getConnection().prepareStatement(q); p.setInt(1, userId); ResultSet rs = p.executeQuery(); User u = new User(); if (rs.next()) { this.fillUserFromResultSet(u, rs); u.setPrivateMessagesCount(rs.getInt("private_messages")); // User groups p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.selectGroups")); p.setInt(1, userId); rs = p.executeQuery(); while (rs.next()) { Group g = new Group(); g.setName(rs.getString("group_name")); g.setId(rs.getInt("group_id")); u.getGroupsList().add(g); } } rs.close(); p.close(); return u; } public User selectByName(String username) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.selectByName")); p.setString(1, username); ResultSet rs = p.executeQuery(); User u = null; if (rs.next()) { u = new User(); fillUserFromResultSet(u, rs); } rs.close(); p.close(); return u; } protected void fillUserFromResultSet(User u, ResultSet rs) throws Exception { u.setAim(rs.getString("user_aim")); u.setAvatar(rs.getString("user_avatar")); u.setGender(rs.getString("gender")); u.setRankId(rs.getInt("rank_id")); u.setThemeId(rs.getInt("themes_id")); u.setPrivateMessagesEnabled("1".equals(rs.getString("user_allow_pm"))); u.setNotifyOnMessagesEnabled("1".equals(rs.getString("user_notify"))); u.setViewOnlineEnabled("1".equals(rs.getString("user_viewonline"))); u.setPassword(rs.getString("user_password")); u.setViewEmailEnabled("1".equals(rs.getString("user_viewemail"))); u.setViewOnlineEnabled("1".equals(rs.getString("user_allow_viewonline"))); u.setAvatarEnabled("1".equals(rs.getString("user_allowavatar"))); u.setBbCodeEnabled("1".equals(rs.getString("user_allowbbcode"))); u.setHtmlEnabled("1".equals(rs.getString("user_allowhtml"))); u.setSmiliesEnabled("1".equals(rs.getString("user_allowsmilies"))); u.setEmail(rs.getString("user_email")); u.setFrom(rs.getString("user_from")); u.setIcq(rs.getString("user_icq")); u.setId(rs.getInt("user_id")); u.setInterests(rs.getString("user_interests")); u.setLastVisit(rs.getTimestamp("user_lastvisit")); u.setOccupation(rs.getString("user_occ")); u.setTotalPosts(rs.getInt("user_posts")); u.setRegistrationDate(rs.getTimestamp("user_regdate")); u.setSignature(rs.getString("user_sig")); u.setWebSite(rs.getString("user_website")); u.setYim(rs.getString("user_yim")); u.setUsername(rs.getString("username")); u.setAttachSignatureEnabled(rs.getInt("user_attachsig") == 1); u.setMsnm(rs.getString("user_msnm")); u.setLang(rs.getString("user_lang")); u.setActive(rs.getInt("user_active")); u.setKarma(new KarmaStatus(u.getId(), rs.getDouble("user_karma"))); String actkey = rs.getString("user_actkey"); u.setActivationKey(actkey == null || "".equals(actkey) ? null : actkey); u.setDeleted(rs.getInt("deleted")); } /** * @see net.jforum.model.UserModel#delete(int) */ public void delete(int userId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.deletedStatus")); p.setInt(1, 1); p.setInt(2, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#update(net.jforum.User) */ public void update(User user) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.update")); p.setString(1, user.getAim()); p.setString(2, user.getAvatar()); p.setString(3, user.getGender()); p.setInt(4, user.getThemeId()); p.setInt(5, user.isPrivateMessagesEnabled() ? 1 : 0); p.setInt(6, user.isAvatarEnabled() ? 1 : 0); p.setInt(7, user.isBbCodeEnabled() ? 1 : 0); p.setInt(8, user.isHtmlEnabled() ? 1 : 0); p.setInt(9, user.isSmiliesEnabled() ? 1 : 0); p.setString(10, user.getEmail()); p.setString(11, user.getFrom()); p.setString(12, user.getIcq()); p.setString(13, user.getInterests()); p.setString(14, user.getOccupation()); p.setString(15, user.getSignature()); p.setString(16, user.getWebSite()); p.setString(17, user.getYim()); p.setString(18, user.getMsnm()); p.setString(19, user.getPassword()); p.setInt(20, user.isViewEmailEnabled() ? 1 : 0); p.setInt(21, user.isViewOnlineEnabled() ? 1 : 0); p.setInt(22, user.isNotifyOnMessagesEnabled() ? 1 : 0); p.setInt(23, user.getAttachSignatureEnabled() ? 1 : 0); p.setString(24, user.getUsername()); p.setString(25, user.getLang()); p.setInt(26, user.getId()); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#addNew(net.jforum.User) */ public int addNew(User user) throws Exception { PreparedStatement p = this.getStatementForAutoKeys("UserModel.addNew"); this.initNewUser(user, p); int id = this.executeAutoKeysQuery(p); p.close(); this.addToGroup(id, new int[] { SystemGlobals.getIntValue(ConfigKeys.DEFAULT_USER_GROUP) }); return id; } protected void initNewUser(User user, PreparedStatement p) throws Exception { p.setString(1, user.getUsername()); p.setString(2, user.getPassword()); p.setString(3, user.getEmail()); p.setTimestamp(4, new Timestamp(System.currentTimeMillis())); p.setString(5, user.getActivationKey()); } /** * @see net.jforum.model.UserModel#addNewWithId(net.jforum.User) */ public void addNewWithId(User user) throws Exception { PreparedStatement p = this.getStatementForAutoKeys("UserModel.addNewWithId"); this.initNewUser(user, p); p.setInt(6, user.getId()); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#decrementPosts(int) */ public void decrementPosts(int userId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.decrementPosts")); p.setInt(1, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#incrementPosts(int) */ public void incrementPosts(int userId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.incrementPosts")); p.setInt(1, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#incrementRanking(int) */ public void setRanking(int userId, int rankingId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.rankingId")); p.setInt(1, rankingId); p.setInt(2, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#setActive(int, boolean) */ public void setActive(int userId, boolean active) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.activeStatus")); p.setInt(1, active ? 1 : 0); p.setInt(2, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#undelete(int) */ public void undelete(int userId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.deletedStatus")); p.setInt(1, 0); p.setInt(2, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#selectAll() */ public List selectAll() throws Exception { return selectAll(0, 0); } /** * @see net.jforum.model.UserModel#selectAll(int, int) */ public List selectAll(int startFrom, int count) throws Exception { PreparedStatement p; if (count > 0) { p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.selectAllByLimit")); p.setInt(1, startFrom); p.setInt(2, count); } else { p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.selectAll")); } ResultSet rs = p.executeQuery(); List list = this.processSelectAll(rs); rs.close(); p.close(); return list; } /** * @see net.jforum.model.UserModel#selectAllWithKarma() */ public List selectAllWithKarma() throws Exception { return selectAllWithKarma(0, 0); } /** * @see net.jforum.model.UserModel#selectAllWithKarma(int, int) */ public List selectAllWithKarma(int startFrom, int count) throws Exception { return this.loadKarma( this.selectAll(startFrom, count) ); } protected List processSelectAll(ResultSet rs) throws Exception { List list = new ArrayList(); while (rs.next()) { User u = new User(); u.setEmail(rs.getString("user_email")); u.setId(rs.getInt("user_id")); u.setTotalPosts(rs.getInt("user_posts")); u.setRegistrationDate(rs.getTimestamp("user_regdate")); u.setUsername(rs.getString("username")); u.setDeleted(rs.getInt("deleted")); KarmaStatus karma = new KarmaStatus(); karma.setKarmaPoints(rs.getInt("user_karma")); u.setKarma( karma ); u.setFrom(rs.getString("user_from")); u.setWebSite(rs.getString("user_website")); list.add(u); } return list; } /** * @see net.jforum.model.UserModel#getLastUserInfo() */ public User getLastUserInfo() throws Exception { User u = new User(); PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.lastUserRegistered")); ResultSet rs = p.executeQuery(); rs.next(); u.setUsername(rs.getString("username")); u.setId(rs.getInt("user_id")); rs.close(); p.close(); return u; } /** * @see net.jforum.model.UserModel#getTotalUsers() */ public int getTotalUsers() throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.totalUsers")); ResultSet rs = p.executeQuery(); rs.next(); int total = rs.getInt("total_users"); rs.close(); p.close(); return total; } /** * @see net.jforum.model.UserModel#isDeleted(int user_id) */ public boolean isDeleted(int userId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.isDeleted")); p.setInt(1, userId); int deleted = 0; ResultSet rs = p.executeQuery(); if (rs.next()) { deleted = rs.getInt("deleted"); } rs.close(); p.close(); return deleted == 1; } /** * @see net.jforum.model.UserModel#isUsernameRegistered(java.lang.String) */ public boolean isUsernameRegistered(String username) throws Exception { boolean status = false; PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.isUsernameRegistered")); p.setString(1, username); ResultSet rs = p.executeQuery(); if (rs.next() && rs.getInt("registered") > 0) { status = true; } rs.close(); p.close(); return status; } /** * @see net.jforum.model.UserModel#validateLogin(java.lang.String, java.lang.String) */ public User validateLogin(String username, String password) throws NoSuchAlgorithmException, Exception { return loginAuthenticator.validateLogin(username, password); } /** * @see net.jforum.model.UserModel#addToGroup(int, int[]) */ public void addToGroup(int userId, int[] groupId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.addToGroup")); p.setInt(1, userId); for (int i = 0; i < groupId.length; i++) { p.setInt(2, groupId[i]); p.executeUpdate(); } p.close(); } /** * @see net.jforum.model.UserModel#removeFromGroup(int, int[]) */ public void removeFromGroup(int userId, int[] groupId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.removeFromGroup")); p.setInt(1, userId); for (int i = 0; i < groupId.length; i++) { p.setInt(2, groupId[i]); p.executeUpdate(); } p.close(); } /** * @see net.jforum.model.UserModel#saveNewPassword(java.lang.String, java.lang.String) */ public void saveNewPassword(String password, String email) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.saveNewPassword")); p.setString(1, password); p.setString(2, email); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#validateLostPasswordHash(java.lang.String, java.lang.String) */ public boolean validateLostPasswordHash(String email, String hash) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.validateLostPasswordHash")); p.setString(1, hash); p.setString(2, email); boolean status = false; ResultSet rs = p.executeQuery(); if (rs.next() && rs.getInt("valid") == 1) { status = true; this.writeLostPasswordHash(email, ""); } rs.close(); p.close(); return status; } /** * @see net.jforum.model.UserModel#writeLostPasswordHash(java.lang.String, java.lang.String) */ public void writeLostPasswordHash(String email, String hash) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.writeLostPasswordHash")); p.setString(1, hash); p.setString(2, email); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#getUsernameByEmail(java.lang.String) */ public String getUsernameByEmail(String email) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.getUsernameByEmail")); p.setString(1, email); String username = ""; ResultSet rs = p.executeQuery(); if (rs.next()) { username = rs.getString("username"); } rs.close(); p.close(); return username; } /** * @see net.jforum.model.UserModel#findByName(java.lang.String, boolean) */ public List findByName(String input, boolean exactMatch) throws Exception { List namesList = new ArrayList(); PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.findByName")); p.setString(1, exactMatch ? input : "%" + input + "%"); ResultSet rs = p.executeQuery(); while (rs.next()) { User u = new User(); u.setId(rs.getInt("user_id")); u.setUsername(rs.getString("username")); u.setEmail(rs.getString("user_email")); namesList.add(u); } rs.close(); p.close(); return namesList; } /** * @see net.jforum.model.UserModel#validateActivationKeyHash(int, java.lang.String) */ public boolean validateActivationKeyHash(int userId , String hash) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.validateActivationKeyHash")); p.setString(1, hash); p.setInt(2, userId); boolean status = false; ResultSet rs = p.executeQuery(); if (rs.next() && rs.getInt("valid") == 1) { status = true; } rs.close(); p.close(); return status; } /** * @see net.jforum.model.UserModel#writeUserActive(int) */ public void writeUserActive(int userId) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.writeUserActive")); p.setInt(1, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#updateUsername(int, String) */ public void updateUsername(int userId, String username) throws Exception { PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.updateUsername")); p.setString(1, username); p.setInt(2, userId); p.executeUpdate(); p.close(); } /** * @see net.jforum.model.UserModel#hasUsernameChanged(int, java.lang.String) */ public boolean hasUsernameChanged(int userId, String usernameToCheck) throws Exception { boolean status = false; PreparedStatement p = JForum.getConnection().prepareStatement(SystemGlobals.getSql("UserModel.getUsername")); p.setString(1, usernameToCheck); p.setInt(2, userId); String dbUsername = null; ResultSet rs = p.executeQuery(); if (rs.next()) { dbUsername = rs.getString("username"); } if (!usernameToCheck.equals(dbUsername)) { status = true; } rs.close(); p.close(); return status; } /** * Load KarmaStatus from a list of users. * @param users * @return * @throws Exception */ protected List loadKarma(List users) throws Exception{ List result = new ArrayList(users.size()); User user = null; Iterator iter = users.iterator(); while (iter.hasNext()) { user = (User) iter.next(); //load Karma DataAccessDriver.getInstance().newKarmaModel().getUserTotalKarma(user); result.add(user); } return result; } }
package netspy.components.logging; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import netspy.components.filehandling.manager.FileManager; import netspy.components.mailing.Email; /** * The Class LogManager. */ public class LogManager { /** The date format logging. */ public final String LOG_FORMAT = "dd-MM-yyyy HH:mm:ss"; /** The Constant LOG_FILE_PREFIX. */ public final String LOG_FILE_PREFIX = "log_"; /** The Constant LOG_FILE_EXTENSION. */ public final String LOG_FILE_EXTENSION = ".txt"; /** The Constant LOG_PATH. */ public final String LOG_PATH = "log/"; /** The Constant LOG_ENTRY_SEPARATOR. */ private static final String LOG_ENTRY_SEPARATOR = " | "; /** * Log. * * @param scanResult the scan result */ public void log(Email email) { String logLine = "Scan vom: " + new SimpleDateFormat(LOG_FORMAT).format(new Date()); logLine += LOG_ENTRY_SEPARATOR; logLine += "Gesendet am: " + email.getSendingDate(); logLine += LOG_ENTRY_SEPARATOR; logLine += "Betreff: " + email.getSubject(); logLine += LOG_ENTRY_SEPARATOR; logLine += "Absender: " + email.getSender(); logLine += LOG_ENTRY_SEPARATOR; logLine += "Empfänger: " + email.getReceiver(); logLine += LOG_ENTRY_SEPARATOR; logLine += "Dateiname: " + email.getFilename(); logLine += LOG_ENTRY_SEPARATOR; logLine += "Gefundene Wörter: " + email.getHitMap().entrySet().toString(); new FileManager().createLogfile(); new FileManager().log(FileManager.LOG_FILE, logLine); } /** * Gets the formatted date. * * @param dateFormat the date format * @return the formatted date as String */ }
package com.intellij.util; import com.intellij.openapi.util.SystemInfo; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; /** * Utility wrappers for accessing system properties. * * @see SystemInfo * @author yole */ public class SystemProperties { private static String ourTestUserName; private SystemProperties() { } @NotNull public static String getUserHome() { return System.getProperty("user.home"); } public static String getUserName() { return ourTestUserName != null ? ourTestUserName : System.getProperty("user.name"); } @TestOnly public static void setTestUserName(@Nullable String name) { ourTestUserName = name; } public static String getLineSeparator() { return System.getProperty("line.separator"); } /** @deprecated use {@link SystemInfo#OS_NAME} (to be removed in IDEA 2020) */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2020") public static String getOsName() { return SystemInfo.OS_NAME; } /** @deprecated use {@link SystemInfo#JAVA_VERSION} (to be removed in IDEA 2020) */ @Deprecated public static String getJavaVersion() { return SystemInfo.JAVA_VERSION; } /** @deprecated use {@link SystemInfo#JAVA_VENDOR} (to be removed in IDEA 2020) */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2020") public static String getJavaVmVendor() { return SystemInfo.JAVA_VENDOR; } public static String getJavaHome() { return System.getProperty("java.home"); } /** * Returns the value of given property as integer, or {@code defaultValue} if the property is not specified or malformed. */ public static int getIntProperty(@NotNull final String key, final int defaultValue) { final String value = System.getProperty(key); if (value != null) { try { return Integer.parseInt(value); } catch (NumberFormatException ignored) { } } return defaultValue; } public static float getFloatProperty(@NotNull String key, float defaultValue) { String value = System.getProperty(key); if (value != null) { try { return Float.parseFloat(value); } catch (NumberFormatException ignored) { } } return defaultValue; } /** * Returns the value of given property as a boolean, or {@code defaultValue} if the property is not specified or malformed. */ public static boolean getBooleanProperty(@NotNull final String key, final boolean defaultValue) { final String value = System.getProperty(key); if (value != null) { return Boolean.parseBoolean(value); } return defaultValue; } /** @deprecated use {@link SystemInfo#JAVA_VENDOR} (to be removed in IDEA 2020) */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2020") public static String getJavaVendor() { return SystemInfo.JAVA_VENDOR; } public static boolean is(String key) { return getBooleanProperty(key, false); } public static boolean has(String key) { return System.getProperty(key) != null; } public static boolean isTrueSmoothScrollingEnabled() { return getBooleanProperty("idea.true.smooth.scrolling", false); } }
package soot.jimple.spark.sets; import soot.Type; import soot.util.BitSetIterator; import soot.util.BitVector; import soot.jimple.spark.pag.Node; import soot.jimple.spark.pag.PAG; import java.util.*; /* * Possible sources of inefficiency: * -It seems like there must be a way to immediately know which subset bitvector * will exist, since sets are shared when a node with a smaller points-to set is * pointing to another node. Why not just take that node's bitvector as a base? * -addAll could probably use many improvements. * -Cast masking - calling typeManager.get * -An interesting problem is that when merging a bitvector into an overflow list, if * the one being merged * in has a bitvector, the mask or exclude might mask it down to a bitvector with very * few ones. (In fact, this might even result in one with 0 ones!) * Should that new bitvector stay as a bitvector, or be converted to an * overflow list? And how can we tell when it will have few ones? (Modify BitVector?) * */ /** * A shared representation of a points-to set which uses a bit vector + a list * of extra elements, an "overflow list", to make adding single elements fast in * most cases. * * The bit vector may be shared by multiple points-to sets, while the overflow * list is specific to each points-to set. * * To facilitate sharing of the bitvectors, there is a "hash table" of all * existing bitvectors kept, called BitVectorLookupMap, where the ith element * contains a list of all existing bitvectors of cardinality i (i.e. has i one * bits). * * @author Adam Richard * */ public class SharedHybridSet extends PointsToSetInternal { public SharedHybridSet(Type type, PAG pag) { // I'm not sure what "type" is for, but this is the way the other set // representations // did it super(type); this.pag = pag; } // The following 2 constants should be tweaked for efficiency public final static int OVERFLOW_SIZE = 20; /** * The max number of elements allowed in the set before creating a new * bitvector for it. */ public final static int OVERFLOW_THRESHOLD = 5; /** * When the overflow list overflows, the maximum number of elements that may * remain in the overflow list (the rest are moved into the base bit vector) */ public boolean contains(Node n) { // Which should be checked first, bitVector or overflow? (for // performance) // I think the bit vector, since it only takes O(1) to check many // elements // Check the bit vector if (bitVector != null && bitVector.contains(n)) return true; // Check overflow if (overflow.contains(n)) return true; return false; } public boolean isEmpty() { return numElements == 0; } /** * @return an overflow list of all elements in a that aren't in b (b is * assumed to be a subset of a) */ private OverflowList remainder(PointsToBitVector a, PointsToBitVector b) { // Since a contains everything b contains, doing an XOR will give // everything // in a not in b PointsToBitVector xorResult = new PointsToBitVector(a); xorResult.xor(b); // xorResult must now contain <= 20 elements, assuming // OVERFLOW_THRESHOLD <= OVERFLOW_SIZE return new OverflowList(xorResult); } // Look for an existing bitvector in the lookupMap which is a subset of the // newBitVector (the bitVector to set as the new points-to set), with only a // few // elements missing. If we find one, make that set the new `bitVector', and // the leftovers the new `overflow' //szBitVector is the size of the ORIGINAL bit vector, NOT the size of newBitVector private void findAppropriateBitVector(PointsToBitVector newBitVector, PointsToBitVector otherBitVector, int otherSize, int szBitvector) { //First check "other" and "this"'s bitvector, to maximize sharing and //minimize searching for a new bitvector if (otherBitVector != null && otherSize <= numElements && otherSize + OVERFLOW_THRESHOLD >= numElements && otherBitVector.isSubsetOf(newBitVector)) { setNewBitVector(szBitvector, otherBitVector); overflow = remainder(newBitVector, otherBitVector); } else if (bitVector != null && szBitvector <= numElements && szBitvector + OVERFLOW_THRESHOLD >= numElements && bitVector.isSubsetOf(newBitVector)) { overflow = remainder(newBitVector, bitVector); } else { for (int overFlowSize = 0; overFlowSize < OVERFLOW_THRESHOLD; ++overFlowSize) { int bitVectorCardinality = numElements - overFlowSize; if (bitVectorCardinality < 0) break; //We might be trying to add a bitvector //with <OVERFLOW_THRESHOLD ones (in fact, there might be bitvectors with 0 //ones). This results from merging bitvectors and masking out certain values. if (bitVectorCardinality < AllSharedHybridNodes.v().lookupMap.map.length && AllSharedHybridNodes.v().lookupMap.map[bitVectorCardinality] != null) { ListIterator i = AllSharedHybridNodes.v().lookupMap.map[bitVectorCardinality] .listIterator(); while (i.hasNext()) { // for each existing bit vector with bitVectorCardinality // ones PointsToBitVector candidate = (PointsToBitVector) (i.next()); if (candidate.isSubsetOf(newBitVector)) { setNewBitVector(szBitvector, candidate); overflow = remainder(newBitVector, candidate); return; } } } } // Didn't find an appropriate bit vector to use as a base; add the new // bit vector to the map of all bit vectors and set it as the new base // bit vector setNewBitVector(szBitvector, newBitVector); overflow.removeAll(); AllSharedHybridNodes.v().lookupMap.add(numElements, newBitVector); } } //Allows for reference counting and deleting the old bit vector if it //isn't being shared private void setNewBitVector(int size, PointsToBitVector newBitVector) { newBitVector.incRefCount(); if (bitVector != null) { bitVector.decRefCount(); if (bitVector.unused()) { //delete bitVector from lookupMap AllSharedHybridNodes.v().lookupMap.remove(size, bitVector); } } bitVector = newBitVector; } public boolean add(Node n) { /* * This algorithm is described in the paper "IBM Research Report: Fast * Pointer Analysis" by Hirzel, Dincklage, Diwan, and Hind, pg. 11 */ if (contains(n)) return false; ++numElements; if (!overflow.full()) { overflow.add(n); } else { // Put everything in the bitvector PointsToBitVector newBitVector; if (bitVector == null) newBitVector = new PointsToBitVector(pag.getAllocNodeNumberer() .size()); else newBitVector = new PointsToBitVector(bitVector); newBitVector.add(n); // add n to it newBitVector.add(overflow.overflow, overflow.size()); // add // overflow // newBitVector // Now everything is in newBitVector, and it must have numElements // ones // The algorithm would still work without this step, but wouldn't be // shared implmentation at all. findAppropriateBitVector(newBitVector, null, 0, numElements - overflow.size() - 1); } return true; } private boolean nativeAddAll(SharedHybridSet other, SharedHybridSet exclude) { /* * If one of the shared hybrid sets has a bitvector but the other * doesn't, set that bitvector as the base bitvector and add the stuff * from the other overflow list. If they both have a bitvector, AND them * together, then add it to the lookupMap. If neither of them has a * bitvector, just combine the overflow lists. */ BitVector mask = getBitMask(other, pag); if (exclude != null) { if (exclude.overflow.size() > 0) { // Make exclude only a bitvector, for simplicity PointsToBitVector newBitVector; if (exclude.bitVector == null) { newBitVector = new PointsToBitVector(pag.getAllocNodeNumberer() .size()); } else { newBitVector = new PointsToBitVector(exclude.bitVector); } newBitVector .add(exclude.overflow.overflow, exclude.overflow.size()); exclude = new SharedHybridSet(type, pag); exclude.bitVector = newBitVector; } //It's possible at this point that exclude could have been passed in non-null, //but with no elements. Simplify the rest of the algorithm by setting it to null //in that case. else if (exclude.bitVector == null) exclude = null; } int originalSize = size(), originalOnes = originalSize - overflow.size(), otherBitVectorSize = other.size() - other.overflow.size(); // Decide on the base bitvector if (bitVector == null) { bitVector = other.bitVector; if (bitVector != null) { // Maybe both bitvectors were null; in // that case, no need to do this bitVector.incRefCount(); // Since merging in new bits might add elements that // were // already in the overflow list, we have to remove and re-add // them all. // TODO: Can this be avoided somehow? // Maybe by allowing an element to be both in the overflow set // and // the bitvector? // Or could it be better done by checking just the bitvector and // removing elements that are there? OverflowList toReAdd = overflow; overflow = new OverflowList(); boolean newBitVectorCreated = false; //whether a new bit vector //was created, which is used to decide whether to re-add the //overflow list as an overflow list again or merge it into the //new bit vector. numElements = otherBitVectorSize; if (exclude != null || mask != null) { PointsToBitVector result = new PointsToBitVector(bitVector); if (exclude != null) result.andNot(exclude.bitVector); if (mask != null) result.and(mask); if (!result.equals(bitVector)) { result.add(toReAdd.overflow, toReAdd.size()); int newBitVectorSize = result.cardinality(); numElements = newBitVectorSize; findAppropriateBitVector(result, other.bitVector, otherBitVectorSize, otherBitVectorSize); newBitVectorCreated = true; } } if (!newBitVectorCreated) //if it was, then toReAdd has //already been re-added { for (int i = 0; i < toReAdd.size(); ++i) { add(toReAdd.overflow[i]); } } } } else if (other.bitVector != null) { // Now both bitvectors are non-null; merge them PointsToBitVector newBitVector = new PointsToBitVector(other.bitVector); if (exclude != null) newBitVector.andNot(exclude.bitVector); if (mask != null) newBitVector.and(mask); newBitVector.or(bitVector); if (!newBitVector.equals(bitVector)) // if some elements were // actually added { //At this point newBitVector is bitVector + some new bits // Have to make a tough choice - is it better at this point to // put both overflow lists into this bitvector (which involves // recalculating bitVector.cardinality() again since there might // have been overlap), or is it better to re-add both the // overflow lists to the set? // I suspect the former, so I'll do that. // Basically we now want to merge both overflow lists into this // new // bitvector (if it is indeed a new bitvector), then add that // resulting // huge bitvector to the lookupMap, unless a subset of it is // already there. if (other.overflow.size() != 0) { PointsToBitVector toAdd = new PointsToBitVector(newBitVector.size()); toAdd.add(other.overflow.overflow, other.overflow.size()); if (mask != null) toAdd.and(mask); if (exclude != null) toAdd.andNot(exclude.bitVector); newBitVector.or(toAdd); } //At this point newBitVector is still bitVector + some new bits int numOnes = newBitVector.cardinality(); //# of bits in the //new bitvector int numAdded = newBitVector.add(overflow.overflow, overflow.size()); numElements += numOnes - originalOnes //number of new bits + numAdded - overflow.size(); //might be negative due to //elements in overflow already being in the new bits if (size() > originalSize) { findAppropriateBitVector(newBitVector, other.bitVector, otherBitVectorSize, originalOnes); //checkSize(); return true; } else { //checkSize(); return false; //It might happen that the bitvector being merged in adds some bits //to the existing bitvector, but that those new bits are all elements that were already //in the overflow list. In that case, the set might not change, and if not we return false. //We also leave the set the way it was by not calling findAppropriateBitvector, //which maximizes sharing and is fastest in the short term. I'm not sure whether it //would be faster overall to keep the already calculated bitvector anyway. } } } // Add all the elements in the overflow list of other, unless they're in // exclude OverflowList overflow = other.overflow; for (int i = 0; i < overflow.size(); ++i) { Node nodeToMaybeAdd = overflow.overflow[i]; // Here's where // overloaded operators // would be better if ((exclude == null) || !exclude.contains(nodeToMaybeAdd)) { if (mask == null || mask.get(nodeToMaybeAdd.getNumber())) { add(nodeToMaybeAdd); } } } //checkSize(); return size() > originalSize; } //A class invariant - numElements correctly holds the size //Only used for testing private void checkSize() { int realSize = overflow.size(); if (bitVector != null) realSize += bitVector.cardinality(); if (numElements != realSize) { throw new RuntimeException("Assertion failed."); } } public boolean addAll(PointsToSetInternal other, final PointsToSetInternal exclude) { // Look at the sort of craziness we have to do just because of a lack of // multimethods if (other == null) return false; if ((!(other instanceof SharedHybridSet)) || (exclude != null && !(exclude instanceof SharedHybridSet))) { return super.addAll(other, exclude); } else { return nativeAddAll((SharedHybridSet) other, (SharedHybridSet) exclude); } } public boolean forall(P2SetVisitor v) { // Iterate through the bit vector. Ripped from BitPointsToSet again. // It seems there should be a way to share code between BitPointsToSet // and // SharedHybridSet, but I don't know how at the moment. if (bitVector != null) { for (BitSetIterator it = bitVector.iterator(); it.hasNext();) { v.visit((Node) pag.getAllocNodeNumberer().get(it.next())); } } // Iterate through the overflow list for (int i = 0; i < overflow.size(); ++i) { v.visit(overflow.overflow[i]); } return v.getReturnValue(); } // Ripped from the other points-to sets - returns a factory that can be // used to construct SharedHybridSets public final static P2SetFactory getFactory() { return new P2SetFactory() { public final PointsToSetInternal newSet(Type type, PAG pag) { return new SharedHybridSet(type, pag); } }; } private PointsToBitVector bitVector = null; // Shared with other points-to // sets private OverflowList overflow = new OverflowList(); private PAG pag; // I think this is needed to get the size of the bit // vector and the mask for casting private int numElements = 0; // # of elements in the set public int size() { return numElements; } private class OverflowList { public OverflowList() { } public OverflowList(PointsToBitVector bv) { BitSetIterator it = bv.iterator(); // Iterates over only the 1 bits while (it.hasNext()) { // Get the next node in the bitset by looking it up in the // pointer assignment graph. // Ripped from BitPointsToSet. Node n = (Node) (pag.getAllocNodeNumberer().get(it.next())); add(n); } } public void add(Node n) { if (full()) throw new RuntimeException( "Can't add an element to a full overflow list."); overflow[overflowElements] = n; overflowElements++; } public int size() { return overflowElements; } public boolean full() { return overflowElements == OVERFLOW_SIZE; } public boolean contains(Node n) { for (int i = 0; i < overflowElements; ++i) { if (n == overflow[i]) return true; } return false; } public void removeAll() { overflow = new Node[OVERFLOW_SIZE]; overflowElements = 0; } public Node[] overflow = new Node[OVERFLOW_SIZE]; // Not shared with // other // points-to sets - the extra elements besides the ones in bitVector private int overflowElements = 0; // # of elements actually in the // array `overflow' } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package robot; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Victor; /** * Class that owns the intake system of the robot. Includes belts and unobtanium. * * @author Tanner Smith (creator) * @package robot */ public class Intake { private Joystick joystick; private Victor beltMotorOne, beltMotorTwo, unobtaniumMotor; private int intakeMode, previousMode; private DriverStation driverStation; private ButtonChange intakeButton; /** * Creates our intake system. * @param joystick Joystick of which it is to be controlled by. * @param intakeMotorOne First belt motor. * @param intakeMotorTwo Second belt motor. * @param unobtaniumMotor Unobtanium motor. */ public Intake(Joystick joystick, Victor beltMotorOne, Victor beltMotorTwo, Victor unobtaniumMotor) { this.joystick = joystick; this.beltMotorOne = beltMotorOne; this.beltMotorTwo = beltMotorTwo; this.unobtaniumMotor = unobtaniumMotor; //Set our mode to nothing so we don't go anywhere until they, the enlightened ones, tell us to. intakeMode = 0; previousMode = 0; driverStation = DriverStation.getInstance(); //Initialize button change object intakeButton = new ButtonChange(joystick, 3); } /** * Perform the actions that the mode we are in requires. */ public void doAction() { double beltSpeed = 0; double unobtaniumSpeed = 0; //Set the mode of the system, based on our button input if (intakeButton.didButtonChange(true)) { //Intake Button - Only do this if we let go of the button if (intakeMode == 1) { //Mode is at intake, ergo stop. intakeMode = 0; } else { //Mode is not at intake intakeMode = 1; } } else { //Reverse Button toggleModeFromJoystickButton(2, -1); //Fire Button toggleModeFromJoystickButton(1, 2); } //Put our chosen mode into action! switch (intakeMode) { case -1: //Reverse mode beltSpeed = 1; unobtaniumSpeed = 0; break; case 0: //Stop mode beltSpeed = 0; unobtaniumSpeed = 0; break; case 1: //Intake mode beltSpeed = -1; unobtaniumSpeed = 0.5; break; case 2: //Fire mode beltSpeed = -1; unobtaniumSpeed = -1; break; default: //Ahhh! mode beltSpeed = 0; unobtaniumSpeed = 0; break; } //Put mode into action setBeltSpeed(beltSpeed); setUnobtaniumSpeed(unobtaniumSpeed); intakeButton.setPreviousState(); } /** * Switch the mode using the desired joystick button like a toggle switch. * i.e. Press once turns it on or off depending on its current state * @param joystickButton The joystick button you plan to use as a toggle button * @param desiredMode The mode you want to goto with the toggle switch */ public void toggleModeFromJoystickButton(int joystickButton, int desiredMode) { if (joystick.getRawButton(joystickButton)) { //Joystick button was hit if (intakeMode != desiredMode) { //Don't set the previous mode if I'm already in the new mode //i.e. - No infinite loops! previousMode = intakeMode; } intakeMode = desiredMode; } else if (!joystick.getRawButton(joystickButton) && intakeMode == desiredMode) { //We don't want to be acting anymore intakeMode = previousMode; previousMode = 0; } } /** * Set the speed of the both belt motors. * @param speed Value of motor speed from -1 to 1 */ public void setBeltSpeed(double speed) { //As a safety measure of un-tested code, the following line is commented out to prevent *boom* beltMotorOne.set(speed); beltMotorTwo.set(speed); } /** * Set the speed of the unobtanium motor for easy access. * @param speed Value of motor speed from -1 to 1 */ public void setUnobtaniumSpeed(double speed) { unobtaniumMotor.set(speed); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; import javax.servlet.*; public class TranslatorReaderTest extends TestCase { Properties props = new Properties(); Vector created = new Vector(); static final String PAGE_NAME = "testpage"; TestEngine testEngine; public TranslatorReaderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); props.setProperty( "jspwiki.translatorReader.matchEnglishPlurals", "true" ); testEngine = new TestEngine( props ); } public void tearDown() { deleteCreatedPages(); } private void newPage( String name ) { testEngine.saveText( name, "<test>" ); created.addElement( name ); } private void deleteCreatedPages() { for( Iterator i = created.iterator(); i.hasNext(); ) { String name = (String) i.next(); testEngine.deletePage(name); } created.clear(); } private String translate( String src ) throws IOException, NoRequiredPropertyException, ServletException { WikiContext context = new WikiContext( testEngine, PAGE_NAME ); Reader r = new TranslatorReader( context, new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } public void testHyperlinks2() throws Exception { newPage("Hyperlink"); String src = "This should be a [hyperlink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>\n", translate(src) ); } public void testHyperlinks3() throws Exception { newPage("HyperlinkToo"); String src = "This should be a [hyperlink too]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>\n", translate(src) ); } public void testHyperlinks4() throws Exception { newPage("HyperLink"); String src = "This should be a [HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>\n", translate(src) ); } public void testHyperlinks5() throws Exception { newPage("HyperLink"); String src = "This should be a [here|HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">here</A>\n", translate(src) ); } /** When using CC links, this seems to crash 1.9.2. */ public void testHyperLinks6() throws Exception { newPage("DiscussionAboutWiki"); newPage("WikiMarkupDevelopment"); String src = "[DiscussionAboutWiki] [WikiMarkupDevelopment]."; assertEquals( "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=DiscussionAboutWiki\">DiscussionAboutWiki</A> <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=WikiMarkupDevelopment\">WikiMarkupDevelopment</A>.\n", translate(src) ); } public void testHyperlinksCC() throws Exception { newPage("HyperLink"); String src = "This should be a HyperLink."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>.\n", translate(src) ); } public void testHyperlinksCCNonExistant() throws Exception { String src = "This should be a HyperLink."; assertEquals( "This should be a <U>HyperLink</U><A HREF=\"Edit.jsp?page=HyperLink\">?</A>.\n", translate(src) ); } /** * Check if the CC hyperlink translator gets confused with * unorthodox bracketed links. */ public void testHyperlinksCC2() throws Exception { newPage("HyperLink"); String src = "This should be a [ HyperLink ]."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\"> HyperLink </A>.\n", translate(src) ); } public void testHyperlinksCC3() throws Exception { String src = "This should be a nonHyperLink."; assertEquals( "This should be a nonHyperLink.\n", translate(src) ); } /** Two links on same line. */ public void testHyperlinksCC4() throws Exception { newPage("HyperLink"); newPage("ThisToo"); String src = "This should be a HyperLink, and ThisToo."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.\n", translate(src) ); } /** Two mixed links on same line. */ public void testHyperlinksCC5() throws Exception { newPage("HyperLink"); newPage("ThisToo"); String src = "This should be a [HyperLink], and ThisToo."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.\n", translate(src) ); } /** Closing tags only. */ public void testHyperlinksCC6() throws Exception { newPage("HyperLink"); newPage("ThisToo"); String src = "] This ] should be a HyperLink], and ThisToo."; assertEquals( "] This ] should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>], and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.\n", translate(src) ); } /** First and last words on line. */ public void testHyperlinksCCFirstAndLast() throws Exception { newPage("HyperLink"); newPage("ThisToo"); String src = "HyperLink, and ThisToo"; assertEquals( "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>\n", translate(src) ); } /** Hyperlinks inside URIs. */ public void testHyperlinksCCURLs() throws Exception { String src = "http: assertEquals( "http: translate(src) ); } public void testHyperlinksCCNegated() throws Exception { String src = "This should not be a ~HyperLink."; assertEquals( "This should not be a HyperLink.\n", translate(src) ); } public void testHyperlinksCCNegated2() throws Exception { String src = "~HyperLinks should not be matched."; assertEquals( "HyperLinks should not be matched.\n", translate(src) ); } public void testHyperlinksExt() throws Exception { String src = "This should be a [http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksExt2() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksPluralMatch() throws Exception { String src = "This should be a [HyperLinks]"; newPage("HyperLink"); assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLinks</A>\n", translate(src) ); } public void testHyperlinksPluralMatch2() throws Exception { String src = "This should be a [HyperLinks]"; assertEquals( "This should be a <U>HyperLinks</U><A HREF=\"Edit.jsp?page=HyperLinks\">?</A>\n", translate(src) ); } public void testHyperlinksPluralMatch3() throws Exception { String src = "This should be a [HyperLink]"; newPage("HyperLinks"); assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLinks\">HyperLink</A>\n", translate(src) ); } public void testHyperlinkJS1() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksInterWiki1() throws Exception { String src = "This should be a [link|JSPWiki:HyperLink]"; assertEquals( "This should be a <A CLASS=\"interwiki\" HREF=\"http: translate(src) ); } public void testNoHyperlink() throws Exception { newPage("HyperLink"); String src = "This should not be a [[HyperLink]"; assertEquals( "This should not be a [HyperLink]\n", translate(src) ); } public void testNoHyperlink2() throws Exception { String src = "This should not be a [[[[HyperLink]"; assertEquals( "This should not be a [[[HyperLink]\n", translate(src) ); } public void testNoHyperlink3() throws Exception { String src = "[[HyperLink], and this [[Neither]."; assertEquals( "[HyperLink], and this [Neither].\n", translate(src) ); } public void testErroneousHyperlink() throws Exception { String src = "What if this is the last char ["; assertEquals( "What if this is the last char \n", translate(src) ); } public void testErroneousHyperlink2() throws Exception { String src = "What if this is the last char [["; assertEquals( "What if this is the last char [\n", translate(src) ); } public void testExtraPagename1() throws Exception { String src = "Link [test_page]"; newPage("Test_page"); assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test_page\">test_page</A>\n", translate(src) ); } public void testExtraPagename2() throws Exception { String src = "Link [test.page]"; newPage("Test.page"); assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test.page\">test.page</A>\n", translate(src) ); } public void testExtraPagename3() throws Exception { String src = "Link [.testpage_]"; newPage(".testpage_"); assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=.testpage_\">.testpage_</A>\n", translate(src) ); } public void testInlineImages() throws Exception { String src = "Link [test|http: assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http: translate(src) ); } public void testInlineImages2() throws Exception { String src = "Link [test|http: assertEquals("Link <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testInlineImages3() throws Exception { String src = "Link [test|http://images.com/testi]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://images.com/testi\" ALT=\"test\">\n", translate(src) ); } public void testInlineImages4() throws Exception { String src = "Link [test|http://foobar.jpg]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"test\">\n", translate(src) ); } // No link text should be just embedded link. public void testInlineImagesLink2() throws Exception { String src = "Link [http://foobar.jpg]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http: translate(src) ); } public void testInlineImagesLink() throws Exception { String src = "Link [http: assertEquals("Link <A HREF=\"http: translate(src) ); } public void testInlineImagesLink3() throws Exception { String src = "Link [SandBox|http://foobar.jpg]"; newPage("SandBox"); assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=SandBox\"><IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"SandBox\"></A>\n", translate(src) ); } public void testScandicPagename1() throws Exception { String src = "Link [Test]"; newPage("Test"); // FIXME: Should be capital assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=%C5%E4Test\">Test</A>\n", translate(src)); } public void testParagraph() throws Exception { String src = "1\n\n2\n\n3"; assertEquals( "1\n<P>\n2\n<P>\n3\n", translate(src) ); } public void testLinebreak() throws Exception { String src = "1\\\\2"; assertEquals( "1<BR>2\n", translate(src) ); } public void testTT() throws Exception { String src = "1{{2345}}6"; assertEquals( "1<TT>2345</TT>6\n", translate(src) ); } public void testTTAcrossLines() throws Exception { String src = "1{{\n2345\n}}6"; assertEquals( "1<TT>\n2345\n</TT>6\n", translate(src) ); } public void testTTLinks() throws Exception { String src = "1{{\n2345\n[a link]\n}}6"; newPage("ALink"); assertEquals( "1<TT>\n2345\n<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ALink\">a link</A>\n</TT>6\n", translate(src) ); } public void testPre() throws Exception { String src = "1{{{2345}}}6"; assertEquals( "1<PRE>2345</PRE>6\n", translate(src) ); } public void testPre2() throws Exception { String src = "1 {{{ {{{ 2345 }}} }}} 6"; assertEquals( "1 <PRE> {{{ 2345 </PRE> }}} 6\n", translate(src) ); } public void testList1() throws Exception { String src = "A list:\n* One\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } /** Plain multi line testing: <pre> * One continuing * Two * Three </pre> */ public void testMultilineList1() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } public void testMultilineList2() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\nShould be normal."; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\nShould be normal.\n", translate(src) ); } public void testHTML() throws Exception { String src = "<B>Test</B>"; assertEquals( "&lt;B&gt;Test&lt;/B&gt;\n", translate(src) ); } public void testHTML2() throws Exception { String src = "<P>"; assertEquals( "&lt;P&gt;\n", translate(src) ); } public void testQuotes() throws Exception { String src = "\"Test\"\""; assertEquals( "&quot;Test&quot;&quot;\n", translate(src) ); } public void testItalicAcrossLinebreak() throws Exception { String src="''This is a\ntest.''"; assertEquals( "<I>This is a\ntest.</I>\n", translate(src) ); } public void testBoldAcrossLinebreak() throws Exception { String src="__This is a\ntest.__"; assertEquals( "<B>This is a\ntest.</B>\n", translate(src) ); } public void testBoldItalic() throws Exception { String src="__This ''is'' a test.__"; assertEquals( "<B>This <I>is</I> a test.</B>\n", translate(src) ); } public void testFootnote1() throws Exception { String src="Footnote[1]"; assertEquals( "Footnote<A CLASS=\"footnoteref\" HREF=\"#ref-testpage-1\">[1]</A>\n", translate(src) ); } public void testFootnote2() throws Exception { String src="[#2356] Footnote."; assertEquals( "<A CLASS=\"footnote\" NAME=\"ref-testpage-2356\">[#2356]</A> Footnote.\n", translate(src) ); } /** Check an reported error condition where empty list items could cause crashes */ public void testEmptySecondLevelList() throws Exception { String src="A\n\n**\n\nB"; assertEquals( "A\n<P>\n<UL>\n<UL>\n<LI>\n</UL>\n</UL>\n<P>\nB\n", translate(src) ); } public void testEmptySecondLevelList2() throws Exception { String src="A\n\n##\n\nB"; assertEquals( "A\n<P>\n<OL>\n<OL>\n<LI>\n</OL>\n</OL>\n<P>\nB\n", translate(src) ); } /** * <pre> * *Item A * ##Numbered 1 * ##Numbered 2 * *Item B * </pre> * * would come out as: *<ul> * <li>Item A * </ul> * <ol> * <ol> * <li>Numbered 1 * <li>Numbered 2 * <ul> * <li></ol> * </ol> * Item B * </ul> * * (by Mahlen Morris). */ // FIXME: does not run - code base is too screwed for that. /* public void testMixedList() throws Exception { String src="*Item A\n##Numbered 1\n##Numbered 2\n*Item B\n"; String result = translate(src); // Remove newlines for easier parsing. result = TextUtil.replaceString( result, "\n", "" ); assertEquals( "<UL><LI>Item A"+ "<OL><OL><LI>Numbered 1"+ "<LI>Numbered 2"+ "</OL></OL>"+ "<LI>Item B"+ "</UL>", result ); } */ /** * Like testMixedList() but the list types have been reversed. */ // FIXME: does not run - code base is too screwed for that. /* public void testMixedList2() throws Exception { String src="#Item A\n**Numbered 1\n**Numbered 2\n#Item B\n"; String result = translate(src); // Remove newlines for easier parsing. result = TextUtil.replaceString( result, "\n", "" ); assertEquals( "<OL><LI>Item A"+ "<UL><UL><LI>Numbered 1"+ "<LI>Numbered 2"+ "</UL></UL>"+ "<LI>Item B"+ "</OL>", result ); } */ public void testPluginInsert() throws Exception { String src="[{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text=test}]"; assertEquals( "test\n", translate(src) ); } public void testPluginNoInsert() throws Exception { String src="[{SamplePlugin text=test}]"; assertEquals( "test\n", translate(src) ); } public void testPluginInsertJS() throws Exception { String src="Today: [{INSERT JavaScriptPlugin}] ''day''."; assertEquals( "Today: <script language=\"JavaScript\"><!--\nfoo='';\n--></script>\n <I>day</I>.\n", translate(src) ); } public void testShortPluginInsert() throws Exception { String src="[{INSERT SamplePlugin WHERE text=test}]"; assertEquals( "test\n", translate(src) ); } /** * Test two plugins on same row. */ public void testShortPluginInsert2() throws Exception { String src="[{INSERT SamplePlugin WHERE text=test}] [{INSERT SamplePlugin WHERE text=test2}]"; assertEquals( "test test2\n", translate(src) ); } public void testPluginQuotedArgs() throws Exception { String src="[{INSERT SamplePlugin WHERE text='test me now'}]"; assertEquals( "test me now\n", translate(src) ); } public void testPluginDoublyQuotedArgs() throws Exception { String src="[{INSERT SamplePlugin WHERE text='test \\'me too\\' now'}]"; assertEquals( "test 'me too' now\n", translate(src) ); } public void testPluginQuotedArgs2() throws Exception { String src="[{INSERT SamplePlugin WHERE text=foo}] [{INSERT SamplePlugin WHERE text='test \\'me too\\' now'}]"; assertEquals( "foo test 'me too' now\n", translate(src) ); } /** * Plugin output must not be parsed as Wiki text. */ public void testPluginWikiText() throws Exception { String src="[{INSERT SamplePlugin WHERE text=PageContent}]"; assertEquals( "PageContent\n", translate(src) ); } public void testMultilinePlugin1() throws Exception { String src="Test [{INSERT SamplePlugin\nWHERE text=PageContent}]"; assertEquals( "Test PageContent\n", translate(src) ); } public void testMultilinePluginBodyContent() throws Exception { String src="Test [{INSERT SamplePlugin\ntext=PageContent\n\n123\n456\n}]"; assertEquals( "Test PageContent (123+456+)\n", translate(src) ); } public void testMultilinePluginBodyContent2() throws Exception { String src="Test [{INSERT SamplePlugin\ntext=PageContent\n\n\n123\n456\n}]"; assertEquals( "Test PageContent (+123+456+)\n", translate(src) ); } public void testVariableInsert() throws Exception { String src="[{$pagename}]"; assertEquals( PAGE_NAME+"\n", translate(src) ); } public void testTable1() throws Exception { String src="|| heading || heading2 \n| Cell 1 | Cell 2 \n| Cell 3 | Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TH> heading <TH> heading2 </TR>\n"+ "<TR><TD> Cell 1 <TD> Cell 2 </TR>\n"+ "<TR><TD> Cell 3 <TD> Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTable2() throws Exception { String src="||heading||heading2\n|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TH>heading<TH>heading2</TR>\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD> Cell 3 <TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTable3() throws Exception { String src="|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD> Cell 3 <TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTableLink() throws Exception { String src="|Cell 1| Cell 2\n|[Cell 3|ReallyALink]|Cell 4\n\n"; newPage("ReallyALink"); assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ReallyALink\">Cell 3</A><TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testDescription() throws Exception { String src=";:Foo"; assertEquals( "<DL>\n<DT></DT><DD>Foo</DD>\n</DL>\n", translate(src) ); } public void testDescription2() throws Exception { String src=";Bar:Foo"; assertEquals( "<DL>\n<DT>Bar</DT><DD>Foo</DD>\n</DL>\n", translate(src) ); } public void testDescription3() throws Exception { String src=";:"; assertEquals( "<DL>\n<DT></DT><DD></DD>\n</DL>\n", translate(src) ); } public void testRuler() throws Exception { String src=" assertEquals( "<HR />\n", translate(src) ); } public static Test suite() { return new TestSuite( TranslatorReaderTest.class ); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; public class TranslatorReaderTest extends TestCase { Properties props = new Properties(); public TranslatorReaderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); } public void tearDown() { } private String translate( String src ) throws IOException, NoRequiredPropertyException { Reader r = new TranslatorReader( new TestEngine( props ), new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } public void testHyperlinks2() throws Exception { String src = "This should be a [hyperlink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>\n", translate(src) ); } public void testHyperlinks3() throws Exception { String src = "This should be a [hyperlink too]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>\n", translate(src) ); } public void testHyperlinks4() throws Exception { String src = "This should be a [HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>\n", translate(src) ); } public void testHyperlinks5() throws Exception { String src = "This should be a [here|HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">here</A>\n", translate(src) ); } public void testHyperlinksExt() throws Exception { String src = "This should be a [http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksExt2() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinkJS1() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksInterWiki1() throws Exception { String src = "This should be a [link|JSPWiki:HyperLink]"; assertEquals( "This should be a <A CLASS=\"interwiki\" HREF=\"http: translate(src) ); } public void testExtraPagename1() throws Exception { String src = "Link [test_page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test_page\">test_page</A>\n", translate(src) ); } public void testExtraPagename2() throws Exception { String src = "Link [test.page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test.page\">test.page</A>\n", translate(src) ); } public void testExtraPagename3() throws Exception { String src = "Link [.testpage_]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=.testpage_\">.testpage_</A>\n", translate(src) ); } public void testInlineImages() throws Exception { String src = "Link [test|http: assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http: translate(src) ); } public void testInlineImages2() throws Exception { String src = "Link [test|http: assertEquals("Link <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testInlineImages3() throws Exception { String src = "Link [test|http://images.com/testi]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://images.com/testi\" ALT=\"test\">\n", translate(src) ); } public void testInlineImages4() throws Exception { String src = "Link [test|http://foobar.jpg]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"test\">\n", translate(src) ); } public void testScandicPagename1() throws Exception { String src = "Link [Test]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=%C5%E4Test\">Test</A>\n", translate(src)); } public void testParagraph() throws Exception { String src = "1\n\n2\n\n3"; assertEquals( "1\n<P>\n2\n<P>\n3\n", translate(src) ); } public void testLinebreak() throws Exception { String src = "1\\\\2"; assertEquals( "1<BR>2\n", translate(src) ); } public void testTT() throws Exception { String src = "1{{2345}}6"; assertEquals( "1<TT>2345</TT>6\n", translate(src) ); } public void testPre() throws Exception { String src = "1{{{2345}}}6"; assertEquals( "1<PRE>2345</PRE>6\n", translate(src) ); } public void testPre2() throws Exception { String src = "1 {{{ {{{ 2345 }}} }}} 6"; assertEquals( "1 <PRE> {{{ 2345 </PRE> }}} 6\n", translate(src) ); } public void testList1() throws Exception { String src = "A list:\n* One\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } /** Plain multi line testing: <pre> * One continuing * Two * Three </pre> */ public void testMultilineList1() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } public void testMultilineList2() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\nShould be normal."; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\nShould be normal.\n", translate(src) ); } public void testHTML() throws Exception { String src = "<B>Test</B>"; assertEquals( "&lt;B&gt;Test&lt;/B&gt;\n", translate(src) ); } public void testHTML2() throws Exception { String src = "<P>"; assertEquals( "&lt;P&gt;\n", translate(src) ); } public void testItalicAcrossLinebreak() throws Exception { String src="''This is a\ntest.''"; assertEquals( "<I>This is a\ntest.</I>\n", translate(src) ); } public void testBoldAcrossLinebreak() throws Exception { String src="__This is a\ntest.__"; assertEquals( "<B>This is a\ntest.</B>\n", translate(src) ); } public void testBoldItalic() throws Exception { String src="__This ''is'' a test.__"; assertEquals( "<B>This <I>is</I> a test.</B>\n", translate(src) ); } public void testFootnote1() throws Exception { String src="Footnote[1]"; assertEquals( "Footnote<A CLASS=\"footnoteref\" HREF=\"#ref1\">[1]</A>\n", translate(src) ); } public void testFootnote2() throws Exception { String src="[#2356] Footnote."; assertEquals( "<A CLASS=\"footnote\" NAME=\"ref2356\">[#2356]</A> Footnote.\n", translate(src) ); } public static Test suite() { return new TestSuite( TranslatorReaderTest.class ); } }
package scal.io.liger; import timber.log.Timber; import android.content.Context; import android.os.Environment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.android.vending.expansion.zipfile.APKExpansionSupport; import com.android.vending.expansion.zipfile.ZipResourceFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Set; import scal.io.liger.model.ExpansionIndexItem; import scal.io.liger.model.sqlbrite.InstalledIndexItemDao; /** * @author Matt Bogner * @author Josh Steiner */ public class ZipHelper { public static final String TAG = "ZipHelper"; @NonNull public static String getExpansionZipFilename(Context ctx, String mainOrPatch, int version) { String packageName = ctx.getPackageName(); return mainOrPatch + "." + version + "." + packageName + ".obb"; } @Nullable public static String getExpansionZipDirectory(Context ctx, String mainOrPatch, int version) { // basically a wrapper for getExpansionFileFolder, but defaults to files directory String filePath = getExpansionFileFolder(ctx, mainOrPatch, version); if (filePath == null) { return getFileFolderName(ctx); } else { return filePath; } } @NonNull public static String getObbFolderName(Context ctx) { String packageName = ctx.getPackageName(); File root = Environment.getExternalStorageDirectory(); return root.toString() + "/Android/obb/" + packageName + "/"; } @Nullable public static String getFileFolderName(Context ctx) { // TODO Why doesn't this use ctx.getExternalFilesDir(null) (like JsonHelper)? // String packageName = ctx.getPackageName(); // File root = Environment.getExternalStorageDirectory(); // return root.toString() + "/Android/data/" + packageName + "/files/"; File file = StorageHelper.getActualStorageDirectory(ctx); String path = null; if (file != null) { path = file.getPath() + "/"; } return path; } @Nullable public static String getFileFolderName(Context context, String fileName) { // need to account for patch files if (fileName.contains(Constants.PATCH)) { fileName = fileName.replace(Constants.PATCH, Constants.MAIN); } ExpansionIndexItem expansionIndexItem = IndexManager.loadInstalledFileIndex(context).get(fileName); if (expansionIndexItem == null) { Timber.e("FAILED TO LOCATE EXPANSION INDEX ITEM FOR " + fileName); return null; } // TODO - switching to the new storage method ignores the value set in the expansion index item // File root = Environment.getExternalStorageDirectory(); // return root.toString() + File.separator + expansionIndexItem.getExpansionFilePath(); File file = StorageHelper.getActualStorageDirectory(context); if (file != null) { return file.getPath() + "/"; } else { return null; } } public static String getFileFolderName(Context context, String fileName, ExpansionIndexItem item) { // need to account for patch files if (fileName.contains(Constants.PATCH)) { fileName.replace(Constants.PATCH, Constants.MAIN); } // TODO - switching to the new storage method ignores the value set in the expansion index item // File root = Environment.getExternalStorageDirectory(); // return root.toString() + File.separator + item.getExpansionFilePath(); return StorageHelper.getActualStorageDirectory(context).getPath() + "/"; } // supressing messages for less text during polling @Nullable public static String getExpansionFileFolder(Context ctx, String mainOrPatch, int version) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // check and/or attempt to create obb folder String checkPath = getObbFolderName(ctx); File checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + getExpansionZipFilename(ctx, mainOrPatch, version)); if (checkFile.exists()) { Timber.d("FOUND " + mainOrPatch + " " + version + " IN OBB DIRECTORY: " + checkFile.getPath()); return checkPath; } } // check and/or attempt to create files folder checkPath = getFileFolderName(ctx); checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + getExpansionZipFilename(ctx, mainOrPatch, version)); if (checkFile.exists()) { Timber.d("FOUND " + mainOrPatch + " " + version + " IN FILES DIRECTORY: " + checkFile.getPath()); return checkPath; } } } Timber.e(mainOrPatch + " " + version + " NOT FOUND IN OBB DIRECTORY OR FILES DIRECTORY"); return null; } // for additional expansion files, check files folder for specified file @Nullable public static String getExpansionFileFolder(Context ctx, String fileName) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // check and/or attempt to create files folder String checkPath = getFileFolderName(ctx, fileName); if (checkPath == null) { return null; } File checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + fileName); if (checkFile.exists()) { Timber.d("FOUND " + fileName + " IN DIRECTORY: " + checkFile.getPath()); return checkPath; } } } Timber.e(fileName + " NOT FOUND"); return null; } @Nullable public static String getExpansionFileFolder(Context ctx, String fileName, ExpansionIndexItem item) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // check and/or attempt to create files folder String checkPath = getFileFolderName(ctx, fileName, item); if (checkPath == null) { return null; } File checkDir = new File(checkPath); if (checkDir.isDirectory() || checkDir.mkdirs()) { File checkFile = new File(checkPath + fileName); if (checkFile.exists()) { Timber.d("FOUND " + fileName + " IN DIRECTORY: " + checkFile.getPath()); return checkPath; } } } Timber.e(fileName + " NOT FOUND"); return null; } @Nullable public static ZipResourceFile getResourceFile(Context context) { try { // resource file contains main file and patch file ArrayList<String> paths = getExpansionPaths(context); ZipResourceFile resourceFile = APKExpansionSupport.getResourceZipFile(paths.toArray(new String[paths.size()])); return resourceFile; } catch (IOException ioe) { Timber.e("Could not open resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); return null; } } @Nullable public static InputStream getFileInputStream(String path, Context context, String language) { String localizedFilePath = path; // check language setting and insert country code if necessary if (language != null) { // just in case, check whether country code has already been inserted if (path.lastIndexOf("-" + language + path.substring(path.lastIndexOf("."))) < 0) { // if not already appended, don't bother to append -en if (!"en".equals(language)) { localizedFilePath = path.substring(0, path.lastIndexOf(".")) + "-" + language + path.substring(path.lastIndexOf(".")); Timber.d("getFileInputStream() - TRYING LOCALIZED PATH: " + localizedFilePath); } else { Timber.d("getFileInputStream() - TRYING PATH: " + localizedFilePath); } } else { Timber.d("getFileInputStream() - TRYING LOCALIZED PATH: " + localizedFilePath); } } else { Timber.d("getFileInputStream() - TRYING PATH: " + localizedFilePath); } InputStream fileStream = getFileInputStream(localizedFilePath, context); // if there is no result with the localized path, retry with default path if (fileStream == null) { if (localizedFilePath.contains("-")) { localizedFilePath = localizedFilePath.substring(0, localizedFilePath.lastIndexOf("-")) + localizedFilePath.substring(localizedFilePath.lastIndexOf(".")); Timber.d("getFileInputStream() - NO RESULT WITH LOCALIZED PATH, TRYING DEFAULT PATH: " + localizedFilePath); fileStream = ZipHelper.getFileInputStream(localizedFilePath, context); } } else { return fileStream; } if (fileStream == null) { Timber.d("getFileInputStream() - NO RESULT WITH DEFAULT PATH: " + localizedFilePath); } else { return fileStream; } return null; } @Nullable public static InputStream getFileInputStreamForExpansionAndPath(@NonNull ExpansionIndexItem expansion, @NonNull String path, @NonNull Context context) { return getFileInputStreamFromFile(IndexManager.buildFileAbsolutePath(expansion, Constants.MAIN, context), path, context); } @Nullable public static InputStream getThumbnailInputStreamForItem(@NonNull ExpansionIndexItem item, @NonNull Context context) { ZipResourceFile resourceFile = null; try { resourceFile = APKExpansionSupport.getResourceZipFile(new String[]{IndexManager.buildFileAbsolutePath(item, Constants.MAIN, context)}); return resourceFile.getInputStream(item.getThumbnailPath()); } catch (IOException e) { e.printStackTrace(); } return null; } // private static ArrayList<String> expansionPaths; /** * @return an absolute path to an expansion file with the given expansionId, or null if no * match could be made. */ // unused, removing for now /* public static @Nullable String getExpansionPathForExpansionId(Context context, String expansionId) { String targetExpansionPath = null; ArrayList<String> expansionPaths = getExpansionPaths(context); for (String expansionPath : expansionPaths) { if (expansionPath.contains(expansionId)) { targetExpansionPath = expansionPath; break; } } return targetExpansionPath; } */ public static void clearCache() { // expansionPaths = null; } /** * @return a list of absolute paths to all available expansion files. */ @NonNull private static ArrayList<String> getExpansionPaths(@NonNull Context context) { //if (expansionPaths == null) { ArrayList<String> expansionPaths = new ArrayList<>(); File mainFile = new File(getExpansionFileFolder(context, Constants.MAIN, Constants.MAIN_VERSION) + getExpansionZipFilename(context, Constants.MAIN, Constants.MAIN_VERSION)); if (mainFile.exists() && (mainFile.length() > 0)) { expansionPaths.add(mainFile.getPath()); } else { Timber.e(mainFile.getPath() + " IS MISSING OR EMPTY, EXCLUDING FROM ZIP RESOURCE"); } if (Constants.PATCH_VERSION > 0) { // if the main file is newer than the patch file, do not apply a patch file if (Constants.PATCH_VERSION < Constants.MAIN_VERSION) { Timber.d("PATCH VERSION " + Constants.PATCH_VERSION + " IS OUT OF DATE (MAIN VERSION IS " + Constants.MAIN_VERSION + ")"); } else { Timber.d("APPLYING PATCH VERSION " + Constants.PATCH_VERSION + " (MAIN VERSION IS " + Constants.MAIN_VERSION + ")"); File patchFile = new File(getExpansionFileFolder(context, Constants.PATCH, Constants.PATCH_VERSION) + getExpansionZipFilename(context, Constants.PATCH, Constants.PATCH_VERSION)); if (patchFile.exists() && (patchFile.length() > 0)) { expansionPaths.add(patchFile.getPath()); }else { Timber.e(patchFile.getPath() + " IS MISSING OR EMPTY, EXCLUDING FROM ZIP RESOURCE"); } } } // need db access to get installed files InstalledIndexItemDao dao = null; if (context instanceof MainActivity) { dao = ((MainActivity)context).getInstalledIndexItemDao(); // FIXME this isn't a safe cast as context can sometimes not be an activity (getApplicationContext()) } else { Timber.e("NO DAO IN getExpansionPaths"); } // add 3rd party stuff HashMap<String, scal.io.liger.model.sqlbrite.ExpansionIndexItem> expansionIndex = StorymakerIndexManager.loadInstalledOrderIndex(context, dao); // need to sort patch order keys, numbers may not be consecutive ArrayList<String> orderNumbers = new ArrayList<String>(expansionIndex.keySet()); Collections.sort(orderNumbers); for (String orderNumber : orderNumbers) { scal.io.liger.model.sqlbrite.ExpansionIndexItem item = expansionIndex.get(orderNumber); if (item == null) { Timber.d("EXPANSION FILE ENTRY MISSING AT PATCH ORDER NUMBER " + orderNumber); } else { // construct name String pathName = StorymakerIndexManager.buildFilePath(item, context); String fileName = StorymakerIndexManager.buildFileName(item, Constants.MAIN); File checkFile = new File(pathName + fileName); // should be able to do this locally // if (DownloadHelper.checkExpansionFiles(context, fileName)) { if (checkFile.exists() && (checkFile.length() > 0)) { Timber.d("EXPANSION FILE " + checkFile.getPath() + " FOUND, ADDING TO ZIP"); expansionPaths.add(checkFile.getPath()); if ((item.getPatchFileVersion() != null) && (item.getExpansionFileVersion() != null) && (Integer.parseInt(item.getPatchFileVersion()) > 0) && (Integer.parseInt(item.getPatchFileVersion()) >= Integer.parseInt(item.getExpansionFileVersion()))) { // construct name String patchName = StorymakerIndexManager.buildFileName(item, Constants.PATCH); checkFile = new File(pathName + patchName); // should be able to do this locally // if (DownloadHelper.checkExpansionFiles(context, patchName)) { if (checkFile.exists() && (checkFile.length() > 0)) { Timber.d("EXPANSION FILE " + checkFile.getPath() + " FOUND, ADDING TO ZIP"); expansionPaths.add(checkFile.getPath()); } else { Timber.e(checkFile.getPath() + " IS MISSING OR EMPTY, EXCLUDING FROM ZIP RESOURCE"); } } } else { Timber.e(checkFile.getPath() + " IS MISSING OR EMPTY, EXCLUDING FROM ZIP RESOURCE"); } } } return expansionPaths; } /** * @return the {@link scal.io.liger.model.ExpansionIndexItem} which is likely to contain the * given path. * * This method is useful as an optimization step until StoryPathLibrarys hold reference * to the ExpansionIndexItem from which they were created, if applicable. The inspection * is performed by searching for installed ExpansionIndexItem expansionId values * within the given path parameter, and does not involve inspection of the files belonging to * each ExpansionIndexItem. * */ @Nullable public static ExpansionIndexItem guessExpansionIndexItemForPath(@NonNull String path, @NonNull Context context) { // need db access to get list of installed content packs if (context instanceof MainActivity) { InstalledIndexItemDao dao = ((MainActivity)context).getInstalledIndexItemDao(); // FIXME this isn't a safe cast as context can sometimes not be an activity (getApplicationContext()) HashMap<String, scal.io.liger.model.sqlbrite.ExpansionIndexItem> expansions = StorymakerIndexManager.loadInstalledIdIndex(context, dao); Set<String> expansionIds = expansions.keySet(); for(String expansionId : expansionIds) { if (path.contains(expansionId)) { // turning this into an instance of the non sql-brite class to minimize impact ExpansionIndexItem eii = new ExpansionIndexItem((expansions.get(expansionId))); return eii; } } } else { Timber.e("could not find a dao to access the installed item list in the db"); } return null; } /** * @return an {@link java.io.InputStream} corresponding to the given path which must reside within * one of the installed index items. On disk this corresponds to a zip archive packaged as an .obb file. * */ @Deprecated @Nullable public static InputStream getFileInputStream(@NonNull String path, @NonNull Context context) { // resource file contains main file and patch file ArrayList<String> allExpansionPaths = getExpansionPaths(context); ArrayList<String> targetExpansionPaths = new ArrayList<>(); // try to extract expansion id from target path // assumes format org.storymaker.app/learning_guide/content_metadata-en.json String[] parts = path.split("/"); for (String expansionPath : allExpansionPaths) { if (expansionPath.contains(parts[1])) { Timber.d("FOUND MATCH FOR " + parts[1] + " IN PATH " + expansionPath); targetExpansionPaths.add(expansionPath); } } // this shouldn't happen... if (targetExpansionPaths.size() == 0) { Timber.d("NO MATCHES FOR " + parts[1] + ", USING ALL PATHS"); targetExpansionPaths = allExpansionPaths; } StringBuilder paths = new StringBuilder(); for (String expansionPath : targetExpansionPaths) { paths.append(expansionPath); paths.append(", "); } paths.delete(paths.length()-2, paths.length()); Timber.d(String.format("Searching for %s in %s", path, paths)); return getFileInputStreamFromFiles(targetExpansionPaths, path, context); } @Nullable public static InputStream getFileInputStreamFromFile(String zipPath, String filePath, Context context) { ArrayList<String> zipPaths = new ArrayList<String>(); zipPaths.add(zipPath); return getFileInputStreamFromFiles(zipPaths, filePath, context); } @Nullable public static InputStream getFileInputStreamFromFiles(ArrayList<String> zipPaths, String filePath, Context context) { try { ZipResourceFile resourceFile = APKExpansionSupport.getResourceZipFile(zipPaths.toArray(new String[zipPaths.size()])); if (resourceFile == null) { return null; } // file path must be relative to the root of the resource file InputStream resourceStream = resourceFile.getInputStream(filePath); if (resourceStream == null) { Timber.d("Could not find file " + filePath + " within resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); } else { Timber.d("Found file " + filePath + " within resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); } return resourceStream; } catch (IOException ioe) { Timber.e("Could not find file " + filePath + " within resource file (main version " + Constants.MAIN_VERSION + ", patch version " + Constants.PATCH_VERSION + ")"); return null; } } /** * Copy the expansion asset at path to a temporary file within tempPath. If * a temp file exists for the given arguments it will be deleted and remade. */ @Deprecated @Nullable public static File getTempFile(String path, String tempPath, Context context) { String extension = path.substring(path.lastIndexOf(".")); File tempFile = new File(tempPath + File.separator + "TEMP" + extension); try { if (tempFile.exists()) { tempFile.delete(); Timber.d("Deleted temp file " + tempFile.getPath()); } tempFile.createNewFile(); Timber.d("Made temp file " + tempFile.getPath()); } catch (IOException ioe) { Timber.e("Failed to clean up existing temp file " + tempFile.getPath() + ", " + ioe.getMessage()); return null; } InputStream zipInput = getFileInputStream(path, context); if (zipInput == null) { Timber.e("Failed to open input stream for " + path + " in .zip file"); return null; } try { FileOutputStream tempOutput = new FileOutputStream(tempFile); byte[] buf = new byte[1024]; int i; while((i = zipInput.read(buf)) > 0) { tempOutput.write(buf, 0, i); } tempOutput.close(); zipInput.close(); Timber.d("Wrote temp file " + tempFile.getPath()); } catch (IOException ioe) { Timber.e("Failed to write to temp file " + tempFile.getPath() + ", " + ioe.getMessage()); return null; } Timber.e("Created temp file " + tempFile.getPath()); return tempFile; } }
package scal.io.liger.view; import android.app.Activity; import android.content.Intent; import android.graphics.Point; import android.graphics.Rect; import android.support.v7.widget.LinearLayoutManager; import android.view.ActionMode; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.PopupWindow; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import scal.io.liger.Constants; import scal.io.liger.MainActivity; import scal.io.liger.R; import scal.io.liger.adapter.OrderMediaAdapter; import scal.io.liger.model.AudioClip; import scal.io.liger.model.AudioClipFull; import scal.io.liger.model.Card; import scal.io.liger.model.FullMetadata; import scal.io.liger.model.StoryPath; public class Util { /** * @return a String of form "MM:SS:MS" from a raw ms value */ public static String makeTimeString(long timeMs) { long millisecond = timeMs % 1000; long second = (timeMs / 1000) % 60; long minute = (timeMs / (1000 * 60)) % 60; return String.format("%02d:%02d:%02d", minute, second, millisecond); } public static void startPublishActivity(Activity host, StoryPath storyPath) { ArrayList<FullMetadata> exportMetadata = storyPath.exportAllMetadata(); // TODO : Place in AsyncTask? ArrayList<AudioClipFull> exportAudioClipsMetadata = storyPath.exportAudioClips(); if (exportMetadata.size() > 0) { Intent i = new Intent(); i.setAction(Constants.ACTION_PUBLISH); i.putExtra(Constants.EXTRA_STORY_TITLE, storyPath.getTitle()); i.putExtra(Constants.EXTRA_STORY_INSTANCE_PATH, storyPath.getStoryPathLibraryFile()); // i.putExtra(Constants.EXTRA_REQUIRED_UPLOAD_TARGETS, storyPath.getRequiredUploadTargets()); // i.putExtra(Constants.EXTRA_REQUIRED_PUBLISH_TARGETS, storyPath.getRequiredPublishTargets()); // i.putExtra(Constants.EXTRA_REQUIRED_TAGS, storyPath.getRequiredTags()); i.putParcelableArrayListExtra(Constants.EXTRA_EXPORT_CLIPS, exportMetadata); if (exportAudioClipsMetadata != null) { i.putParcelableArrayListExtra(Constants.EXTRA_EXPORT_AUDIOCLIPS, exportAudioClipsMetadata); } host.startActivity(i); host.finish(); // Do we definitely want to finish the host Activity? } else { Toast.makeText(host, host.getString(R.string.this_story_has_no_clips_to_publish), Toast.LENGTH_LONG).show(); } } public static int safeLongToInt(long l) { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { throw new IllegalArgumentException (l + " cannot be cast to int without changing its value."); } return (int) l; } }
package org.apache.fop.fo.flow; // FOP import org.apache.fop.fo.*; import org.apache.fop.fo.properties.*; import org.apache.fop.fo.pagination.*; import org.apache.fop.layout.Area; import org.apache.fop.apps.FOPException; // Java import java.util.Enumeration; public class StaticContent extends Flow { public StaticContent(FONode parent) { super(parent); ((PageSequence)parent).setIsFlowSet(false); // hacquery of sorts } public Status layout(Area area) throws FOPException { return layout(area, null); } public Status layout(Area area, Region region) throws FOPException { // int numChildren = this.children.size(); // // Set area absolute height so that link rectangles will be drawn correctly in xsl-before and xsl-after // String regionClass = "none"; // if (region != null) { // regionClass = region.getRegionClass(); // } else { // if (getFlowName().equals("xsl-region-before")) { // regionClass = RegionBefore.REGION_CLASS; // } else if (getFlowName().equals("xsl-region-after")) { // regionClass = RegionAfter.REGION_CLASS; // } else if (getFlowName().equals("xsl-region-start")) { // regionClass = RegionStart.REGION_CLASS; // } else if (getFlowName().equals("xsl-region-end")) { // regionClass = RegionEnd.REGION_CLASS; // if (area instanceof org.apache.fop.layout.AreaContainer) // ((org.apache.fop.layout.AreaContainer)area).setAreaName(regionClass); // if (regionClass.equals(RegionBefore.REGION_CLASS)) { // area.setAbsoluteHeight(-area.getMaxHeight()); // } else if (regionClass.equals(RegionAfter.REGION_CLASS)) { // area.setAbsoluteHeight(area.getPage().getBody().getMaxHeight()); // setContentWidth(area.getContentWidth()); // for (int i = 0; i < numChildren; i++) { // FObj fo = (FObj)children.elementAt(i); // Status status; // if ((status = fo.layout(area)).isIncomplete()) { // // in fact all should be laid out and clip, error etc depending on 'overflow' // log.warn("Some static content could not fit in the area."); // this.marker = i; // if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE)) { // status = new Status(Status.AREA_FULL_SOME); // return (status); // resetMarker(); return new Status(Status.OK); } protected String getElementName() { return "fo:static-content"; } // flowname checking is more stringient for static content currently protected void setFlowName(String name) throws FOPException { if (name == null || name.equals("")) { throw new FOPException("A 'flow-name' is required for " + getElementName() + "."); } else { super.setFlowName(name); } } }
package org.appwork.controlling; import java.util.ArrayList; import java.util.HashMap; import org.appwork.utils.logging.Log; public class StateMachine { private static State checkState(final State state) { State finalState = null; for (final State s : state.getChildren()) { final State ret = StateMachine.checkState(s); if (finalState == null) { finalState = ret; } if (finalState != ret) { throw new StateConflictException("States do not all result in one common final state"); } } if (finalState == null) { throw new StateConflictException(state + " is a blind state (has no children)"); } return finalState; } /** * validates a statechain and checks if all states can be reached, and if * all chans result in one common finalstate * * @param initState * @throws StateConflictException */ public static void validateStateChain(final State initState) { if (initState.getParents().size() > 0) { throw new StateConflictException("initState must not have a parent"); } StateMachine.checkState(initState); } private final State initState; private volatile State currentState; private final StateEventsender eventSender; private final State finalState; private final ArrayList<StatePathEntry> path; private final StateMachineInterface owner; private final Object lock = new Object(); private final Object lock2 = new Object(); private final HashMap<State, Throwable> exceptionMap; public StateMachine(final StateMachineInterface interfac, final State startState, final State endState) { this.owner = interfac; this.initState = startState; this.currentState = startState; this.finalState = endState; this.exceptionMap = new HashMap<State, Throwable>(); this.eventSender = new StateEventsender(); this.path = new ArrayList<StatePathEntry>(); this.path.add(new StatePathEntry(this.initState)); } public void addListener(final StateEventListener listener) { this.eventSender.addListener(listener); } /* * synchronized hasPassed/addListener to start run when state has * reached/passed */ public void executeOnceOnState(final Runnable run, final State state) { if (run == null || state == null) { return; } boolean reached = false; synchronized (this.lock) { if (this.hasPassed(state)) { reached = true; } else { this.addListener(new StateListener(state) { @Override public void onStateReached(final StateEvent event) { StateMachine.this.removeListener(this); run.run(); } }); } } if (reached) { run.run(); } } /** * synchronized execution of a runnable if statemachine is currently in a * given state * * @param run * @param state * @return */ public boolean executeIfOnState(final Runnable run, final State state) { if (run == null || state == null) { return false; } synchronized (this.lock) { if (this.isState(state)) { run.run(); return true; } } return false; } public void fireUpdate(final State currentState) { if (currentState != null) { synchronized (this.lock) { if (this.currentState != currentState) { throw new StateConflictException("Cannot update state " + currentState + " because current state is " + this.currentState); } } } final StateEvent event = new StateEvent(this, StateEvent.Types.UPDATED, currentState, currentState); this.eventSender.fireEvent(event); } public void forceState(final State newState) { StateEvent event; synchronized (this.lock) { if (this.currentState == newState) { return; } event = new StateEvent(this, StateEvent.Types.CHANGED, this.currentState, newState); synchronized (this.lock2) { this.path.add(new StatePathEntry(newState)); } Log.L.finest(this.owner + " State changed " + this.currentState + " -> " + newState); this.currentState = newState; } this.eventSender.fireEvent(event); } public Throwable getCause(final State newState) { return this.exceptionMap.get(newState); } /** * TODO: not synchronized * * @param failedState * @return */ public StatePathEntry getLatestStateEntry(final State failedState) { try { StatePathEntry entry = null; synchronized (this.lock2) { for (int i = this.path.size() - 1; i >= 0; i entry = this.path.get(i); if (entry.getState() == failedState) { return entry; } } } } catch (final Exception e) { } return null; } public StateMachineInterface getOwner() { return this.owner; } /** * @return the path */ public ArrayList<StatePathEntry> getPath() { return this.path; } public State getState() { return this.currentState; } // public void forceState(int id) { // State newState; // synchronized (lock) { // newState = getStateById(this.initState, id, null); // if (newState == null) throw new // StateConflictException("No State with ID " + id); // forceState(newState); public boolean hasPassed(final State... states) { synchronized (this.lock2) { for (final State s : states) { for (final StatePathEntry e : this.path) { if (e.getState() == s) { return true; } } } } return false; } // private State getStateById(State startState, int id, ArrayList<State> // foundStates) { // if (foundStates == null) foundStates = new ArrayList<State>(); // if (foundStates.contains(startState)) return null; // foundStates.add(startState); // State ret = null; // for (State s : startState.getChildren()) { // if (s.getID() == id) return s; // ret = getStateById(s, id, foundStates); // if (ret != null) return ret; // return null; public boolean isFinal() { synchronized (this.lock) { return this.finalState == this.currentState; } } /** * returns if the statemachine is in startstate currently */ public boolean isStartState() { synchronized (this.lock) { return this.currentState == this.initState; } } public boolean isState(final State... states) { synchronized (this.lock) { for (final State s : states) { if (s == this.currentState) { return true; } } } return false; } public void removeListener(final StateEventListener listener) { this.eventSender.removeListener(listener); } public void reset() { StateEvent event; synchronized (this.lock) { if (this.currentState == this.initState) { return; } if (this.finalState != this.currentState) { throw new StateConflictException("Cannot reset from state " + this.currentState); } event = new StateEvent(this, StateEvent.Types.CHANGED, this.currentState, this.initState); Log.L.finest(this.owner + " State changed (reset) " + this.currentState + " -> " + this.initState); this.currentState = this.initState; synchronized (this.lock2) { this.path.clear(); this.path.add(new StatePathEntry(this.initState)); } } this.eventSender.fireEvent(event); } public void setCause(final State failedState, final Throwable e) { this.exceptionMap.put(failedState, e); } public void setStatus(final State newState) { synchronized (this.lock) { if (this.currentState == newState) { return; } if (!this.currentState.getChildren().contains(newState)) { throw new StateConflictException("Cannot change state from " + this.currentState + " to " + newState); } } this.forceState(newState); } }
package org.egordorichev.lasttry.world; import org.egordorichev.lasttry.LastTry; import org.egordorichev.lasttry.entity.Enemy; import org.egordorichev.lasttry.entity.Entity; import org.egordorichev.lasttry.item.Block; import org.egordorichev.lasttry.item.Item; import org.egordorichev.lasttry.item.Wall; import org.egordorichev.lasttry.util.FileReader; import org.egordorichev.lasttry.util.FileWriter; import org.egordorichev.lasttry.util.Rectangle; import org.egordorichev.lasttry.world.tile.TileData; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; public class World { /** * Current world version generated by the game. Future versions may * increment this number. */ public static final int CURENT_VERSION = 0; /** * Value indicating if the world has been fully loaded <i>(Entities placed, * tiles added, dimensions set, etc.)</i> */ private boolean loaded; /** * World width in tiles. */ private int width; /** * World height in tiles. */ private int height; /** * World version. */ private int version; /** * World name. */ private String name; /** * Array of tile data. 2D coordinates are encoded by: * * <pre> * index = x + y * world - width * </pre> */ private TileData[] tiles; /** * List of entities in the world. */ private List<Entity> entities; public World(String name) { this.loaded = false; this.name = name; this.entities = new ArrayList<>(); Block.preload(); Wall.preload(); this.load(); spawnEnemy(Enemy.SLIME_GREEN, 10, 90); spawnEnemy(Enemy.SLIME_BLUE, 40, 90); } /** * Render the world. */ public void render() { int windowWidth = LastTry.getWindowWidth(); int windowHeight = LastTry.getWindowHeight(); int tww = windowWidth / Block.TEX_SIZE; int twh = windowHeight / Block.TEX_SIZE; int tcx = (int) LastTry.camera.getX() / Block.TEX_SIZE; int tcy = (int) LastTry.camera.getY() / Block.TEX_SIZE; int minY = Math.max(0, tcy - 2); int maxY = Math.min(this.height - 1, tcy + twh + 2); int minX = Math.max(0, tcx - 2); int maxX = Math.min(this.width - 1, tcx + tww + 2); // Iterate coordinates, exclude ones not visible to the camera for (int y = minY; y < maxY; y++) { for (int x = minX; x < maxX; x++) { TileData tileData = this.getTile(x, y); tileData.render(x, y); } } // Render entities, exclude ones not visible to the camera for (Entity entity : this.entities) { int gx = entity.getGridX(); int gy = entity.getGridY(); if ((gx > minX && gx < maxX) && (gy > minY && gy < maxY)) { entity.render(); } } } /** * Update the world. * * @param dt * The milliseconds passed since the last update. */ public void update(int dt) { for (Entity entity : this.entities) { entity.update(dt); } } /** * Spawn an enemy in the world <i>(Type dictated by the name)</i> * * @param name * Name of the type of entity to spawn. * @param x * X-position to spawn entity at. * @param y * Y-position to spawn entity at. * @return */ public Enemy spawnEnemy(String name, int x, int y) { Enemy enemy = Enemy.create(name); enemy.spawn(x, y); this.entities.add(enemy); return enemy; } /** * Return the TileData for the given position. * * @param x * X-position of the world. * @param y * Y-position of the world. * @return */ public TileData getTile(int x, int y) { return this.tiles[x + y * this.width]; } /** * Set a block in the world at the given position. * * @param block * Block to place. * @param x * X-position of the world. * @param y * Y-position of the world. */ public void setBlock(Block block, int x, int y) { TileData data = this.getTile(x, y); data.block = block; data.blockHp = data.maxHp; data.data = 0; } /** * Set a wall in the world at the given position. * * @param wall * Wall to place. * @param x * X-position of the world. * @param y * Y-position of the world. */ public void setWall(Wall wall, int x, int y) { TileData data = this.getTile(x, y); data.wall = wall; data.wallHp = data.maxHp; data.data = 0; } /** * Set the data tag of the tile in the world at the given position. * * @param data * Tag value. * @param x * X-position of the world. * @param y * Y-position of the world. */ public void setData(byte data, int x, int y) { TileData tileData = this.getTile(x, y); tileData.data = data; } /** * Return the data tag of the tile in the world at the given position. * * @param x * X-position of the world. * @param y * Y-position of the world. * @returnd Data tag value. */ public byte getData(int x, int y) { TileData tileData = this.getTile(x, y); return tileData.data; } /** * Return the block in the world at the given position. * * @param x * X-position of the world. * @param y * Y-position of the world. * @return Block in world. */ public Block getBlock(int x, int y) { TileData data = this.getTile(x, y); return data.block; } /** * Return the wall in the world at the given position. * * @param x * X-position of the world. * @param y * Y-position of the world. * @return Wall in world. */ public Wall getWall(int x, int y) { TileData data = this.getTile(x, y); return data.wall; } /** * Return the ID of the block in the world at the given position. * * @param x * X-position of the world. * @param y * Y-position of the world. * @return Block ID in world. */ public int getBlockId(int x, int y) { if (!this.isInside(x, y)) { return 0; } TileData data = this.getTile(x, y); if (data.block == null) { return 0; } return data.block.getId(); } /** * Return the ID of the wall in the world at the given position. * * @param x * X-position of the world. * @param y * Y-position of the world. * @return Wall ID in world. */ public int getWallId(int x, int y) { if (!this.isInside(x, y)) { return 0; } TileData data = this.getTile(x, y); if (data.wall == null) { return 0; } return data.wall.getId(); } /** * Check if the given bounds collide with blocks in the world. * * @param bounds * Bounds to check collision for. * @return If bounds collide with world's blocks. */ public boolean isColliding(Rectangle bounds) { Rectangle gridBounds = new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height); gridBounds.x /= Block.TEX_SIZE; gridBounds.y /= Block.TEX_SIZE; gridBounds.width /= Block.TEX_SIZE; gridBounds.height /= Block.TEX_SIZE; for (int y = (int) gridBounds.y - 1; y < gridBounds.y + gridBounds.height + 1; y++) { for (int x = (int) gridBounds.x - 1; x < gridBounds.x + gridBounds.width + 1; x++) { if (!this.isInside(x, y)) { return true; } TileData data = this.getTile(x, y); if (data.block == null || !data.block.isSolid()) { continue; } Rectangle blockRect = new Rectangle(x * Block.TEX_SIZE, y * Block.TEX_SIZE, Block.TEX_SIZE, Block.TEX_SIZE); if (blockRect.intersects(bounds)) { return true; } } } return false; } /** * Check if the world has been loaded. * * @return World loaded. */ public boolean isLoaded() { return this.loaded; } /** * Check if the given position resides within the world's bounds. * * @param x * X-position to check. * @param y * Y-position to check. * @return Position is inside world. */ public boolean isInside(int x, int y) { return (x >= 0 && x < this.width && y >= 0 && y < this.height); } /** * Return the world's width. * * @return World width. */ public int getWidth() { return this.width; } /** * Return the world's height. * * @return World height. */ public int getHeight() { return this.height; } /** * Return the world's name. * * @return World name. */ public String getName() { return this.name; } /** * Return the world's file path. * * @return World file path. */ public String getFilePath() { return "assets/worlds/" + this.name + ".wld"; } /** * Generate the world. */ private void generate() { this.width = 500; this.height = 500; this.version = World.CURENT_VERSION; int totalSize = this.width * this.height; this.tiles = new TileData[totalSize]; int tiles[][] = new int[this.width][this.height]; for (int y = 0; y < this.height; y++) { for (int x = 0; x < this.width; x++) { if (y == 120) { tiles[x][y] = Block.GRASS_BLOCK; } else if (y > 120) { tiles[x][y] = Block.DIRT_BLOCK; } else { tiles[x][y] = 0; } } } for (int y = 0; y < this.height; y++) { for (int x = 0; x < this.width; x++) { int id = tiles[x][y]; this.tiles[x + y * this.width] = new TileData((Block) Item.fromId(id), Wall.getForBlockId(id)); } } System.out.println("done generating!"); this.loaded = true; } private void load() { try { FileReader stream = new FileReader(this.getFilePath()); // Header int version = stream.readInt32(); if (version > World.CURENT_VERSION) { throw new RuntimeException("Unsupported version"); } String worldName = stream.readString(); this.name = worldName; this.width = stream.readInt32(); this.height = stream.readInt32(); // Tile data int totalSize = this.width * this.height; this.tiles = new TileData[totalSize]; for (int i = 0; i < totalSize; i++) { this.tiles[i] = new TileData((Block) Item.fromId(stream.readInt32()), (Wall) Item.fromId(stream.readInt32())); // TODO: RLE } if (stream.readBoolean() == false) { throw new RuntimeException("Verification failed"); } worldName = stream.readString(); if (!worldName.equals(this.name)) { throw new RuntimeException("Verification failed"); } // Verification } catch (FileNotFoundException exception) { this.generate(); // this.save(); } System.out.println("done loading!"); this.loaded = true; } public void save() { FileWriter stream = new FileWriter(this.getFilePath()); // Header stream.writeInt32(this.version); stream.writeString(this.name); stream.writeInt32(this.width); stream.writeInt32(this.height); // Tile data int totalSize = this.width * this.height; for (int i = 0; i < totalSize; i++) { TileData data = this.tiles[i]; int blockId = 0; int wallId = 0; if (data.block != null) { blockId = data.block.getId(); } if (data.wall != null) { wallId = data.wall.getId(); } stream.writeInt32(blockId); stream.writeInt32(wallId); // TODO: RLE } // Verification stream.writeBoolean(true); stream.writeString(this.name); stream.close(); System.out.println("done saving!"); } }
import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.Date; import java.lang.Math; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.cloudwatch.model.Dimension; import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest; import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult; import com.amazonaws.services.cloudwatch.model.Datapoint; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; public class AutoScaler { private static AmazonEC2 ec2; private static AmazonCloudWatchClient cloudWatch; private static Set<Instance> instances; private static final int INCR_POLICY_PERIOD = 60 * 1; //in seconds private static final long INCR_DATAPOINTS_OFFSET = 1000 * (INCR_POLICY_PERIOD * 2 + 30); //Max number of the last datapoints retrieved private static final int DECR_POLICY_PERIOD = 60 * 7; //in seconds private static final long DECR_DATAPOINTS_OFFSET = 1000 * (DECR_POLICY_PERIOD * 2 + 30); private static final int MAX_N_INSTANCES = 5; private static final int MIN_N_INSTANCES = 2; private static final long COOLDOWN_PERIOD = 1000 * 30; //in miliseconds private static final long POOLING_PERIOD = 1000 * 60 * 1; //in miliseconds private static final double MAX_CPU_UTILIZATION = 60.0; //in percentage private static final double MIN_CPU_UTILIZATION = 30.0; //in percentage private static final String WEBSERVER_AMI_ID = "ami-7808840b"; private static final String KEY_PAIR_NAME = "CNV-proj-AWS"; private static final String SECGROUP_NAME = "CNV-ssh+http"; /** * The only information needed to create a client are security credentials * consisting of the AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints, are performed * automatically. Client parameters, such as proxies, can be specified in an * optional ClientConfiguration object when constructing a client. * * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration */ private static void init() throws Exception { AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider().getCredentials(); } catch (Exception e) { throw new AmazonClientException( "Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } ec2 = new AmazonEC2Client(credentials); cloudWatch = new AmazonCloudWatchClient(credentials); instances = new HashSet<Instance>(); // Using AWS Ireland. Pick the zone where you have AMI, key and secgroup ec2.setEndpoint("ec2.eu-west-1.amazonaws.com"); cloudWatch.setEndpoint("monitoring.eu-west-1.amazonaws.com"); } private static Instance launchNewInstance(){ RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); //check if the following options match with the desired AMI and Security Group at AWS runInstancesRequest.withImageId(WEBSERVER_AMI_ID) .withInstanceType("t2.micro") .withMinCount(1) .withMaxCount(1) .withKeyName(KEY_PAIR_NAME) .withSecurityGroups(SECGROUP_NAME) .withMonitoring(true); RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); Instance newInstance = runInstancesResult.getReservation().getInstances().get(0); System.out.println("Starting a new instance with id = " + newInstance.getInstanceId()); return newInstance; } private static void terminateInstance(String instanceId){ System.out.println("Terminating instance with id = " + instanceId); TerminateInstancesRequest termInstanceReq = new TerminateInstancesRequest(); termInstanceReq.withInstanceIds(instanceId); ec2.terminateInstances(termInstanceReq); } private static boolean checkIncreaseGroupSizePolicy(List<Datapoint> datapoints) { //when CPU utilization > 60% for 60 seconds System.out.println("checkIncreaseGroupSizePolicy:"); for (Datapoint dp : datapoints) { double cpuUtilization = Math.floor(dp.getAverage() * 100) / 100; System.out.println(" CPU utilization = " + cpuUtilization + " with time = " + dp.getTimestamp().toString()); if(cpuUtilization <= MAX_CPU_UTILIZATION){ return false; } } //decrease group size launchNewInstance(); return true; //TODO: TIMER } private static boolean checkDecreaseGroupSizePolicy(List<Datapoint> datapoints, String instanceId) { //when CPU utilization < 30% for 2 consecutive 7 minutes period System.out.println("checkDecreaseGroupSizePolicy:"); for (Datapoint dp : datapoints) { double cpuUtilization = Math.floor(dp.getAverage() * 100) / 100; System.out.println(" CPU utilization = " + cpuUtilization + " with time = " + dp.getTimestamp().toString()); if(cpuUtilization >= MIN_CPU_UTILIZATION){ return false; } } //decrease group size terminateInstance(instanceId); return true; //TODO: TIMER } public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS Java SDK!"); System.out.println("==========================================="); try { init(); //Uncomment below if you need to start an instance //launchNewInstance(); //Pooling the information about all WebServer instances DescribeInstancesResult describeInstancesResult = ec2.describeInstances(); List<Reservation> reservations = describeInstancesResult.getReservations(); System.out.println("total reservations = " + reservations.size()); for (Reservation reservation : reservations) { for (Instance instance : reservation.getInstances()) { if(!instance.getState().getName().equals("terminated") && instance.getImageId().equals(WEBSERVER_AMI_ID)){ instances.add(instance); } } } System.out.println("total instances = " + instances.size()); while (instances.size() < MIN_N_INSTANCES){ instances.add(launchNewInstance()); } System.out.println("total instances = " + instances.size()); Dimension instanceDimension = new Dimension(); instanceDimension.setName("InstanceId"); //auto scaling monitoring loop long offsetInMilliseconds = 0; GetMetricStatisticsRequest request; GetMetricStatisticsResult getMetricStatisticsResult; List<Datapoint> datapoints; for(;;){ for (Instance instance : instances) { String name = instance.getInstanceId(); String state = instance.getState().getName(); System.out.println("Instance Name : " + name +"."); System.out.println("Instance State : " + state +"."); if (state.equals("running")) { instanceDimension.setValue(name); //Get metrics to check the increase policy if (instances.size() < MAX_N_INSTANCES) { offsetInMilliseconds = INCR_DATAPOINTS_OFFSET; request = new GetMetricStatisticsRequest() .withStartTime(new Date(new Date().getTime() - offsetInMilliseconds)) .withNamespace("AWS/EC2") .withPeriod(INCR_POLICY_PERIOD) .withMetricName("CPUUtilization") .withStatistics("Average") .withUnit("Percent") .withDimensions(instanceDimension) .withEndTime(new Date()); getMetricStatisticsResult = cloudWatch.getMetricStatistics(request); datapoints = getMetricStatisticsResult.getDatapoints(); System.out.println("datapoints size = " + datapoints.size()); if(datapoints.size() >= 2){ if(checkIncreaseGroupSizePolicy(datapoints)){ System.out.println("Coolling down for : " + COOLDOWN_PERIOD +" miliseconds."); Thread.sleep(COOLDOWN_PERIOD); System.out.println("Cooldown period expired!"); break; } } } //Get metrics to check the decrease policy if (instances.size() > MIN_N_INSTANCES) { offsetInMilliseconds = DECR_DATAPOINTS_OFFSET; request = new GetMetricStatisticsRequest() .withStartTime(new Date(new Date().getTime() - offsetInMilliseconds)) .withNamespace("AWS/EC2") .withPeriod(DECR_POLICY_PERIOD) .withMetricName("CPUUtilization") .withStatistics("Average") .withUnit("Percent") .withDimensions(instanceDimension) .withEndTime(new Date()); getMetricStatisticsResult = cloudWatch.getMetricStatistics(request); datapoints = getMetricStatisticsResult.getDatapoints(); System.out.println("datapoints size = " + datapoints.size()); if(datapoints.size() >= 2){ if(checkDecreaseGroupSizePolicy(datapoints, name)){ System.out.println("Coolling down for : " + COOLDOWN_PERIOD +" miliseconds."); Thread.sleep(COOLDOWN_PERIOD); System.out.println("Cooldown period expired!"); break; } } } } else { System.out.println("Instance id = " + name + " is not running!"); } } //Stop pooling for 1 minute System.out.println("Waiting: " + POOLING_PERIOD +" miliseconds for the next pooling."); Thread.sleep(POOLING_PERIOD); System.out.println("==========================================="); //Pooling the information about all WebServer instances describeInstancesResult = ec2.describeInstances(); reservations = describeInstancesResult.getReservations(); instances = new HashSet<Instance>(); System.out.println("total reservations = " + reservations.size()); for (Reservation reservation : reservations) { for (Instance instance : reservation.getInstances()) { if(!instance.getState().getName().equals("terminated") && instance.getImageId().equals(WEBSERVER_AMI_ID)){ instances.add(instance); } } } System.out.println("total instances = " + instances.size()); } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Collections; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); String[] columnNames = {"String", "Integer", "Boolean"}; Object[][] data = { {"aaa", 12, true}, {"bbb", 5, false}, {"CCC", 92, true}, {"DDD", 0, false} }; TableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; JTable table = new JTable(model); table.setAutoCreateRowSorter(true); int index = 0; // table.getRowSorter().toggleSortOrder(index); // SortOrder.ASCENDING table.getRowSorter().setSortKeys(Collections.singletonList(new RowSorter.SortKey(index, SortOrder.DESCENDING))); add(new JScrollPane(table)); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package org.hcjf.properties; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.hcjf.log.Log; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.*; /** * This class overrides the system properties default implementation adding * some default values and properties definitions for the service-oriented platforms * works. * @author javaito * @email javaito@gmail.com */ public final class SystemProperties extends Properties { public static final String HCJF_DEFAULT_DATE_FORMAT = "hcjf.default.date.format"; public static final String HCJF_DEFAULT_NUMBER_FORMAT = "hcjf.default.number.format"; public static final String HCJF_DEFAULT_DECIMAL_SEPARATOR = "hcjf.default.decimal.separator"; public static final String HCJF_DEFAULT_GROUPING_SEPARATOR = "hcjf.default.grouping.separator"; public static final String HCJF_DEFAULT_LOCALE = "hcjf.default.locale"; public static final String HCJF_DEFAULT_PROPERTIES_FILE_PATH = "hcjf.default.properties.file.path"; public static final String HCJF_DEFAULT_PROPERTIES_FILE_XML = "hcjf.default.properties.file.xml"; public static final String SERVICE_THREAD_POOL_CORE_SIZE = "hcjf.service.thread.pool.core.size"; public static final String SERVICE_THREAD_POOL_MAX_SIZE = "hcfj.service.thread.pool.max.size"; public static final String SERVICE_THREAD_POOL_KEEP_ALIVE_TIME = "hcfj.service.thread.pool.keep.alive.time"; public static final String SERVICE_GUEST_SESSION_NAME = "hcjf.service.guest.session.name"; public static final String SERVICE_SHUTDOWN_TIME_OUT = "hcjf.service.shutdown.time.out"; public static final String LOG_FILE_PREFIX = "hcfj.log.file.prefix"; public static final String LOG_ERROR_FILE = "hcfj.log.error.file"; public static final String LOG_WARNING_FILE = "hcfj.log.warning.file"; public static final String LOG_INFO_FILE = "hcfj.log.info.file"; public static final String LOG_DEBUG_FILE = "hcfj.log.debug.file"; public static final String LOG_LEVEL= "hcfj.log.level"; public static final String LOG_DATE_FORMAT = "hcfj.log.date.format"; public static final String LOG_CONSUMERS = "hcjf.log.consumers"; public static final String LOG_SYSTEM_OUT_ENABLED = "hcjf.log.system.out.enabled"; public static final String LOG_QUEUE_INITIAL_SIZE = "hcjf.log.queue.initial.size"; public static final String LOG_TRUNCATE_TAG = "hcjf.log.truncate.tag"; public static final String LOG_TRUNCATE_TAG_SIZE = "hcjf.log.truncate.tag.size"; public static final String NET_INPUT_BUFFER_SIZE = "hcfj.net.input.buffer.size"; public static final String NET_OUTPUT_BUFFER_SIZE = "hcfj.net.output.buffer.size"; public static final String NET_DISCONNECT_AND_REMOVE = "hcfj.net.disconnect.and.remove"; public static final String NET_CONNECTION_TIMEOUT_AVAILABLE = "hcfj.net.connection.timeout.available"; public static final String NET_CONNECTION_TIMEOUT = "hcfj.net.connection.timeout"; public static final String NET_WRITE_TIMEOUT = "hcjf.net.write.timeout"; public static final String NET_IO_THREAD_POOL_KEEP_ALIVE_TIME = "hcjf.net.io.thread.pool.keep.alive.time"; public static final String NET_IO_THREAD_POOL_MAX_SIZE = "hcjf.net.io.thread.pool.max.size"; public static final String NET_IO_THREAD_POOL_CORE_SIZE = "hcjf.net.io.thread.pool.core.size"; public static final String NET_DEFAULT_INPUT_BUFFER_SIZE = "hcjf.net.default.input.buffer.size"; public static final String NET_DEFAULT_OUTPUT_BUFFER_SIZE = "hcjf.net.default.output.buffer.size"; public static final String NET_IO_THREAD_DIRECT_ALLOCATE_MEMORY = "hcjf.net.io.thread.direct.allocate.memory"; public static final String NET_SSL_MAX_IO_THREAD_POOL_SIZE = "hcjf.net.ssl.max.io.thread.pool.size"; public static final String HTTP_SERVER_NAME = "hcjf.http.server.name"; public static final String HTTP_RESPONSE_DATE_HEADER_FORMAT_VALUE = "hcjf.http.response.date.header.format.value"; public static final String HTTP_INPUT_LOG_BODY_MAX_LENGTH = "hcjf.http.input.log.body.max.length"; public static final String HTTP_OUTPUT_LOG_BODY_MAX_LENGTH = "hcjf.http.output.log.body.max.length"; public static final String HTTP_DEFAULT_SERVER_PORT = "hcjf.http.default.server.port"; public static final String HTTP_DEFAULT_CLIENT_PORT = "hcjf.http.default.client.port"; public static final String HTTP_STREAMING_LIMIT_FILE_SIZE = "hcjf.http.streaming.limit.file.size"; public static final String HTTP_DEFAULT_ERROR_FORMAT_SHOW_STACK = "hcjf.http.default.error.format.show.stack"; public static final String HTTP_DEFAULT_CLIENT_CONNECT_TIMEOUT = "hcjf.http.default.client.connect.timeout"; public static final String HTTP_DEFAULT_CLIENT_READ_TIMEOUT = "hcjf.http.default.client.read.timeout"; public static final String HTTP_DEFAULT_CLIENT_WRITE_TIMEOUT = "hcjf.http.default.client.write.timeout"; public static final String HTTP_DEFAULT_GUEST_SESSION_NAME = "hcjf.http.default.guest.session.name"; public static final String HTTPS_DEFAULT_SERVER_PORT = "hcjf.https.default.server.port"; public static final String HTTPS_DEFAULT_CLIENT_PORT = "hcjf.https.default.server.port"; public static final String REST_DEFAULT_MIME_TYPE = "hcjf.rest.default.mime.type"; public static final String REST_DEFAULT_ENCODING_IMPL = "hcjf.rest.default.encoding.impl"; public static final String REST_QUERY_PATH = "hcjf.rest.query.path"; public static final String REST_QUERY_PARAMETER_PATH = "hcjf.rest.query.parameter.path"; public static final String QUERY_DEFAULT_LIMIT = "hcjf.query.default.limit"; public static final String QUERY_DEFAULT_DESC_ORDER = "hcjf.query.default.desc.order"; public static final String CLOUD_IMPL = "hcjf.cloud.impl"; //Java property names public static final String FILE_ENCODING = "file.encoding"; private static final SystemProperties instance; static { instance = new SystemProperties(); } private final Map<String, Object> instancesCache; private final JsonParser jsonParser; private SystemProperties() { super(new Properties()); instancesCache = new HashMap<>(); jsonParser = new JsonParser(); defaults.put(HCJF_DEFAULT_DATE_FORMAT, "yyyy-MM-dd HH:mm:ss"); defaults.put(HCJF_DEFAULT_NUMBER_FORMAT, "0.000"); defaults.put(HCJF_DEFAULT_DECIMAL_SEPARATOR, "."); defaults.put(HCJF_DEFAULT_GROUPING_SEPARATOR, ","); defaults.put(HCJF_DEFAULT_LOCALE, "EN"); defaults.put(HCJF_DEFAULT_PROPERTIES_FILE_XML, "false"); defaults.put(SERVICE_THREAD_POOL_CORE_SIZE, "100"); defaults.put(SERVICE_THREAD_POOL_MAX_SIZE, Integer.toString(Integer.MAX_VALUE)); defaults.put(SERVICE_THREAD_POOL_KEEP_ALIVE_TIME, "10"); defaults.put(SERVICE_GUEST_SESSION_NAME, "Guest"); defaults.put(SERVICE_SHUTDOWN_TIME_OUT, "200"); defaults.put(LOG_FILE_PREFIX, "hcfj"); defaults.put(LOG_ERROR_FILE, "false"); defaults.put(LOG_WARNING_FILE, "false"); defaults.put(LOG_INFO_FILE, "false"); defaults.put(LOG_DEBUG_FILE, "false"); defaults.put(LOG_LEVEL, "1"); defaults.put(LOG_DATE_FORMAT, "yyyy-MM-dd HH:mm:ss,SSS"); defaults.put(LOG_CONSUMERS, "[]"); defaults.put(LOG_SYSTEM_OUT_ENABLED, "false"); defaults.put(LOG_QUEUE_INITIAL_SIZE, "10000"); defaults.put(LOG_TRUNCATE_TAG, "false"); defaults.put(LOG_TRUNCATE_TAG_SIZE, "35"); defaults.put(NET_INPUT_BUFFER_SIZE, "1024"); defaults.put(NET_OUTPUT_BUFFER_SIZE, "1024"); defaults.put(NET_CONNECTION_TIMEOUT_AVAILABLE, "true"); defaults.put(NET_CONNECTION_TIMEOUT, "30000"); defaults.put(NET_DISCONNECT_AND_REMOVE, "true"); defaults.put(NET_WRITE_TIMEOUT, "100"); defaults.put(NET_IO_THREAD_POOL_KEEP_ALIVE_TIME, "120"); defaults.put(NET_IO_THREAD_POOL_MAX_SIZE, "10000"); defaults.put(NET_IO_THREAD_POOL_CORE_SIZE, "100"); defaults.put(NET_DEFAULT_INPUT_BUFFER_SIZE, "5000"); defaults.put(NET_DEFAULT_OUTPUT_BUFFER_SIZE, "5000"); defaults.put(NET_IO_THREAD_DIRECT_ALLOCATE_MEMORY, "false"); defaults.put(NET_SSL_MAX_IO_THREAD_POOL_SIZE, "2"); defaults.put(HTTP_SERVER_NAME, "HCJF Web Server"); defaults.put(HTTP_RESPONSE_DATE_HEADER_FORMAT_VALUE, "EEE, dd MMM yyyy HH:mm:ss z"); defaults.put(HTTP_INPUT_LOG_BODY_MAX_LENGTH, "128"); defaults.put(HTTP_OUTPUT_LOG_BODY_MAX_LENGTH, "128"); defaults.put(HTTP_DEFAULT_SERVER_PORT, "80"); defaults.put(HTTP_DEFAULT_CLIENT_PORT, "80"); defaults.put(HTTP_STREAMING_LIMIT_FILE_SIZE, "10240"); defaults.put(HTTP_DEFAULT_ERROR_FORMAT_SHOW_STACK, "true"); defaults.put(HTTP_DEFAULT_CLIENT_CONNECT_TIMEOUT, "10000"); defaults.put(HTTP_DEFAULT_CLIENT_READ_TIMEOUT, "10000"); defaults.put(HTTP_DEFAULT_CLIENT_WRITE_TIMEOUT, "10000"); defaults.put(HTTP_DEFAULT_GUEST_SESSION_NAME, "Http guest session"); defaults.put(HTTPS_DEFAULT_SERVER_PORT, "443"); defaults.put(HTTPS_DEFAULT_CLIENT_PORT, "443"); defaults.put(REST_DEFAULT_MIME_TYPE, "application/json"); defaults.put(REST_DEFAULT_ENCODING_IMPL, "hcjf"); defaults.put(REST_QUERY_PATH, "query"); defaults.put(REST_QUERY_PARAMETER_PATH, "q"); defaults.put(QUERY_DEFAULT_LIMIT, "1000"); defaults.put(QUERY_DEFAULT_DESC_ORDER, "false"); Properties system = System.getProperties(); putAll(system); System.setProperties(this); } /** * Put the default value for a property. * @param propertyName Property name. * @param defaultValue Property default value. * @throws NullPointerException Throw a {@link NullPointerException} when the * property name or default value are null. */ public static void putDefaultValue(String propertyName, String defaultValue) { if(propertyName == null) { throw new NullPointerException("Invalid property name null"); } if(defaultValue == null) { throw new NullPointerException("Invalid default value null"); } instance.defaults.put(propertyName, defaultValue); } /** * Calls the <tt>Hashtable</tt> method {@code put}. Provided for * parallelism with the <tt>getProperty</tt> method. Enforces use of * strings for property keys and values. The value returned is the * result of the <tt>Hashtable</tt> call to {@code put}. * * @param key the key to be placed into this property list. * @param value the value corresponding to <tt>key</tt>. * @return the previous value of the specified key in this property * list, or {@code null} if it did not have one. * @see #getProperty * @since 1.2 */ @Override public synchronized Object setProperty(String key, String value) { Object result = super.setProperty(key, value); synchronized (instancesCache) { instancesCache.remove(key); } try { //TODO: Create listeners } catch (Exception ex){} return result; } /** * This method return the string value of the system property * named like the parameter. * @param propertyName Name of the find property. * @param validator * @return Return the value of the property or null if the property is no defined. */ public static String get(String propertyName, PropertyValueValidator<String> validator) { String result = System.getProperty(propertyName); if(result == null) { Log.d("Property not found: $1", propertyName); } if(validator != null) { if(!validator.validate(result)){ throw new IllegalPropertyValueException(propertyName + "=" + result); } } return result; } /** * This method return the string value of the system property * named like the parameter. * @param propertyName Name of the find property. * @return Return the value of the property or null if the property is no defined. */ public static String get(String propertyName) { return get(propertyName, null); } /** * This method return the value of the system property as boolean. * @param propertyName Name of the find property. * @return Value of the system property as boolean, or null if the property is not found. */ public static Boolean getBoolean(String propertyName) { Boolean result = null; String propertyValue = get(propertyName); try { if (propertyValue != null) { result = Boolean.valueOf(propertyValue); } } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a boolean valid format: '" + propertyName + ":" + propertyValue + "'", ex); } return result; } /** * This method return the value of the system property as integer. * @param propertyName Name of the find property. * @return Value of the system property as integer, or null if the property is not found. */ public static Integer getInteger(String propertyName) { Integer result = null; String propertyValue = get(propertyName); try { if(propertyValue != null) { result = Integer.decode(propertyValue); } } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a integer valid format: '" + propertyName + ":" + propertyValue + "'", ex); } return result; } /** * This method return the value of the system property as long. * @param propertyName Name of the find property. * @return Value of the system property as long, or null if the property is not found. */ public static Long getLong(String propertyName) { Long result = null; String propertyValue = get(propertyName); try { if (propertyValue != null) { result = Long.decode(propertyValue); } } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a long valid format: '" + propertyName + ":" + propertyValue + "'", ex); } return result; } /** * This method return the value of the system property as double. * @param propertyName Name of the find property. * @return Value of the system property as double, or null if the property is not found. */ public static Double getDouble(String propertyName) { Double result = null; String propertyValue = get(propertyName); try { if (propertyValue != null) { result = Double.valueOf(propertyValue); } } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a double valid format: '" + propertyName + ":" + propertyValue + "'", ex); } return result; } /** * This method return the value of the system property as class. * @param propertyName Name of the find property. * @param <O> Type of the class instance expected. * @return Class instance. */ public static <O extends Object> Class<O> getClass(String propertyName) { Class<O> result; String propertyValue = get(propertyName); try { result = (Class<O>) Class.forName(propertyValue); } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a class name valid format: '" + propertyName + ":" + propertyValue + "'", ex); } return result; } /** * Return the default charset of the JVM instance. * @return Default charset. */ public static String getDefaultCharset() { return System.getProperty(FILE_ENCODING); } /** * This method return the value of the property as Locale instance. * The instance returned will be stored on near cache and will be removed when the * value of the property has been updated. * @param propertyName Name of the property that contains locale representation. * @return Locale instance. */ public static Locale getLocale(String propertyName) { Locale result; synchronized (instance.instancesCache) { result = (Locale) instance.instancesCache.get(propertyName); if(result == null) { String propertyValue = get(propertyName); try { result = Locale.forLanguageTag(propertyValue); instance.instancesCache.put(propertyName, result); } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a locale tag valid format: '" + propertyName + ":" + propertyValue + "'", ex); } } } return result; } /** * This method return the valuo of the property called 'hcjf.default.locale' as a locale instance. * The instance returned will be stored on near cache and will be removed when the * value of the property has been updated. * @return Locale instance. */ public static Locale getLocale() { return getLocale(HCJF_DEFAULT_LOCALE); } /** * This method return the value of the property as a DecimalFormat instnace. * The instance returned will be stored on near cache and will be removed when the * value of the property has been updated. * @param propertyName Name of the property that contains decimal pattern. * @return DecimalFormat instance. */ public static DecimalFormat getDecimalFormat(String propertyName) { DecimalFormat result; synchronized (instance.instancesCache) { result = (DecimalFormat) instance.instancesCache.get(propertyName); if(result == null) { String propertyValue = get(propertyName); try { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(get(HCJF_DEFAULT_DECIMAL_SEPARATOR).charAt(0)); symbols.setGroupingSeparator(get(HCJF_DEFAULT_GROUPING_SEPARATOR).charAt(0)); result = new DecimalFormat(propertyValue, symbols); instance.instancesCache.put(propertyName, result); } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a decimal pattern valid format: '" + propertyName + ":" + propertyValue + "'", ex); } } } return result; } /** * This method return the value of the property as a SimpleDateFormat instance. * The instance returned will be stored on near cache and will be removed when the * value of the property has been updated. * @param propertyName Name of the property that contains date representation. * @return Simple date format instance. */ public static SimpleDateFormat getDateFormat(String propertyName) { SimpleDateFormat result; synchronized (instance.instancesCache) { result = (SimpleDateFormat) instance.instancesCache.get(propertyName); if(result == null) { String propertyValue = get(propertyName); try { result = new SimpleDateFormat(get(propertyName)); instance.instancesCache.put(propertyName, result); } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a date pattern valid format: '" + propertyName + ":" + propertyValue + "'", ex); } } } return result; } /** * This method return the value of the property as instance of list. * @param propertyName Name of the property that contains the json array representation. * @return List instance. */ public static List<String> getList(String propertyName) { String propertyValue = get(propertyName); List<String> result = new ArrayList<>(); if(instance.instancesCache.containsKey(propertyName)) { result.addAll((List<? extends String>) instance.instancesCache.get(propertyName)); } else { try { JsonArray array = (JsonArray) instance.jsonParser.parse(propertyValue); array.forEach(A -> result.add(A.getAsString())); List<String> cachedResult = new ArrayList<>(); cachedResult.addAll(result); instance.instancesCache.put(propertyName, cachedResult); } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a json array valid format: '" + propertyName + ":" + propertyValue + "'", ex); } } return result; } /** * This method return the value of the property as instance of set. * @param propertyName Name of the property that contains the json array representation. * @return Set instance. */ public static Set<String> getSet(String propertyName) { String propertyValue = get(propertyName); Set<String> result = new TreeSet<>(); if(instance.instancesCache.containsKey(propertyName)) { result.addAll((List<? extends String>) instance.instancesCache.get(propertyName)); } else { try { JsonArray array = (JsonArray) instance.jsonParser.parse(propertyValue); array.forEach(A -> result.add(A.getAsString())); List<String> cachedResult = new ArrayList<>(); cachedResult.addAll(result); instance.instancesCache.put(propertyName, cachedResult); } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a json array valid format: '" + propertyName + ":" + propertyValue + "'", ex); } } return result; } /** * This method return the value of the property as instance of map. * @param propertyName The name of the property that contains the json object representation. * @return Map instance. */ public static Map<String, String> getMap(String propertyName) { String propertyValue = get(propertyName); Map<String, String> result = new HashMap<>(); if(instance.instancesCache.containsKey(propertyName)) { result.putAll((Map<String, String>) instance.instancesCache.get(propertyName)); } else { try { JsonObject object = (JsonObject) instance.jsonParser.parse(propertyValue); object.entrySet().forEach(S -> result.put(S.getKey(), object.get(S.getKey()).getAsString())); Map<String, String> cachedResult = new HashMap<>(); cachedResult.putAll(result); instance.instancesCache.put(propertyName, cachedResult); } catch (Exception ex) { throw new IllegalArgumentException("The property value has not a json object valid format: '" + propertyName + ":" + propertyValue + "'", ex); } } return result; } }
package org.helioviewer.jhv.opengl; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.Arrays; import org.helioviewer.jhv.math.Vec3; public class BufVertex { private static final int chunk = 1024; private int multiplier = 1; private final byte[] byteLast = new byte[16]; private final FloatBuffer bufferLast = ByteBuffer.wrap(byteLast).order(ByteOrder.nativeOrder()).asFloatBuffer(); private int count; private ByteBuffer vertxBuffer; private byte[] arrayVertx; private int lengthVertx; private ByteBuffer colorBuffer; private byte[] arrayColor; private int lengthColor; public BufVertex(int size) { arrayVertx = new byte[size < 16 ? 16 : size]; vertxBuffer = ByteBuffer.wrap(arrayVertx); size /= 4; arrayColor = new byte[size < 4 ? 4 : size]; colorBuffer = ByteBuffer.wrap(arrayColor); } private void ensureVertx(int nbytes) { int size = arrayVertx.length; if (lengthVertx + nbytes > size) { arrayVertx = Arrays.copyOf(arrayVertx, size + chunk * multiplier++); vertxBuffer = ByteBuffer.wrap(arrayVertx); } } private void ensureColor(int nbytes) { int size = arrayColor.length; if (lengthColor + nbytes > size) { arrayColor = Arrays.copyOf(arrayColor, size + chunk * multiplier++); colorBuffer = ByteBuffer.wrap(arrayColor); } } public void putVertex(Vec3 v, byte[] b) { putVertex((float) v.x, (float) v.y, (float) v.z, 1, b); } public void putVertex(float x, float y, float z, float w, byte[] b) { bufferLast.put(0, x).put(1, y).put(2, z).put(3, w); repeatVertex(b); } public void repeatVertex(byte[] b) { ensureVertx(16); System.arraycopy(byteLast, 0, arrayVertx, lengthVertx, 16); lengthVertx += 16; ensureColor(4); arrayColor[lengthColor] = b[0]; arrayColor[lengthColor + 1] = b[1]; arrayColor[lengthColor + 2] = b[2]; arrayColor[lengthColor + 3] = b[3]; lengthColor += 4; count++; } public int getCount() { return count; } public void clear() { lengthVertx = 0; lengthColor = 0; count = 0; } public Buffer toVertexBuffer() { return vertxBuffer.limit(lengthVertx); } public Buffer toColorBuffer() { return colorBuffer.limit(lengthColor); } }
package org.jgroups.blocks; import org.jgroups.*; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.protocols.TP; import org.jgroups.stack.Protocol; import org.jgroups.stack.StateTransferInfo; import org.jgroups.util.*; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.*; /** * Provides synchronous and asynchronous message sending with request-response * correlation; i.e., matching responses with the original request. * It also offers push-style message reception (by internally using the PullPushAdapter). * <p> * Channels are simple patterns to asynchronously send a receive messages. * However, a significant number of communication patterns in group communication * require synchronous communication. For example, a sender would like to send a * message to the group and wait for all responses. Or another application would * like to send a message to the group and wait only until the majority of the * receivers have sent a response, or until a timeout occurred. MessageDispatcher * offers a combination of the above pattern with other patterns. * <p> * Used on top of channel to implement group requests. Client's <code>handle()</code> * method is called when request is received. Is the equivalent of RpcProtocol on * the application instead of protocol level. * * @author Bela Ban * @version $Id: MessageDispatcher.java,v 1.103 2010/04/21 09:02:46 belaban Exp $ */ public class MessageDispatcher implements RequestHandler { protected Channel channel=null; protected RequestCorrelator corr=null; protected MessageListener msg_listener=null; protected MembershipListener membership_listener=null; protected RequestHandler req_handler=null; protected ProtocolAdapter prot_adapter=null; protected TransportAdapter transport_adapter=null; protected final Collection<Address> members=new TreeSet<Address>(); protected Address local_addr=null; protected PullPushAdapter adapter=null; protected PullPushHandler handler=null; protected Serializable id=null; protected final Log log=LogFactory.getLog(getClass()); protected boolean hardware_multicast_supported=false; public MessageDispatcher() { } public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2) { this.channel=channel; prot_adapter=new ProtocolAdapter(); if(channel != null) { local_addr=channel.getAddress(); } setMessageListener(l); setMembershipListener(l2); if(channel != null) { channel.setUpHandler(prot_adapter); } start(); } @Deprecated public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, boolean deadlock_detection) { this.channel=channel; prot_adapter=new ProtocolAdapter(); if(channel != null) { local_addr=channel.getAddress(); } setMessageListener(l); setMembershipListener(l2); if(channel != null) { channel.setUpHandler(prot_adapter); } start(); } @Deprecated public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, boolean deadlock_detection, boolean concurrent_processing) { this.channel=channel; prot_adapter=new ProtocolAdapter(); if(channel != null) { local_addr=channel.getAddress(); } setMessageListener(l); setMembershipListener(l2); if(channel != null) { channel.setUpHandler(prot_adapter); } start(); } public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler) { this(channel, l, l2); setRequestHandler(req_handler); } @Deprecated public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler, boolean deadlock_detection) { this(channel, l, l2, deadlock_detection, false); setRequestHandler(req_handler); } @Deprecated public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler, boolean deadlock_detection, boolean concurrent_processing) { this(channel, l, l2, deadlock_detection, concurrent_processing); setRequestHandler(req_handler); } @Deprecated public MessageDispatcher(PullPushAdapter adapter, Serializable id, MessageListener l, MembershipListener l2) { this.adapter=adapter; this.id=id; setMembers(((Channel) adapter.getTransport()).getView().getMembers()); setMessageListener(l); setMembershipListener(l2); handler=new PullPushHandler(); transport_adapter=new TransportAdapter(); adapter.addMembershipListener(handler); // remove in stop() if(id == null) { // no other building block around, let's become the main consumer of this PullPushAdapter adapter.setListener(handler); } else { adapter.registerListener(id, handler); } Transport tp; if((tp=adapter.getTransport()) instanceof Channel) { local_addr=((Channel) tp).getAddress(); } start(); } @Deprecated public MessageDispatcher(PullPushAdapter adapter, Serializable id, MessageListener l, MembershipListener l2, RequestHandler req_handler) { this.adapter=adapter; this.id=id; setMembers(((Channel) adapter.getTransport()).getView().getMembers()); setRequestHandler(req_handler); setMessageListener(l); setMembershipListener(l2); handler=new PullPushHandler(); transport_adapter=new TransportAdapter(); adapter.addMembershipListener(handler); if(id == null) { // no other building block around, let's become the main consumer of this PullPushAdapter adapter.setListener(handler); } else { adapter.registerListener(id, handler); } Transport tp; if((tp=adapter.getTransport()) instanceof Channel) { local_addr=((Channel) tp).getAddress(); // fixed bug #800774 } start(); } @Deprecated public MessageDispatcher(PullPushAdapter adapter, Serializable id, MessageListener l, MembershipListener l2, RequestHandler req_handler, boolean concurrent_processing) { this.adapter=adapter; this.id=id; setMembers(((Channel) adapter.getTransport()).getView().getMembers()); setRequestHandler(req_handler); setMessageListener(l); setMembershipListener(l2); handler=new PullPushHandler(); transport_adapter=new TransportAdapter(); adapter.addMembershipListener(handler); if(id == null) { // no other building block around, let's become the main consumer of this PullPushAdapter adapter.setListener(handler); } else { adapter.registerListener(id, handler); } Transport tp; if((tp=adapter.getTransport()) instanceof Channel) { local_addr=((Channel) tp).getAddress(); // fixed bug #800774 } start(); } public UpHandler getProtocolAdapter() { return prot_adapter; } /** Returns a copy of members */ protected Collection getMembers() { synchronized(members) { return new ArrayList(members); } } /** * If this dispatcher is using a user-provided PullPushAdapter, then need to set the members from the adapter * initially since viewChange has most likely already been called in PullPushAdapter. */ private void setMembers(Vector new_mbrs) { if(new_mbrs != null) { synchronized(members) { members.clear(); members.addAll(new_mbrs); } } } @Deprecated public boolean getDeadlockDetection() {return false;} @Deprecated public void setDeadlockDetection(boolean flag) { } @Deprecated public boolean getConcurrentProcessing() {return false;} @Deprecated public void setConcurrentProcessing(boolean flag) { } public void start() { if(corr == null) { if(transport_adapter != null) { corr=createRequestCorrelator(transport_adapter, this, local_addr); } else { corr=createRequestCorrelator(prot_adapter, this, local_addr); } } correlatorStarted(); corr.start(); if(channel != null) { Vector tmp_mbrs=channel.getView() != null ? channel.getView().getMembers() : null; setMembers(tmp_mbrs); if(channel instanceof JChannel) { TP transport=channel.getProtocolStack().getTransport(); corr.registerProbeHandler(transport); } TP transport=channel.getProtocolStack().getTransport(); hardware_multicast_supported=transport.supportsMulticasting(); } } protected RequestCorrelator createRequestCorrelator(Object transport, RequestHandler handler, Address local_addr) { return new RequestCorrelator(transport, handler, local_addr); } protected void correlatorStarted() { ; } public void stop() { if(corr != null) { corr.stop(); } if(channel instanceof JChannel) { TP transport=channel.getProtocolStack().getTransport(); corr.unregisterProbeHandler(transport); } if(adapter != null && handler != null) { adapter.removeMembershipListener(handler); } } public final void setMessageListener(MessageListener l) { msg_listener=l; } /** * Gives access to the currently configured MessageListener. Returns null if there is no * configured MessageListener. */ public MessageListener getMessageListener() { return msg_listener; } public final void setMembershipListener(MembershipListener l) { membership_listener=l; } public final void setRequestHandler(RequestHandler rh) { req_handler=rh; } /** * Offers access to the underlying Channel. * @return a reference to the underlying Channel. */ public Channel getChannel() { return channel; } public void setChannel(Channel ch) { if(ch == null) return; this.channel=ch; local_addr=channel.getAddress(); if(prot_adapter == null) prot_adapter=new ProtocolAdapter(); if (channel.getUpHandler() == null) { channel.setUpHandler(prot_adapter); } } @Deprecated public void send(Message msg) throws ChannelNotConnectedException, ChannelClosedException { if(channel != null) { channel.send(msg); return; } if(adapter != null) { try { if(id != null) adapter.send(id, msg); else adapter.send(msg); } catch(Throwable ex) { log.error("exception=" + Util.print(ex)); } } else { log.error("channel == null"); } } @Deprecated public RspList castMessage(final Vector dests, Message msg, int mode, long timeout) { return castMessage(dests, msg, new RequestOptions(mode, timeout, false, null)); } @Deprecated public RspList castMessage(final Vector dests, Message msg, int mode, long timeout, boolean use_anycasting) { return castMessage(dests, msg, new RequestOptions(mode, timeout, use_anycasting, null)); } // used by Infinispan @Deprecated /** * @deprecated Use {@link #castMessage(java.util.Collection, org.jgroups.Message, RequestOptions)} instead */ public RspList castMessage(final Vector dests, Message msg, int mode, long timeout, boolean use_anycasting, RspFilter filter) { RequestOptions opts=new RequestOptions(mode, timeout, use_anycasting, filter); return castMessage(dests, msg, opts); } /** * Sends a message to the members listed in dests. If dests is null, the message is sent to all current group * members. * @param dests A list of group members. The message is sent to all members of the current group if null * @param msg The message to be sent * @param options A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details * @return * @since 2.9 */ public RspList castMessage(final Collection<Address> dests, Message msg, RequestOptions options) { GroupRequest req=cast(dests, msg, options, true); return req != null? req.getResults() : RspList.EMPTY_RSP_LIST; } @Deprecated public NotifyingFuture<RspList> castMessageWithFuture(final Vector dests, Message msg, int mode, long timeout, boolean use_anycasting, RspFilter filter) { return castMessageWithFuture(dests, msg, new RequestOptions(mode, timeout, use_anycasting, filter)); } public NotifyingFuture<RspList> castMessageWithFuture(final Collection<Address> dests, Message msg, RequestOptions options) { GroupRequest req=cast(dests, msg, options, false); return req != null? req : new NullFuture(RspList.EMPTY_RSP_LIST); } protected GroupRequest cast(final Collection<Address> dests, Message msg, RequestOptions options, boolean block_for_results) { List<Address> real_dests; // we need to clone because we don't want to modify the original // (we remove ourselves if LOCAL is false, see below) ! // real_dests=dests != null ? (Vector) dests.clone() : (members != null ? new Vector(members) : null); if(dests != null) { real_dests=new ArrayList<Address>(dests); real_dests.retainAll(this.members); } else { synchronized(members) { real_dests=new ArrayList(members); } } // if local delivery is off, then we should not wait for the message from the local member. // therefore remove it from the membership Channel tmp=channel; if(tmp == null) { if(adapter != null && adapter.getTransport() instanceof Channel) { tmp=(Channel) adapter.getTransport(); } } if(tmp != null && tmp.getOpt(Channel.LOCAL).equals(Boolean.FALSE)) { if(local_addr == null) { local_addr=tmp.getAddress(); } if(local_addr != null) { real_dests.remove(local_addr); } } // don't even send the message if the destination list is empty if(log.isTraceEnabled()) log.trace("real_dests=" + real_dests); if(real_dests.isEmpty()) { if(log.isTraceEnabled()) log.trace("destination list is empty, won't send message"); return null; } GroupRequest req=new GroupRequest(msg, corr, real_dests, options); req.setResponseFilter(options.getRspFilter()); req.setBlockForResults(block_for_results); // we override anycasting and always send a multicast if the transport supports IP multicasting // boolean use_anycasting=options.getAnycasting() && !hardware_multicast_supported; // req.setAnycasting(use_anycasting); req.setAnycasting(options.getAnycasting()); try { req.execute(); return req; } catch(Exception ex) { throw new RuntimeException("failed executing request " + req, ex); } } public void done(long req_id) { corr.done(req_id); } /** * Sends a message to a single member (destination = msg.dest) and returns the response. The message's destination * must be non-zero ! * @deprecated Use {@link #sendMessage(org.jgroups.Message, RequestOptions)} instead */ @Deprecated public Object sendMessage(Message msg, int mode, long timeout) throws TimeoutException, SuspectedException { return sendMessage(msg, new RequestOptions(mode, timeout, false, null)); } public Object sendMessage(Message msg, RequestOptions opts) throws TimeoutException, SuspectedException { Address dest=msg.getDest(); if(dest == null) { if(log.isErrorEnabled()) log.error("the message's destination is null, cannot send message"); return null; } UnicastRequest req=new UnicastRequest(msg, corr, dest, opts); try { req.execute(); } catch(Exception t) { throw new RuntimeException("failed executing request " + req, t); } if(opts.getMode() == Request.GET_NONE) return null; Rsp rsp=req.getResult(); if(rsp.wasSuspected()) throw new SuspectedException(dest); if(!rsp.wasReceived()) throw new TimeoutException("timeout sending message to " + dest); return rsp.getValue(); } @Deprecated public <T> NotifyingFuture<T> sendMessageWithFuture(Message msg, int mode, long timeout) throws TimeoutException, SuspectedException { return sendMessageWithFuture(msg, new RequestOptions(mode, timeout, false, null)); } public <T> NotifyingFuture<T> sendMessageWithFuture(Message msg, RequestOptions options) throws TimeoutException, SuspectedException { Address dest=msg.getDest(); if(dest == null) { if(log.isErrorEnabled()) log.error("the message's destination is null, cannot send message"); return null; } UnicastRequest req=new UnicastRequest(msg, corr, dest, options); req.setBlockForResults(false); try { req.execute(); if(options.getMode() == Request.GET_NONE) return new NullFuture(null); return req; } catch(Exception t) { throw new RuntimeException("failed executing request " + req, t); } } public Object handle(Message msg) { if(req_handler != null) { return req_handler.handle(msg); } else { return null; } } class ProtocolAdapter extends Protocol implements UpHandler { public String getName() { return "MessageDispatcher"; } private Object handleUpEvent(Event evt) { switch(evt.getType()) { case Event.MSG: if(msg_listener != null) { msg_listener.receive((Message) evt.getArg()); } break; case Event.GET_APPLSTATE: // reply with GET_APPLSTATE_OK StateTransferInfo info=(StateTransferInfo)evt.getArg(); String state_id=info.state_id; byte[] tmp_state=null; if(msg_listener != null) { try { if(msg_listener instanceof ExtendedMessageListener && state_id!=null) { tmp_state=((ExtendedMessageListener)msg_listener).getState(state_id); } else { tmp_state=msg_listener.getState(); } } catch(Throwable t) { this.log.error("failed getting state from message listener (" + msg_listener + ')', t); } } return new StateTransferInfo(null, state_id, 0L, tmp_state); case Event.GET_STATE_OK: if(msg_listener != null) { try { info=(StateTransferInfo)evt.getArg(); String id=info.state_id; if(msg_listener instanceof ExtendedMessageListener && id!=null) { ((ExtendedMessageListener)msg_listener).setState(id, info.state); } else { msg_listener.setState(info.state); } } catch(ClassCastException cast_ex) { if(this.log.isErrorEnabled()) this.log.error("received SetStateEvent, but argument " + evt.getArg() + " is not serializable. Discarding message."); } } break; case Event.STATE_TRANSFER_OUTPUTSTREAM: StateTransferInfo sti=(StateTransferInfo)evt.getArg(); OutputStream os=sti.outputStream; if(msg_listener instanceof ExtendedMessageListener) { if(os != null && msg_listener instanceof ExtendedMessageListener) { if(sti.state_id == null) ((ExtendedMessageListener)msg_listener).getState(os); else ((ExtendedMessageListener)msg_listener).getState(sti.state_id, os); } return new StateTransferInfo(null, os, sti.state_id); } else if(msg_listener instanceof MessageListener){ if(log.isWarnEnabled()){ log.warn("Channel has STREAMING_STATE_TRANSFER, however," + " application does not implement ExtendedMessageListener. State is not transfered"); Util.close(os); } } break; case Event.STATE_TRANSFER_INPUTSTREAM: sti=(StateTransferInfo)evt.getArg(); InputStream is=sti.inputStream; if(msg_listener instanceof ExtendedMessageListener) { if(is!=null && msg_listener instanceof ExtendedMessageListener) { if(sti.state_id == null) ((ExtendedMessageListener)msg_listener).setState(is); else ((ExtendedMessageListener)msg_listener).setState(sti.state_id, is); } } else if(msg_listener instanceof MessageListener){ if(log.isWarnEnabled()){ log.warn("Channel has STREAMING_STATE_TRANSFER, however," + " application does not implement ExtendedMessageListener. State is not transfered"); Util.close(is); } } break; case Event.VIEW_CHANGE: View v=(View) evt.getArg(); Vector new_mbrs=v.getMembers(); setMembers(new_mbrs); if(membership_listener != null) { membership_listener.viewAccepted(v); } break; case Event.SET_LOCAL_ADDRESS: if(log.isTraceEnabled()) log.trace("setting local_addr (" + local_addr + ") to " + evt.getArg()); local_addr=(Address)evt.getArg(); break; case Event.SUSPECT: if(membership_listener != null) { membership_listener.suspect((Address) evt.getArg()); } break; case Event.BLOCK: if(membership_listener != null) { membership_listener.block(); } channel.blockOk(); break; case Event.UNBLOCK: if(membership_listener instanceof ExtendedMembershipListener) { ((ExtendedMembershipListener)membership_listener).unblock(); } break; } return null; } /** * Called by channel (we registered before) when event is received. This is the UpHandler interface. */ public Object up(Event evt) { if(corr != null) { if(!corr.receive(evt)) { return handleUpEvent(evt); } } else { if(log.isErrorEnabled()) { //Something is seriously wrong, correlator should not be null since latch is not locked! log.error("correlator is null, event will be ignored (evt=" + evt + ")"); } } return null; } public Object down(Event evt) { if(channel != null) { // if(!channel.isOpen() || !channel.isConnected()) // throw new RuntimeException("channel is closed or not connected"); return channel.downcall(evt); } else if(this.log.isWarnEnabled()) { this.log.warn("channel is null, discarding event " + evt); } return null; } } @Deprecated class TransportAdapter implements Transport { public void send(Message msg) throws Exception { if(channel != null) { channel.send(msg); } else if(adapter != null) { try { if(id != null) { adapter.send(id, msg); } else { adapter.send(msg); } } catch(Throwable ex) { if(log.isErrorEnabled()) { log.error("exception=" + Util.print(ex)); } } } else { if(log.isErrorEnabled()) { log.error("channel == null"); } } } public Object receive(long timeout) throws Exception { return null; // not supported and not needed } } @Deprecated class PullPushHandler implements ExtendedMessageListener, MembershipListener { public void receive(Message msg) { boolean consumed=false; if(corr != null) { consumed=corr.receiveMessage(msg); } if(!consumed) { // pass on to MessageListener if(msg_listener != null) { msg_listener.receive(msg); } } } public byte[] getState() { return msg_listener != null ? msg_listener.getState() : null; } public byte[] getState(String state_id) { if(msg_listener == null) return null; if(msg_listener instanceof ExtendedMessageListener && state_id!=null) { return ((ExtendedMessageListener)msg_listener).getState(state_id); } else { return msg_listener.getState(); } } public void setState(byte[] state) { if(msg_listener != null) { msg_listener.setState(state); } } public void setState(String state_id, byte[] state) { if(msg_listener != null) { if(msg_listener instanceof ExtendedMessageListener && state_id!=null) { ((ExtendedMessageListener)msg_listener).setState(state_id, state); } else { msg_listener.setState(state); } } } public void getState(OutputStream ostream) { if (msg_listener instanceof ExtendedMessageListener) { ((ExtendedMessageListener) msg_listener).getState(ostream); } } public void getState(String state_id, OutputStream ostream) { if (msg_listener instanceof ExtendedMessageListener && state_id!=null) { ((ExtendedMessageListener) msg_listener).getState(state_id,ostream); } } public void setState(InputStream istream) { if (msg_listener instanceof ExtendedMessageListener) { ((ExtendedMessageListener) msg_listener).setState(istream); } } public void setState(String state_id, InputStream istream) { if (msg_listener instanceof ExtendedMessageListener && state_id != null) { ((ExtendedMessageListener) msg_listener).setState(state_id,istream); } } public void viewAccepted(View v) { if(corr != null) { corr.receiveView(v); } Vector new_mbrs=v.getMembers(); setMembers(new_mbrs); if(membership_listener != null) { membership_listener.viewAccepted(v); } } public void suspect(Address suspected_mbr) { if(corr != null) { corr.receiveSuspect(suspected_mbr); } if(membership_listener != null) { membership_listener.suspect(suspected_mbr); } } public void block() { if(membership_listener != null) { membership_listener.block(); } } // @todo: receive SET_LOCAL_ADDR event and call corr.setLocalAddress(addr) } }
package org.jitsi.service.neomedia; /** * The <tt>MediaType</tt> enumeration contains a list of media types * currently known to and handled by the <tt>MediaService</tt>. * * @author Emil Ivov */ public enum MediaType { /** * Represents an AUDIO media type. */ AUDIO("audio"), /** * Represents a (chat-) MESSAGE media type. */ MESSAGE("message"), /** * Represents a VIDEO media type. */ VIDEO("video"); /** * The name of this <tt>MediaType</tt>. */ private final String mediaTypeName; /** * Creates a <tt>MediaType</tt> instance with the specified name. * * @param mediaTypeName the name of the <tt>MediaType</tt> we'd like to * create. */ private MediaType(String mediaTypeName) { this.mediaTypeName = mediaTypeName; } /** * Returns the name of this MediaType (e.g. "audio", "message" or "video"). * The name returned by this method is meant for use by session description * mechanisms such as SIP/SDP or XMPP/Jingle. * * @return the name of this MediaType (e.g. "audio" or "video"). */ @Override public String toString() { return mediaTypeName; } public static MediaType parseString(String mediaTypeName) throws IllegalArgumentException { if(AUDIO.toString().equals(mediaTypeName)) return AUDIO; if(MESSAGE.toString().equals(mediaTypeName)) return MESSAGE; if(VIDEO.toString().equals(mediaTypeName)) return VIDEO; throw new IllegalArgumentException( mediaTypeName + " is not a currently supported MediaType"); } }
package org.jmist.framework.services; import java.io.IOException; import java.util.zip.ZipOutputStream; import org.jmist.framework.AbstractParallelizableJob; import org.jmist.framework.TaskWorker; import org.jmist.framework.reporting.ProgressMonitor; /** * A <code>ParallelizableJob</code> whose <code>TaskWorker</code>s idle for a * specified amount of time. * @author bkimmel */ public final class IdleJob extends AbstractParallelizableJob { /** * Creates a new <code>IdleJob</code>. */ public IdleJob() { /* nothing to do. */ } public IdleJob(int idleSeconds) throws IllegalArgumentException { if (idleSeconds < 0) { throw new IllegalArgumentException("idleSeconds must be non-negative."); } this.idleSeconds = idleSeconds; } public void setIdleTime(int idleSeconds) throws IllegalArgumentException { if (idleSeconds < 0) { throw new IllegalArgumentException("idleSeconds must be non-negative."); } this.idleSeconds = idleSeconds; } /* (non-Javadoc) * @see org.jmist.framework.ParallelizableJob#getNextTask() */ @Override public Object getNextTask() { return this.idleSeconds; } /* (non-Javadoc) * @see org.jmist.framework.ParallelizableJob#isComplete() */ @Override public boolean isComplete() { return false; } /* (non-Javadoc) * @see org.jmist.framework.ParallelizableJob#submitTaskResults(java.lang.Object, java.lang.Object, org.jmist.framework.reporting.ProgressMonitor) */ @Override public void submitTaskResults(Object task, Object results, ProgressMonitor monitor) { monitor.notifyIndeterminantProgress(); } /* (non-Javadoc) * @see org.jmist.framework.ParallelizableJob#worker() */ @Override public TaskWorker worker() { return worker; } /* (non-Javadoc) * @see org.jmist.framework.ParallelizableJob#writeJobResults(java.util.zip.ZipOutputStream) */ @Override public void writeJobResults(ZipOutputStream stream) throws IOException { assert(false); } /** * A <code>TaskWorker</code> that sleeps for the specified amount of time * (in seconds), waking up each second to notify the * <code>ProgressMonitor</code>. * @author bkimmel */ private static class IdleTaskWorker implements TaskWorker { /* (non-Javadoc) * @see org.jmist.framework.TaskWorker#performTask(java.lang.Object, org.jmist.framework.reporting.ProgressMonitor) */ @Override public Object performTask(Object task, ProgressMonitor monitor) { int seconds = (Integer) task; monitor.notifyStatusChanged("Idling..."); for (int i = 0; i < seconds; i++) { if (!monitor.notifyProgress(i, seconds)) { monitor.notifyCancelled(); return null; } this.sleep(); } monitor.notifyProgress(seconds, seconds); monitor.notifyComplete(); return null; } /** * Sleeps for one second. */ private void sleep() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Serialization version ID. */ private static final long serialVersionUID = 4249862961124801480L; } /** The amount of time (in seconds) that workers should idle. */ private int idleSeconds = DEFAULT_IDLE_SECONDS; /** The <code>TaskWorker</code> that idles for the given amount of time. */ private static final TaskWorker worker = new IdleTaskWorker(); /** The default amount of time (in seconds) that workers should idle. */ private static final int DEFAULT_IDLE_SECONDS = 60; }
package org.openid4java.server; import org.openid4java.message.*; import org.openid4java.association.AssociationSessionType; import org.openid4java.association.AssociationException; import org.openid4java.association.DiffieHellmanSession; import org.openid4java.association.Association; import org.openid4java.OpenIDException; import java.net.URL; import java.net.MalformedURLException; import org.apache.log4j.Logger; /** * Manages OpenID communications with an OpenID Relying Party (Consumer). * * @author Marius Scurtescu, Johnny Bufu */ public class ServerManager { private static Logger _log = Logger.getLogger(ServerManager.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Keeps track of the associations established with consumer sites. */ private ServerAssociationStore _sharedAssociations = new InMemoryServerAssociationStore(); /** * Keeps track of private (internal) associations created for signing * authentication responses for stateless consumer sites. */ private ServerAssociationStore _privateAssociations = new InMemoryServerAssociationStore(); /** * Nonce generator implementation. */ private NonceGenerator _nonceGenerator = new IncrementalNonceGenerator(); /** * The lowest encryption level session accepted for association sessions */ private AssociationSessionType _minAssocSessEnc = AssociationSessionType.NO_ENCRYPTION_SHA1MAC; /** * The preferred association session type; will be attempted first. */ private AssociationSessionType _prefAssocSessEnc = AssociationSessionType.DH_SHA256; /** * Expiration time (in seconds) for associations. */ private int _expireIn = 1800; /** * In OpenID 1.x compatibility mode, the URL at the OpenID Provider where * the user should be directed when a immediate authentication request * fails. * <p> * MUST be configured in order for the OpenID provider to be able to * respond correctly with AuthImmediateFailure messages in compatibility * mode. */ private String _userSetupUrl = null; /** * List of coma-separated fields to be signed in authentication responses. */ private String _signFields; /** * Array of extension namespace URIs that the consumer manager will sign, * if present in auth responses. */ private String[] _signExtensions; /** * Used to perform verify realms against return_to URLs. */ private RealmVerifier _realmVerifier; /** * The OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. * <p> * This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ private String _opEndpointUrl; /** * Gets the store implementation used for keeping track of the generated * associations established with consumer sites. * * @see ServerAssociationStore */ public ServerAssociationStore getSharedAssociations() { return _sharedAssociations; } /** * Sets the store implementation that will be used for keeping track of * the generated associations established with consumer sites. * * @param sharedAssociations ServerAssociationStore implementation * @see ServerAssociationStore */ public void setSharedAssociations(ServerAssociationStore sharedAssociations) { _sharedAssociations = sharedAssociations; } /** * Gets the store implementation used for keeping track of the generated * private associations (used for signing responses to stateless consumer * sites). * * @see ServerAssociationStore */ public ServerAssociationStore getPrivateAssociations() { return _privateAssociations; } /** * Sets the store implementation that will be used for keeping track of * the generated private associations (used for signing responses to * stateless consumer sites). * * @param privateAssociations ServerAssociationStore implementation * @see ServerAssociationStore */ public void setPrivateAssociations(ServerAssociationStore privateAssociations) { _privateAssociations = privateAssociations; } /** * Gets the minimum level of encryption configured for association sessions. * <p> * Default: no-encryption session, SHA1 MAC association */ public AssociationSessionType getMinAssocSessEnc() { return _minAssocSessEnc; } /** * Gets the NonceGenerator used for generating nonce tokens to uniquely * identify authentication responses. * * @see NonceGenerator */ public NonceGenerator getNonceGenerator() { return _nonceGenerator; } /** * Sets the NonceGenerator implementation that will be used to generate * nonce tokens to uniquely identify authentication responses. * * @see NonceGenerator */ public void setNonceGenerator(NonceGenerator nonceGenerator) { _nonceGenerator = nonceGenerator; } /** * Configures the minimum level of encryption accepted for association * sessions. * <p> * Default: no-encryption session, SHA1 MAC association */ public void setMinAssocSessEnc(AssociationSessionType minAssocSessEnc) { this._minAssocSessEnc = minAssocSessEnc; } /** * Gets the preferred association / session type. */ public AssociationSessionType getPrefAssocSessEnc() { return _prefAssocSessEnc; } /** * Sets the preferred association / session type. * * @see AssociationSessionType */ public void setPrefAssocSessEnc(AssociationSessionType type) throws ServerException { if (! Association.isHmacSupported(type.getAssociationType()) || ! DiffieHellmanSession.isDhSupported(type) ) throw new ServerException("Unsupported association / session type: " + type.getSessionType() + " : " + type.getAssociationType()); if (_minAssocSessEnc.isBetter(type) ) throw new ServerException( "Minimum encryption settings cannot be better than the preferred"); this._prefAssocSessEnc = type; } /** * Gets the expiration time (in seconds) for the generated associations */ public int getExpireIn() { return _expireIn; } /** * Sets the expiration time (in seconds) for the generated associations */ public void setExpireIn(int _expireIn) { this._expireIn = _expireIn; } /** * Gets the URL at the OpenID Provider where the user should be directed * when a immediate authentication request fails. */ public String getUserSetupUrl() { return _userSetupUrl; } /** * Sets the URL at the OpenID Provider where the user should be directed * when a immediate authentication request fails. */ public void setUserSetupUrl(String userSetupUrl) { this._userSetupUrl = userSetupUrl; } /** * Sets the list of parameters that the OpenID Provider will sign when * generating authentication responses. * <p> * The fields in the list must be coma-separated and must not include the * 'openid.' prefix. Fields that are required to be signed are automatically * added by the underlying logic, so that a valid message is generated, * regardles if they are included in the user-supplied list or not. */ public void setSignFields(String signFields) { this._signFields = signFields; } /** * Gets the list of parameters that the OpenID Provider will sign when * generating authentication responses. * <p> * Coma-separated list. */ public String getSignFields() { return _signFields; } public void setSignExtensions(String[] extensins) { _signExtensions = extensins; } public String[] getSignExtensions() { return _signExtensions; } /** * Gets the RealmVerifier used to verify realms against return_to URLs. */ public RealmVerifier getRealmVerifier() { return _realmVerifier; } /** * Sets the RealmVerifier used to verify realms against return_to URLs. */ public void setRealmVerifier(RealmVerifier realmVerifier) { this._realmVerifier = realmVerifier; } /** * Gets OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. * <p> * This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ public String getOPEndpointUrl() { return _opEndpointUrl; } /** * Sets the OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. * <p> * This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ public void setOPEndpointUrl(String opEndpointUrl) { this._opEndpointUrl = opEndpointUrl; } /** * Constructs a ServerManager with default settings. */ public ServerManager() { // initialize a default realm verifier _realmVerifier = new RealmVerifier(); } /** * Processes a Association Request and returns a Association Response * message, according to the request parameters and the preferences * configured for the OpenID Provider * * @return AssociationResponse upon successfull association, * or AssociationError if no association * was established * */ public Message associationResponse(ParameterList requestParams) { boolean isVersion2 = requestParams.hasParameter("openid.ns"); _log.info("Processing association request..."); try { // build request message from response params (+ integrity check) AssociationRequest assocReq = AssociationRequest.createAssociationRequest(requestParams); isVersion2 = assocReq.isVersion2(); AssociationSessionType type = assocReq.getType(); // is supported / allowed ? if (! Association.isHmacSupported(type.getAssociationType()) || ! DiffieHellmanSession.isDhSupported(type) || _minAssocSessEnc.isBetter(type)) { throw new AssociationException("Unable create association for: " + type.getSessionType() + " / " + type.getAssociationType() ); } else // all ok, go ahead { Association assoc = _sharedAssociations.generate( type.getAssociationType(), _expireIn); _log.info("Returning shared association; handle: " + assoc.getHandle()); return AssociationResponse.createAssociationResponse(assocReq, assoc); } } catch (OpenIDException e) { // association failed, respond accordingly if (isVersion2) { _log.warn("Cannot establish association, " + "responding with an OpenID2 association error.", e); return AssociationError.createAssociationError( e.getMessage(), _prefAssocSessEnc); } else { _log.warn("Error processing an OpenID1 association request; " + "responding with a dummy association", e); try { // generate dummy association & no-encryption response // for compatibility mode Association dummyAssoc = _sharedAssociations.generate( Association.TYPE_HMAC_SHA1, 0); AssociationRequest dummyRequest = AssociationRequest.createAssociationRequest( AssociationSessionType.NO_ENCRYPTION_COMPAT_SHA1MAC); return AssociationResponse.createAssociationResponse( dummyRequest, dummyAssoc); } catch (OpenIDException ee) { _log.error("Error creating negative OpenID1 association response.", e); return null; } } } } /** * Processes a Authentication Request received from a consumer site. * <p> * Uses ServerManager's global OpenID Provider endpoint URL. * * @return An signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, true); } /** * Processes a Authentication Request received from a consumer site. * <p> * Uses ServerManager's global OpenID Provider endpoint URL. * * @return A positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, boolean signNow) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, signNow); } /** * Processes a Authentication Request received from a consumer site. * <p> * * @return An signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, opEndpoint, true); } /** * Processes a Authentication Request received from a consumer site. * * @param opEndpoint The endpoint URL where the OP accepts OpenID * authentication requests. * @param requestParams The parameters contained * in the authentication request message received * from a consumer site. * @param userSelId OP-specific Identifier selected by the user at * the OpenID Provider; if present it will override * the one received in the authentication request. * @param userSelClaimed Claimed Identifier selected by the user at * the OpenID Provider; if present it will override * the one received in the authentication request. * @param authenticatedAndApproved Flag indicating that the IdP has * authenticated the user and the user * has approved the authentication * transaction * @param signNow If true, the returned AuthSuccess will be signed. * If false, the signature will not be computed and * set - this will have to be performed later, * using #sign(org.openid4java.message.Message). * * @return <ul><li> AuthSuccess, if authenticatedAndApproved * <li> AuthFailure (negative response) if either * of authenticatedAndApproved is false; * <li> A IndirectError or DirectError message * if the authentication could not be performed, or * <li> Null if there was no return_to parameter * specified in the AuthRequest.</ul> */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint, boolean signNow) { _log.info("Processing authentication request..."); boolean isVersion2 = true; try { new URL(opEndpoint); } catch (MalformedURLException e) { _log.error("Invalid OP-endpoint configured; " + "cannot issue OpenID authentication responses." + opEndpoint); return DirectError.createDirectError( "Invalid OpenID Provider endpoint URL; " + "cannot issue authentication response", isVersion2); } try { // build request message from response params (+ integrity check) AuthRequest authReq = AuthRequest.createAuthRequest( requestParams, _realmVerifier); isVersion2 = authReq.isVersion2(); if (authReq.getReturnTo() == null) { _log.error("Received valid auth request, but no return_to " + "specified; authResponse() should not be called."); return null; } String id; String claimed; if (AuthRequest.SELECT_ID.equals(authReq.getIdentity())) { id = userSelId; claimed = userSelClaimed; } else { id = userSelId != null ? userSelId : authReq.getIdentity(); claimed = userSelClaimed != null ? userSelClaimed : authReq.getClaimed(); } if (id == null) throw new ServerException( "No identifier provided by the authntication request" + "or by the OpenID Provider"); if (DEBUG) _log.debug("Using ClaimedID: " + claimed + " OP-specific ID: " + id); if (authenticatedAndApproved) // positive response { Association assoc = null; String handle = authReq.getHandle(); String invalidateHandle = null; if (handle != null) { assoc = _sharedAssociations.load(handle); if (assoc == null) { _log.info("Invalidating handle: " + handle); invalidateHandle = handle; } else _log.info("Loaded shared association; hadle: " + handle); } if (assoc == null) { assoc = _privateAssociations.generate( _prefAssocSessEnc.getAssociationType(), _expireIn); _log.info("Generated private association; handle: " + assoc.getHandle()); } AuthSuccess response = AuthSuccess.createAuthSuccess( opEndpoint, claimed, id, !isVersion2, authReq.getReturnTo(), isVersion2 ? _nonceGenerator.next() : null, invalidateHandle, assoc, false); if (_signFields != null) response.setSignFields(_signFields); if (_signExtensions != null) response.setSignExtensions(_signExtensions); if (signNow) response.setSignature(assoc.sign(response.getSignedText())); _log.info("Returning positive assertion for " + response.getReturnTo()); return response; } else // negative response { if (authReq.isImmediate()) { _log.error("Responding with immediate authentication " + "failure to " + authReq.getReturnTo()); return AuthImmediateFailure.createAuthImmediateFailure( _userSetupUrl, authReq.getReturnTo(), ! isVersion2); } else { _log.error("Responding with authentication failure to " + authReq.getReturnTo()); return new AuthFailure(! isVersion2, authReq.getReturnTo()); } } } catch (OpenIDException e) { if (requestParams.hasParameter("openid.return_to")) { _log.error("Error processing an authentication request; " + "responding with an indirect error message.", e); return IndirectError.createIndirectError(e.getMessage(), requestParams.getParameterValue("openid.return_to"), ! isVersion2 ); } else { _log.error("Error processing an authentication request; " + "responding with an direct error message.", e); return DirectError.createDirectError( e.getMessage(), isVersion2 ); } } } /** * Signs an AuthSuccess message, using the association identified by the * handle specified within the message. */ public void sign(Message msg) throws ServerException, AssociationException { if (! (msg instanceof AuthSuccess) ) throw new ServerException( "Cannot sign message of type: " + msg.getClass()); AuthSuccess authResp = (AuthSuccess) msg; String handle = authResp.getHandle(); // try shared associations first, then private Association assoc = _sharedAssociations.load(handle); if (assoc == null) assoc = _privateAssociations.load(handle); if (assoc == null) throw new ServerException( "No association found for handle: " + handle); authResp.setSignature(assoc.sign(authResp.getSignedText())); } /** * Responds to a verification request from the consumer. * * @param requestParams ParameterList containing the parameters received * in a verification request from a consumer site. * @return VerificationResponse to be sent back to the * consumer site. */ public Message verify(ParameterList requestParams) { _log.info("Processing verification request..."); boolean isVersion2 = true; try { // build request message from response params (+ ntegrity check) VerifyRequest vrfyReq = VerifyRequest.createVerifyRequest(requestParams); isVersion2 = vrfyReq.isVersion2(); String handle = vrfyReq.getHandle(); boolean verified = false; Association assoc = _privateAssociations.load(handle); if (assoc != null) // verify the signature { _log.info("Loaded private association; handle: " + handle); verified = assoc.verifySignature( vrfyReq.getSignedText(), vrfyReq.getSignature()); // remove the association so that the request // cannot be verified more than once _privateAssociations.remove(handle); } VerifyResponse vrfyResp = VerifyResponse.createVerifyResponse(! vrfyReq.isVersion2()); vrfyResp.setSignatureVerified(verified); if (verified) { String invalidateHandle = vrfyReq.getInvalidateHandle(); if (invalidateHandle != null && _sharedAssociations.load(invalidateHandle) == null) { _log.info("Confirming shared association invalidate handle: " + invalidateHandle); vrfyResp.setInvalidateHandle(invalidateHandle); } } else _log.error("Signature verification failed, handle: " + handle); _log.info("Responding with " + (verified? "positive" : "negative") + " verification response"); return vrfyResp; } catch (OpenIDException e) { _log.error("Error processing verification request; " + "responding with verificatioin error.", e); return DirectError.createDirectError(e.getMessage(), ! isVersion2); } } }
package org.spine3.examples.todolist.c.aggregates.definition; import com.google.protobuf.Message; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.spine3.base.CommandContext; import org.spine3.examples.todolist.TaskId; import org.spine3.examples.todolist.c.aggregates.TaskDefinitionPart; import org.spine3.examples.todolist.c.commands.CreateBasicTask; import org.spine3.examples.todolist.c.events.TaskCreated; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.DESCRIPTION; import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.createTaskInstance; /** * @author Illia Shepilov */ @DisplayName("CreateBasicTask command") public class CreateBasicTaskTest extends TaskDefinitionCommandTest<CreateBasicTask> { private final CommandContext commandContext = createCommandContext(); private TaskDefinitionPart aggregate; private TaskId taskId; @Override @BeforeEach public void setUp() { taskId = createTaskId(); aggregate = createTaskDefinitionPart(taskId); } @Test @DisplayName("produces TaskCreated event") public void producesEvent() { final CreateBasicTask createTaskCmd = createTaskInstance(taskId, DESCRIPTION); final List<? extends Message> messageList = aggregate.dispatchForTest(createTaskCmd, commandContext); assertNotNull(aggregate.getState() .getCreated()); assertNotNull(aggregate.getId()); final int expectedListSize = 1; assertEquals(expectedListSize, messageList.size()); assertEquals(TaskCreated.class, messageList.get(0) .getClass()); final TaskCreated taskCreated = (TaskCreated) messageList.get(0); assertEquals(taskId, taskCreated.getId()); assertEquals(DESCRIPTION, taskCreated.getDetails() .getDescription()); } }
import org.junit.Test; import org.junit.Ignore; import java.util.Arrays; import java.util.List; import java.util.Collections; import static org.junit.Assert.assertEquals; public class AllergiesTest { @Test public void noAllergiesMeansNotAllergicToAnything() { Allergies allergies = new Allergies(0); assertEquals(false, allergies.isAllergicTo(Allergen.EGGS)); assertEquals(false, allergies.isAllergicTo(Allergen.PEANUTS)); assertEquals(false, allergies.isAllergicTo(Allergen.STRAWBERRIES)); assertEquals(false, allergies.isAllergicTo(Allergen.CATS)); } @Ignore("Remove to run test") @Test public void allergicToEggs() { Allergies allergies = new Allergies(1); assertEquals(true, allergies.isAllergicTo(Allergen.EGGS)); } @Ignore("Remove to run test") @Test public void allergicToPeanuts() { Allergies allergies = new Allergies(2); assertEquals(true, allergies.isAllergicTo(Allergen.PEANUTS)); } @Ignore("Remove to run test") @Test public void allergicToShellfish() { Allergies allergies = new Allergies(4); assertEquals(true, allergies.isAllergicTo(Allergen.SHELLFISH)); } @Ignore("Remove to run test") @Test public void allergicToStrawberries() { Allergies allergies = new Allergies(8); assertEquals(true, allergies.isAllergicTo(Allergen.STRAWBERRIES)); } @Ignore("Remove to run test") @Test public void allergicToTomatoes() { Allergies allergies = new Allergies(16); assertEquals(true, allergies.isAllergicTo(Allergen.TOMATOES)); } @Ignore("Remove to run test") @Test public void allergicToChocolate() { Allergies allergies = new Allergies(32); assertEquals(true, allergies.isAllergicTo(Allergen.CHOCOLATE)); } @Ignore("Remove to run test") @Test public void allergicToPollen() { Allergies allergies = new Allergies(64); assertEquals(true, allergies.isAllergicTo(Allergen.POLLEN)); } @Ignore("Remove to run test") @Test public void allergicToCats() { Allergies allergies = new Allergies(128); assertEquals(true, allergies.isAllergicTo(Allergen.CATS)); } @Ignore("Remove to run test") @Test public void isAllergicToEggsInAdditionToOtherStuff() { Allergies allergies = new Allergies(5); assertEquals(true, allergies.isAllergicTo(Allergen.EGGS)); assertEquals(true, allergies.isAllergicTo(Allergen.SHELLFISH)); assertEquals(false, allergies.isAllergicTo(Allergen.STRAWBERRIES)); } @Ignore("Remove to run test") @Test public void noAllergies() { Allergies allergies = new Allergies(0); assertEquals(0, allergies.getList().size()); } @Ignore("Remove to run test") @Test public void isAllergicToJustEggs() { Allergies allergies = new Allergies(1); List<Allergen> expectedAllergens = Collections.singletonList(Allergen.EGGS); assertEquals(expectedAllergens, allergies.getList()); } @Ignore("Remove to run test") @Test public void isAllergicToJustPeanuts() { Allergies allergies = new Allergies(2); List<Allergen> expectedAllergens = Collections.singletonList(Allergen.PEANUTS); assertEquals(expectedAllergens, allergies.getList()); } @Ignore("Remove to run test") @Test public void isAllergicToJustStrawberries() { Allergies allergies = new Allergies(8); List<Allergen> expectedAllergens = Collections.singletonList(Allergen.STRAWBERRIES); assertEquals(expectedAllergens, allergies.getList()); } @Ignore("Remove to run test") @Test public void isAllergicToEggsAndPeanuts() { Allergies allergies = new Allergies(3); List<Allergen> expectedAllergens = Arrays.asList( Allergen.EGGS, Allergen.PEANUTS ); assertEquals(expectedAllergens, allergies.getList()); } @Ignore("Remove to run test") @Test public void isAllergicToEggsAndShellfish() { Allergies allergies = new Allergies(5); List<Allergen> expectedAllergens = Arrays.asList( Allergen.EGGS, Allergen.SHELLFISH ); assertEquals(expectedAllergens, allergies.getList()); } @Ignore("Remove to run test") @Test public void isAllergicToLotsOfStuff() { Allergies allergies = new Allergies(248); List<Allergen> expectedAllergens = Arrays.asList( Allergen.STRAWBERRIES, Allergen.TOMATOES, Allergen.CHOCOLATE, Allergen.POLLEN, Allergen.CATS ); assertEquals(expectedAllergens, allergies.getList()); } @Ignore("Remove to run test") @Test public void isAllergicToEverything() { Allergies allergies = new Allergies(255); List<Allergen> expectedAllergens = Arrays.asList( Allergen.EGGS, Allergen.PEANUTS, Allergen.SHELLFISH, Allergen.STRAWBERRIES, Allergen.TOMATOES, Allergen.CHOCOLATE, Allergen.POLLEN, Allergen.CATS ); assertEquals(expectedAllergens, allergies.getList()); } @Ignore("Remove to run test") @Test public void ignoreNonAllergenScoreParts() { Allergies allergies = new Allergies(509); List<Allergen> expectedAllergens = Arrays.asList( Allergen.EGGS, Allergen.SHELLFISH, Allergen.STRAWBERRIES, Allergen.TOMATOES, Allergen.CHOCOLATE, Allergen.POLLEN, Allergen.CATS ); assertEquals(expectedAllergens, allergies.getList()); } }
package org.phenoscape.io; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Comparator; import java.util.List; import org.phenoscape.model.Character; import org.phenoscape.model.DataSet; import org.phenoscape.model.Phenotype; import org.phenoscape.model.Specimen; import org.phenoscape.model.State; import org.phenoscape.model.Taxon; import com.eekboom.utils.Strings; import phenote.datamodel.OboUtil; import ca.odell.glazedlists.SortedList; public class TabDelimitedWriter { private static final String TTO = "http://bioportal.bioontology.org/virtual/1081/"; private static final String TAO = "http://bioportal.bioontology.org/virtual/1110/"; private static final String PATO = "http://bioportal.bioontology.org/virtual/1107/"; private static final String LINK_FORMAT = "=HYPERLINK(\"%s\", \"%s\")"; private DataSet data; public void setDataSet(DataSet data) { this.data = data; } public void write(File aFile) throws IOException { final BufferedWriter writer = new BufferedWriter(new FileWriter(aFile)); writer.write(this.getTaxonHeader()); writer.newLine(); for (Taxon taxon : this.data.getTaxa()) { writer.write(this.getTaxonRow(taxon)); writer.newLine(); } writer.newLine(); writer.newLine(); writer.write(this.getCharacterHeader()); writer.newLine(); int i = 1; for (Character character : this.data.getCharacters()) { writer.write(i + "\t"); i++; writer.write(this.getCharacterRow(character)); writer.newLine(); } writer.close(); } private String getTaxonHeader() { return "Publication Taxon\tTTO Taxon\tMatrix Taxon\tTaxon Comment\tSpecimens\t" + this.getColumnHeadings(); } private String getColumnHeadings() { final StringBuffer sb = new StringBuffer(); for (int i = 1; i <= data.getCharacters().size(); i++) { sb.append(i); if (i < data.getCharacters().size()) sb.append("\t"); } return sb.toString(); } private String getTaxonRow(Taxon taxon) { final StringBuffer sb = new StringBuffer(); sb.append(taxon.getPublicationName()); sb.append("\t"); if (taxon.getValidName() != null) { sb.append(String.format(LINK_FORMAT, TTO + taxon.getValidName().getID(), taxon.getValidName().getName())); } sb.append("\t"); sb.append(taxon.getMatrixTaxonName()); sb.append("\t"); sb.append(taxon.getComment()); sb.append("\t"); sb.append(this.getSpecimens(taxon)); sb.append("\t"); sb.append(this.getMatrix(taxon)); return sb.toString(); } private String getSpecimens(Taxon taxon) { final StringBuffer sb = new StringBuffer(); boolean first = true; for (Specimen specimen : taxon.getSpecimens()) { if (!first) sb.append(", "); first = false; sb.append(specimen.getCollectionCode() != null ? specimen.getCollectionCode().getName() + " " : ""); sb.append(specimen.getCatalogID()); } return sb.toString(); } private String getMatrix(Taxon taxon) { final StringBuffer sb = new StringBuffer(); boolean first = true; for (Character character : this.data.getCharacters()) { if (!first) sb.append("\t"); first = false; final State state = this.data.getStateForTaxon(taxon, character); sb.append(state != null ? state.getSymbol() : "?"); } return sb.toString(); } private String getCharacterHeader() { return "Character Number\tCharacter Description\tCharacter Comment\tState Number\tState Description\tState Comment\tEntity\tQuality\tRelated Entity\tCount\tComment"; } private String getCharacterRow(Character character) { final StringBuffer sb = new StringBuffer(); sb.append(character.getLabel()); sb.append("\t"); sb.append(character.getComment()); sb.append("\t"); sb.append(this.getStates(character)); return sb.toString(); } private String getStates(Character character) { final StringBuffer sb = new StringBuffer(); boolean first = true; final List<State> sortedStates = new SortedList<State>(character.getStates(), new Comparator<State>() { public int compare(State o1, State o2) { return Strings.compareNatural(o1.getSymbol(), o2.getSymbol()); }}); for (State state : sortedStates) { if (!first) sb.append("\n\t\t\t"); first = false; sb.append(state.getSymbol()); sb.append("\t"); sb.append(state.getLabel()); sb.append("\t"); sb.append(state.getComment()); sb.append("\t"); sb.append(this.getPhenotypes(state)); } return sb.toString(); } private String getPhenotypes(State state) { final StringBuffer sb = new StringBuffer(); boolean first = true; for (Phenotype phenotype : state.getPhenotypes()) { if (!first) sb.append("\n\t\t\t\t\t\t"); first = false; if (phenotype.getEntity() != null) { if (!OboUtil.isPostCompTerm(phenotype.getEntity())) { sb.append(String.format(LINK_FORMAT, TAO + phenotype.getEntity().getID(), phenotype.getEntity().getName())); } else { sb.append(phenotype.getEntity().getName()); } } sb.append("\t"); if (phenotype.getQuality() != null) { if (!OboUtil.isPostCompTerm(phenotype.getQuality())) { sb.append(String.format(LINK_FORMAT, PATO + phenotype.getQuality().getID(), phenotype.getQuality().getName())); } else { sb.append(phenotype.getQuality().getName()); } } sb.append("\t"); if (phenotype.getRelatedEntity() != null) { if (!OboUtil.isPostCompTerm(phenotype.getRelatedEntity())) { sb.append(String.format(LINK_FORMAT, TAO + phenotype.getRelatedEntity().getID(), phenotype.getRelatedEntity().getName())); } else { sb.append(phenotype.getRelatedEntity().getName()); } } sb.append("\t"); sb.append(phenotype.getCount() != null ? phenotype.getCount() : ""); sb.append("\t"); sb.append(phenotype.getComment() != null ? phenotype.getComment() : ""); } return sb.toString(); } }
package org.sugr.gearshift; import java.util.Comparator; import org.sugr.gearshift.G.SortBy; import org.sugr.gearshift.G.SortOrder; public class TorrentComparator implements Comparator<Torrent> { private SortBy mSortBy = SortBy.STATUS; private SortOrder mSortOrder = SortOrder.ASCENDING; private SortBy mBaseSort = SortBy.AGE; public void setSortingMethod(SortBy by, SortOrder order) { mSortBy = by; mSortOrder = order; } public SortBy getSortBy() { return mSortBy; } public SortOrder getSortOrder() { return mSortOrder; } public void setBaseComparator(SortBy by) { mBaseSort = by; } public SortBy getBaseComparator() { return mBaseSort; } @Override public int compare(Torrent a, Torrent b) { int ret = compare(a, b, mSortBy, mSortOrder); if (ret == 0 && mBaseSort != mSortBy) { ret = compare(a, b, mBaseSort, mSortOrder); } return ret; } private int compare(Torrent a, Torrent b, SortBy sort, SortOrder order) { int ret = 0; float delta; switch(sort) { case NAME: ret = a.getName() == null && b.getName() == null ? 0 : a.getName() == null ? -1 : a.getName().compareToIgnoreCase(b.getName()); break; case SIZE: ret = (int) (a.getTotalSize() - b.getTotalSize()); break; case STATUS: ret = (a.getStatus() == Torrent.Status.STOPPED ? a.getStatus() + 100 : a.getStatus() == Torrent.Status.CHECK_WAITING ? a.getStatus() + 10 : a.getStatus() == Torrent.Status.DOWNLOAD_WAITING ? a.getStatus() + 20 : a.getStatus() == Torrent.Status.SEED_WAITING ? a.getStatus() + 30 : a.getStatus()) - (b.getStatus() == Torrent.Status.STOPPED ? b.getStatus() + 100 : b.getStatus() == Torrent.Status.CHECK_WAITING ? b.getStatus() + 10 : b.getStatus() == Torrent.Status.DOWNLOAD_WAITING ? b.getStatus() + 20 : b.getStatus() == Torrent.Status.SEED_WAITING ? b.getStatus() + 30 : b.getStatus()); break; case ACTIVITY: ret = (int) ((b.getRateDownload() + b.getRateUpload()) - (a.getRateDownload() + a.getRateUpload())); break; case AGE: ret = (int) (b.getAddedDate() - a.getAddedDate()); break; case LOCATION: ret = a.getDownloadDir() == null && b.getDownloadDir() == null ? 0 : a.getDownloadDir() == null ? -1 : a.getDownloadDir().compareToIgnoreCase(b.getDownloadDir()); break; case PEERS: ret = a.getPeersConnected() - b.getPeersConnected(); break; case PROGRESS: delta = a.getPercentDone() - b.getPercentDone(); ret = delta < 0 ? -1 : delta > 0 ? 1 : 0; break; case QUEUE: ret = a.getQueuePosition() - b.getQueuePosition(); break; case RATE_DOWNLOAD: ret = (int) (a.getRateDownload() - b.getRateDownload()); break; case RATE_UPLOAD: ret = (int) (a.getRateUpload() - b.getRateUpload()); break; case RATIO: delta = b.getUploadRatio() - a.getUploadRatio(); ret = delta < 0 ? -1 : delta > 0 ? 1 : 0; break; default: break; } return order == SortOrder.ASCENDING ? ret : -ret; } }
package main; import gcm.gui.GCM2SBMLEditor; import gcm.gui.modelview.movie.MovieContainer; import gcm.network.GeneticNetwork; import gcm.parser.CompatibilityFixer; import gcm.parser.GCMFile; import gcm.parser.GCMParser; import gcm.util.GlobalConstants; import lpn.gui.*; import lpn.parser.LhpnFile; import lpn.parser.Lpn2verilog; import lpn.parser.Translator; 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.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.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; import java.util.regex.Matcher; 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.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.JViewport; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import java.io.Writer; import learn.LearnGCM; import learn.LearnLHPN; import synthesis.Synthesis; import verification.*; import org.sbml.libsbml.*; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import sbol.SbolBrowser; import datamanager.DataManager; import java.net.*; import uk.ac.ebi.biomodels.*; import util.Utility; import util.tabs.CloseAndMaxTabbedPane; /** * 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 Gui implements MouseListener, ActionListener, MouseMotionListener, MouseWheelListener { public static JFrame frame; // Frame where components of the GUI are // displayed private JMenuBar menuBar; private JMenu file, edit, view, tools, help, importMenu, exportMenu, newMenu, viewModel; // The // file // menu private JMenuItem newProj; // The new menu item private JMenuItem newSBMLModel; // The new menu item private JMenuItem newGCMModel; // 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 importSbol; 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, exportSBML, exportSBOL; 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; 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; // treeSelected // = false; public boolean atacs, lema; private String viewer; private String[] BioModelIds = null; private JMenuItem copy, rename, delete, save, saveAs, saveSBOL, check, run, refresh, viewCircuit, viewRules, viewTrace, viewLog, viewCoverage, viewLHPN, 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 Gui(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); 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 + "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); imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "run-icon.jpg"; runButton = makeToolButton(imgName, "run", "Save and Run", "Run"); toolbar.add(runButton); imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "refresh.jpg"; refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh"); toolbar.add(refreshButton); 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"); help = new JMenu("Help"); edit = new JMenu("Edit"); importMenu = new JMenu("Import"); exportMenu = new JMenu("Export"); newMenu = new JMenu("New"); view = new JMenu("View"); viewModel = new JMenu("Model"); tools = new JMenu("Tools"); menuBar.add(file); menuBar.add(edit); if (lema) { 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"); newGCMModel = new JMenuItem("Model"); newSBMLModel = new JMenuItem("SBML Model"); newSpice = new JMenuItem("Spice Circuit"); newVhdl = new JMenuItem("VHDL Model"); newS = new JMenuItem("Assembly File"); newInst = new JMenuItem("Instruction File"); newLhpn = new JMenuItem("LPN Model"); 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"); importSbol = new JMenuItem("SBOL File"); importSbml = new JMenuItem("SBML Model"); importBioModel = new JMenuItem("BioModel"); importDot = new JMenuItem("iBioSim Model"); importG = new JMenuItem("Petri Net"); importLpn = new JMenuItem("LPN Model"); importVhdl = new JMenuItem("VHDL 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"); /* exportSBML = new JMenuItem("Systems Biology Markup Language (SBML)"); exportSBOL = new JMenuItem("Synthetic Biology Open Language (SBOL)"); 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)"); */ exportSBML = new JMenuItem("SBML"); exportSBOL = new JMenuItem("SBOL"); exportCsv = new JMenuItem("CSV"); exportDat = new JMenuItem("DAT"); exportEps = new JMenuItem("EPS"); exportJpg = new JMenuItem("JPG"); exportPdf = new JMenuItem("PDF"); exportPng = new JMenuItem("PNG"); exportSvg = new JMenuItem("SVG"); exportTsd = new JMenuItem("TSD"); save = new JMenuItem("Save"); if (async) { saveModel = new JMenuItem("Save Learned LPN"); } else { saveModel = new JMenuItem("Save Learned Model"); } saveAsVerilog = new JMenuItem("Save as Verilog"); saveAsVerilog.addActionListener(this); saveAsVerilog.setActionCommand("saveAsVerilog"); saveAsVerilog.setEnabled(false); saveAs = new JMenuItem("Save As"); run = new JMenuItem("Save and Run"); check = new JMenuItem("Save and Check"); saveSBOL = new JMenuItem("Save SBOL"); refresh = new JMenuItem("Refresh"); viewCircuit = new JMenuItem("Circuit"); viewRules = new JMenuItem("Production Rules"); viewTrace = new JMenuItem("Error Trace"); viewLog = new JMenuItem("Log"); viewCoverage = new JMenuItem("Coverage Report"); 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); newGCMModel.addActionListener(this); newSBMLModel.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); importSbol.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); exportSBML.addActionListener(this); exportSBOL.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); saveSBOL.addActionListener(this); run.addActionListener(this); check.addActionListener(this); refresh.addActionListener(this); saveModel.addActionListener(this); viewCircuit.addActionListener(this); viewRules.addActionListener(this); viewTrace.addActionListener(this); viewLog.addActionListener(this); viewCoverage.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"); saveSBOL.setActionCommand("saveSBOL"); run.setActionCommand("run"); check.setActionCommand("check"); refresh.setActionCommand("refresh"); 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(); 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)); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.SHIFT_MASK)); run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); if (lema) { } else { check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey)); saveSBOL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_MASK)); refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); newGCMModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey | KeyEvent.SHIFT_MASK)); createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey | KeyEvent.SHIFT_MASK)); } newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey)); graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ShortCutKey)); probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ShortCutKey | KeyEvent.SHIFT_MASK)); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey | KeyEvent.SHIFT_MASK)); rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ShortCutKey | KeyEvent.SHIFT_MASK)); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey | KeyEvent.SHIFT_MASK)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.SHIFT_MASK)); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey)); /* if (lema) { 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)); } viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0)); Action newAction = new NewAction(); 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); 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); newMenu.setMnemonic(KeyEvent.VK_N); 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); newGCMModel.setMnemonic(KeyEvent.VK_G); newSBMLModel.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); } //importSbol.setMnemonic(KeyEvent.VK_O); importSbml.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); importSbol.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); exportSBML.setEnabled(false); exportSBOL.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); newGCMModel.setEnabled(false); newSBMLModel.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); saveSBOL.setEnabled(false); run.setEnabled(false); check.setEnabled(false); refresh.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); 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(delete); file.add(newMenu); newMenu.add(newProj); if (!async) { newMenu.add(newGCMModel); newMenu.add(newLhpn); } 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(saveAs); if (!async) { file.add(saveSBOL); file.add(check); } file.add(run); if (lema) { file.add(saveAsVerilog); } else { file.addSeparator(); file.add(refresh); } if (lema) { file.add(saveModel); } file.addSeparator(); file.add(importMenu); if (!async) { importMenu.add(importDot); importMenu.add(importSbml); importMenu.add(importBioModel); importMenu.add(importLpn); importMenu.add(importSbol); } 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(exportSBML); exportMenu.add(exportSBOL); exportMenu.addSeparator(); exportMenu.add(exportTsd); exportMenu.add(exportCsv); exportMenu.add(exportDat); exportMenu.add(exportEps); exportMenu.add(exportJpg); exportMenu.add(exportPdf); exportMenu.add(exportPng); exportMenu.add(exportSvg); 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 { 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 (LPN2SBML) { 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[10]; recentProjectPaths = new String[10]; for (int i = 0; i < 10; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjects[i].setActionCommand("recent" + i); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_0); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_1); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_2); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_3); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_4); recentProjects[5].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[5].setMnemonic(KeyEvent.VK_5); recentProjects[6].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_6, ShortCutKey)); recentProjects[6].setMnemonic(KeyEvent.VK_6); recentProjects[7].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_7, ShortCutKey)); recentProjects[7].setMnemonic(KeyEvent.VK_7); recentProjects[8].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_8, ShortCutKey)); recentProjects[8].setMnemonic(KeyEvent.VK_8); recentProjects[9].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_9, ShortCutKey)); recentProjects[9].setMnemonic(KeyEvent.VK_9); Preferences biosimrc = Preferences.userRoot(); viewer = biosimrc.get("biosim.general.viewer", ""); for (int i = 0; i < 10; 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.KECDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KECDECAY_VALUE", ".005"); } 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.gcm.MEMDIFF_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MEMDIFF_VALUE", "1.0/0.01"); } if (biosimrc.get("biosim.gcm.KECDIFF_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KECDIFF_VALUE", "1.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); } // builds the edit>preferences panel public void preferences() { if (!async) { // sbml preferences 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(); // general preferences 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); } // create sbml preferences panel JPanel levelPrefs = new JPanel(new GridLayout(1, 2)); levelPrefs.add(SBMLlabel); levelPrefs.add(LevelVersion); // gcm preferences 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 KECDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KECDECAY_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", "")); final JTextField MEMDIFF_VALUE = new JTextField(biosimrc.get("biosim.gcm.MEMDIFF_VALUE", "")); final JTextField KECDIFF_VALUE = new JTextField(biosimrc.get("biosim.gcm.KECDIFF_VALUE", "")); JPanel labels = new JPanel(new GridLayout(19, 1)); labels.add(SBMLlabel); labels.add(Undeclared); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + GlobalConstants.ACTIVED_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + GlobalConstants.KACT_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + GlobalConstants.KBASAL_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + GlobalConstants.KDECAY_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KECDECAY_STRING) + " (" + GlobalConstants.KECDECAY_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + GlobalConstants.COOPERATIVITY_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + GlobalConstants.RNAP_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + GlobalConstants.PROMOTER_COUNT_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + GlobalConstants.INITIAL_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + GlobalConstants.OCR_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + GlobalConstants.RNAP_BINDING_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING) + " (" + GlobalConstants.ACTIVATED_RNAP_BINDING_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + GlobalConstants.KREP_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + GlobalConstants.STOICHIOMETRY_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KCOMPLEX_STRING) + " (" + GlobalConstants.KCOMPLEX_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MEMDIFF_STRING) + " (" + GlobalConstants.MEMDIFF_STRING + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KECDIFF_STRING) + " (" + GlobalConstants.KECDIFF_STRING + "):")); JPanel fields = new JPanel(new GridLayout(19, 1)); fields.add(LevelVersion); fields.add(Units); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KDECAY_VALUE); fields.add(KECDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_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); fields.add(MEMDIFF_VALUE); fields.add(KECDIFF_VALUE); // create gcm preferences panel JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); // analysis preferences 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", "reachability-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("Model"); 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("Model"); 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("Model"); 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("reachability-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); // create analysis preferences panel JPanel analysisPrefs = new JPanel(new GridLayout(1, 2)); analysisPrefs.add(analysisLabels); analysisPrefs.add(analysisFields); // learning preferences 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); // create learning preferences panel JPanel learnPrefs = new JPanel(new GridLayout(1, 2)); learnPrefs.add(learnLabels); learnPrefs.add(learnFields); // create general preferences panel 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); // create tabs JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", generalPrefs); prefTabs.addTab("Model 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 user hits "save", store and/or check new data 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(KECDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KECDECAY_VALUE", KECDECAY_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 { String[] fdrv = MEMDIFF_VALUE.getText().trim().split("/"); //if the user specifies a forward and reverse rate if (fdrv.length == 2) { biosimrc.put("biosim.gcm.MEMDIFF_VALUE", Double.parseDouble(fdrv[0]) + "/" + Double.parseDouble(fdrv[1])); } else if (fdrv.length == 1) { Double.parseDouble(MEMDIFF_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MEMDIFF_VALUE", MEMDIFF_VALUE.getText().trim()); } } catch (Exception e1) { } try { Double.parseDouble(KECDIFF_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KECDIFF_VALUE", KECDIFF_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(); } } } // if user clicks "cancel" else { } } // if (async) 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.9", 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.9", 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 2.0", JLabel.CENTER); developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen\nNicholas 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 LearnGCM) { ((LearnGCM) 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 LearnGCM) { ((LearnGCM) 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() == saveModel) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { for (Component component : ((JTabbedPane) comp).getComponents()) { if (component instanceof LearnGCM) { ((LearnGCM) 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() == 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() == exportSBML) { Component comp = tab.getSelectedComponent(); if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).exportSBML(); } } else if (e.getSource() == exportSBOL) { Component comp = tab.getSelectedComponent(); if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).exportSBOL(); } } else if (e.getSource() == saveSBOL) { Component comp = tab.getSelectedComponent(); if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).saveSBOL(); } } 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")) { try { openSim(); } catch (Exception e0) { } } 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")) { try { simulate(2); } catch (Exception e1) { e1.printStackTrace(); 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) { e1.printStackTrace(); 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(); 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(); 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) { delete(); } else if (e.getActionCommand().equals("openLPN")) { openLPN(); } else if (e.getActionCommand().equals("browseSbol")) { openSBOL(); } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("gcmEditor")) { openGCM(false); } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("gcmTextEditor")) { openGCM(true); } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { openSBML(tree.getFile()); } 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 LearnGCM) { ((LearnGCM) 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 + theFile); // 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, 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 LearnGCM) { ((LearnGCM) 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, true); } else if (component instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) component).saveParams(false, "", true); } 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 LearnGCM) { ((LearnGCM) component).save(); new Thread((LearnGCM) 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, true); ((SBML_Editor) comp).check(); } else if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).save("Save and Check GCM"); } } else if (e.getActionCommand().equals("export")) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(); } else if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).exportSBML(); // TODO: should give choice of SBML or SBOL } 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 = Utility.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 to create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbol.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); newGCMModel.setEnabled(true); newSBMLModel.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]) || (e.getSource() == recentProjects[5]) || (e.getSource() == recentProjects[6]) || (e.getSource() == recentProjects[7]) || (e.getSource() == recentProjects[8]) || (e.getSource() == recentProjects[9])) { 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 = Utility.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]; } else if (e.getSource() == recentProjects[5]) { projDir = recentProjectPaths[5]; } else if (e.getSource() == recentProjects[6]) { projDir = recentProjectPaths[6]; } else if (e.getSource() == recentProjects[7]) { projDir = recentProjectPaths[7]; } else if (e.getSource() == recentProjects[8]) { projDir = recentProjectPaths[8]; } else if (e.getSource() == recentProjects[9]) { projDir = recentProjectPaths[9]; } // 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); importSbol.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); newGCMModel.setEnabled(true); newSBMLModel.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() == newGCMModel) { createGCM(); } // if the new SBML model menu item is selected else if (e.getSource() == newSBMLModel) { createSBML(); } // if the new vhdl menu item is selected else if (e.getSource() == newVhdl) { newModel("VHDL", ".vhd"); } // if the new assembly menu item is selected else if (e.getSource() == newS) { newModel("Assembly", ".s"); } // if the new instruction file menu item is selected else if (e.getSource() == newInst) { newModel("Instruction", ".inst"); } // if the new petri net menu item is selected else if (e.getSource() == newG) { newModel("Petri Net", ".g"); } // if the new lhpn menu item is selected else if (e.getSource() == newLhpn) { createLPN(); } // if the new csp menu item is selected else if (e.getSource() == newCsp) { newModel("CSP", ".csp"); } // if the new hse menu item is selected else if (e.getSource() == newHse) { newModel("Handshaking Expansion", ".hse"); } // if the new unc menu item is selected else if (e.getSource() == newUnc) { newModel("Extended Burst Mode Machine", ".unc"); } // if the new rsg menu item is selected else if (e.getSource() == newRsg) { newModel("Reduced State Graph", ".rsg"); } // if the new rsg menu item is selected else if (e.getSource() == newSpice) { newModel("Spice Circuit", ".cir"); } else if (e.getSource().equals(importSbol)) { importFile("SBOL", ".rdf"); } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { importSBML(null); } else if (e.getSource() == importBioModel) { importBioModel(); } // if the import dot menu item is selected else if (e.getSource() == importDot) { importGCM(); } // if the import vhdl menu item is selected else if (e.getSource() == importVhdl) { importFile("VHDL", ".vhd"); } else if (e.getSource() == importS) { importFile("Assembly", ".s"); } else if (e.getSource() == importInst) { importFile("Instruction", ".inst"); } else if (e.getSource() == importLpn) { importLPN(); } else if (e.getSource() == importG) { importFile("Petri Net", ".g"); } // if the import csp menu item is selected else if (e.getSource() == importCsp) { importFile("CSP", ".csp"); } // if the import hse menu item is selected else if (e.getSource() == importHse) { importFile("Handshaking Expansion", ".hse"); } // if the import unc menu item is selected else if (e.getSource() == importUnc) { importFile("Extended Burst State Machine", ".unc"); } // if the import rsg menu item is selected else if (e.getSource() == importRsg) { importFile("Reduced State Graph", ".rsg"); } // if the import spice menu item is selected else if (e.getSource() == importSpice) { importFile("Spice Circuit", ".cir"); } // if the Graph data menu item is clicked else if (e.getSource() == graph) { createGraph(); } else if (e.getSource() == probGraph) { createHistogram(); } else if (e.getActionCommand().equals("createLearn")) { createLearn(); } else if (e.getActionCommand().equals("viewModel")) { viewModel(); } else if (e.getActionCommand().equals("copy") || e.getSource() == copy) { copy(); } else if (e.getActionCommand().equals("rename") || e.getSource() == rename) { rename(); } else if (e.getActionCommand().equals("openGraph")) { openGraph(); } else if (e.getActionCommand().equals("openHistogram")) { openHistogram(); } enableTabMenu(tab.getSelectedIndex()); enableTreeMenu(); } private void 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(); if (tree.getFile().endsWith(".gcm")) { new File(tree.getFile().replace(".gcm", ".xml")).delete(); } 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); } } } } private void importBioModel() { 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); return; } } 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: } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open http: } else { command = "cmd /c start http: } 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: } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open http: } else { command = "cmd /c start http: } 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]); if (value == JOptionPane.YES_OPTION && ListOfBioModels.getSelectedValue() != null) { String ModelId = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0]; String filename = ModelId + ".xml"; try { if (overwrite(root + separator + filename, filename)) { String model = client.getModelSBMLById(ModelId); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(root + separator + filename), "UTF-8")); out.write(model); out.close(); 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]); openSBML(root + separator + 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); } } } private void createLPN() { 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); } } private void importLPN() { 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 = Utility.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); } } } private void importGCM() { 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 = Utility.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); importSBML(filename.trim().replace(".gcm", ".xml")); } } 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]); importSBML(filename.trim().replace(".gcm", ".xml")); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void createSBML() { 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(Gui.SBML_LEVEL, Gui.SBML_VERSION); document.createModel(); 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); 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); } } private void createGCM() { if (root != null) { try { String simName = null; JTextField modelChooser = new JTextField(""); modelChooser.setColumns(20); JCheckBox gridCheckBox = new JCheckBox("Make Grid"); JPanel modelPanel = new JPanel(new GridLayout(2, 2)); modelPanel.add(new JLabel("Enter Model ID: ")); modelPanel.add(modelChooser); modelPanel.add(gridCheckBox); frame.add(modelPanel); String[] options = {GlobalConstants.OK, GlobalConstants.CANCEL}; int okCancel = JOptionPane.showOptionDialog(frame, modelPanel, "Model ID", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); //if the user clicks "ok" on the panel if (okCancel == JOptionPane.OK_OPTION) { simName = modelChooser.getText(); } else return; //String simName = JOptionPane.showInputDialog(frame, "Enter 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); } /* SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION); Model m = document.createModel(); document.setModel(m); m.setId(simName); Compartment c = m.createCompartment(); c.setId("default"); c.setSize(1); c.setSpatialDimensions(3); c.setConstant(true); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + simName.replace(".gcm", ".xml")); addToTree(simName.replace(".gcm", ".xml")); */ GCM2SBMLEditor gcm2sbml = new GCM2SBMLEditor(root + separator, f.getName(), this, log, false, null, null, null, false); // gcm2sbml.addMouseListener(this); addTab(f.getName(), gcm2sbml, "GCM Editor"); addToTree(f.getName()); if (gridCheckBox.isSelected()) gcm2sbml.launchGridPanel(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } private void importSBML(String filename) { Preferences biosimrc = Preferences.userRoot(); if (filename == null) { File importFile; if (biosimrc.get("biosim.general.import_dir", "").equals("")) { importFile = null; } else { importFile = new File(biosimrc.get("biosim.general.import_dir", "")); } filename = Utility.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); openSBML(root + separator + newFile); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void importFile(String fileType, String extension) { 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 = Utility.browse(frame, importFile, null, JFileChooser.FILES_ONLY, "Import " + fileType, -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals(extension)) { JOptionPane.showMessageDialog(frame, "You must select a valid " + fileType + " 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); } } } private void createGraph() { 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()); } } } private void createHistogram() { 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()); } } } private void 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 { LearnGCM learn = new LearnGCM(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); } } private void 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); File work = new File(root); Runtime exec = Runtime.getRuntime(); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { 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")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { 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 Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "VHDL model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view VHDL 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(); } } private void 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 copy = JOptionPane.showInputDialog(frame, "Enter a New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy == null || copy.equals("")) { return; } copy = copy.trim(); if (tree.getFile().contains(".")) { String extension = tree.getFile().substring(tree.getFile().lastIndexOf("."), tree.getFile().length()); if (!copy.endsWith(extension)) { copy += extension; } } 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; } try { if (overwrite(root + separator + copy, copy)) { if (copy.endsWith(".xml")) { SBMLDocument document = readSBML(tree.getFile()); document.getModel().setId(copy.substring(0, copy.lastIndexOf("."))); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy); } else if (copy.endsWith(".gcm")) { SBMLDocument document = readSBML(tree.getFile().replace(".gcm", ".xml")); document.getModel().setId(copy.substring(0, copy.lastIndexOf("."))); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy.replace(".gcm", ".xml")); addToTree(copy.replace(".gcm", ".xml")); GCMFile gcm = new GCMFile(root); gcm.load(tree.getFile()); gcm.setSBMLFile(copy.replace(".gcm", ".xml")); gcm.save(root + separator + copy); } else if (copy.contains(".")) { 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(); 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); } } } private void rename() { if (!tree.getFile().equals(root)) { String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 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; } } String rename = JOptionPane.showInputDialog(frame, "Enter a New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename == null || rename.equals("")) { return; } rename = rename.trim(); if (tree.getFile().contains(".")) { String extension = tree.getFile().substring(tree.getFile().lastIndexOf("."), tree.getFile().length()); if (!rename.endsWith(extension)) { rename += extension; } } 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; } String modelID = rename.substring(0, rename.lastIndexOf(".")); try { if (overwrite(root + separator + rename, rename)) { if (tree.getFile().endsWith(".sbml") || tree.getFile().endsWith(".xml") || tree.getFile().endsWith(".gcm") || tree.getFile().endsWith(".lpn") || tree.getFile().endsWith(".vhd") || tree.getFile().endsWith(".csp") || tree.getFile().endsWith(".hse") || tree.getFile().endsWith(".unc") || tree.getFile().endsWith(".rsg")) { reassignViews(oldName, rename); } if (tree.getFile().endsWith(".gcm")) { String newSBMLfile = rename.replace(".gcm", ".xml"); new File(tree.getFile()).renameTo(new File(root + separator + rename)); new File(tree.getFile().replace(".gcm", ".xml")).renameTo(new File(root + separator + newSBMLfile)); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + rename); gcm.setSBMLFile(newSBMLfile); gcm.save(root + separator + rename); SBMLDocument document = readSBML(root + separator + newSBMLfile); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + newSBMLfile); deleteFromTree(oldName.replace(".gcm", ".xml")); addToTree(newSBMLfile); } else if (tree.getFile().endsWith(".xml")) { new File(tree.getFile()).renameTo(new File(root + separator + rename)); SBMLDocument document = readSBML(root + separator + rename); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + rename); } else { 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 (tree.getFile().endsWith(".sbml") || tree.getFile().endsWith(".xml") || tree.getFile().endsWith(".gcm") || tree.getFile().endsWith(".lpn") || tree.getFile().endsWith(".vhd") || tree.getFile().endsWith(".csp") || tree.getFile().endsWith(".hse") || tree.getFile().endsWith(".unc") || tree.getFile().endsWith(".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 + 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(".rdf")) { tab.setTitleAt(i, rename); } 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, 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 LearnGCM) { LearnGCM l = ((LearnGCM) 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 LearnGCM && ((LearnGCM) c).getBackgroundFile().equals(oldName)) { ((LearnGCM) c).updateBackgroundFile(rename); } } } } // updateAsyncViews(rename); updateViewNames(tree.getFile(), rename); deleteFromTree(oldName); addToTree(rename); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } } private void openGCM(boolean textBased) { String file = tree.getFile(); String filename = ""; if (file.lastIndexOf('/') >= 0) { filename = file.substring(file.lastIndexOf('/') + 1); } if (file.lastIndexOf('\\') >= 0) { filename = file.substring(file.lastIndexOf('\\') + 1); } openGCM(filename, textBased); } public void openGCM(String filename, boolean textBased) { try { File work = new File(root); int i = getTab(filename); if (i == -1) { i = getTab(filename.replace(".gcm", ".xml")); } if (i != -1) { tab.setSelectedIndex(i); } else { String path = work.getAbsolutePath(); /* * GCMFile gcmFile = new GCMFile(path); String gcmname = * theFile.replace(".gcm", ""); gcmFile.load(filename); if * ((gcmFile.getSBMLFile() == null || * !gcmFile.getSBMLFile().equals(gcmname + ".xml")) && new * File(path + separator + gcmname + ".xml").exists()) { * Object[] options = { "Overwrite", "Cancel" }; int value; * value = JOptionPane.showOptionDialog(Gui.frame, gcmname + * ".xml already exists." + "\nDo you want to overwrite?", * "Overwrite", JOptionPane.YES_NO_OPTION, * JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if * (value == JOptionPane.YES_OPTION) { GCM2SBMLEditor gcm = new * GCM2SBMLEditor(path, theFile, this, log, false, null, null, * null, textBased); addTab(theFile, gcm, "GCM Editor"); } } * else { */ try { GCM2SBMLEditor gcm = new GCM2SBMLEditor(path, filename, this, log, false, null, null, null, textBased); addTab(filename, gcm, "GCM Editor"); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to open this GCM file.", "Error", JOptionPane.ERROR_MESSAGE); } } private void openSBML(String fullPath) { try { boolean done = false; String theSBMLFile = fullPath.split(separator)[fullPath.split(separator).length - 1]; String theGCMFile = theSBMLFile.replace(".xml", ".gcm"); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(theSBMLFile) || tab.getTitleAt(i).equals(theGCMFile)) { tab.setSelectedIndex(i); done = true; break; } } if (!done) { createGCMFromSBML(root, fullPath, theSBMLFile, theGCMFile, false); addToTree(theGCMFile); GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, theGCMFile, this, log, false, null, null, null, false); addTab(theGCMFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } public static boolean createGCMFromSBML(String root, String fullPath, String theSBMLFile, String theGCMFile, boolean force) { if (force || !new File(fullPath.replace(".xml", ".gcm").replace(".sbml", ".gcm")).exists()) { SBMLDocument document = readSBML(fullPath); Model m = document.getModel(); GCMFile gcmFile = new GCMFile(root); int x = 50; int y = 50; if (m != null) { for (int i = 0; i < m.getNumSpecies(); i++) { gcmFile.createSpecies(document.getModel().getSpecies(i).getId(), x, y); if (m.getSpecies(i).isSetInitialAmount()) { gcmFile.getSpecies().get(m.getSpecies(i).getId()) .setProperty(GlobalConstants.INITIAL_STRING, m.getSpecies(i).getInitialAmount() + ""); } else { gcmFile.getSpecies().get(m.getSpecies(i).getId()) .setProperty(GlobalConstants.INITIAL_STRING, "[" + m.getSpecies(i).getInitialConcentration() + "]"); } gcmFile.getSpecies().get(m.getSpecies(i).getId()).setProperty(GlobalConstants.KDECAY_STRING, "0.0"); x += 50; y += 50; } } gcmFile.setSBMLDocument(document); gcmFile.setSBMLFile(theSBMLFile); gcmFile.save(fullPath.replace(".xml", ".gcm").replace(".sbml", ".gcm")); return true; } else return false; } private void openSBOL() { String filePath = tree.getFile(); String fileName = ""; String mySeparator = File.separator; int spacer = 1; if (mySeparator.equals("\\")) { mySeparator = "\\\\"; spacer = 2; } fileName = filePath.substring(filePath.lastIndexOf(mySeparator) + spacer); int i = getTab(fileName); if (i != -1) { tab.setSelectedIndex(i); } else { SbolBrowser browser = new SbolBrowser(filePath, this); } } private void 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(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"); } } private void openHistogram() { 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"); } } private void openLPN() { 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); File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile, lhpn, this, log); addTab(theFile, editor, "LHPN Editor"); } } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to view this LPN file.", "Error", JOptionPane.ERROR_MESSAGE); } } private void newModel(String fileType, String extension) { if (root != null) { try { String modelID = JOptionPane.showInputDialog(frame, "Enter " + fileType + " Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (modelID != null && !modelID.trim().equals("")) { String fileName; modelID = modelID.trim(); if (modelID.length() >= extension.length()) { if (!modelID.substring(modelID.length() - extension.length()).equals(extension)) { fileName = modelID + extension; } else { fileName = modelID; modelID = modelID.substring(0, modelID.length() - extension.length()); } } else { fileName = modelID + extension; } 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 + fileName); f.createNewFile(); addToTree(fileName); if (!viewer.equals("")) { String command = viewer + " " + root + separator + fileName; 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); addTab(fileName, scroll, fileType + " Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } private void openModel(String fileType) { 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); addTab(theFile, scroll, fileType + " Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this " + fileType + " file.", "Error", JOptionPane.ERROR_MESSAGE); } } 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 < 10) { 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 addToTreeNoUpdate(String item) { tree.addToTree(item, root); mainPanel.validate(); } public void deleteFromTree(String item) { tree.deleteFromTree(item); //updateGCM(); mainPanel.validate(); } public FileTree getFileTree() { return tree; } /** * 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); if (tab.getTabCount() > 0) { tab.setSelectedIndex(tab.getTabCount() - 1); enableTabMenu(tab.getSelectedIndex()); } else { enableTreeMenu(); } } 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, 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, true); return 2; } else if (value == NO_TO_ALL_OPTION) { return 3; } } else if (autosave == 1) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true, 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, 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, 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, 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) instanceof MovieContainer) { if (((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).getGCM2SBMLEditor().isDirty() || ((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).getIsDirty()) { 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) { ((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).savePreferences(); } else if (value == CANCEL_OPTION) { return 0; } else if (value == YES_TO_ALL_OPTION) { ((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).savePreferences(); autosave = 1; } else if (value == NO_TO_ALL_OPTION) { autosave = 2; } } else if (autosave == 1) { ((MovieContainer) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).savePreferences(); } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals("Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnGCM) { if (((LearnGCM) ((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 LearnGCM) { ((LearnGCM) ((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 LearnGCM) { ((LearnGCM) ((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 LearnGCM) { ((LearnGCM) ((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 copySFiles(String filename, String directory) { StringBuffer data = new StringBuffer(); try { BufferedReader in = new BufferedReader(new FileReader(directory + separator + filename)); String str; while ((str = in.readLine()) != null) { data.append(str + "\n"); } in.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Error opening file"); } Pattern sLinePattern = Pattern.compile(SFILELINE); Matcher sLineMatcher = sLinePattern.matcher(data); while (sLineMatcher.find()) { String sFilename = sLineMatcher.group(1); try { File newFile = new File(directory + separator + sFilename); newFile.createNewFile(); FileOutputStream copyin = new FileOutputStream(newFile); FileInputStream copyout = new FileInputStream(new File(root + separator + sFilename)); int read = copyout.read(); while (read != -1) { copyin.write(read); read = copyout.read(); } copyin.close(); copyout.close(); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(Gui.frame, "Cannot copy file " + sFilename, "Copy 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) { executePopupMenu(e); } public void mouseReleased(MouseEvent e) { executePopupMenu(e); } public void executePopupMenu(MouseEvent e) { 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(".rdf")) { JMenuItem view = new JMenuItem("View"); view.addActionListener(this); view.addMouseListener(this); view.setActionCommand("browseSbol"); 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"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.addMouseListener(this); delete.setActionCommand("delete"); popup.add(view); 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 edit = new JMenuItem("View/Edit (graphical)"); edit.addActionListener(this); edit.addMouseListener(this); edit.setActionCommand("gcmEditor"); JMenuItem editText = new JMenuItem("View/Edit (tabular)"); editText.addActionListener(this); editText.addMouseListener(this); editText.setActionCommand("gcmTextEditor"); //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.addSeparator(); //popup.add(graph); //popup.addSeparator(); popup.add(edit); popup.add(editText); 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("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 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("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 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 view = new JMenuItem("View/Edit"); view.addActionListener(this); view.addMouseListener(this); view.setActionCommand("openLPN"); 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); popup.addSeparator(); popup.add(viewModel); } if (atacs || lema) { popup.add(createVerification); } // popup.add(createAnalysis); // TODO // 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(view); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) { JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createAnalysis"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.addMouseListener(this); createVerification.setActionCommand("createVerify"); 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(createAnalysis); popup.add(createVerification); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) { JMenuItem 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("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 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("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 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("openHistogram"); 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()); } } } public void executeMouseClickEvent(MouseEvent e) { if (!(e.getSource() instanceof JTree)) { enableTabMenu(tab.getSelectedIndex()); // frame.getGlassPane().setVisible(true); } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2 && e.getSource() instanceof JTree && 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")) { openSBML(tree.getFile()); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { openGCM(false); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rdf")) { openSBOL(); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { openModel("VHDL"); } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) { openModel("Assembly File"); } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) { openModel("Instruction File"); } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { openModel("Verilog-AMS"); } else if (tree.getFile().length() >= 3 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { openModel("SystemVerilog"); } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { openModel("Petri Net"); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { openLPN(); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { openModel("CSP"); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { openModel("Handshaking Expansion"); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { openModel("Extended Burst-Mode Machine"); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { openModel("Reduced State Graph"); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) { openModel("Spice Circuit"); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { openGraph(); } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { openHistogram(); } 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) { try { openSim(); } catch (Exception e0) { } } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else if (learn) { if (lema) { openLearnLHPN(); } else { openLearn(); } } } } else { enableTreeMenu(); return; } enableTabMenu(tab.getSelectedIndex()); } 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())); } } 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; //ArrayList<String> interestingSpecies = new ArrayList<String>(); if (fileType == 1) { sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1].length() - 3) + "xml"); //GCMParser parser = new GCMParser(tree.getFile()); //GeneticNetwork network = parser.buildNetwork(); //interestingSpecies.addAll(network.getInterestingSpecies()); //GeneticNetwork.setRoot(root + separator); //network.mergeSBML(root + separator + simName + separator + sbmlFile); new File(root + separator + simName + separator + sbmlFile).createNewFile(); sbmlFileProp = root + separator + simName + separator + (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1].length() - 3) + "xml"); sbmlFile = sbmlFileProp; } else if (fileType == 2) { sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1].length() - 3) + "xml"); 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) + "xml"); 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, 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, false); 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]; if (learnFile.endsWith(".xml")) { learnFile = learnFile.replace(".xml", ".gcm"); load.setProperty("genenet.file", learnFile); } } } 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"); LearnGCM learn = new LearnGCM(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() throws Exception { 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(".xml")) { getAFile = filename + separator + list[i]; } else if (end.equals("sbml") && 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 = ""; // ArrayList<String> interestingSpecies = new // ArrayList<String>(); 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.contains(".xml")) sbmlLoadFile = sbmlLoadFile.replace(".xml", ".gcm"); 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(); // interestingSpecies.addAll(network.getInterestingSpecies()); //GeneticNetwork.setRoot(root + separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".xml"); //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", ".xml"); //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) { e.printStackTrace(); 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, null); } else { reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile, null, 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, false); 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(""); } Graph tsdGraph = reb2sac.createGraph(open); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(openProb); simTab.addTab("Histogram", probGraph); 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 { private static final long serialVersionUID = 1L; NewAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(newProj); if (!async) { popup.add(newGCMModel); popup.add(newSBMLModel); } 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 ImportAction extends AbstractAction { private static final long serialVersionUID = 1L; ImportAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(importDot); popup.add(importSbol); 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 { private static final long serialVersionUID = 1L; 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 { private static final long serialVersionUID = 1L; 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) { 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); 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 Gui(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) { e.printStackTrace(); 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, 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, false); 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 LearnGCM) { } else { if (lema) { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnLHPN(root + separator + learnName, log, this)); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnGCM(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 boolean updateOpenGCM(String gcmName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (gcmName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { try { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmName, this, log, false, null, null, null, false); this.tab.setComponentAt(i, gcm); this.tab.getComponentAt(i).setName("GCM Editor"); // gcm.save(false, "", false, true); } catch (Exception e) { e.printStackTrace(); } return true; } } } return false; } 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++) { // String tabName = sim.getComponentAt(j).getName(); // boolean b = // sim.getComponentAt(j).getName().equals("ModelViewMovie"); if (sim.getComponentAt(j) instanceof Reb2Sac) { ((Reb2Sac) sim.getComponentAt(j)).updateProperties(); } else 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, 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", ".xml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".xml")); } 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, "", true); ((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); } for (int k = 0; k < sim.getTabCount(); k++) { if (sim.getComponentAt(k) instanceof MovieContainer) { //display the schematic and reload the grid ((MovieContainer) (sim.getComponentAt(k))).display(); ((MovieContainer) (sim.getComponentAt(k))).reloadGrid(); } } } } } } 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")) { ((LearnGCM) (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) { saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); saveAs.setEnabled(false); saveSBOL.setEnabled(false); saveModel.setEnabled(false); run.setEnabled(false); check.setEnabled(false); exportMenu.setEnabled(false); exportSBML.setEnabled(false); exportSBOL.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); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(false); viewSG.setEnabled(false); viewLog.setEnabled(false); viewCoverage.setEnabled(false); viewLearnedModel.setEnabled(false); refresh.setEnabled(false); if (selectedTab != -1) { tab.setSelectedIndex(selectedTab); } Component comp = tab.getSelectedComponent(); if (comp instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); checkButton.setEnabled(true); exportButton.setEnabled(true); save.setEnabled(true); saveAs.setEnabled(true); saveSBOL.setEnabled(true); check.setEnabled(true); exportMenu.setEnabled(true); exportSBML.setEnabled(true); exportSBOL.setEnabled(true); } else if (comp instanceof SbolBrowser) { //save.setEnabled(true); } else if (comp instanceof LHPNEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); save.setEnabled(true); saveAs.setEnabled(true); viewCircuit.setEnabled(true); exportMenu.setEnabled(true); exportSBML.setEnabled(true); } else if (comp instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); checkButton.setEnabled(true); save.setEnabled(true); saveAs.setEnabled(true); check.setEnabled(true); } else if (comp instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); refreshButton.setEnabled(true); exportButton.setEnabled(true); save.setEnabled(true); saveAs.setEnabled(true); refresh.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); } 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 LearnGCM) { 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); exportButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(((LearnGCM) learnComponent).getViewGcmEnabled()); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(((LearnGCM) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((LearnGCM) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); 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); refresh.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); } else if (component instanceof Reb2Sac) { saveButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); } else if (component instanceof SBML_Editor) { saveButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); } else if (component instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); } else if (component instanceof LearnGCM) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } saveButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); viewCircuit.setEnabled(((LearnGCM) component).getViewGcmEnabled()); viewLog.setEnabled(((LearnGCM) component).getViewLogEnabled()); saveModel.setEnabled(((LearnGCM) component).getViewGcmEnabled()); } else if (component instanceof LearnLHPN) { saveButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); viewLearnedModel.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled()); saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); } else if (component instanceof DataManager) { saveButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); saveAs.setEnabled(true); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(((LearnGCM) learnComponent).getViewGcmEnabled()); viewCircuit.setEnabled(((LearnGCM) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((LearnGCM) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); 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); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(((LearnGCM) learnComponent).getViewGcmEnabled()); viewCircuit.setEnabled(((LearnGCM) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((LearnGCM) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); 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); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); } else if (comp.getName().equals("Synthesis")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); save.setEnabled(true); run.setEnabled(true); viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled()); viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); } } else if (comp instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(true); save.setEnabled(true); saveAs.setEnabled(true); } } private void enableTreeMenu() { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createVer.setEnabled(false); createSbml.setEnabled(false); check.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewModel.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLHPN.setEnabled(false); saveAsVerilog.setEnabled(false); if (tree.getFile() != null) { if (tree.getFile().equals(root)) { } 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); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { viewModGraph.setEnabled(true); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSbml.setEnabled(true); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); } else if (tree.getFile().length() > 3 && (tree.getFile().substring(tree.getFile().length() - 4).equals(".rdf") || tree.getFile().substring(tree.getFile().length() - 4) .equals(".grf"))) { copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) { copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); } else if (tree.getFile().length() > 2 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewLHPN.setEnabled(true); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); createAnal.setEnabled(true); createAnal.setActionCommand("createAnalysis"); if (lema) { createLearn.setEnabled(true); } createSynth.setEnabled(true); createVer.setEnabled(true); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewLHPN.setEnabled(true); saveAsVerilog.setEnabled(true); } else if (tree.getFile().length() > 3 && (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(".csp") || tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd") || tree.getFile() .substring(tree.getFile().length() - 4).equals(".rsg"))) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewLHPN.setEnabled(true); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s") || tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) { createAnal.setEnabled(true); createVer.setEnabled(true); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewLHPN.setEnabled(true); } 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) { copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); } } } } public String getRoot() { return root; } 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?"; } 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?"; } 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?"; } JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); value = JOptionPane.showOptionDialog(frame, scroll, "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); 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, true); 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) { JButton button = new JButton(); button.setActionCommand(actionCommand); button.setToolTipText(toolTipText); button.addActionListener(this); button.setIcon(new ImageIcon(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() < SBML_LEVEL || document.getVersion() < SBML_VERSION) { 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); } } static final String SFILELINE = "input (\\S+?)\n"; }
package org.treetank.pagelayer; import org.treetank.api.IPage; import org.treetank.utils.FastByteArrayReader; import org.treetank.utils.FastByteArrayWriter; public class PageReference { private boolean mIsDirty; private IPage mPage; private long mStart; private int mLength; private long mChecksum; public PageReference() { this(null, -1L, -1, -1L); } public PageReference(final PageReference pageReference) { this( pageReference.mPage, pageReference.mStart, pageReference.mLength, pageReference.mChecksum); mIsDirty = true; } public PageReference( final IPage page, final long start, final int length, final long checksum) { mIsDirty = false; mPage = page; mStart = start; mLength = length; mChecksum = checksum; } public PageReference(final FastByteArrayReader in) throws Exception { this(null, in.readVarLong(), in.readVarInt(), in.readVarLong()); } public final boolean isInstantiated() { return (mPage != null); } public final boolean isCommitted() { return (mStart != -1L); } public final boolean isDirty() { return mIsDirty; } public final long getChecksum() { return mChecksum; } public final void setChecksum(final long checksum) { mChecksum = checksum; } public final IPage getPage() { return mPage; } public final void setPage(final IPage page) { mPage = page; mIsDirty = true; } public final int getLength() { return mLength; } public final void setLength(final int length) { mLength = length; } public final long getStart() { return mStart; } public final void setStart(final long start) { mStart = start; } public final void serialize(final FastByteArrayWriter out) throws Exception { mIsDirty = false; out.writeVarLong(mStart); out.writeVarInt(mLength); out.writeVarLong(mChecksum); } @Override public final boolean equals(final Object object) { final PageReference pageReference = (PageReference) object; return ((mChecksum == pageReference.mChecksum) && (mStart == pageReference.mStart) && (mLength == pageReference.mLength)); } @Override public final String toString() { return "start=" + mStart + ", length=" + mLength + ", checksum=" + mChecksum; } }
package org.opencms.ugc.client; import org.opencms.ugc.client.export.CmsXmlContentUgcApi; import org.timepedia.exporter.client.ExporterUtil; import com.google.gwt.core.client.EntryPoint; /** * Entry point for client-side form handling code for user-generated content module.<p> */ public class CmsUgcEntryPoint implements EntryPoint { /** * Exports the API objects as native Javascript objects.<p> * * @param api the API to expose as Javascript object */ public native void installJavascriptApi(CmsXmlContentUgcApi api) /*-{ $wnd.OpenCmsUgc = new $wnd.opencms.CmsXmlContentUgcApi(api); }-*/; /** * @see com.google.gwt.core.client.EntryPoint#onModuleLoad() */ public void onModuleLoad() { ExporterUtil.exportAll(); CmsXmlContentUgcApi api = new CmsXmlContentUgcApi(); installJavascriptApi(api); callInitFunction(); } /** * Calls the init form method after the API has been exported.<p> */ private native void callInitFunction() /*-{ if ($wnd.initUgc != undefined && typeof $wnd.initUgc == 'function') { $wnd.initUgc(); } }-*/; }
package org.elasticsearch.gradle.internal.info; import org.apache.commons.io.IOUtils; import org.elasticsearch.gradle.internal.BwcVersions; import org.elasticsearch.gradle.OS; import org.elasticsearch.gradle.internal.conventions.info.GitInfo; import org.elasticsearch.gradle.internal.conventions.info.ParallelDetector; import org.elasticsearch.gradle.internal.conventions.util.Util; import org.gradle.api.GradleException; import org.gradle.api.JavaVersion; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.api.provider.Provider; import org.gradle.api.provider.ProviderFactory; import org.gradle.internal.jvm.Jvm; import org.gradle.internal.jvm.inspection.JvmInstallationMetadata; import org.gradle.internal.jvm.inspection.JvmMetadataDetector; import org.gradle.internal.jvm.inspection.JvmVendor; import org.gradle.jvm.toolchain.internal.InstallationLocation; import org.gradle.jvm.toolchain.internal.JavaInstallationRegistry; import org.gradle.util.GradleVersion; import javax.inject.Inject; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.file.Files; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; public class GlobalBuildInfoPlugin implements Plugin<Project> { private static final Logger LOGGER = Logging.getLogger(GlobalBuildInfoPlugin.class); private static final String DEFAULT_VERSION_JAVA_FILE_PATH = "server/src/main/java/org/elasticsearch/Version.java"; private static Integer _defaultParallel = null; private final JavaInstallationRegistry javaInstallationRegistry; private final JvmMetadataDetector metadataDetector; private final ProviderFactory providers; @Inject public GlobalBuildInfoPlugin( JavaInstallationRegistry javaInstallationRegistry, JvmMetadataDetector metadataDetector, ProviderFactory providers ) { this.javaInstallationRegistry = javaInstallationRegistry; this.metadataDetector = new ErrorTraceMetadataDetector(metadataDetector); this.providers = providers; } @Override public void apply(Project project) { if (project != project.getRootProject()) { throw new IllegalStateException(this.getClass().getName() + " can only be applied to the root project."); } GradleVersion minimumGradleVersion = GradleVersion.version(getResourceContents("/minimumGradleVersion")); if (GradleVersion.current().compareTo(minimumGradleVersion) < 0) { throw new GradleException("Gradle " + minimumGradleVersion.getVersion() + "+ is required"); } JavaVersion minimumCompilerVersion = JavaVersion.toVersion(getResourceContents("/minimumCompilerVersion")); JavaVersion minimumRuntimeVersion = JavaVersion.toVersion(getResourceContents("/minimumRuntimeVersion")); File runtimeJavaHome = findRuntimeJavaHome(); File rootDir = project.getRootDir(); GitInfo gitInfo = GitInfo.gitInfo(rootDir); BuildParams.init(params -> { params.reset(); params.setRuntimeJavaHome(runtimeJavaHome); params.setRuntimeJavaVersion(determineJavaVersion("runtime java.home", runtimeJavaHome, minimumRuntimeVersion)); params.setIsRuntimeJavaHomeSet(Jvm.current().getJavaHome().equals(runtimeJavaHome) == false); JvmInstallationMetadata runtimeJdkMetaData = metadataDetector.getMetadata(getJavaInstallation(runtimeJavaHome).getLocation()); params.setRuntimeJavaDetails(formatJavaVendorDetails(runtimeJdkMetaData)); params.setJavaVersions(getAvailableJavaVersions()); params.setMinimumCompilerVersion(minimumCompilerVersion); params.setMinimumRuntimeVersion(minimumRuntimeVersion); params.setGradleJavaVersion(Jvm.current().getJavaVersion()); params.setGitRevision(gitInfo.getRevision()); params.setGitOrigin(gitInfo.getOrigin()); params.setBuildDate(ZonedDateTime.now(ZoneOffset.UTC)); params.setTestSeed(getTestSeed()); params.setIsCi(System.getenv("JENKINS_URL") != null); params.setDefaultParallel(ParallelDetector.findDefaultParallel(project)); params.setInFipsJvm(Util.getBooleanProperty("tests.fips.enabled", false)); params.setIsSnapshotBuild(Util.getBooleanProperty("build.snapshot", true)); params.setBwcVersions(providers.provider(() -> resolveBwcVersions(rootDir))); }); // Enforce the minimum compiler version assertMinimumCompilerVersion(minimumCompilerVersion); // Print global build info header just before task execution project.getGradle().getTaskGraph().whenReady(graph -> logGlobalBuildInfo()); } private String formatJavaVendorDetails(JvmInstallationMetadata runtimeJdkMetaData) { JvmVendor vendor = runtimeJdkMetaData.getVendor(); return runtimeJdkMetaData.getVendor().getKnownVendor().name() + "/" + vendor.getRawVendor(); } /* Introspect all versions of ES that may be tested against for backwards * compatibility. It is *super* important that this logic is the same as the * logic in VersionUtils.java. */ private static BwcVersions resolveBwcVersions(File root) { File versionsFile = new File(root, DEFAULT_VERSION_JAVA_FILE_PATH); try { List<String> versionLines = IOUtils.readLines(new FileInputStream(versionsFile), "UTF-8"); return new BwcVersions(versionLines); } catch (IOException e) { throw new IllegalStateException("Unable to resolve to resolve bwc versions from versionsFile.", e); } } private void logGlobalBuildInfo() { final String osName = System.getProperty("os.name"); final String osVersion = System.getProperty("os.version"); final String osArch = System.getProperty("os.arch"); final Jvm gradleJvm = Jvm.current(); JvmInstallationMetadata gradleJvmMetadata = metadataDetector.getMetadata(gradleJvm.getJavaHome()); final String gradleJvmVendorDetails = gradleJvmMetadata.getVendor().getDisplayName(); final String gradleJvmImplementationVersion = gradleJvmMetadata.getImplementationVersion(); LOGGER.quiet("======================================="); LOGGER.quiet("Elasticsearch Build Hamster says Hello!"); LOGGER.quiet(" Gradle Version : " + GradleVersion.current().getVersion()); LOGGER.quiet(" OS Info : " + osName + " " + osVersion + " (" + osArch + ")"); if (BuildParams.getIsRuntimeJavaHomeSet()) { JvmInstallationMetadata runtimeJvm = metadataDetector.getMetadata(BuildParams.getRuntimeJavaHome()); final String runtimeJvmVendorDetails = runtimeJvm.getVendor().getDisplayName(); final String runtimeJvmImplementationVersion = runtimeJvm.getImplementationVersion(); LOGGER.quiet(" Runtime JDK Version : " + runtimeJvmImplementationVersion + " (" + runtimeJvmVendorDetails + ")"); LOGGER.quiet(" Runtime java.home : " + BuildParams.getRuntimeJavaHome()); LOGGER.quiet(" Gradle JDK Version : " + gradleJvmImplementationVersion + " (" + gradleJvmVendorDetails + ")"); LOGGER.quiet(" Gradle java.home : " + gradleJvm.getJavaHome()); } else { LOGGER.quiet(" JDK Version : " + gradleJvmImplementationVersion + " (" + gradleJvmVendorDetails + ")"); LOGGER.quiet(" JAVA_HOME : " + gradleJvm.getJavaHome()); } LOGGER.quiet(" Random Testing Seed : " + BuildParams.getTestSeed()); LOGGER.quiet(" In FIPS 140 mode : " + BuildParams.isInFipsJvm()); LOGGER.quiet("======================================="); } private JavaVersion determineJavaVersion(String description, File javaHome, JavaVersion requiredVersion) { InstallationLocation installation = getJavaInstallation(javaHome); JavaVersion actualVersion = metadataDetector.getMetadata(installation.getLocation()).getLanguageVersion(); if (actualVersion.isCompatibleWith(requiredVersion) == false) { throwInvalidJavaHomeException( description, javaHome, Integer.parseInt(requiredVersion.getMajorVersion()), Integer.parseInt(actualVersion.getMajorVersion()) ); } return actualVersion; } private InstallationLocation getJavaInstallation(File javaHome) { return getAvailableJavaInstallationLocationSteam().filter(installationLocation -> isSameFile(javaHome, installationLocation)) .findFirst() .orElseThrow(() -> new GradleException("Could not locate available Java installation in Gradle registry at: " + javaHome)); } private boolean isSameFile(File javaHome, InstallationLocation installationLocation) { try { return Files.isSameFile(installationLocation.getLocation().toPath(), javaHome.toPath()); } catch (IOException ioException) { throw new UncheckedIOException(ioException); } } /** * We resolve all available java versions using auto detected by gradles tool chain * To make transition more reliable we only take env var provided installations into account for now */ private List<JavaHome> getAvailableJavaVersions() { return getAvailableJavaInstallationLocationSteam().map(installationLocation -> { File installationDir = installationLocation.getLocation(); JvmInstallationMetadata metadata = metadataDetector.getMetadata(installationDir); int actualVersion = Integer.parseInt(metadata.getLanguageVersion().getMajorVersion()); return JavaHome.of(actualVersion, providers.provider(() -> installationDir)); }).collect(Collectors.toList()); } private Stream<InstallationLocation> getAvailableJavaInstallationLocationSteam() { return Stream.concat( javaInstallationRegistry.listInstallations().stream(), Stream.of(new InstallationLocation(Jvm.current().getJavaHome(), "Current JVM")) ); } private static String getTestSeed() { String testSeedProperty = System.getProperty("tests.seed"); final String testSeed; if (testSeedProperty == null) { long seed = new Random(System.currentTimeMillis()).nextLong(); testSeed = Long.toUnsignedString(seed, 16).toUpperCase(Locale.ROOT); } else { testSeed = testSeedProperty; } return testSeed; } private static void throwInvalidJavaHomeException(String description, File javaHome, int expectedVersion, int actualVersion) { String message = String.format( Locale.ROOT, "The %s must be set to a JDK installation directory for Java %d but is [%s] corresponding to [%s]", description, expectedVersion, javaHome, actualVersion ); throw new GradleException(message); } private static void assertMinimumCompilerVersion(JavaVersion minimumCompilerVersion) { JavaVersion currentVersion = Jvm.current().getJavaVersion(); if (System.getProperty("idea.active", "false").equals("true") == false && minimumCompilerVersion.compareTo(currentVersion) > 0) { throw new GradleException( "Project requires Java version of " + minimumCompilerVersion + " or newer but Gradle JAVA_HOME is " + currentVersion ); } } private File findRuntimeJavaHome() { String runtimeJavaProperty = System.getProperty("runtime.java"); if (runtimeJavaProperty != null) { return new File(findJavaHome(runtimeJavaProperty)); } return System.getenv("RUNTIME_JAVA_HOME") == null ? Jvm.current().getJavaHome() : new File(System.getenv("RUNTIME_JAVA_HOME")); } private String findJavaHome(String version) { Provider<String> javaHomeNames = providers.gradleProperty("org.gradle.java.installations.fromEnv").forUseAtConfigurationTime(); String javaHomeEnvVar = getJavaHomeEnvVarName(version); // Provide a useful error if we're looking for a Java home version that we haven't told Gradle about yet Arrays.stream(javaHomeNames.get().split(",")) .filter(s -> s.equals(javaHomeEnvVar)) .findFirst() .orElseThrow( () -> new GradleException( "Environment variable '" + javaHomeEnvVar + "' is not registered with Gradle installation supplier. Ensure 'org.gradle.java.installations.fromEnv' is " + "updated in gradle.properties file." ) ); String versionedJavaHome = System.getenv(javaHomeEnvVar); if (versionedJavaHome == null) { final String exceptionMessage = String.format( Locale.ROOT, "$%s must be set to build Elasticsearch. " + "Note that if the variable was just set you " + "might have to run `./gradlew --stop` for " + "it to be picked up. See https://github.com/elastic/elasticsearch/issues/31399 details.", javaHomeEnvVar ); throw new GradleException(exceptionMessage); } return versionedJavaHome; } private static String getJavaHomeEnvVarName(String version) { return "JAVA" + version + "_HOME"; } private static int findDefaultParallel(Project project) { // Since it costs IO to compute this, and is done at configuration time we want to cache this if possible // It's safe to store this in a static variable since it's just a primitive so leaking memory isn't an issue if (_defaultParallel == null) { File cpuInfoFile = new File("/proc/cpuinfo"); if (cpuInfoFile.exists()) { // Count physical cores on any Linux distro ( don't count hyper-threading ) Map<String, Integer> socketToCore = new HashMap<>(); String currentID = ""; try (BufferedReader reader = new BufferedReader(new FileReader(cpuInfoFile))) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (line.contains(":")) { List<String> parts = Arrays.stream(line.split(":", 2)).map(String::trim).collect(Collectors.toList()); String name = parts.get(0); String value = parts.get(1); // the ID of the CPU socket if (name.equals("physical id")) { currentID = value; } // Number of cores not including hyper-threading if (name.equals("cpu cores")) { assert currentID.isEmpty() == false; socketToCore.put("currentID", Integer.valueOf(value)); currentID = ""; } } } } catch (IOException e) { throw new UncheckedIOException(e); } _defaultParallel = socketToCore.values().stream().mapToInt(i -> i).sum(); } else if (OS.current() == OS.MAC) { // Ask macOS to count physical CPUs for us ByteArrayOutputStream stdout = new ByteArrayOutputStream(); project.exec(spec -> { spec.setExecutable("sysctl"); spec.args("-n", "hw.physicalcpu"); spec.setStandardOutput(stdout); }); _defaultParallel = Integer.parseInt(stdout.toString().trim()); } _defaultParallel = Runtime.getRuntime().availableProcessors() / 2; } return _defaultParallel; } public static String getResourceContents(String resourcePath) { try ( BufferedReader reader = new BufferedReader(new InputStreamReader(GlobalBuildInfoPlugin.class.getResourceAsStream(resourcePath))) ) { StringBuilder b = new StringBuilder(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (b.length() != 0) { b.append('\n'); } b.append(line); } return b.toString(); } catch (IOException e) { throw new UncheckedIOException("Error trying to read classpath resource: " + resourcePath, e); } } private static class ErrorTraceMetadataDetector implements JvmMetadataDetector { private final JvmMetadataDetector delegate; ErrorTraceMetadataDetector(JvmMetadataDetector delegate) { this.delegate = delegate; } @Override public JvmInstallationMetadata getMetadata(File file) { JvmInstallationMetadata metadata = delegate.getMetadata(file); if(metadata instanceof JvmInstallationMetadata.FailureInstallationMetadata) { throw new GradleException("Jvm Metadata cannot be resolved for " + metadata.getJavaHome().toString()); } return metadata; } } }
package gov.nih.nci.cagrid.dorian.gridca.common; import gov.nih.nci.cagrid.common.FaultUtil; import gov.nih.nci.cagrid.gridca.common.CRLEntry; import gov.nih.nci.cagrid.gridca.common.CertUtil; import gov.nih.nci.cagrid.gridca.common.KeyUtil; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import org.bouncycastle.asn1.x509.CRLReason; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.jce.PKCS10CertificationRequest; /** * @author <A href="mailto:langella@bmi.osu.edu">Stephen Langella </A> * @author <A href="mailto:oster@bmi.osu.edu">Scott Oster </A> * @author <A href="mailto:hastings@bmi.osu.edu">Shannon Hastings </A> * @version $Id: ArgumentManagerTable.java,v 1.2 2004/10/15 16:35:16 langella * Exp $ */ public class TestCertUtil extends TestCase { public void testCreateCertificateSimpleCARoot() { try { InputStream certLocation = TestCase.class.getResourceAsStream(Constants.SIMPLECA_CACERT); InputStream keyLocation = TestCase.class.getResourceAsStream(Constants.SIMPLECA_CAKEY); String keyPassword = "gomets123"; X509Certificate[] certs = createCertificateSpecifyRootCA(certLocation, keyLocation, keyPassword, "John Doe"); assertEquals(2, certs.length); String rootSub = "O=caBIG,OU=Ohio State University,OU=Department of Biomedical Informatics,CN=caBIG Certificate Authority"; String issuedSub = "O=caBIG,OU=Ohio State University,OU=Department of Biomedical Informatics,CN=John Doe"; X509Certificate rootCert = certs[1]; X509Certificate issuedCert = certs[0]; checkCert(rootCert, rootSub, rootSub); checkCert(issuedCert, rootSub, issuedSub); checkWriteReadCertificate(rootCert); checkWriteReadCertificate(issuedCert); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } } public void testCreateCertificateDorianCARoot() { try { InputStream certLocation = TestCase.class.getResourceAsStream(Constants.BMI_CACERT); InputStream keyLocation = TestCase.class.getResourceAsStream(Constants.BMI_CAKEY); String keyPassword = "gomets123"; X509Certificate[] certs = createCertificateSpecifyRootCA(certLocation, keyLocation, keyPassword, "John Doe"); assertEquals(2, certs.length); String rootSub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=BMI Certificate Authority"; String issuedSub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=John Doe"; X509Certificate rootCert = certs[1]; X509Certificate issuedCert = certs[0]; checkCert(rootCert, rootSub, rootSub); checkCert(issuedCert, rootSub, issuedSub); checkWriteReadCertificate(rootCert); checkWriteReadCertificate(issuedCert); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } } public void testCreateCertificateNewDorianCARootCert() { try { KeyPair rootPair = KeyUtil.generateRSAKeyPair1024(); assertNotNull(rootPair); String rootSub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=Temp Certificate Authority"; X509Name rootSubject = new X509Name(rootSub); X509Certificate root = CertUtil.generateCACertificate(rootSubject, new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 500000000), rootPair); assertNotNull(root); String certLocation = "temp-cacert.pem"; String keyLocation = "temp-cakey.pem"; String keyPassword = "gomets123"; KeyUtil.writePrivateKey(rootPair.getPrivate(), new File(keyLocation), keyPassword); CertUtil.writeCertificate(root, new File(certLocation)); X509Certificate[] certs = createCertificateSpecifyRootCA(certLocation, keyLocation, keyPassword, "John Doe"); File f1 = new File(certLocation); f1.delete(); File f2 = new File(keyLocation); f2.delete(); assertEquals(2, certs.length); String issuedSub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=John Doe"; X509Certificate rootCert = certs[1]; X509Certificate issuedCert = certs[0]; checkCert(rootCert, rootSub, rootSub); checkCert(issuedCert, rootSub, issuedSub); checkWriteReadCertificate(rootCert); checkWriteReadCertificate(issuedCert); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } } public void testCreateCertificateExpiredRootCert() { try { KeyPair rootPair = KeyUtil.generateRSAKeyPair1024(); assertNotNull(rootPair); String rootSub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=Temp Certificate Authority"; X509Name rootSubject = new X509Name(rootSub); X509Certificate root = CertUtil.generateCACertificate(rootSubject, new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis()), rootPair); Thread.sleep(10); assertNotNull(root); String certLocation = "temp-cacert.pem"; String keyLocation = "temp-cakey.pem"; String keyPassword = "gomets123"; KeyUtil.writePrivateKey(rootPair.getPrivate(), new File(keyLocation), keyPassword); CertUtil.writeCertificate(root, new File(certLocation)); checkCert(root, rootSub, rootSub); checkWriteReadCertificate(root); try { createCertificateSpecifyRootCA(certLocation, keyLocation, keyPassword, "John Doe"); assertTrue(false); } catch (Exception e) { assertEquals("Root Certificate Expired.", e.getMessage()); } File f1 = new File(certLocation); f1.delete(); File f2 = new File(keyLocation); f2.delete(); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } } public void testCreateCertificateNotYetValidRootCert() { try { KeyPair rootPair = KeyUtil.generateRSAKeyPair1024(); assertNotNull(rootPair); String rootSub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=Temp Certificate Authority"; X509Name rootSubject = new X509Name(rootSub); X509Certificate root = CertUtil.generateCACertificate(rootSubject, new Date( System.currentTimeMillis() + 50000), new Date(System.currentTimeMillis() + 500000), rootPair); assertNotNull(root); String certLocation = "temp-cacert.pem"; String keyLocation = "temp-cakey.pem"; String keyPassword = "gomets123"; KeyUtil.writePrivateKey(rootPair.getPrivate(), new File(keyLocation), keyPassword); CertUtil.writeCertificate(root, new File(certLocation)); checkCert(root, rootSub, rootSub); checkWriteReadCertificate(root); try { createCertificateSpecifyRootCA(certLocation, keyLocation, keyPassword, "John Doe"); assertTrue(false); } catch (Exception e) { assertEquals("Root Certificate not yet valid.", e.getMessage()); } File f1 = new File(certLocation); f1.delete(); File f2 = new File(keyLocation); f2.delete(); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } } private void checkWriteReadCertificate(X509Certificate cert) throws Exception { String temp = "temp.pem"; CertUtil.writeCertificate(cert, new File(temp)); X509Certificate in = CertUtil.loadCertificate(new File(temp)); assertEquals(cert, in); File f = new File(temp); f.delete(); } private void checkCert(X509Certificate cert, String issuer, String subject) { assertEquals(subject, cert.getSubjectDN().toString()); assertEquals(issuer, cert.getIssuerDN().toString()); } public X509Certificate[] createCertificateSpecifyRootCA(String certLocation, String keyLocation, String keyPassword, String cn) throws Exception { return createCertificateSpecifyRootCA(getFileInputStream(certLocation), getFileInputStream(keyLocation), keyPassword, cn); } public X509Certificate[] createCertificateSpecifyRootCA(InputStream certLocation, InputStream keyLocation, String keyPassword, String cn) throws Exception { // Load a root certificate PrivateKey rootKey = KeyUtil.loadPrivateKey(keyLocation, keyPassword); assertNotNull(rootKey); X509Certificate rootCert = CertUtil.loadCertificate(certLocation); assertNotNull(rootCert); String rootSub = rootCert.getSubjectDN().toString(); Date now = new Date(System.currentTimeMillis()); if (now.after(rootCert.getNotAfter())) { throw new Exception("Root Certificate Expired."); } if (now.before(rootCert.getNotBefore())) { throw new Exception("Root Certificate not yet valid."); } // create the certification request KeyPair pair = KeyUtil.generateRSAKeyPair1024(); assertNotNull(pair); int index = rootSub.lastIndexOf(","); String sub = rootSub.substring(0, index) + ",CN=" + cn; PKCS10CertificationRequest request = CertUtil.generateCertficateRequest(sub, pair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1); } X509Certificate issuedCert = CertUtil.signCertificateRequest(request, new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 500000000), rootCert, rootKey); assertNotNull(issuedCert); return new X509Certificate[]{issuedCert, rootCert}; } public void testCRL() { try { String rootSub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=TestCA"; String user1Sub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=John Doe"; String user2Sub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=Jane Doe"; String user3Sub = "O=Ohio State University,OU=BMI,OU=MSCL,CN=Tom Doe"; KeyPair rootKeys = KeyUtil.generateRSAKeyPair512(); assertNotNull(rootKeys); Calendar c = new GregorianCalendar(); Date now = c.getTime(); c.add(Calendar.YEAR, 1); Date end = c.getTime(); X509Certificate cacert = CertUtil.generateCACertificate(new X509Name(rootSub), now, end, rootKeys); checkCert(cacert, rootSub, rootSub); checkWriteReadCertificate(cacert); KeyPair user1Keys = KeyUtil.generateRSAKeyPair512(); assertNotNull(user1Keys); X509Certificate user1 = CertUtil.generateCertificate(new X509Name(user1Sub), now, end, user1Keys .getPublic(), cacert, rootKeys.getPrivate()); checkCert(user1, rootSub, user1Sub); checkWriteReadCertificate(user1); KeyPair user2Keys = KeyUtil.generateRSAKeyPair512(); assertNotNull(user2Keys); X509Certificate user2 = CertUtil.generateCertificate(new X509Name(user2Sub), now, end, user2Keys .getPublic(), cacert, rootKeys.getPrivate()); checkCert(user2, rootSub, user2Sub); checkWriteReadCertificate(user2); KeyPair user3Keys = KeyUtil.generateRSAKeyPair512(); assertNotNull(user3Keys); X509Certificate user3 = CertUtil.generateCertificate(new X509Name(user3Sub), now, end, user3Keys .getPublic(), cacert, rootKeys.getPrivate()); checkCert(user3, rootSub, user3Sub); checkWriteReadCertificate(user3); CRLEntry[] crls = new CRLEntry[2]; crls[0] = new CRLEntry(user1.getSerialNumber(), CRLReason.PRIVILEGE_WITHDRAWN); crls[1] = new CRLEntry(user3.getSerialNumber(), CRLReason.PRIVILEGE_WITHDRAWN); X509CRL crl = CertUtil.createCRL(cacert, rootKeys.getPrivate(), crls, cacert.getNotAfter()); assertNotNull(crl); // Test validity of CRL crl.verify(cacert.getPublicKey()); try { crl.verify(user1.getPublicKey()); fail("CRL verified against invalid certificate"); } catch (Exception ex) { } assertTrue(crl.isRevoked(user1)); assertTrue(!crl.isRevoked(user2)); assertTrue(crl.isRevoked(user3)); // Test validity after reading writing to string String crlStr = CertUtil.writeCRL(crl); X509CRL crl2 = CertUtil.loadCRL(crlStr); assertEquals(crl, crl2); crl2.verify(cacert.getPublicKey()); try { crl2.verify(user1.getPublicKey()); fail("CRL verified against invalid certificate"); } catch (Exception ex) { } assertTrue(crl2.isRevoked(user1)); assertTrue(!crl2.isRevoked(user2)); assertTrue(crl2.isRevoked(user3)); // Test validity after reading writing to file File f = new File("temp-crl.pem"); CertUtil.writeCRL(crl,f); X509CRL crl3 = CertUtil.loadCRL(f); assertEquals(crl, crl3); crl3.verify(cacert.getPublicKey()); try { crl3.verify(user1.getPublicKey()); fail("CRL verified against invalid certificate"); } catch (Exception ex) { } assertTrue(crl3.isRevoked(user1)); assertTrue(!crl3.isRevoked(user2)); assertTrue(crl3.isRevoked(user3)); f.delete(); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } } private static FileInputStream getFileInputStream(String file) throws Exception { return new FileInputStream(new File(file)); } }
package com.ForgeEssentials.chat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.TreeSet; import java.util.regex.Matcher; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.packet.NetHandler; import net.minecraft.network.packet.Packet3Chat; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.ServerChatEvent; import com.ForgeEssentials.core.PlayerInfo; import com.ForgeEssentials.permission.Group; import com.ForgeEssentials.permission.APIHelper; import com.ForgeEssentials.permission.SqlHelper; import com.ForgeEssentials.permission.Zone; import com.ForgeEssentials.permission.ZoneManager; import com.ForgeEssentials.permission.query.PermQueryPlayer; import com.ForgeEssentials.util.FEChatFormatCodes; import com.ForgeEssentials.util.FunctionHelper; import com.ForgeEssentials.util.OutputHandler; import com.ForgeEssentials.util.AreaSelector.Point; import cpw.mods.fml.common.network.IChatListener; public class Chat implements IChatListener { public static List<String> bannedWords = new ArrayList<String>(); public static boolean censor; @ForgeSubscribe public void chatEvent(ServerChatEvent event) { /* * Mute? */ if (event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).getBoolean("mute")) { event.setCanceled(true); event.player.sendChatToPlayer("You are muted."); return; } String message = event.message; String nickname = event.username; //Perhaps add option to completely remove message? /*if (censor && remove) { event.setCanceled(true); event.player.sendChatToPlayer("Such language is not tolerated."); return; }*/ if (censor) { for (String word : bannedWords) { message = replaceAllIgnoreCase(message, word, " } } /* * Nickname */ if (event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).hasKey("nickname")) { nickname = event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).getString("nickname"); } /* * Colorize! */ if (event.message.contains("&")) { if (APIHelper.checkPermAllowed(new PermQueryPlayer(event.player, "ForgeEssentials.chat.usecolor"))) { message = FunctionHelper.formatColors(event.message); } } String rank = ""; String zoneID = ""; String gPrefix = ""; String gSuffix = ""; PlayerInfo info = PlayerInfo.getPlayerInfo(event.player); String playerPrefix = info.prefix == null ? "" : FunctionHelper.formatColors(info.prefix).trim(); String playerSuffix = info.suffix == null ? "" : FunctionHelper.formatColors(info.suffix).trim(); Zone zone = ZoneManager.getWhichZoneIn(new Point(event.player), event.player.worldObj); zoneID = zone.getZoneName(); // Group stuff!!! DO NOT TOUCH!!! { rank = getGroupRankString(event.username); gPrefix = getGroupPrefixString(event.username); gPrefix = FunctionHelper.formatColors(gPrefix).trim(); gSuffix = getGroupSuffixString(event.username); gSuffix = FunctionHelper.formatColors(gSuffix).trim(); } //It may be beneficial to make this a public function. -RlonRyan String format = ConfigChat.chatFormat; format = ConfigChat.chatFormat == null || ConfigChat.chatFormat.trim().isEmpty() ? "<%username>%message" : ConfigChat.chatFormat; // replace group, zone, and rank format = replaceAllIgnoreCase(format, "%rank", rank); format = replaceAllIgnoreCase(format, "%zone", zoneID); format = replaceAllIgnoreCase(format, "%groupPrefix", gPrefix); format = replaceAllIgnoreCase(format, "%groupSuffix", gSuffix); // replace colors format = replaceAllIgnoreCase(format, "%red", FEChatFormatCodes.RED.toString()); format = replaceAllIgnoreCase(format, "%yellow", FEChatFormatCodes.YELLOW.toString()); format = replaceAllIgnoreCase(format, "%black", FEChatFormatCodes.BLACK.toString()); format = replaceAllIgnoreCase(format, "%darkblue", FEChatFormatCodes.DARKBLUE.toString()); format = replaceAllIgnoreCase(format, "%darkgreen", FEChatFormatCodes.DARKGREEN.toString()); format = replaceAllIgnoreCase(format, "%darkaqua", FEChatFormatCodes.DARKAQUA.toString()); format = replaceAllIgnoreCase(format, "%darkred", FEChatFormatCodes.DARKRED.toString()); format = replaceAllIgnoreCase(format, "%purple", FEChatFormatCodes.PURPLE.toString()); format = replaceAllIgnoreCase(format, "%gold", FEChatFormatCodes.GOLD.toString()); format = replaceAllIgnoreCase(format, "%grey", FEChatFormatCodes.GREY.toString()); format = replaceAllIgnoreCase(format, "%darkgrey", FEChatFormatCodes.DARKGREY.toString()); format = replaceAllIgnoreCase(format, "%indigo", FEChatFormatCodes.INDIGO.toString()); format = replaceAllIgnoreCase(format, "%green", FEChatFormatCodes.GREEN.toString()); format = replaceAllIgnoreCase(format, "%aqua", FEChatFormatCodes.AQUA.toString()); format = replaceAllIgnoreCase(format, "%pink", FEChatFormatCodes.PINK.toString()); format = replaceAllIgnoreCase(format, "%white", FEChatFormatCodes.WHITE.toString()); // replace MC formating format = replaceAllIgnoreCase(format, "%random", FEChatFormatCodes.RANDOM.toString()); format = replaceAllIgnoreCase(format, "%bold", FEChatFormatCodes.BOLD.toString()); format = replaceAllIgnoreCase(format, "%strike", FEChatFormatCodes.STRIKE.toString()); format = replaceAllIgnoreCase(format, "%underline", FEChatFormatCodes.UNDERLINE.toString()); format = replaceAllIgnoreCase(format, "%italics", FEChatFormatCodes.ITALICS.toString()); format = replaceAllIgnoreCase(format, "%reset", FEChatFormatCodes.RESET.toString()); // random nice things... format = replaceAllIgnoreCase(format, "%health", "" + event.player.getHealth()); // essentials format = replaceAllIgnoreCase(format, "%playerPrefix", playerPrefix); format = replaceAllIgnoreCase(format, "%playerSuffix", playerSuffix); format = replaceAllIgnoreCase(format, "%username", nickname); format = format.replace("%message", message); // finally make it the chat line. event.line = format; } @Override public Packet3Chat serverChat(NetHandler handler, Packet3Chat message) { return message; } @Override public Packet3Chat clientChat(NetHandler handler, Packet3Chat message) { return message; } private String replaceAllIgnoreCase(String text, String search, String replacement) { if (search.equals(replacement)) { return text; } StringBuilder buffer = new StringBuilder(text); String lowerSearch = search.toLowerCase(); int i = 0; int prev = 0; while ((i = buffer.toString().toLowerCase().indexOf(lowerSearch, prev)) > -1) { buffer.replace(i, i + search.length(), replacement); prev = i + replacement.length(); } return buffer.toString(); } private String getGroupRankString(String username) { Matcher match = ConfigChat.groupRegex.matcher(ConfigChat.groupRankFormat); ArrayList<TreeSet<Group>> list = getGroupsList(match, username); String end = ""; StringBuilder temp = new StringBuilder(); for (TreeSet<Group> set : list) { for (Group g: set) temp.append(g.name); end = match.replaceFirst(temp.toString()); temp = new StringBuilder(); } return end; } private String getGroupPrefixString(String username) { Matcher match = ConfigChat.groupRegex.matcher(ConfigChat.groupPrefixFormat); ArrayList<TreeSet<Group>> list = getGroupsList(match, username); String end = ""; StringBuilder temp = new StringBuilder(); for (TreeSet<Group> set : list) { for (Group g: set) temp.insert(0, g.prefix); end = match.replaceFirst(temp.toString()); temp = new StringBuilder(); } return end; } private String getGroupSuffixString(String username) { Matcher match = ConfigChat.groupRegex.matcher(ConfigChat.groupSuffixFormat); ArrayList<TreeSet<Group>> list = getGroupsList(match, username); String end = ""; StringBuilder temp = new StringBuilder(); for (TreeSet<Group> set : list) { for (Group g: set) temp.append(g.suffix); end = match.replaceFirst(temp.toString()); temp = new StringBuilder(); } return end; } private ArrayList<TreeSet<Group>> getGroupsList(Matcher match, String username) { ArrayList<TreeSet<Group>> list = new ArrayList<TreeSet<Group>>(); String whole; String[] p; TreeSet<Group> set; while (match.find()) { whole = match.group(); whole = whole.replaceAll("\\{", "").replaceAll("\\}", ""); p = whole.split("\\<\\:\\>", 2); if (p[0].equalsIgnoreCase("...")) p[0] = null; if (p[1].equalsIgnoreCase("...")) p[1] = null; set = SqlHelper.getGroupsForChat(p[0], p[1], username); if (set != null) list.add(set); } list = removeDuplicates(list); return list; } private ArrayList<TreeSet<Group>> removeDuplicates(ArrayList<TreeSet<Group>> list) { HashSet<Group> used = new HashSet<Group>(); for (TreeSet set: list) { for (Group g : used) set.remove(g); // add all the remaining... used.addAll(set); } return list; } }
package org.jgroups.tests; import org.jgroups.Channel; import org.jgroups.Global; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.util.Util; import org.testng.annotations.Test; import java.io.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * Tests correct state transfer while other members continue sending messages to the group * @author Bela Ban * @version $Id: StateTransferTest.java,v 1.35 2009/10/01 21:09:55 vlada Exp $ */ @Test(groups=Global.STACK_DEPENDENT,sequential=false) public class StateTransferTest extends ChannelTestBase { static final int MSG_SEND_COUNT=5000; static final String[] names= { "A", "B", "C", "D"}; static final int APP_COUNT=names.length; @Test public void testStateTransferFromSelfWithRegularChannel() throws Exception { Channel ch=createChannel(true); ch.connect("StateTransferTest"); try { boolean rc=ch.getState(null, 2000); assert !rc : "getState() on singleton should return false"; } finally { ch.close(); } } @Test public void testStateTransferWhileSending() throws Exception { StateTransferApplication[] apps=new StateTransferApplication[APP_COUNT]; try { Semaphore semaphore=new Semaphore(APP_COUNT); semaphore.acquire(APP_COUNT); int from=0, to=MSG_SEND_COUNT; for(int i=0;i < apps.length;i++) { if(i == 0) apps[i]=new StateTransferApplication(semaphore, names[i], from, to); else apps[i]=new StateTransferApplication((JChannel)apps[0].getChannel(), semaphore, names[i], from, to); from+=MSG_SEND_COUNT; to+=MSG_SEND_COUNT; } for(int i=0;i < apps.length;i++) { StateTransferApplication app=apps[i]; app.start(); semaphore.release(); //avoid merge Util.sleep(3000); } // Make sure everyone is in sync Channel[] tmp=new Channel[apps.length]; for(int i=0; i < apps.length; i++) tmp[i]=apps[i].getChannel(); Util.blockUntilViewsReceived(60000, 1000, tmp); // Reacquire the semaphore tickets; when we have them all // we know the threads are done boolean acquired=semaphore.tryAcquire(apps.length, 30, TimeUnit.SECONDS); if(!acquired) { log.warn("Most likely a bug, analyse the stack below:"); log.warn(Util.dumpThreads()); } // Sleep to ensure async messages arrive System.out.println("Waiting for all channels to have received the " + MSG_SEND_COUNT * APP_COUNT + " messages:"); long end_time=System.currentTimeMillis() + 40000L; while(System.currentTimeMillis() < end_time) { boolean terminate=true; for(StateTransferApplication app: apps) { Map map=app.getMap(); if(map.size() != MSG_SEND_COUNT * APP_COUNT) { terminate=false; break; } } if(terminate) break; else Util.sleep(500); } // have we received all and the correct messages? System.out.println("++++++++++++++++++++++++++++++++++++++"); for(int i=0;i < apps.length;i++) { StateTransferApplication w=apps[i]; Map m=w.getMap(); log.info("map has " + m.size() + " elements"); assert m.size() == MSG_SEND_COUNT * APP_COUNT; } System.out.println("++++++++++++++++++++++++++++++++++++++"); Set keys=apps[0].getMap().keySet(); for(int i=0;i < apps.length;i++) { StateTransferApplication app=apps[i]; Map m=app.getMap(); Set s=m.keySet(); assert keys.equals(s); } } finally { for(StateTransferApplication app: apps) app.getChannel().setReceiver(null); for(StateTransferApplication app: apps) app.cleanup(); } } protected class StateTransferApplication extends PushChannelApplicationWithSemaphore { private final Map<Object,Object> map=new HashMap<Object,Object>(MSG_SEND_COUNT * APP_COUNT); private int from, to; public StateTransferApplication(Semaphore semaphore, String name, int from, int to) throws Exception { super(name, semaphore); this.from=from; this.to=to; } public StateTransferApplication(JChannel copySource,Semaphore semaphore, String name, int from, int to) throws Exception { super(copySource,name, semaphore); this.from=from; this.to=to; } public Map<Object,Object> getMap() { synchronized(map) { return Collections.unmodifiableMap(map); } } public void receive(Message msg) { Object[] data=(Object[])msg.getObject(); int num_received=0; boolean changed=false; synchronized(map) { int tmp_size=map.size(); map.put(data[0], data[1]); num_received=map.size(); changed=tmp_size != num_received; } if(changed && num_received % 1000 == 0) log.info(channel.getAddress() + ": received " + num_received); // are we done? if(num_received >= MSG_SEND_COUNT * APP_COUNT) semaphore.release(); } public byte[] getState() { synchronized(map) { try { return Util.objectToByteBuffer(map); } catch(Exception e) { e.printStackTrace(); } } return null; } @SuppressWarnings("unchecked") public void setState(byte[] state) { synchronized(map) { try { Map<Object,Object> tmp=(Map<Object,Object>)Util.objectFromByteBuffer(state); map.putAll(tmp); log.info(channel.getAddress() + ": received state, map has " + map.size() + " elements"); } catch(Exception e) { e.printStackTrace(); } } } public void getState(OutputStream ostream) { synchronized(map) { try { ObjectOutputStream out=new ObjectOutputStream(ostream); out.writeObject(map); out.close(); } catch(IOException e) { e.printStackTrace(); } } } @SuppressWarnings("unchecked") public void setState(InputStream istream) { synchronized(map) { try { ObjectInputStream in=new ObjectInputStream(istream); Map<Object,Object> tmp=(Map<Object,Object>)in.readObject(); Util.close(in); map.putAll(tmp); log.info(channel.getAddress() + ": received state, map has " + map.size() + " elements"); } catch(Exception e) { e.printStackTrace(); } } } public void run() { boolean acquired=false; try { acquired=semaphore.tryAcquire(60000L, TimeUnit.MILLISECONDS); if(!acquired) { throw new Exception(channel.getAddress() + " cannot acquire semaphore"); } useChannel(); } catch(Exception e) { log.error(channel.getAddress() + ": " + e.getLocalizedMessage(), e); exception=e; } } protected void useChannel() throws Exception { System.out.println(channel.getName() + ": connecting and fetching the state"); channel.connect("StateTransferTest", null, null, 30000); System.out.println(channel.getName() + ": state transfer is done"); Object[] data=new Object[2]; for(int i=from; i < to; i++) { data[0]=new Integer(i); data[1]="Value try { channel.send(null, null, data); if(i % 100 == 0) Util.sleep(50); if(i % 1000 == 0) log.info(channel.getAddress() + ": sent " + i); } catch(Exception e) { e.printStackTrace(); break; } } } } }
package org.jfree.chart.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.annotations.junit.AnnotationsPackageTests; import org.jfree.chart.axis.junit.AxisPackageTests; import org.jfree.chart.block.junit.BlockPackageTests; import org.jfree.chart.entity.junit.EntityPackageTests; import org.jfree.chart.labels.junit.LabelsPackageTests; import org.jfree.chart.needle.junit.NeedlePackageTests; import org.jfree.chart.plot.junit.PlotPackageTests; import org.jfree.chart.renderer.category.junit.RendererCategoryPackageTests; import org.jfree.chart.renderer.junit.RendererPackageTests; import org.jfree.chart.renderer.xy.junit.RendererXYPackageTests; import org.jfree.chart.title.junit.TitlePackageTests; import org.jfree.chart.urls.junit.UrlsPackageTests; import org.jfree.chart.util.junit.UtilPackageTests; import org.jfree.data.category.junit.DataCategoryPackageTests; import org.jfree.data.gantt.junit.DataGanttPackageTests; import org.jfree.data.junit.DataPackageTests; import org.jfree.data.statistics.junit.DataStatisticsPackageTests; import org.jfree.data.time.junit.DataTimePackageTests; import org.jfree.data.time.ohlc.junit.OHLCPackageTests; import org.jfree.data.xy.junit.DataXYPackageTests; public class JFreeChartTestSuite extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return The test suite. */ public static Test suite() { TestSuite suite = new TestSuite("JFreeChart"); suite.addTest(ChartPackageTests.suite()); suite.addTest(AnnotationsPackageTests.suite()); suite.addTest(AxisPackageTests.suite()); suite.addTest(BlockPackageTests.suite()); suite.addTest(EntityPackageTests.suite()); suite.addTest(LabelsPackageTests.suite()); suite.addTest(NeedlePackageTests.suite()); suite.addTest(PlotPackageTests.suite()); suite.addTest(RendererPackageTests.suite()); suite.addTest(RendererCategoryPackageTests.suite()); suite.addTest(RendererXYPackageTests.suite()); suite.addTest(TitlePackageTests.suite()); suite.addTest(UrlsPackageTests.suite()); suite.addTest(UtilPackageTests.suite()); suite.addTest(DataPackageTests.suite()); suite.addTest(DataCategoryPackageTests.suite()); suite.addTest(DataStatisticsPackageTests.suite()); suite.addTest(DataTimePackageTests.suite()); suite.addTest(OHLCPackageTests.suite()); suite.addTest(DataXYPackageTests.suite()); suite.addTest(DataGanttPackageTests.suite()); return suite; } /** * Runs the test suite using JUnit's text-based runner. * * @param args ignored. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
package cgeo.geocaching.files; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase; import cgeo.geocaching.test.R; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.Log; import android.net.Uri; import android.os.Message; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { private TestHandler importStepHandler = new TestHandler(); private TestHandler progressHandler = new TestHandler(); private int listId; private File tempDir; private boolean importCacheStaticMaps; private boolean importWpStaticMaps; public void testGetWaypointsFileNameForGpxFile() throws IOException { String[] gpxFiles = new String[] { "1234567.gpx", "1.gpx", "1234567.9.gpx", "1234567.GPX", "gpx.gpx.gpx", ".gpx", "1234567_query.gpx", "123-4.gpx", "123(5).gpx" }; String[] wptsFiles = new String[] { "1234567-wpts.gpx", "1-wpts.gpx", "1234567.9-wpts.gpx", "1234567-wpts.GPX", "gpx.gpx-wpts.gpx", "-wpts.gpx", "1234567_query-wpts.gpx", "123-wpts-4.gpx", "123-wpts(5).gpx" }; for (int i = 0; i < gpxFiles.length; i++) { String gpxFileName = gpxFiles[i]; String wptsFileName = wptsFiles[i]; File gpx = new File(tempDir, gpxFileName); File wpts = new File(tempDir, wptsFileName); // the files need to exist - we create them assertTrue(gpx.createNewFile()); assertTrue(wpts.createNewFile()); // the "real" method check assertEquals(wptsFileName, GPXImporter.getWaypointsFileNameForGpxFile(gpx)); // they also need to be deleted, because of case sensitive tests that will not work correct on case insensitive file systems gpx.delete(); wpts.delete(); } File gpx1 = new File(tempDir, "abc.gpx"); assertNull(GPXImporter.getWaypointsFileNameForGpxFile(gpx1)); } public void testImportGpx() throws IOException { File gc31j2h = new File(tempDir, "gc31j2h.gpx"); copyResourceToFile(R.raw.gc31j2h, gc31j2h); GPXImporter.ImportGpxFileThread importThread = new GPXImporter.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler); runImportThread(importThread); assertEquals(5, importStepHandler.messages.size()); Iterator<Message> iMsg = importStepHandler.messages.iterator(); assertEquals(GPXImporter.IMPORT_STEP_START, iMsg.next().what); assertEquals(GPXImporter.IMPORT_STEP_READ_FILE, iMsg.next().what); assertEquals(GPXImporter.IMPORT_STEP_STORE_CACHES, iMsg.next().what); assertEquals(GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, iMsg.next().what); assertEquals(GPXImporter.IMPORT_STEP_FINISHED, iMsg.next().what); SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj; assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes())); cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); // can't assert, for whatever reason the waypoints are remembered in DB // assertNull(cache.waypoints); } private void runImportThread(GPXImporter.ImportThread importThread) { importThread.start(); try { importThread.join(); } catch (InterruptedException e) { Log.e("GPXImporterTest.runImportThread", e); } importStepHandler.waitForCompletion(); } public void testImportGpxWithWaypoints() throws IOException { File gc31j2h = new File(tempDir, "gc31j2h.gpx"); copyResourceToFile(R.raw.gc31j2h, gc31j2h); copyResourceToFile(R.raw.gc31j2h_wpts, new File(tempDir, "gc31j2h-wpts.gpx")); GPXImporter.ImportGpxFileThread importThread = new GPXImporter.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_READ_WPT_FILE, GPXImporter.IMPORT_STEP_STORE_CACHES, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); SearchResult search = (SearchResult) importStepHandler.messages.get(5).obj; assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes())); cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals(2, cache.getWaypoints().size()); } public void testImportGpxWithLowercaseNames() throws IOException { final File tc2012 = new File(tempDir, "tc2012.gpx"); copyResourceToFile(R.raw.tc2012, tc2012); final GPXImporter.ImportGpxFileThread importThread = new GPXImporter.ImportGpxFileThread(tc2012, listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_STORE_CACHES, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); final cgCache cache = cgeoapplication.getInstance().loadCache("AID1", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals("First Aid Station #1", cache.getName()); } private void assertImportStepMessages(int... importSteps) { for (int i = 0; i < Math.min(importSteps.length, importStepHandler.messages.size()); i++) { assertEquals(importSteps[i], importStepHandler.messages.get(i).what); } assertEquals(importSteps.length, importStepHandler.messages.size()); } public void testImportLoc() throws IOException { File oc5952 = new File(tempDir, "oc5952.loc"); copyResourceToFile(R.raw.oc5952_loc, oc5952); GPXImporter.ImportLocFileThread importThread = new GPXImporter.ImportLocFileThread(oc5952, listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_STORE_CACHES, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj; assertEquals(Collections.singletonList("OC5952"), new ArrayList<String>(search.getGeocodes())); cgCache cache = cgeoapplication.getInstance().loadCache("OC5952", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); } private static void assertCacheProperties(cgCache cache) { assertNotNull(cache); assertFalse(cache.getLocation().startsWith(",")); assertTrue(cache.isReliableLatLon()); } public void testImportGpxError() throws IOException { File gc31j2h = new File(tempDir, "gc31j2h.gpx"); copyResourceToFile(R.raw.gc31j2h_err, gc31j2h); GPXImporter.ImportGpxFileThread importThread = new GPXImporter.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_FINISHED_WITH_ERROR); } public void testImportGpxCancel() throws IOException { File gc31j2h = new File(tempDir, "gc31j2h.gpx"); copyResourceToFile(R.raw.gc31j2h, gc31j2h); progressHandler.cancel(); GPXImporter.ImportGpxFileThread importThread = new GPXImporter.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_CANCELED); } public void testImportGpxAttachment() { Uri uri = Uri.parse("android.resource://cgeo.geocaching.test/raw/gc31j2h"); GPXImporter.ImportGpxAttachmentThread importThread = new GPXImporter.ImportGpxAttachmentThread(uri, getInstrumentation().getContext().getContentResolver(), listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_STORE_CACHES, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj; assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes())); cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); // can't assert, for whatever reason the waypoints are remembered in DB // assertNull(cache.waypoints); } public void testImportGpxZip() throws IOException { File pq7545915 = new File(tempDir, "7545915.zip"); copyResourceToFile(R.raw.pq7545915, pq7545915); GPXImporter.ImportGpxZipFileThread importThread = new GPXImporter.ImportGpxZipFileThread(pq7545915, listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_READ_WPT_FILE, GPXImporter.IMPORT_STEP_STORE_CACHES, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); SearchResult search = (SearchResult) importStepHandler.messages.get(5).obj; assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes())); cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals(1, cache.getWaypoints().size()); // this is the original pocket query result without test waypoint } public void testImportGpxZipErr() throws IOException { File pqError = new File(tempDir, "pq_error.zip"); copyResourceToFile(R.raw.pq_error, pqError); GPXImporter.ImportGpxZipFileThread importThread = new GPXImporter.ImportGpxZipFileThread(pqError, listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_FINISHED_WITH_ERROR); } public void testImportGpxZipAttachment() { Uri uri = Uri.parse("android.resource://cgeo.geocaching.test/raw/pq7545915"); GPXImporter.ImportGpxZipAttachmentThread importThread = new GPXImporter.ImportGpxZipAttachmentThread(uri, getInstrumentation().getContext().getContentResolver(), listId, importStepHandler, progressHandler); runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_READ_WPT_FILE, GPXImporter.IMPORT_STEP_STORE_CACHES, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); SearchResult search = (SearchResult) importStepHandler.messages.get(5).obj; assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes())); cgCache cache = cgeoapplication.getInstance().loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals(1, cache.getWaypoints().size()); // this is the original pocket query result without test waypoint } static class TestHandler extends CancellableHandler { private final List<Message> messages = new ArrayList<Message>(); private long lastMessage = System.currentTimeMillis(); @Override public synchronized void handleRegularMessage(Message msg) { final Message msg1 = Message.obtain(); msg1.copyFrom(msg); messages.add(msg1); lastMessage = System.currentTimeMillis(); notify(); } public synchronized void waitForCompletion(final long milliseconds, final int maxMessages) { try { while (System.currentTimeMillis() - lastMessage <= milliseconds && messages.size() <= maxMessages) { wait(milliseconds); } } catch (InterruptedException e) { // intentionally left blank } } public void waitForCompletion() { // Use reasonable defaults waitForCompletion(1000, 10); } } @Override protected void setUp() throws Exception { super.setUp(); tempDir = new File(System.getProperty("java.io.tmpdir"), "cgeogpxesTest"); tempDir.mkdir(); // workaround to get storage initialized cgeoapplication.getInstance().getAllHistoricCachesCount(); listId = cgeoapplication.getInstance().createList("cgeogpxesTest"); importCacheStaticMaps = Settings.isStoreOfflineMaps(); Settings.setStoreOfflineMaps(true); importWpStaticMaps = Settings.isStoreOfflineWpMaps(); Settings.setStoreOfflineWpMaps(true); } @Override protected void tearDown() throws Exception { cgeoapplication.getInstance().removeList(listId); deleteDirectory(tempDir); Settings.setStoreOfflineMaps(importCacheStaticMaps); Settings.setStoreOfflineWpMaps(importWpStaticMaps); super.tearDown(); } private static void deleteDirectory(File dir) { for (File f : dir.listFiles()) { if (f.isFile()) { f.delete(); } else if (f.isDirectory()) { deleteDirectory(f); } } dir.delete(); } }
package SimpleSocketTwimeClient; import org.agrona.concurrent.UnsafeBuffer; import sbe.*; import java.io.IOException; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; public class AbstractTwimeClient implements Runnable{ private MessageHeaderDecoder messageHeaderDecoder = new MessageHeaderDecoder(); protected long receivedSequenceNum = 0; protected long retransmissionCount = 0; private TwimeHeartBeatProcess heartBeatProcess = null; private long intervalMsec = 0; private WritableByteChannel outputChannel = null; private String userAccount = null; private String clientId = null; private long lastSendTime = 0; private int socketReadTimeoutMsec = 10000; private ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096); private UnsafeBuffer directBuffer = new UnsafeBuffer(byteBuffer); private int bufferOffset = 0; private int encodingLength = 0; private String hostAddress = null; private int connectionPort; //decoders private EstablishmentAckDecoder establishmentAckDecoder = new EstablishmentAckDecoder(); private EstablishmentRejectDecoder establishmentRejectDecoder = new EstablishmentRejectDecoder(); private SequenceDecoder sequenceDecoder = new SequenceDecoder(); private TerminateDecoder terminateDecoder = new TerminateDecoder(); private OrderMassCancelResponseDecoder orderMassCancelResponseDecoder = new OrderMassCancelResponseDecoder(); private SessionRejectDecoder sessionRejectDecoder = new SessionRejectDecoder(); private RetransmissionDecoder retransmissionDecoder = new RetransmissionDecoder(); private NewOrderRejectDecoder newOrderRejectDecoder = new NewOrderRejectDecoder(); private NewOrderSingleResponseDecoder newOrderSingleResponseDecoder = new NewOrderSingleResponseDecoder(); private OrderCancelResponseDecoder orderCancelResponseDecoder = new OrderCancelResponseDecoder(); private ExecutionSingleReportDecoder executionSingleReportDecoder = new ExecutionSingleReportDecoder(); private SystemEventDecoder systemEventDecoder = new SystemEventDecoder(); private EmptyBookDecoder emptyBookDecoder = new EmptyBookDecoder(); private OrderReplaceResponseDecoder orderReplaceResponseDecoder = new OrderReplaceResponseDecoder(); //encoders private MessageHeaderEncoder headerEncoder = new MessageHeaderEncoder(); private EstablishEncoder establishEncoder = new EstablishEncoder(); private RetransmitRequestEncoder retransmitRequestEncoder = new RetransmitRequestEncoder(); private OrderMassCancelRequestEncoder orderMassCancelRequestEncoder = new OrderMassCancelRequestEncoder(); private NewOrderSingleEncoder newOrderSingleEncoder = new NewOrderSingleEncoder(); private OrderCancelRequestEncoder orderCancelRequestEncoder = new OrderCancelRequestEncoder(); private OrderReplaceRequestEncoder orderReplaceRequestEncoder = new OrderReplaceRequestEncoder(); protected BigDecimal priceMultiplier = new BigDecimal(100000); private ReadSocketProcess readSocketProcess = null; @Override public void run() { SimpleSocketClient simpleSocketClient = new SimpleSocketClient(this.hostAddress, this.connectionPort); simpleSocketClient.doConnect(); if (simpleSocketClient.isConnected()){ try { outputChannel = Channels.newChannel(simpleSocketClient.getSocket().getOutputStream()); readSocketProcess = new ReadSocketProcess(simpleSocketClient.getSocket(), socketReadTimeoutMsec){ @Override protected void processMessage(int actualReaded) { super.processMessage(actualReaded); int currentOffset = 0; while(currentOffset < actualReaded) { currentOffset = AbstractTwimeClient.this.decodeMessage(unsafeBuffer, currentOffset); } } @Override protected void onStop() { super.onStop(); AbstractTwimeClient.this.stopHeartBeatProcess(); } }; Thread connectionThread = new Thread(readSocketProcess); connectionThread.start(); this.sendEstablish(); try { connectionThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } AbstractTwimeClient.this.stopHeartBeatProcess(); simpleSocketClient.doDisconnect(); } catch (IOException e) { e.printStackTrace(); } } } public void stopConnectionProcess(){ if (readSocketProcess != null && !readSocketProcess.isStopped()){ readSocketProcess.setStopped(true); } } private void initSender(int templateId, int blockLength){ bufferOffset = encodingLength = 0; byteBuffer.clear(); headerEncoder.wrap(directBuffer, bufferOffset) .blockLength(blockLength) .templateId(templateId) .schemaId(establishEncoder.sbeSchemaId()) .version(establishEncoder.sbeSchemaVersion()); bufferOffset += headerEncoder.encodedLength(); encodingLength += headerEncoder.encodedLength(); } public void sendNewOrderSingle(long clOrdId, int securityId, double price, long amount, int clOrdLinkId, TimeInForceEnum timeInForce, SideEnum side) throws IOException { initSender(newOrderSingleEncoder.sbeTemplateId(), newOrderSingleEncoder.sbeBlockLength()); newOrderSingleEncoder.wrap(directBuffer, bufferOffset); long longPrice = new BigDecimal(price).multiply(priceMultiplier).longValue(); newOrderSingleEncoder.price().mantissa(longPrice); newOrderSingleEncoder.account(userAccount).clOrdID(clOrdId).clOrdLinkID(clOrdLinkId).orderQty(amount).securityID(securityId).timeInForce(timeInForce).side(side).checkLimit(CheckLimitEnum.Check).expireDate(NewOrderSingleEncoder.expireDateNullValue()); encodingLength += newOrderSingleEncoder.encodedLength(); sendBuffer(encodingLength); } public void sendOrderMassCancelRequest(long clOrdId, int clOrdLinkID, int securityId, SecurityTypeEnum securityTypeEnum, SideEnum sideEnum, String securityGroup) throws IOException { initSender(orderMassCancelRequestEncoder.sbeTemplateId(), orderMassCancelRequestEncoder.sbeBlockLength()); orderMassCancelRequestEncoder.wrap(directBuffer, bufferOffset).account(userAccount).clOrdID(clOrdId).clOrdLinkID(clOrdLinkID).securityID(securityId).securityType(securityTypeEnum).side(sideEnum).securityGroup(securityGroup); encodingLength += orderMassCancelRequestEncoder.encodedLength(); sendBuffer(encodingLength); } public void sendOrderCancelRequest(long clOrdId, long orderId) throws IOException { initSender(orderCancelRequestEncoder.sbeTemplateId(), orderCancelRequestEncoder.sbeBlockLength()); orderCancelRequestEncoder.wrap(directBuffer, bufferOffset); orderCancelRequestEncoder.account(userAccount).clOrdID(clOrdId).orderID(orderId); encodingLength += orderCancelRequestEncoder.encodedLength(); sendBuffer(encodingLength); } public void sendOrderReplaceRequest(long clOrdId, long orderId, double newPrice, long newAmount, int clOrdLinkId, ModeEnum mode) throws IOException { initSender(orderReplaceRequestEncoder.sbeTemplateId(), orderReplaceRequestEncoder.sbeBlockLength()); orderReplaceRequestEncoder.wrap(directBuffer, bufferOffset); long longPrice = new BigDecimal(newPrice).multiply(priceMultiplier).longValue(); orderReplaceRequestEncoder.price().mantissa(longPrice); orderReplaceRequestEncoder.account(userAccount).clOrdID(clOrdId).orderID(orderId).orderQty(newAmount).clOrdLinkID(clOrdLinkId).mode(mode); encodingLength += orderReplaceRequestEncoder.encodedLength(); sendBuffer(encodingLength); } public void sendEstablish() throws IOException { if (outputChannel != null) { initSender(establishEncoder.sbeTemplateId(), establishEncoder.sbeBlockLength()); establishEncoder.wrap(directBuffer, bufferOffset).credentials(clientId).keepaliveInterval(intervalMsec).timestamp(System.currentTimeMillis()); encodingLength += establishEncoder.encodedLength(); sendBuffer(encodingLength); } } public void sendRetransmitRequest(long timestamp, long fromSeqNum, long count) throws IOException{ initSender(retransmitRequestEncoder.sbeTemplateId(), retransmitRequestEncoder.sbeBlockLength()); retransmitRequestEncoder.wrap(directBuffer, bufferOffset).timestamp(timestamp).fromSeqNo(fromSeqNum).count(count); encodingLength += retransmitRequestEncoder.encodedLength(); sendBuffer(encodingLength); } private void sendBuffer(int length) throws IOException { byteBuffer.limit(length); outputChannel.write(byteBuffer); lastSendTime = System.currentTimeMillis(); } private void increaseSequence(){ if (retransmissionCount > 0) { System.out.println(" retransmissionCount } receivedSequenceNum ++; } public synchronized int decodeMessage(UnsafeBuffer unsafeBuffer, int startOffset){ int bytesOffset = startOffset; messageHeaderDecoder.wrap(unsafeBuffer, bytesOffset); int templateId = messageHeaderDecoder.templateId(); int schemaId = messageHeaderDecoder.schemaId(); int version = messageHeaderDecoder.version(); int blockLength = messageHeaderDecoder.blockLength(); bytesOffset += messageHeaderDecoder.encodedLength(); if (templateId > 0 && version > 0) { if (SequenceDecoder.TEMPLATE_ID != templateId) { System.out.println(" <<<< AbstractTwimeClient decodeMessage, schemaId: " + schemaId + " |version: " + version + " |templateId: " + templateId + " |blockLength: " + blockLength + " |bytesOffset: " + bytesOffset); } switch (templateId) { case EstablishmentAckDecoder.TEMPLATE_ID: establishmentAckDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onEstablishmentAck(establishmentAckDecoder); break; case EstablishmentRejectDecoder.TEMPLATE_ID: establishmentRejectDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onEstablishmentReject(establishmentRejectDecoder); break; case SequenceDecoder.TEMPLATE_ID://heartbeat (sequence) sequenceDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onSequence(sequenceDecoder); break; case TerminateDecoder.TEMPLATE_ID: //terminate terminateDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onTerminate(terminateDecoder); break; case SessionRejectDecoder.TEMPLATE_ID: sessionRejectDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onSessionReject(sessionRejectDecoder); break; case RetransmissionDecoder.TEMPLATE_ID: retransmissionDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); retransmissionCount = retransmissionDecoder.count(); onRetransmission(retransmissionDecoder); break; case OrderMassCancelResponseDecoder.TEMPLATE_ID: orderMassCancelResponseDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onOrderMassCancelResponse(orderMassCancelResponseDecoder); increaseSequence(); break; case NewOrderRejectDecoder.TEMPLATE_ID: newOrderRejectDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onNewOrderReject(newOrderRejectDecoder); increaseSequence(); break; case NewOrderSingleResponseDecoder.TEMPLATE_ID: newOrderSingleResponseDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onNewOrderSingleResponse(newOrderSingleResponseDecoder); increaseSequence(); break; case OrderCancelResponseDecoder.TEMPLATE_ID: orderCancelResponseDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onOrderCancelResponse(orderCancelResponseDecoder); increaseSequence(); break; case ExecutionSingleReportDecoder.TEMPLATE_ID: executionSingleReportDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onExecutionSingleReport(executionSingleReportDecoder); increaseSequence(); break; case OrderReplaceRequestDecoder.TEMPLATE_ID: orderReplaceResponseDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onOrderReplaceResponse(orderReplaceResponseDecoder); increaseSequence(); break; case SystemEventDecoder.TEMPLATE_ID: systemEventDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onSystemEvent(systemEventDecoder); increaseSequence(); break; case EmptyBookDecoder.TEMPLATE_ID: emptyBookDecoder.wrap(unsafeBuffer, bytesOffset, blockLength, version); onEmptyBook(emptyBookDecoder); increaseSequence(); break; } bytesOffset += blockLength; } return bytesOffset; } protected void onEstablishmentAck(EstablishmentAckDecoder decoder){ if (heartBeatProcess == null) { heartBeatProcess = new TwimeHeartBeatProcess(outputChannel, intervalMsec); } new Thread(heartBeatProcess).start(); } protected void onTerminate(TerminateDecoder decoder){} protected void onOrderMassCancelResponse(OrderMassCancelResponseDecoder decoder){} protected void onSessionReject(SessionRejectDecoder decoder){} protected void onEstablishmentReject(EstablishmentRejectDecoder decoder){} protected void onSequence(SequenceDecoder decoder){} protected void onRetransmission(RetransmissionDecoder decoder){} protected void onNewOrderReject(NewOrderRejectDecoder decoder){} protected void onNewOrderSingleResponse(NewOrderSingleResponseDecoder decoder){} protected void onOrderCancelResponse(OrderCancelResponseDecoder decoder){} protected void onOrderReplaceResponse(OrderReplaceResponseDecoder decoder){} protected void onExecutionSingleReport(ExecutionSingleReportDecoder decoder){} protected void onSystemEvent(SystemEventDecoder decoder){} protected void onEmptyBook(EmptyBookDecoder decoder){} public TwimeHeartBeatProcess getHeartBeatProcess() { return heartBeatProcess; } public long getIntervalMsec() { return intervalMsec; } public AbstractTwimeClient setIntervalMsec(long intervalMsec) { this.intervalMsec = intervalMsec; return this; } public String getUserAccount() { return userAccount; } public AbstractTwimeClient setUserAccount(String userAccount) { this.userAccount = userAccount; return this; } public String getClientId() { return clientId; } public AbstractTwimeClient setClientId(String clientId) { this.clientId = clientId; return this; } public long getLastSendTime() { return lastSendTime; } public void stopHeartBeatProcess(){ if (this.getHeartBeatProcess() != null && !this.getHeartBeatProcess().isStopped()) { this.getHeartBeatProcess().setStopped(true); } } public long generateNewClientOrderId(){ return System.currentTimeMillis(); } public String getHostAddress() { return hostAddress; } public AbstractTwimeClient setHostAddress(String hostAddress) { this.hostAddress = hostAddress; return this; } public int getConnectionPort() { return connectionPort; } public AbstractTwimeClient setConnectionPort(int connectionPort) { this.connectionPort = connectionPort; return this; } public long getReceivedSequenceNum() { return receivedSequenceNum; } public AbstractTwimeClient setReceivedSequenceNum(long receivedSequenceNum) { this.receivedSequenceNum = receivedSequenceNum; return this; } public long getRetransmissionCount() { return retransmissionCount; } public int getSocketReadTimeoutMsec() { return socketReadTimeoutMsec; } public AbstractTwimeClient setSocketReadTimeoutMsec(int socketReadTimeoutMsec) { this.socketReadTimeoutMsec = socketReadTimeoutMsec; return this; } }
package arez.processor; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.lang.model.AnnotatedConstruct; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; final class ProcessorUtil { static final String SENTINEL_NAME = "<default>"; private ProcessorUtil() { } @Nonnull static List<TypeElement> getSuperTypes( @Nonnull final TypeElement element ) { final List<TypeElement> superTypes = new ArrayList<>(); enumerateSuperTypes( element, superTypes ); return superTypes; } private static void enumerateSuperTypes( @Nonnull final TypeElement element, @Nonnull final List<TypeElement> superTypes ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement(); superTypes.add( superclassElement ); enumerateSuperTypes( superclassElement, superTypes ); } for ( final TypeMirror interfaceType : element.getInterfaces() ) { final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement(); enumerateSuperTypes( interfaceElement, superTypes ); } } @Nonnull static PackageElement getPackageElement( @Nonnull final TypeElement element ) { Element enclosingElement = element.getEnclosingElement(); while ( null != enclosingElement ) { if ( enclosingElement instanceof PackageElement ) { return (PackageElement) enclosingElement; } enclosingElement = enclosingElement.getEnclosingElement(); } assert false; return null; } @Nonnull static List<TypeVariableName> getTypeArgumentsAsNames( @Nonnull final DeclaredType declaredType ) { final List<TypeVariableName> variables = new ArrayList<>(); for ( final TypeMirror argument : declaredType.getTypeArguments() ) { variables.add( TypeVariableName.get( (TypeVariable) argument ) ); } return variables; } @Nonnull static List<VariableElement> getFieldElements( @Nonnull final TypeElement element ) { final Map<String, VariableElement> methodMap = new LinkedHashMap<>(); enumerateFieldElements( element, methodMap ); return new ArrayList<>( methodMap.values() ); } private static void enumerateFieldElements( @Nonnull final TypeElement element, @Nonnull final Map<String, VariableElement> fields ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { enumerateFieldElements( (TypeElement) ( (DeclaredType) superclass ).asElement(), fields ); } for ( final Element member : element.getEnclosedElements() ) { if ( member.getKind() == ElementKind.FIELD ) { fields.put( member.getSimpleName().toString(), (VariableElement) member ); } } } @Nonnull static List<ExecutableElement> getMethods( @Nonnull final TypeElement element, @Nonnull final Elements elementUtils, @Nonnull final Types typeUtils ) { final Map<String, ArrayList<ExecutableElement>> methodMap = new LinkedHashMap<>(); enumerateMethods( element, elementUtils, typeUtils, element, methodMap ); return methodMap.values().stream().flatMap( Collection::stream ).collect( Collectors.toList() ); } private static void enumerateMethods( @Nonnull final TypeElement scope, @Nonnull final Elements elementUtils, @Nonnull final Types typeUtils, @Nonnull final TypeElement element, @Nonnull final Map<String, ArrayList<ExecutableElement>> methods ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement(); enumerateMethods( scope, elementUtils, typeUtils, superclassElement, methods ); } for ( final TypeMirror interfaceType : element.getInterfaces() ) { final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement(); enumerateMethods( scope, elementUtils, typeUtils, interfaceElement, methods ); } for ( final Element member : element.getEnclosedElements() ) { if ( member.getKind() == ElementKind.METHOD ) { final ExecutableElement method = (ExecutableElement) member; processMethod( elementUtils, typeUtils, scope, methods, method ); } } } private static void processMethod( @Nonnull final Elements elementUtils, @Nonnull final Types typeUtils, @Nonnull final TypeElement typeElement, @Nonnull final Map<String, ArrayList<ExecutableElement>> methods, @Nonnull final ExecutableElement method ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), method ); final String key = method.getSimpleName().toString(); final ArrayList<ExecutableElement> elements = methods.computeIfAbsent( key, k -> new ArrayList<>() ); boolean found = false; final int size = elements.size(); for ( int i = 0; i < size; i++ ) { final ExecutableElement executableElement = elements.get( i ); if ( method.equals( executableElement ) ) { found = true; break; } else if ( isSubsignature( typeUtils, typeElement, methodType, executableElement ) ) { if ( !isAbstractInterfaceMethod( method ) ) { elements.set( i, method ); } found = true; break; } else if ( elementUtils.overrides( method, executableElement, typeElement ) ) { elements.set( i, method ); found = true; break; } } if ( !found ) { elements.add( method ); } } private static boolean isAbstractInterfaceMethod( final @Nonnull ExecutableElement method ) { return method.getModifiers().contains( Modifier.ABSTRACT ) && ElementKind.INTERFACE == method.getEnclosingElement().getKind(); } private static boolean isSubsignature( @Nonnull final Types typeUtils, @Nonnull final TypeElement typeElement, @Nonnull final ExecutableType methodType, @Nonnull final ExecutableElement candidate ) { final ExecutableType candidateType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), candidate ); final boolean isEqual = methodType.equals( candidateType ); final boolean isSubsignature = typeUtils.isSubsignature( methodType, candidateType ); return isSubsignature || isEqual; } @Nonnull static List<ExecutableElement> getConstructors( @Nonnull final TypeElement element ) { return element.getEnclosedElements().stream(). filter( m -> m.getKind() == ElementKind.CONSTRUCTOR ). map( m -> (ExecutableElement) m ). collect( Collectors.toList() ); } static void copyAccessModifiers( @Nonnull final TypeElement element, @Nonnull final TypeSpec.Builder builder ) { if ( element.getModifiers().contains( Modifier.PUBLIC ) ) { builder.addModifiers( Modifier.PUBLIC ); } } static void copyAccessModifiers( @Nonnull final TypeElement element, @Nonnull final MethodSpec.Builder builder ) { if ( element.getModifiers().contains( Modifier.PUBLIC ) ) { builder.addModifiers( Modifier.PUBLIC ); } } static void copyAccessModifiers( @Nonnull final ExecutableElement element, @Nonnull final MethodSpec.Builder builder ) { if ( element.getModifiers().contains( Modifier.PUBLIC ) ) { builder.addModifiers( Modifier.PUBLIC ); } else if ( element.getModifiers().contains( Modifier.PROTECTED ) ) { builder.addModifiers( Modifier.PROTECTED ); } } static void copyWhitelistedAnnotations( @Nonnull final AnnotatedConstruct element, @Nonnull final MethodSpec.Builder builder ) { for ( final AnnotationMirror annotation : element.getAnnotationMirrors() ) { if ( shouldCopyAnnotation( annotation.getAnnotationType().toString() ) ) { builder.addAnnotation( AnnotationSpec.get( annotation ) ); } } } static void copyWhitelistedAnnotations( @Nonnull final AnnotatedConstruct element, @Nonnull final ParameterSpec.Builder builder ) { for ( final AnnotationMirror annotation : element.getAnnotationMirrors() ) { if ( shouldCopyAnnotation( annotation.getAnnotationType().toString() ) ) { builder.addAnnotation( AnnotationSpec.get( annotation ) ); } } } static void copyWhitelistedAnnotations( @Nonnull final AnnotatedConstruct element, @Nonnull final FieldSpec.Builder builder ) { for ( final AnnotationMirror annotation : element.getAnnotationMirrors() ) { if ( shouldCopyAnnotation( annotation.getAnnotationType().toString() ) ) { builder.addAnnotation( AnnotationSpec.get( annotation ) ); } } } private static boolean shouldCopyAnnotation( @Nonnull final String classname ) { return Constants.NONNULL_ANNOTATION_CLASSNAME.equals( classname ) || Constants.NULLABLE_ANNOTATION_CLASSNAME.equals( classname ) || Constants.DEPRECATED_ANNOTATION_CLASSNAME.equals( classname ); } static void copyExceptions( @Nonnull final ExecutableType method, @Nonnull final MethodSpec.Builder builder ) { for ( final TypeMirror thrownType : method.getThrownTypes() ) { builder.addException( TypeName.get( thrownType ) ); } } static void copyTypeParameters( @Nonnull final ExecutableType action, @Nonnull final MethodSpec.Builder builder ) { for ( final TypeVariable typeParameter : action.getTypeVariables() ) { builder.addTypeVariable( TypeVariableName.get( typeParameter ) ); } } @Nullable static String deriveName( @Nonnull final ExecutableElement method, @Nonnull final Pattern pattern, @Nonnull final String name ) throws ArezProcessorException { if ( isSentinelName( name ) ) { final String methodName = method.getSimpleName().toString(); final Matcher matcher = pattern.matcher( methodName ); if ( matcher.find() ) { final String candidate = matcher.group( 1 ); return firstCharacterToLowerCase( candidate ); } else { return null; } } else { return name; } } @Nonnull static String firstCharacterToLowerCase( @Nonnull final String name ) { return Character.toLowerCase( name.charAt( 0 ) ) + name.substring( 1 ); } static boolean isSentinelName( @Nonnull final String name ) { return SENTINEL_NAME.equals( name ); } @SuppressWarnings( { "unchecked", "SameParameterValue" } ) @Nonnull static List<TypeMirror> getTypeMirrorsAnnotationParameter( @Nonnull final Elements elements, @Nonnull final TypeElement typeElement, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationValue annotationValue = getAnnotationValue( elements, typeElement, annotationClassName, parameterName ); return ( (List<AnnotationValue>) annotationValue.getValue() ) .stream() .map( v -> (TypeMirror) v.getValue() ).collect( Collectors.toList() ); } @Nonnull static AnnotationValue getAnnotationValue( @Nonnull final Elements elements, @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationValue value = findAnnotationValue( elements, annotated, annotationClassName, parameterName ); assert null != value; return value; } @Nullable private static AnnotationValue findAnnotationValue( @Nonnull final Elements elements, @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationMirror mirror = findAnnotationByType( annotated, annotationClassName ); return null == mirror ? null : findAnnotationValue( elements, mirror, parameterName ); } @Nullable private static AnnotationValue findAnnotationValue( @Nonnull final Elements elements, @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { final Map<? extends ExecutableElement, ? extends AnnotationValue> values = elements.getElementValuesWithDefaults( annotation ); final ExecutableElement annotationKey = values.keySet().stream(). filter( k -> parameterName.equals( k.getSimpleName().toString() ) ).findFirst().orElse( null ); return values.get( annotationKey ); } @SuppressWarnings( "SameParameterValue" ) @Nullable static AnnotationValue findAnnotationValueNoDefaults( @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { final Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotation.getElementValues(); final ExecutableElement annotationKey = values.keySet().stream(). filter( k -> parameterName.equals( k.getSimpleName().toString() ) ).findFirst().orElse( null ); return values.get( annotationKey ); } @SuppressWarnings( "unchecked" ) @Nonnull static <T> T getAnnotationValue( @Nonnull final Elements elements, @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { final AnnotationValue value = findAnnotationValue( elements, annotation, parameterName ); assert null != value; return (T) value.getValue(); } @SuppressWarnings( "SameParameterValue" ) @Nonnull static AnnotationMirror getAnnotationByType( @Nonnull final Element typeElement, @Nonnull final String annotationClassName ) { AnnotationMirror mirror = findAnnotationByType( typeElement, annotationClassName ); assert null != mirror; return mirror; } @Nullable static AnnotationMirror findAnnotationByType( @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName ) { return annotated.getAnnotationMirrors().stream(). filter( a -> a.getAnnotationType().toString().equals( annotationClassName ) ).findFirst().orElse( null ); } @Nonnull static String toSimpleName( @Nonnull final String annotationName ) { return annotationName.replaceAll( ".*\\.", "" ); } static boolean isDisposableTrackableRequired( @Nonnull final Elements elementUtils, @Nonnull final Element element ) { final VariableElement variableElement = (VariableElement) getAnnotationValue( elementUtils, element, Constants.COMPONENT_ANNOTATION_CLASSNAME, "disposeNotifier" ).getValue(); switch ( variableElement.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return null == findAnnotationByType( element, Constants.SINGLETON_ANNOTATION_CLASSNAME ); } } }
package gov.nih.nci.nbia.lookup; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import gov.nih.nci.nbia.dto.StudyDTO; import gov.nih.nci.nbia.dto.ImageDTO; import gov.nih.nci.nbia.dynamicsearch.DynamicSearchCriteria; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.codehaus.jackson.annotate.*; import gov.nih.nci.nbia.searchresult.APIURLHolder; import gov.nih.nci.nbia.searchresult.PatientSearchResult; import gov.nih.nci.nbia.searchresult.PatientSearchResultImpl; import javax.ws.rs.core.MultivaluedMap; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.api.representation.Form; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.*; import com.sun.jersey.api.client.filter.*; import java.io.IOException; import java.util.*; import javax.ws.rs.core.MediaType; import gov.nih.nci.nbia.dto.StudyDTO; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; public class RESTUtil { private static Map<String, String> userMap = new HashMap<String, String>(); private static ObjectMapper mapper = new ObjectMapper(); private static Logger logger = Logger.getLogger(RESTUtil.class); public static List<PatientSearchResult> getDynamicSearch(List<DynamicSearchCriteria> criteria, String stateRelation, String userToken) { // Use a form because there are an unknown number of values MultivaluedMap form = new MultivaluedMapImpl(); // stateRelation is how the criteria are logically related "AND", "OR" form.add("stateRelation", stateRelation); form.add("userName",userToken); int i=0; // Step through all criteria given, the form fields are appended with an integer // to maintain grouping in REST call (dataGroup0, dataGroup1...) for (DynamicSearchCriteria dcriteria:criteria){ form.add("sourceName"+i,dcriteria.getDataGroup()); form.add("itemName"+i,dcriteria.getField()); form.add("operator"+i,dcriteria.getOperator().getValue()); form.add("value"+i,dcriteria.getValue()); i++; } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); client.addFilter(new LoggingFilter(System.out)); WebResource resource = client.resource(APIURLHolder.getUrl() +"/nbia-api/services/getDynamicSearch"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", "Bearer "+userToken) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<PatientSearchResultImpl> myObjects; try { Object json = mapper.readValue(output, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<PatientSearchResultImpl>>(){}); } catch (Exception e) { e.printStackTrace(); return null; } List<PatientSearchResult> returnValue=new ArrayList<PatientSearchResult>(); for (PatientSearchResultImpl result:myObjects) { returnValue.add(result); } return returnValue; } public static List<StudyDTO> getStudyDrillDown(List<Integer> criteria, String userToken) { Form form = new Form(); form.add("userName",userToken); // Add all selected studies to the list for (Integer dcriteria:criteria){ form.add("list",dcriteria.toString()); } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() +"/nbia-api/services/getStudyDrillDown"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON). header("Authorization", "Bearer "+userToken). type(MediaType.APPLICATION_FORM_URLENCODED). post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<StudyDTO> myObjects; try { Object json = mapper.readValue(output, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<StudyDTO>>(){}); } catch (Exception e) { e.printStackTrace(); return null; } return myObjects; } public static DefaultOAuth2AccessToken getToken(String userName, String password) { Form form = new Form(); form.add("username",userName); form.add("password",password); form.add("client_id","nbiaRestAPIClient"); form.add("client_secret","ItsBetweenUAndMe"); form.add("grant_type","password"); ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() +"/nbia-api/oauth/token"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON). type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); output="["+output+"]"; System.out.println(output); List<DefaultOAuth2AccessToken> myObjects; try { Object json = mapper.readValue(output, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<DefaultOAuth2AccessToken>>(){}); } catch (Exception e) { e.printStackTrace(); return null; } return myObjects.get(0); } public static List<ImageDTO> getImageDrillDown(List<Integer> criteria, String userToken) { Form form = new Form(); form.add("userName",userToken); int i=0; // List of selected series for (Integer dcriteria:criteria){ form.add("list",dcriteria.toString()); } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() +"/nbia-api/services/getImageDrillDown"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON). header("Authorization", "Bearer "+userToken). type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<ImageDTO> myObjects; try { Object json = mapper.readValue(output, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<ImageDTO>>(){}); } catch (Exception e) { e.printStackTrace(); return null; } return myObjects; } public static List<PatientSearchResult> getJNLP(List<DynamicSearchCriteria> criteria, String stateRelation, String userToken, List<BasketSeriesItemBean> seriesItems) { // Use a form because there are an unknown number of values MultivaluedMap form = new MultivaluedMapImpl(); int i=0; // Step through all data in series items for display in download manager for (BasketSeriesItemBean item:seriesItems){ form.add("collection"+i,item.getProject()); form.add("patientId"+i,item.getPatientId()); form.add("annotation"+i,item.getAnnotated()); form.add("seriesInstanceUid"+i,item.getSeriesId()); i++; } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); client.addFilter(new LoggingFilter(System.out)); WebResource resource = client.resource(APIURLHolder.getUrl() +"/nbia-api/services/getDynamicSearch"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", "Bearer "+userToken) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<PatientSearchResultImpl> myObjects; try { Object json = mapper.readValue(output, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<PatientSearchResultImpl>>(){}); } catch (Exception e) { e.printStackTrace(); return null; } List<PatientSearchResult> returnValue=new ArrayList<PatientSearchResult>(); for (PatientSearchResultImpl result:myObjects) { returnValue.add(result); } return returnValue; } }
package net.sf.farrago.ddl; import java.util.*; import net.sf.farrago.catalog.*; import net.sf.farrago.fem.security.*; import net.sf.farrago.session.*; import org.eigenbase.sql.*; /** * DdlGrantRoleStmt represents a DDL GRANT ROLE statement. * * @author Quoc Tai Tran * @version $Id$ */ public class DdlGrantRoleStmt extends DdlGrantStmt { protected List<SqlIdentifier> roleList; /** * Constructs a new DdlGrantRoleStmt. */ public DdlGrantRoleStmt() { super(); } // implement DdlStmt public void visit(DdlVisitor visitor) { visitor.visit(this); } // implement FarragoSessionDdlStmt public void preValidate(FarragoSessionDdlValidator ddlValidator) { FarragoRepos repos = ddlValidator.getRepos(); FemAuthId grantorAuthId = determineGrantor(ddlValidator); // TODO: Check that for all roles to be granted (a) the grantor must be // the owner. Or (b) the owner has been granted with Admin Option. Need // model change! for (SqlIdentifier granteeId : granteeList) { // REVIEW: SWZ: 2008-07-29: getAuthIdByName most certainly does // not create an AuthId if it does not exist. An optimization // here would be to modify newRoleGrant to accept AuthId instances // instead of re-doing the lookup for granteeId for each role in // the roleList. // Find the repository element id for the grantee, create one if // it does not exist FemAuthId granteeAuthId = FarragoCatalogUtil.getAuthIdByName( repos, granteeId.getSimple()); // for each role in the list, we instantiate a repository // element. Note that this makes it easier to revoke the privs on // the individual basis. for (SqlIdentifier roleId : roleList) { // create a privilege object and set its properties FemGrant grant = FarragoCatalogUtil.newRoleGrant( repos, grantorAuthId.getName(), granteeId.getSimple(), roleId.getSimple()); // set the privilege name (i.e. action) and properties grant.setWithGrantOption(grantOption); } } } public void setRoleList(List<SqlIdentifier> roleList) { this.roleList = roleList; } } // End DdlGrantRoleStmt.java
package com.intellij.openapi.editor.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.FoldRegion; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.ex.HighlighterIterator; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.markup.*; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; @SuppressWarnings({"ForLoopReplaceableByForEach"}) // Way too many garbage in AbrstractList.iterator() produced otherwise. public class IterationState { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.IterationState"); private TextAttributes myMergedAttributes = new TextAttributes(); private HighlighterIterator myHighlighterIterator; private ArrayList<RangeHighlighterImpl> myViewHighlighters; private int myCurrentViewHighlighterIdx; private ArrayList<RangeHighlighterImpl> myDocumentHighlighters; private int myCurrentDocHighlighterIdx; private int myStartOffset; private int myEndOffset; private int myEnd; private int mySelectionStart; private int mySelectionEnd; private ArrayList<RangeHighlighterImpl> myCurrentHighlighters; private RangeHighlighterImpl myNextViewHighlighter = null; private RangeHighlighterImpl myNextDocumentHighlighter = null; private FoldingModelImpl myFoldingModel = null; private boolean hasSelection = false; private FoldRegion myCurrentFold = null; private TextAttributes myFoldTextAttributes = null; private TextAttributes mySelectionAttributes = null; private TextAttributes myCaretRowAttributes = null; private Color myDefaultBackground = null; private Color myDefaultForeground = null; private int myCaretRowStart; private int myCaretRowEnd; private ArrayList<TextAttributes> myCachedAttributesList; private DocumentImpl myDocument; private EditorImpl myEditor; private Color myReadOnlyColor; public IterationState(EditorImpl editor, int start, boolean useCaretAndSelection) { myDocument = (DocumentImpl)editor.getDocument(); myStartOffset = start; myEnd = editor.getDocument().getTextLength(); myEditor = editor; LOG.assertTrue(myStartOffset <= myEnd); myHighlighterIterator = editor.getHighlighter().createIterator(start); HighlighterList editorList = ((MarkupModelEx)editor.getMarkupModel()).getHighlighterList(); int longestViewHighlighterLength = editorList == null ? 0 : editorList.getLongestHighlighterLength(); myViewHighlighters = editorList == null ? null : editorList.getSortedHighlighters(); final MarkupModelEx docMarkup = (MarkupModelEx)editor.getDocument().getMarkupModel(editor.myProject); final HighlighterList docList = docMarkup.getHighlighterList(); myDocumentHighlighters = docList != null ? docList.getSortedHighlighters() : new ArrayList<RangeHighlighterImpl>(); int longestDocHighlighterLength = docList != null ? docList.getLongestHighlighterLength() : 0; hasSelection = useCaretAndSelection && editor.getSelectionModel().hasSelection(); mySelectionStart = hasSelection ? editor.getSelectionModel().getSelectionStart() : -1; mySelectionEnd = hasSelection ? editor.getSelectionModel().getSelectionEnd() : -1; myFoldingModel = (FoldingModelImpl)editor.getFoldingModel(); myFoldTextAttributes = myFoldingModel.getPlaceholderAttributes(); mySelectionAttributes = ((SelectionModelImpl)editor.getSelectionModel()).getTextAttributes(); myReadOnlyColor = myEditor.getColorsScheme().getColor(EditorColors.READONLY_FRAGMENT_BACKGROUND_COLOR); CaretModelImpl caretModel = (CaretModelImpl)editor.getCaretModel(); myCaretRowAttributes = editor.isRendererMode() ? null : caretModel.getTextAttributes(); myDefaultBackground = editor.getColorsScheme().getDefaultBackground(); myDefaultForeground = editor.getForegroundColor(); myCurrentHighlighters = new ArrayList<RangeHighlighterImpl>(); myCurrentViewHighlighterIdx = initHighlighterIterator(start, myViewHighlighters, longestViewHighlighterLength); while (myCurrentViewHighlighterIdx < myViewHighlighters.size()) { myNextViewHighlighter = myViewHighlighters.get(myCurrentViewHighlighterIdx); if (!skipHighlighter(myNextViewHighlighter)) break; myCurrentViewHighlighterIdx++; } if (myCurrentViewHighlighterIdx == myViewHighlighters.size()) myNextViewHighlighter = null; myCurrentDocHighlighterIdx = initHighlighterIterator(start, myDocumentHighlighters, longestDocHighlighterLength); myNextDocumentHighlighter = null; while (myCurrentDocHighlighterIdx < myDocumentHighlighters.size()) { myNextDocumentHighlighter = myDocumentHighlighters.get(myCurrentDocHighlighterIdx); if (!skipHighlighter(myNextDocumentHighlighter)) break; myCurrentDocHighlighterIdx++; } if (myCurrentDocHighlighterIdx == myDocumentHighlighters.size()) myNextDocumentHighlighter = null; advanceSegmentHighlighters(); myCaretRowStart = caretModel.getVisualLineStart(); myCaretRowEnd = caretModel.getVisualLineEnd(); myEndOffset = Math.min(getHighlighterEnd(myStartOffset), getSelectionEnd(myStartOffset)); myEndOffset = Math.min(myEndOffset, getSegmentHighlightersEnd()); myEndOffset = Math.min(myEndOffset, getFoldRangesEnd(myStartOffset)); myEndOffset = Math.min(myEndOffset, getCaretEnd(myStartOffset)); myEndOffset = Math.min(myEndOffset, getGuardedBlockEnd(myStartOffset)); myCurrentFold = myFoldingModel.getCollapsedRegionAtOffset(myStartOffset); if (myCurrentFold != null) { myEndOffset = myCurrentFold.getEndOffset(); } myCachedAttributesList = new ArrayList<TextAttributes>(5); reinit(); } private int initHighlighterIterator(int start, ArrayList<RangeHighlighterImpl> sortedHighlighters, int longestHighlighterLength) { int low = 0; int high = sortedHighlighters.size(); int search = myDocument.getLineStartOffset(myDocument.getLineNumber(start)) - longestHighlighterLength - 1; if (search > 0) { while (low < high) { int mid = (low + high) / 2; while (mid > 0 && !sortedHighlighters.get(mid).isValid()) mid if (mid < low + 1) break; RangeHighlighterImpl midHighlighter = sortedHighlighters.get(mid); if (midHighlighter.getStartOffset() < search) { low = mid + 1; } else { high = mid - 1; } } } for (int i = low == high ? low : 0; i < sortedHighlighters.size(); i++) { RangeHighlighterImpl rangeHighlighter = sortedHighlighters.get(i); if (!skipHighlighter(rangeHighlighter) && rangeHighlighter.getAffectedAreaEndOffset() >= start) { return i; } } return sortedHighlighters.size(); } private boolean skipHighlighter(RangeHighlighterImpl highlighter) { return !highlighter.isValid() || highlighter.isAfterEndOfLine() || highlighter.getTextAttributes() == null || myFoldingModel.isOffsetCollapsed(highlighter.getAffectedAreaStartOffset()) || myFoldingModel.isOffsetCollapsed(highlighter.getAffectedAreaEndOffset()) || !highlighter.getEditorFilter().avaliableIn(myEditor); } public void advance() { myCurrentFold = null; myStartOffset = myEndOffset; FoldRegion range = myFoldingModel.fetchOutermost(myStartOffset); if (range != null) { myEndOffset = range.getEndOffset(); myCurrentFold = range; } else { advanceSegmentHighlighters(); myEndOffset = Math.min(getHighlighterEnd(myStartOffset), getSelectionEnd(myStartOffset)); myEndOffset = Math.min(myEndOffset, getSegmentHighlightersEnd()); myEndOffset = Math.min(myEndOffset, getFoldRangesEnd(myStartOffset)); myEndOffset = Math.min(myEndOffset, getCaretEnd(myStartOffset)); myEndOffset = Math.min(myEndOffset, getGuardedBlockEnd(myStartOffset)); } reinit(); } private int getHighlighterEnd(int start) { while (!myHighlighterIterator.atEnd()) { int end = myHighlighterIterator.getEnd(); if (end > start) { return end; } myHighlighterIterator.advance(); } return myEnd; } private int getCaretEnd(int start) { if (myCaretRowStart > start) { return myCaretRowStart; } if (myCaretRowEnd > start) { return myCaretRowEnd; } return myEnd; } private int getGuardedBlockEnd(int start) { List<RangeMarker> blocks = myDocument.getGuardedBlocks(); int min = myEnd; for (int i = 0; i < blocks.size(); i++) { RangeMarker block = blocks.get(i); if (block.getStartOffset() > start) { min = Math.min(min, block.getStartOffset()); } else if (block.getEndOffset() > start) { min = Math.min(min, block.getEndOffset()); } } return min; } private int getSelectionEnd(int start) { if (!hasSelection) { return myEnd; } if (mySelectionStart > start) { return mySelectionStart; } if (mySelectionEnd > start) { return mySelectionEnd; } return myEnd; } private void advanceSegmentHighlighters() { if (myNextDocumentHighlighter != null) { if (myNextDocumentHighlighter.getAffectedAreaStartOffset() <= myStartOffset) { myCurrentHighlighters.add(myNextDocumentHighlighter); myNextDocumentHighlighter = null; } } if (myNextViewHighlighter != null) { if (myNextViewHighlighter.getAffectedAreaStartOffset() <= myStartOffset) { myCurrentHighlighters.add(myNextViewHighlighter); myNextViewHighlighter = null; } } RangeHighlighterImpl highlighter; final int docHighlightersSize = myDocumentHighlighters.size(); while (myNextDocumentHighlighter == null && myCurrentDocHighlighterIdx < docHighlightersSize) { highlighter = myDocumentHighlighters.get(myCurrentDocHighlighterIdx++); if (!skipHighlighter(highlighter)) { if (highlighter.getAffectedAreaStartOffset() > myStartOffset) { myNextDocumentHighlighter = highlighter; break; } else { myCurrentHighlighters.add(highlighter); } } } final int viewHighlightersSize = myViewHighlighters.size(); while (myNextViewHighlighter == null && myCurrentViewHighlighterIdx < viewHighlightersSize) { highlighter = myViewHighlighters.get(myCurrentViewHighlighterIdx++); if (!skipHighlighter(highlighter)) { if (highlighter.getAffectedAreaStartOffset() > myStartOffset) { myNextViewHighlighter = highlighter; break; } else { myCurrentHighlighters.add(highlighter); } } } if (myCurrentHighlighters.size() == 1) { //Optimization if (myCurrentHighlighters.get(0).getAffectedAreaEndOffset() <= myStartOffset) { myCurrentHighlighters = new ArrayList<RangeHighlighterImpl>(); } } else if (!myCurrentHighlighters.isEmpty()) { ArrayList<RangeHighlighterImpl> copy = new ArrayList<RangeHighlighterImpl>(myCurrentHighlighters.size()); for (int i = 0; i < myCurrentHighlighters.size(); i++) { highlighter = myCurrentHighlighters.get(i); if (highlighter.getAffectedAreaEndOffset() > myStartOffset) { copy.add(highlighter); } } myCurrentHighlighters = copy; } } private int getFoldRangesEnd(int startOffset) { int end = myEnd; FoldRegion[] topLevelCollapsed = myFoldingModel.fetchTopLevel(); if (topLevelCollapsed != null) { for (int i = myFoldingModel.getLastCollapsedRegionBefore(startOffset) + 1; i >= 0 && i < topLevelCollapsed.length; i++) { FoldRegion range = topLevelCollapsed[i]; if (!range.isValid()) continue; int rangeEnd = range.getStartOffset(); if (rangeEnd > startOffset) { if (rangeEnd < end) { end = rangeEnd; } else { break; } } } } return end; } private int getSegmentHighlightersEnd() { int end = myEnd; for (RangeHighlighterImpl highlighter : myCurrentHighlighters) { if (highlighter.getAffectedAreaEndOffset() < end) { end = highlighter.getAffectedAreaEndOffset(); } } if (myNextDocumentHighlighter != null && myNextDocumentHighlighter.getAffectedAreaStartOffset() < end) { end = myNextDocumentHighlighter.getAffectedAreaStartOffset(); } if (myNextViewHighlighter != null && myNextViewHighlighter.getAffectedAreaStartOffset() < end) { end = myNextViewHighlighter.getAffectedAreaStartOffset(); } return end; } private void reinit() { if (myHighlighterIterator.atEnd()) { return; } boolean isInSelection = hasSelection && myStartOffset >= mySelectionStart && myStartOffset < mySelectionEnd; boolean isInCaretRow = myStartOffset >= myCaretRowStart && myStartOffset < myCaretRowEnd; boolean isInGuardedBlock = myDocument.getOffsetGuard(myStartOffset) != null; TextAttributes syntax = myHighlighterIterator.getTextAttributes(); TextAttributes selection = isInSelection ? mySelectionAttributes : null; TextAttributes caret = isInCaretRow ? myCaretRowAttributes : null; TextAttributes fold = myCurrentFold != null ? myFoldTextAttributes : null; TextAttributes guard = isInGuardedBlock ? new TextAttributes(null, myReadOnlyColor, null, EffectType.BOXED, Font.PLAIN) : null; final int size = myCurrentHighlighters.size(); if (size > 1) { Collections.sort(myCurrentHighlighters, LayerComparator.INSTANCE); } myCachedAttributesList.clear(); for (int i = 0; i < size; i++) { RangeHighlighterImpl highlighter = myCurrentHighlighters.get(i); if (selection != null && highlighter.getLayer() < HighlighterLayer.SELECTION) { myCachedAttributesList.add(selection); selection = null; } if (syntax != null && highlighter.getLayer() < HighlighterLayer.SYNTAX) { if (fold != null) { myCachedAttributesList.add(fold); fold = null; } myCachedAttributesList.add(syntax); syntax = null; } if (guard != null && highlighter.getLayer() < HighlighterLayer.GUARDED_BLOCKS) { myCachedAttributesList.add(guard); guard = null; } if (caret != null && highlighter.getLayer() < HighlighterLayer.CARET_ROW) { myCachedAttributesList.add(caret); caret = null; } TextAttributes textAttributes = highlighter.getTextAttributes(); if (textAttributes != null) { myCachedAttributesList.add(textAttributes); } } if (selection != null) myCachedAttributesList.add(selection); if (fold != null) myCachedAttributesList.add(fold); if (guard != null) myCachedAttributesList.add(guard); if (syntax != null) myCachedAttributesList.add(syntax); if (caret != null) myCachedAttributesList.add(caret); Color fore = null; Color back = isInGuardedBlock ? myReadOnlyColor : null; Color effect = null; EffectType effectType = null; int fontType = TextAttributes.TRANSPARENT; for (int i = 0; i < myCachedAttributesList.size(); i++) { TextAttributes attrs = myCachedAttributesList.get(i); if (fore == null) { fore = attrs.getForegroundColor(); } if (back == null) { back = attrs.getBackgroundColor(); } if (fontType == TextAttributes.TRANSPARENT) { fontType = attrs.getRawFontType(); } if (effect == null) { effect = attrs.getEffectColor(); effectType = attrs.getEffectType(); } } if (fore == null) fore = myDefaultForeground; if (back == null) back = myDefaultBackground; if (fontType == TextAttributes.TRANSPARENT) fontType = Font.PLAIN; if (effectType == null) effectType = EffectType.BOXED; myMergedAttributes.setForegroundColor(fore); myMergedAttributes.setBackgroundColor(back); myMergedAttributes.setFontType(fontType); myMergedAttributes.setEffectColor(effect); myMergedAttributes.setEffectType(effectType); } public boolean atEnd() { return myStartOffset >= myEnd; } public int getStartOffset() { return myStartOffset; } public int getEndOffset() { return myEndOffset; } public TextAttributes getMergedAttributes() { return myMergedAttributes; } public FoldRegion getCurrentFold() { return myCurrentFold; } @Nullable public Color getPastFileEndBackground() { boolean isInCaretRow = myEditor.getCaretModel().getLogicalPosition().line >= myDocument.getLineCount() - 1; Color caret = isInCaretRow && myCaretRowAttributes != null ? myCaretRowAttributes.getBackgroundColor() : null; if (myCurrentHighlighters.size() > 1) { Collections.sort(myCurrentHighlighters, LayerComparator.INSTANCE); } for (int i = 0; i < myCurrentHighlighters.size(); i++) { RangeHighlighterImpl highlighter = myCurrentHighlighters.get(i); if (caret != null && highlighter.getLayer() < HighlighterLayer.CARET_ROW) { return caret; } if (highlighter.getTargetArea() != HighlighterTargetArea.LINES_IN_RANGE || myDocument.getLineNumber(highlighter.getEndOffset()) < myDocument.getLineCount() - 1) { continue; } TextAttributes textAttributes = highlighter.getTextAttributes(); if (textAttributes != null) { Color backgroundColor = textAttributes.getBackgroundColor(); if (backgroundColor != null) return backgroundColor; } } return caret; } private static class LayerComparator implements Comparator<RangeHighlighterImpl> { private static final LayerComparator INSTANCE = new LayerComparator(); public int compare(RangeHighlighterImpl o1, RangeHighlighterImpl o2) { int layerDiff = o2.getLayer() - o1.getLayer(); if (layerDiff != 0) { return layerDiff; } // prefer more specific region int o1Length = o1.getEndOffset() - o1.getStartOffset(); int o2Length = o2.getEndOffset() - o2.getStartOffset(); return o1Length - o2Length; } } }
package liquid; import java.awt.geom.Rectangle2D; import java.lang.InterruptedException; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.JFrame; import lombok.extern.java.Log; import lombok.val; import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.FixtureDef; import org.jbox2d.dynamics.World; @Log public class Launcher { /* Solver */ private static final float DT = 1f / 15f; // seconds private static final int V_ITERATIONS = 8; private static final int P_ITERATIONS = 3; /* World */ private static final float WIDTH = 50f; private static final float HEIGHT = 70f; private static final float THICKNESS = 1f; private static final Vec2 GRAVITY = new Vec2(0, -0.005f); private static final Rectangle2D VIEW = new Rectangle2D.Float(WIDTH / -2, HEIGHT / -2, WIDTH, HEIGHT); private static final long FLIP_RATE = 1500L; /* Balls */ private static final int BALLS = 100; private static final float BALL_RADIUS = 0.75f; private static final float BALL_DENSITY = 1f; private static final float BALL_FRICTION = 0.1f; private static final float BALL_RESTITUTION = 0.6f; public static void main(String[] args) { /* Fix for poor OpenJDK performance. */ System.setProperty("sun.java2d.pmoffscreen", "false"); val world = new World(GRAVITY, false); val viewer = new Viewer(world, VIEW); JFrame frame = new JFrame("Fun Liquid"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(viewer); frame.setResizable(false); frame.pack(); frame.setVisible(true); /* Set up the containment box. */ buildContainer(world); /* Add a ball. */ Random rng = new Random(); for (int i = 0; i < BALLS; i++) { addBall(world, (rng.nextFloat() - 0.5f) * (WIDTH - BALL_RADIUS), (rng.nextFloat() - 0.5f) * (HEIGHT - BALL_RADIUS)); } val exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(new Runnable() { public void run() { while (true) { world.step(DT, V_ITERATIONS, P_ITERATIONS); viewer.repaint(); if (System.currentTimeMillis() / FLIP_RATE % 2 == 0) { world.setGravity(GRAVITY.negate()); } else { world.setGravity(GRAVITY); } } } }, 0L, (long) (DT * 1000.0), TimeUnit.MILLISECONDS); } private static void buildContainer(World world) { BodyDef def = new BodyDef(); PolygonShape box = new PolygonShape(); Body side; def.position = new Vec2(WIDTH / 2, 0); box.setAsBox(THICKNESS / 2, HEIGHT / 2); world.createBody(def).createFixture(box, 0f); def.position = new Vec2(-WIDTH / 2, 0); box.setAsBox(THICKNESS / 2, HEIGHT / 2); world.createBody(def).createFixture(box, 0f); def.position = new Vec2(0, HEIGHT / 2); box.setAsBox(WIDTH / 2, THICKNESS / 2); world.createBody(def).createFixture(box, 0f); def.position = new Vec2(0, -HEIGHT / 2); box.setAsBox(WIDTH / 2, THICKNESS / 2); world.createBody(def).createFixture(box, 0f); } private static void addBall(World world, float x, float y) { BodyDef def = new BodyDef(); def.position = new Vec2(x, y); def.type = BodyType.DYNAMIC; CircleShape circle = new CircleShape(); circle.m_radius = BALL_RADIUS; FixtureDef mass = new FixtureDef(); mass.shape = circle; mass.density = BALL_DENSITY; mass.friction = BALL_FRICTION; mass.restitution = BALL_RESTITUTION; world.createBody(def).createFixture(mass); } }
package tlc2.tool.distributed; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.rmi.AccessException; import java.rmi.ConnectException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.ServerException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import model.InJarFilenameToStream; import model.ModelInJar; import tlc2.TLC; import tlc2.TLCGlobals; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.EvalException; import tlc2.tool.IStateFunctor; import tlc2.tool.ModelChecker; import tlc2.tool.TLCState; import tlc2.tool.TLCTrace; import tlc2.tool.distributed.fp.FPSetManager; import tlc2.tool.distributed.fp.FPSetRMI; import tlc2.tool.distributed.fp.IFPSetManager; import tlc2.tool.distributed.fp.NonDistributedFPSetManager; import tlc2.tool.distributed.management.TLCServerMXWrapper; import tlc2.tool.distributed.selector.BlockSelectorFactory; import tlc2.tool.distributed.selector.IBlockSelector; import tlc2.tool.fp.FPSet; import tlc2.tool.fp.FPSetFactory; import tlc2.tool.management.TLCStandardMBean; import tlc2.tool.queue.DiskStateQueue; import tlc2.tool.queue.IStateQueue; import tlc2.util.FP64; import util.Assert; import util.FileUtil; import util.MailSender; import util.UniqueString; @SuppressWarnings("serial") public class TLCServer extends UnicastRemoteObject implements TLCServerRMI, InternRMI { /** * Name by which {@link FPSetRMI} lookup the {@link TLCServer} (master). */ public static final String SERVER_NAME = "TLCServer"; /** * Name by which {@link TLCWorker} lookup the {@link TLCServer} (master). */ public static final String SERVER_WORKER_NAME = SERVER_NAME + "WORKER"; /** * Prefix master and worker heavy workload threads with this prefix and an incrementing counter to * make the threads identifiable in jmx2munin statistics, which uses simple string matching. */ public static final String THREAD_NAME_PREFIX = "TLCWorkerThread-"; /** * Used by TLCStatistics which are collected after the {@link FPSet} or {@link FPSetManager} shut down. */ static long finalNumberOfDistinctStates = -1L; /** * the port # for tlc server */ public static int Port = Integer.getInteger(TLCServer.class.getName() + ".port", 10997); /** * show statistics every 1 minutes */ private static final int REPORT_INTERVAL = Integer.getInteger(TLCServer.class.getName() + ".report", 1 * 60 * 1000); /** * If the state/ dir should be cleaned up after a successful model run */ private static final boolean VETO_CLEANUP = Boolean.getBoolean(TLCServer.class.getName() + ".vetoCleanup"); /** * The amount of FPset servers to use (use a non-distributed FPSet server on * master node if unset). */ private static final int expectedFPSetCount = Integer.getInteger(TLCServer.class.getName() + ".expectedFPSetCount", 0); /** * Performance metric: distinct states per minute */ private long distinctStatesPerMinute; /** * Performance metric: states per minute */ private long statesPerMinute; /** * A counter used to count the states generated by (remote) * {@link TLCWorker}s but which have been skipped due to a worker-local * fingerprint cache hit. */ protected final AtomicLong workerStatesGenerated = new AtomicLong(0); /** * A thread pool used to execute tasks */ private final ExecutorService es = Executors.newCachedThreadPool(); public final IFPSetManager fpSetManager; public final IStateQueue stateQueue; public final TLCTrace trace; private final DistApp work; private final String metadir; private final String filename; private TLCState errState = null; private boolean done = false; private boolean keepCallStack = false; /** * Main data structure used to maintain the list of active workers (ref * {@link TLCWorkerRMI}) and the corresponding local {@link TLCServerThread} * . * <p> * A worker ({@link TLCWorkerRMI}) requires a local thread counterpart to do * its work concurrently. * <p> * The implementation uses a {@link ConcurrentHashMap}, to allow concurrent * access during the end game phase. It is the phase when * {@link TLCServer#modelCheck()} cleans up threadsToWorkers by waiting * {@link Thread#join()} on the various {@link TLCServerThread}s. If this * action is overlapped with a worker registering - calling * {@link TLCServer#registerWorker(TLCWorkerRMI)} - which would cause a * {@link ConcurrentModificationException}. */ private final Map<TLCServerThread, TLCWorkerRMI> threadsToWorkers = new ConcurrentHashMap<TLCServerThread, TLCWorkerRMI>(); private final IBlockSelector blockSelector; /** * @param work * @throws IOException * @throws NotBoundException */ public TLCServer(TLCApp work) throws IOException, NotBoundException { // LL modified error message on 7 April 2012 Assert.check(work != null, "TLC server found null work."); // TLCApp which calculates the next state relation this.metadir = work.getMetadir(); int end = this.metadir.length(); if (this.metadir.endsWith(FileUtil.separator)) { end } int start = this.metadir.lastIndexOf(FileUtil.separator, end - 1); this.filename = this.metadir.substring(start + 1, end); this.work = work; // State Queue of unexplored states this.stateQueue = new DiskStateQueue(this.metadir); // State trace file this.trace = new TLCTrace(this.metadir, this.work.getFileName(), this.work); // FPSet this.fpSetManager = getFPSetManagerImpl(work, metadir, expectedFPSetCount); // Determines the size of the state queue subset handed out to workers blockSelector = BlockSelectorFactory.getBlockSelector(this); } /** * The {@link IFPSetManager} implementation to be used by the * {@link TLCServer} implementation. Subclass may want to return specialized * {@link IFPSetManager}s with different functionality. * @param expectedfpsetcount2 */ protected IFPSetManager getFPSetManagerImpl(final TLCApp work, final String metadir, final int fpsetCount) throws IOException { // A single FPSet server running on the master node final FPSet fpSet = FPSetFactory.getFPSet(work.getFPSetConfiguration()); fpSet.init(1, metadir, work.getFileName()); return new NonDistributedFPSetManager(fpSet, InetAddress.getLocalHost() .getCanonicalHostName()); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#getCheckDeadlock() */ public final Boolean getCheckDeadlock() { return this.work.getCheckDeadlock(); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#getPreprocess() */ public final Boolean getPreprocess() { return this.work.getPreprocess(); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#getFPSetManager() */ public IFPSetManager getFPSetManager() { return this.fpSetManager; } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#getIrredPolyForFP() */ public final long getIrredPolyForFP() { return FP64.getIrredPoly(); } /* (non-Javadoc) * @see tlc2.tool.distributed.InternRMI#intern(java.lang.String) */ public final UniqueString intern(String str) { // SZ 11.04.2009: changed access method return UniqueString.uniqueStringOf(str); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#registerWorker(tlc2.tool.distributed.TLCWorkerRMI) */ public synchronized final void registerWorker(TLCWorkerRMI worker ) throws IOException { // Wake up potentially stuck TLCServerThreads (in // tlc2.tool.queue.StateQueue.isAvail()) to avoid a deadlock. // Obviously stuck TLCServerThreads will never be reported to // users if resumeAllStuck() is not call by a new worker. stateQueue.resumeAllStuck(); // create new server thread for given worker final TLCServerThread thread = new TLCServerThread(worker, worker.getURI(), this, es, blockSelector); threadsToWorkers.put(thread, worker); thread.start(); MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_REGISTERED, worker.getURI().toString()); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#registerFPSet(tlc2.tool.distributed.fp.FPSetRMI, java.lang.String) */ public synchronized void registerFPSet(FPSetRMI fpSet, String hostname) throws RemoteException { throw new UnsupportedOperationException("Not applicable for non-distributed TLCServer"); } /** * An (idempotent) method to remove a (dead) TLCServerThread from the TLCServer. * * @see Map#remove(Object) * @param thread * @return */ public TLCWorkerRMI removeTLCServerThread(final TLCServerThread thread) { final TLCWorkerRMI worker = threadsToWorkers.remove(thread); if (worker != null) { MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_DEREGISTERED, thread.getUri().toString()); } return worker; } /** * @param s * @param keep * @return true iff setting the error state has succeeded. This is the case * for the first worker to call * {@link TLCServer#setErrState(TLCState, boolean)}. Subsequent * calls by other workers will be ignored. This implies that other * error states are ignored. */ public synchronized final boolean setErrState(TLCState s, boolean keep) { if (this.done) { return false; } this.done = true; this.errState = s; this.keepCallStack = keep; return true; } /** * Indicates the completion of model checking. This is called by * {@link TLCServerThread}s once they find an empty {@link IStateQueue}. An * empty {@link IStateQueue} is the termination condition. */ public final void setDone() { this.done = true; } /** * Number of states generated by (remote) {@link TLCWorker}s but which have * been skipped due to a worker-local fingerprint cache hit. * <p> * We count them here to still report the correct amount of states generated * overall. {@link IFPSetManager#getStatesSeen()} will not count these * states. */ public void addStatesGeneratedDelta(long delta) { workerStatesGenerated.addAndGet(delta); } /** * Creates a checkpoint for the currently running model run * @throws IOException * @throws InterruptedException */ public void checkpoint() throws IOException, InterruptedException { if (this.stateQueue.suspendAll()) { // Checkpoint: MP.printMessage(EC.TLC_CHECKPOINT_START, "-- Checkpointing of run " + this.metadir + " compl"); // start checkpointing: this.stateQueue.beginChkpt(); this.trace.beginChkpt(); this.fpSetManager.checkpoint(this.filename); this.stateQueue.resumeAll(); UniqueString.internTbl.beginChkpt(this.metadir); // commit: this.stateQueue.commitChkpt(); this.trace.commitChkpt(); UniqueString.internTbl.commitChkpt(this.metadir); this.fpSetManager.commitChkpt(); MP.printMessage(EC.TLC_CHECKPOINT_END, "eted."); } } /** * Recovers a model run * @throws IOException * @throws InterruptedException */ public final void recover() throws IOException, InterruptedException { this.trace.recover(); this.stateQueue.recover(); this.fpSetManager.recover(this.filename); } /** * @throws Throwable */ private final void doInit() throws Throwable { final DoInitFunctor functor = new DoInitFunctor(); work.getInitStates(functor); // Iff one of the init states' checks violates any properties, the // functor will record it. if (functor.e != null) { throw functor.e; } } /** * @param cleanup * @throws IOException */ public final void close(boolean cleanup) throws IOException { this.trace.close(); this.fpSetManager.close(cleanup); if (cleanup && !VETO_CLEANUP) { FileUtil.deleteDir(new File(this.metadir), true); } } /** * @param server * @throws IOException * @throws InterruptedException * @throws NotBoundException */ protected void modelCheck() throws IOException, InterruptedException, NotBoundException { final long startTime = System.currentTimeMillis(); /* * Before we initialize the server, we check if recovery is requested */ boolean recovered = false; if (work.canRecover()) { MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_START, metadir); recover(); MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_END, new String[] { String.valueOf(fpSetManager.size()), String.valueOf(stateQueue.size())}); recovered = true; } // Create the central naming authority that is used by _all_ nodes String hostname = InetAddress.getLocalHost().getHostName(); Registry rg = LocateRegistry.createRegistry(Port); rg.rebind(SERVER_NAME, this); MP.printMessage(EC.TLC_DISTRIBUTED_SERVER_RUNNING, hostname); // First register TLCSERVER with RMI and only then wait for all FPSets // to become registered. This only waits if we use distributed // fingerprint set (FPSet) servers which have to partition the // distributed hash table (fingerprint space) prior to starting model // checking. waitForFPSetManager(); /* * Start initializing the server by calculating the init state(s) */ if (!recovered) { // Initialize with the initial states: try { MP.printMessage(EC.TLC_COMPUTING_INIT); doInit(); MP.printMessage(EC.TLC_INIT_GENERATED1, new String[] { String.valueOf(stateQueue.size()), "(s)" }); } catch (Throwable e) { // Assert.printStack(e); done = true; // Distributed TLC does not support TLCGet/TLCSet operator. It // would require synchronization among all (distributed) // workers. In distributed mode, it is of limited use anyway. if (e instanceof EvalException && ((EvalException) e).getErrorCode() == EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE && (((EvalException) e).getMessage().contains("tlc2.module.TLC.TLCSet") || ((EvalException) e).getMessage().contains("tlc2.module.TLC.TLCGet"))) { MP.printError(EC.TLC_FEATURE_UNSUPPORTED, "TLCSet & TLCGet operators not supported by distributed TLC."); } else { String msg = e.getMessage(); if (msg == null) { msg = e.toString(); } if (!this.hasNoErrors()) { MP.printError(EC.TLC_INITIAL_STATE, new String[] { msg, this.errState.toString() }); } else { MP.printError(EC.GENERAL, msg); } // We redo the work on the error state, recording the call // stack. work.setCallStack(); try { doInit(); } catch (Throwable e1) { // Assert.printStack(e); MP.printError(EC.TLC_NESTED_EXPRESSION, work.printCallStack()); } } } } if (done) { printSummary(1, 0, stateQueue.size(), fpSetManager.size(), false); MP.printMessage(EC.TLC_FINISHED, TLC.convertRuntimeToHumanReadable(System.currentTimeMillis() - startTime)); es.shutdown(); // clean up before exit: close(false); return; } // Init states have been computed successfully which marks the point in // time where workers can start generating and exploring next states. rg.rebind(SERVER_WORKER_NAME, this); /* * This marks the end of the master and FPSet server initialization. * Model checking can start now. */ // Model checking results to be collected after model checking has finished long oldNumOfGenStates = 0; long oldFPSetSize = 0; // Wait for completion, but print out progress report and checkpoint // periodically. synchronized (this) { //TODO convert to do/while to move initial wait into loop wait(REPORT_INTERVAL); } while (true) { if (TLCGlobals.doCheckPoint()) { // Periodically create a checkpoint assuming it is activated checkpoint(); } synchronized (this) { if (!done) { final long numOfGenStates = getStatesGenerated(); final long fpSetSize = fpSetManager.size(); // print progress showing states per minute metric (spm) final double factor = REPORT_INTERVAL / 60000d; statesPerMinute = (long) ((numOfGenStates - oldNumOfGenStates) / factor); distinctStatesPerMinute = (long) ((fpSetSize - oldFPSetSize) / factor); // print to system.out MP.printMessage(EC.TLC_PROGRESS_STATS, new String[] { String.valueOf(trace.getLevelForReporting()), String.valueOf(numOfGenStates), String.valueOf(fpSetSize), String.valueOf(getNewStates()), String.valueOf(statesPerMinute), String.valueOf(distinctStatesPerMinute) }); // Make the TLCServer main thread sleep for one report interval wait(REPORT_INTERVAL); // keep current values as old values oldFPSetSize = fpSetSize; oldNumOfGenStates = numOfGenStates; } if (done) { break; } } } // Either model checking has found an error/violation or no // violation has been found represented by an empty state queue. Assert.check(!hasNoErrors() || stateQueue.isEmpty(), EC.GENERAL); /* * From this point on forward, we expect model checking to be done. What * is left open, is to collect results and clean up */ // Wait for all the server threads to die. for (final Entry<TLCServerThread, TLCWorkerRMI> entry : threadsToWorkers.entrySet()) { final TLCServerThread thread = entry.getKey(); final TLCWorkerRMI worker = entry.getValue(); thread.join(); // print worker stats int sentStates = thread.getSentStates(); int receivedStates = thread.getReceivedStates(); double cacheHitRatio = thread.getCacheRateRatio(); URI name = thread.getUri(); MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_STATS, new String[] { name.toString(), Integer.toString(sentStates), Integer.toString(receivedStates), cacheHitRatio < 0 ? "n/a" : String.format("%1$,.2f", cacheHitRatio) }); try { worker.exit(); } catch (NoSuchObjectException e) { // worker might have been lost in the meantime MP.printWarning(EC.GENERAL, "Ignoring attempt to exit dead worker"); } catch (ConnectException e) { // worker might have been lost in the meantime MP.printWarning(EC.GENERAL, "Ignoring attempt to exit dead worker"); } catch (ServerException e) { // worker might have been lost in the meantime MP.printWarning(EC.GENERAL, "Ignoring attempt to exit dead worker"); } finally { threadsToWorkers.remove(thread); } } // Only shutdown the thread pool if we exit gracefully es.shutdown(); // Collect model checking results before exiting remote workers finalNumberOfDistinctStates = fpSetManager.size(); final long statesGenerated = getStatesGenerated(); final long statesLeftInQueue = getNewStates(); final int level = trace.getLevelForReporting(); statesPerMinute = 0; distinctStatesPerMinute = 0; // Postprocessing: if (hasNoErrors()) { // We get here because the checking has succeeded. final double actualProb = fpSetManager.checkFPs(); final long statesSeen = fpSetManager.getStatesSeen(); ModelChecker.reportSuccess(finalNumberOfDistinctStates, actualProb, statesSeen); } else if (keepCallStack) { // We redo the work on the error state, recording the call stack. work.setCallStack(); } // Finally print the results printSummary(level, statesGenerated, statesLeftInQueue, finalNumberOfDistinctStates, hasNoErrors()); MP.printMessage(EC.TLC_FINISHED, TLC.convertRuntimeToHumanReadable(System.currentTimeMillis() - startTime)); MP.flush(); // Close trace and (distributed) _FPSet_ servers! close(hasNoErrors()); // dispose RMI leftovers rg.unbind(SERVER_WORKER_NAME); rg.unbind(SERVER_NAME); UnicastRemoteObject.unexportObject(this, false); } /** * Makes the flow of control wait for the IFPSetManager implementation to * become fully initialized.<p> * For the non-distributed FPSet implementation, this is true right away. */ protected void waitForFPSetManager() throws InterruptedException { // no-op } public long getStatesGeneratedPerMinute() { return statesPerMinute; } public long getDistinctStatesGeneratedPerMinute() { return distinctStatesPerMinute; } public long getAverageBlockCnt() { return blockSelector.getAverageBlockCnt(); } /** * @return true iff model checking has not found an error state */ private boolean hasNoErrors() { return errState == null; } /** * @return */ public synchronized long getNewStates() { long res = stateQueue.size(); for (TLCServerThread thread : threadsToWorkers.keySet()) { res += thread.getCurrentSize(); } return res; } public long getStatesGenerated() { return workerStatesGenerated.get() + fpSetManager.getStatesSeen(); } /** * This allows the toolbox to easily display the last set * of state space statistics by putting them in the same * form as all other progress statistics. * @param workerOverallCacheRate */ public static final void printSummary(int level, long statesGenerated, long statesLeftInQueue, long distinctStates, boolean success) throws IOException { if (TLCGlobals.tool) { MP.printMessage(EC.TLC_PROGRESS_STATS, new String[] { String.valueOf(level), String.valueOf(statesGenerated), String.valueOf(distinctStates), String.valueOf(statesLeftInQueue), "0", "0" }); } MP.printMessage(EC.TLC_STATS, new String[] { String.valueOf(statesGenerated), String.valueOf(distinctStates), String.valueOf(statesLeftInQueue) }); if (success) { MP.printMessage(EC.TLC_SEARCH_DEPTH, String.valueOf(level)); } } public static void main(String argv[]) { MP.printMessage(EC.TLC_VERSION, "TLC Server " + TLCGlobals.versionOfTLC); TLCStandardMBean tlcServerMXWrapper = TLCStandardMBean.getNullTLCStandardMBean(); MailSender mail = null; TLCServer server = null; TLCApp app = null; try { TLCGlobals.setNumWorkers(0); app = TLCApp.create(argv); mail = new MailSender(app.getFileName()); if (expectedFPSetCount > 0) { server = new DistributedFPSetTLCServer(app, expectedFPSetCount); } else { server = new TLCServer(app); } tlcServerMXWrapper = new TLCServerMXWrapper(server); if(server != null) { Runtime.getRuntime().addShutdownHook(new Thread(new WorkerShutdownHook(server))); server.modelCheck(); } } catch (Throwable e) { System.gc(); // Assert.printStack(e); if (e instanceof StackOverflowError) { MP.printError(EC.SYSTEM_STACK_OVERFLOW, e); } else if (e instanceof OutOfMemoryError) { MP.printError(EC.SYSTEM_OUT_OF_MEMORY, e); } else { MP.printError(EC.GENERAL, e); } if (server != null) { try { server.close(false); } catch (Exception e1) { MP.printError(EC.GENERAL, e1); } } } finally { if (!server.es.isShutdown()) { server.es.shutdownNow(); } tlcServerMXWrapper.unregister(); // When creation of TLCApp fails, we get here as well. if (mail != null) { List<File> files = new ArrayList<File>(); if (app != null) { files = app.getModuleFiles(); } boolean send = mail.send(files); // In case sending the mail has failed we treat this as an error. // This is needed when TLC runs on another host and email is // the only means for the user to get access to the model checking // results. // With distributed TLC and CloudDistributedTLCJob in particular, // the cloud node is immediately turned off once the TLC process has // finished. If we were to shutdown the node even when sending out // the email has failed, the result would be lost. if (!send) { MP.printMessage(EC.GENERAL, "Sending result mail failed."); System.exit(1); } } } } /** * @return Number of currently registered workers */ public int getWorkerCount() { return threadsToWorkers.size(); } /** * @return */ synchronized TLCServerThread[] getThreads() { return threadsToWorkers.keySet().toArray(new TLCServerThread[threadsToWorkers.size()]); } public boolean isRunning() { return !done; } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#isDone() */ public boolean isDone() throws RemoteException { return done; } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#getSpec() */ public String getSpecFileName() throws RemoteException { return this.work.getFileName(); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#getConfig() */ public String getConfigFileName() throws RemoteException { return this.work.getConfigName(); } /* (non-Javadoc) * @see tlc2.tool.distributed.TLCServerRMI#getFile(java.lang.String) */ public byte[] getFile(final String file) throws RemoteException { // sanitize file to only last part of the path // to make sure to not load files outside of spec dir String name = new File(file).getName(); // Resolve all File f = new InJarFilenameToStream(ModelInJar.PATH).resolve(name); return read(f); } private byte[] read(final File file) { if (file.isDirectory()) throw new RuntimeException("Unsupported operation, file " + file.getAbsolutePath() + " is a directory"); if (file.length() > Integer.MAX_VALUE) throw new RuntimeException("Unsupported operation, file " + file.getAbsolutePath() + " is too big"); Throwable pending = null; FileInputStream in = null; final byte buffer[] = new byte[(int) file.length()]; try { in = new FileInputStream(file); in.read(buffer); } catch (Exception e) { pending = new RuntimeException("Exception occured on reading file " + file.getAbsolutePath(), e); } finally { if (in != null) { try { in.close(); } catch (Exception e) { if (pending == null) { pending = new RuntimeException( "Exception occured on closing file" + file.getAbsolutePath(), e); } } } if (pending != null) { throw new RuntimeException(pending); } } return buffer; } private class DoInitFunctor implements IStateFunctor { private Throwable e; /* (non-Javadoc) * @see tlc2.tool.IStateFunctor#addElement(tlc2.tool.TLCState) */ public Object addElement(final TLCState curState) { if (e != null) { return curState; } try { final boolean inConstraints = work.isInModel(curState); boolean seen = false; if (inConstraints) { long fp = curState.fingerPrint(); seen = fpSetManager.put(fp); if (!seen) { curState.uid = trace.writeState(fp); stateQueue.enqueue(curState); } } if (!inConstraints || !seen) { work.checkState(null, curState); } } catch (Exception e) { if (setErrState(curState, true)) { this.e = e; } } return curState; } } /** * Tries to exit all connected workers */ private static class WorkerShutdownHook implements Runnable { private final TLCServer server; public WorkerShutdownHook(final TLCServer aServer) { server = aServer; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { if (server.threadsToWorkers.isEmpty()) { // Nothing to be done here. return; } try { // No need to attempt to exit workers if the server itself // isn't registered any longer. It won't be able to connect to // workers anyway. LocateRegistry.getRegistry(Port).lookup(SERVER_NAME); } catch (AccessException e1) { return; } catch (RemoteException e1) { return; } catch (NotBoundException e1) { return; } for (TLCWorkerRMI worker : server.threadsToWorkers.values()) { try { worker.exit(); } catch (java.rmi.ConnectException e) { // happens if worker has exited already } catch (java.rmi.NoSuchObjectException e) { // happens if worker has exited already } catch (IOException e) { //TODO handle more gracefully MP.printError(EC.GENERAL, e); } } } } }
package etomica.normalmode; import java.awt.Color; import etomica.action.BoxInflate; import etomica.action.IAction; import etomica.action.activity.ActivityIntegrate; import etomica.api.IAtom; import etomica.api.IAtomList; import etomica.api.IAtomType; import etomica.api.IBoundary; import etomica.api.IBox; import etomica.api.IIntegratorEvent; import etomica.api.IIntegratorListener; import etomica.api.IVector; import etomica.api.IVectorMutable; import etomica.atom.DiameterHash; import etomica.box.Box; import etomica.data.AccumulatorAverageBlockless; import etomica.data.AccumulatorHistogram; import etomica.data.AccumulatorHistory; import etomica.data.DataDistributer; import etomica.data.DataFork; import etomica.data.DataPumpListener; import etomica.data.DataSourceCountSteps; import etomica.data.DataSplitter.IDataSinkFactory; import etomica.data.DataTag; import etomica.data.IData; import etomica.data.IDataSink; import etomica.data.meter.MeterNMolecules; import etomica.data.meter.MeterPressure; import etomica.graphics.ColorScheme; import etomica.graphics.DeviceBox; import etomica.graphics.DeviceButton; import etomica.graphics.DisplayPlot; import etomica.graphics.DisplayTextBox; import etomica.graphics.SimulationGraphic; import etomica.graphics.SimulationPanel; import etomica.integrator.IntegratorMC; import etomica.integrator.mcmove.MCMoveAtom; import etomica.integrator.mcmove.MCMoveIDBiasAction; import etomica.integrator.mcmove.MCMoveInsertDeleteLatticeVacancy; import etomica.integrator.mcmove.MCMoveOverlapListener; import etomica.integrator.mcmove.MCMoveVolume; import etomica.lattice.crystal.Basis; import etomica.lattice.crystal.BasisCubicFcc; import etomica.lattice.crystal.PrimitiveCubic; import etomica.listener.IntegratorListenerAction; import etomica.modifier.Modifier; import etomica.nbr.cell.Api1ACell; import etomica.nbr.cell.PotentialMasterCell; import etomica.normalmode.DataSourceMuRoot.DataSourceMuRootVacancyConcentration; import etomica.potential.P2LennardJones; import etomica.potential.P2SoftSphericalTruncated; import etomica.simulation.Simulation; import etomica.space.BoundaryRectangularPeriodic; import etomica.space3d.Space3D; import etomica.species.SpeciesSpheresMono; import etomica.statmech.LennardJones; import etomica.units.Dimension; import etomica.units.Null; import etomica.util.HistogramDiscrete; import etomica.util.HistoryCollapsingAverage; import etomica.util.HistoryCollapsingDiscard; import etomica.util.ParameterBase; import etomica.util.ParseArgs; /** * Simple Lennard-Jones molecular dynamics simulation in 3D */ public class SimLJVacancy extends Simulation { public final PotentialMasterCell potentialMaster; public final ActivityIntegrate ai; public IntegratorMC integrator; public SpeciesSpheresMono species; public IBox box; public P2LennardJones p2LJ; public P2SoftSphericalTruncated potential; public MCMoveVolume mcMoveVolume; public MCMoveInsertDeleteLatticeVacancy mcMoveID; public SimLJVacancy(final int numAtoms, double temperature, double density, double rc, final int fixedN, final int maxDN, final double bmu) { super(Space3D.getInstance()); species = new SpeciesSpheresMono(this, space); species.setIsDynamic(true); addSpecies(species); box = new Box(space); addBox(box); box.setNMolecules(species, numAtoms); double L = Math.pow(4.0/density, 1.0/3.0); int n = (int)Math.round(Math.pow(numAtoms/4, 1.0/3.0)); PrimitiveCubic primitive = new PrimitiveCubic(space, n*L); int[] nCells = new int[]{n,n,n}; IBoundary boundary = new BoundaryRectangularPeriodic(space, n * L); Basis basisFCC = new BasisCubicFcc(); BasisBigCell basis = new BasisBigCell(space, basisFCC, nCells); box.setBoundary(boundary); potentialMaster = new PotentialMasterCell(this, rc, space); potentialMaster.setCellRange(2); integrator = new IntegratorMC(this, potentialMaster); integrator.setTemperature(temperature); MCMoveAtom move = new MCMoveAtom(random, potentialMaster, space); move.setStepSize(0.2); // ((MCMoveStepTracker)move.getTracker()).setNoisyAdjustment(true); integrator.getMoveManager().addMCMove(move); ai = new ActivityIntegrate(integrator); getController().addAction(ai); BoxInflate inflater = new BoxInflate(box, space); inflater.setTargetDensity(density); inflater.actionPerformed(); if (rc > 0.49*box.getBoundary().getBoxSize().getX(0)) { throw new RuntimeException("rc is too large"); } double nbr1 = L/Math.sqrt(2); double y = 1.25*nbr1; //nbr1+(L-nbr1)*0.6+0.06; p2LJ = new P2LennardJones(space, 1, 1); potential = new P2SoftSphericalTruncated(space, p2LJ, rc); IAtomType leafType = species.getLeafType(); potentialMaster.addPotential(potential,new IAtomType[]{leafType,leafType}); integrator.setBox(box); CoordinateDefinitionLeaf coordinateDefinition = new CoordinateDefinitionLeaf(box, primitive, basis, space); coordinateDefinition.initializeCoordinates(new int[]{1,1,1}); // we just needed this to initial coordinates, to keep track of lattice positions of atoms coordinateDefinition = null; integrator.getMoveEventManager().addListener(potentialMaster.getNbrCellManager(box).makeMCMoveListener()); potentialMaster.getNbrCellManager(box).assignCellAll(); mcMoveID = new MCMoveInsertDeleteLatticeVacancy(potentialMaster, random, space, integrator, y, fixedN, maxDN); double x = nbr1/40.0; mcMoveID.setMaxInsertDistance(x); mcMoveID.makeFccVectors(nbr1); mcMoveID.setMu(bmu); mcMoveID.setSpecies(species); integrator.getMoveManager().addMCMove(mcMoveID); integrator.getMoveManager().setFrequency(mcMoveID, 0.1); integrator.getMoveEventManager().addListener(mcMoveID); } public static void main(String[] args) { LJParams params = new LJParams(); ParseArgs.doParseArgs(params, args); if (args.length==0) { params.graphics = true; params.numAtoms = 500; params.steps = 1000000; params.density = 1.0; params.temperature = 0.7; params.numV = 4; } final int numAtoms = params.numAtoms; final double density = params.density; final double temperature = params.temperature; final double rc = params.rc*Math.pow(density, -1.0/3.0); long steps = params.steps; boolean graphics = params.graphics; int maxDN = (params.numV+1)/2; int fixedN = params.numAtoms - maxDN; double mu = params.mu; double Alat = params.Alat; System.out.println("Running N="+params.numAtoms+" at rho="+density); if (Double.isNaN(mu)) { // this should get us pretty close Alat = Math.log(density)-1.0 + (LennardJones.aResidualFcc(temperature, density))/temperature; double zLat = LennardJones.ZFcc(temperature, density); System.out.println("lattice pressure "+zLat); mu = (Alat + zLat); System.out.println("beta mu "+mu); } else if (Double.isNaN(Alat)) { // this should get us pretty close Alat = Math.log(density)-1.0 + (LennardJones.aResidualFcc(temperature, density))/temperature; } double daDef = params.daDef; if (Double.isNaN(daDef)) { // use a correlation. this should be with ~1 double Y = temperature/Math.pow(density, 4)/4; double v2 = 1/(density*density); daDef = (-3.6 - 10.5*Y + 8.2*v2)/Y; System.out.println("estimated defect free energy: "+daDef); } else { System.out.println("using defect free energy: "+daDef); } System.out.println("Running LJ MC"); System.out.println("N: "+numAtoms); System.out.println("T: "+temperature); System.out.println("density: "+density); System.out.println("steps: "+steps); final SimLJVacancy sim = new SimLJVacancy(numAtoms, temperature, density, rc, fixedN, maxDN, mu); final int biasInterval = 10*numAtoms; final MCMoveOverlapListener mcMoveOverlapMeter = new MCMoveOverlapListener(sim.mcMoveID, 11, daDef, numAtoms, 6); mcMoveOverlapMeter.setTemperature(temperature); sim.integrator.getMoveEventManager().addListener(mcMoveOverlapMeter); final MeterPressure meterP = new MeterPressure(sim.getSpace()); meterP.setIntegrator(sim.integrator); DataDistributer.Indexer indexer = new DataDistributer.Indexer() { public int getIndex() { return numAtoms-sim.box.getNMolecules(sim.species); } }; final DataDistributer pSplitter = new DataDistributer(indexer, new IDataSinkFactory() { public IDataSink makeDataSink(int i) { return new AccumulatorAverageBlockless(); } }); pSplitter.putDataInfo(meterP.getDataInfo()); // collect pressure data before any insert/delete trials sim.integrator.getEventManager().addListener(new IIntegratorListener() { long countDown = numAtoms, interval = numAtoms; public void integratorInitialized(IIntegratorEvent e) {} public void integratorStepStarted(IIntegratorEvent e) {} public void integratorStepFinished(IIntegratorEvent e) { countDown if (countDown==0) { // everything really wants beta P IData pData = meterP.getData(); pData.TE(1.0/temperature); pSplitter.putData(pData); countDown=interval; } } }); final MCMoveIDBiasAction mcMoveBiasAction; final IntegratorListenerAction mcMoveBiasListener; if (params.doReweight) { mcMoveBiasAction = new MCMoveIDBiasAction(sim.integrator, sim.mcMoveID, maxDN, fixedN, mu, mcMoveOverlapMeter, numAtoms, 1); mcMoveBiasAction.setNMaxReweight(numAtoms); mcMoveBiasAction.setDefaultDaDef(daDef); mcMoveBiasListener = new IntegratorListenerAction(mcMoveBiasAction, biasInterval); sim.integrator.getEventManager().addListener(mcMoveBiasListener); } else { mcMoveBiasAction = null; mcMoveBiasListener = null; } if (graphics) { MeterNMolecules meterN = new MeterNMolecules(); meterN.setBox(sim.box); final AccumulatorHistogram nHistogram = new AccumulatorHistogram(new HistogramDiscrete(0.1)); DataPumpListener nPump = new DataPumpListener(meterN, nHistogram, numAtoms); sim.integrator.getEventManager().addListener(nPump); final String APP_NAME = "LJ Vacancy"; final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, numAtoms, sim.space, sim.getController()); final int nc = (int)Math.round(Math.pow(numAtoms/4, 1.0/3.0)); ColorScheme colorScheme = new ColorScheme() { public Color getAtomColor(IAtom a) { float x = (float)a.getPosition().getX(0); float L = (float)sim.box.getBoundary().getBoxSize().getX(0); x = nc*2*(x/L+0.5f); if (nc%2==0) x+=0.5f; while (x>3) x-=3; float r = 0f, g = 0f, b = 0f; if (x < 1) { r = 1-x; if (r>1) r=1; g = x; if (g<0) g=0; } else if (x < 2) { g = 2-x; b = x-1; } else { b = 3-x; if (b<0) b=0; r = x-2; if (r>1) r=1; } return new Color(r, g, b); } }; colorScheme = new ColorScheme() { IVectorMutable dr = sim.space.makeVector(); double rMax = sim.mcMoveID.getMaxDistance(); double rc2 = rMax*rMax; int nmax = 12; Api1ACell iter = new Api1ACell(3, rMax, sim.potentialMaster.getCellAgentManager()); public Color getAtomColor(IAtom a) { if (!sim.integrator.getEventManager().firingEvent() && !sim.ai.isPaused()) return new Color(1.0f, 1.0f, 1.0f); IVector pi = a.getPosition(); iter.setBox(sim.box); iter.setDirection(null); iter.setTarget(a); iter.reset(); IBoundary boundary = sim.box.getBoundary(); int n = 0; for (IAtomList pair = iter.next(); pair!=null; pair=iter.next()) { IAtom nbrj = pair.getAtom(0); if (nbrj==a) nbrj=pair.getAtom(1); dr.Ev1Mv2(pi, nbrj.getPosition()); boundary.nearestImage(dr); double r2 = dr.squared(); if (r2 < rc2) { n++; } } if (n < nmax) return Color.RED; if (n == nmax) return Color.BLUE; return Color.BLUE; } }; simGraphic.getDisplayBox(sim.box).setColorScheme(colorScheme); DiameterHash dh = new DiameterHash() { IVectorMutable dr = sim.space.makeVector(); double rMax = sim.mcMoveID.getMaxDistance(); double rc2 = rc*rc; int nmax = 12; Api1ACell iter = new Api1ACell(3, rMax, sim.potentialMaster.getCellAgentManager()); public double getDiameter(IAtom a) { IVector pi = a.getPosition(); IBoundary boundary = sim.box.getBoundary(); iter.setBox(sim.box); iter.setDirection(null); iter.setTarget(a); try { iter.reset(); } catch (NullPointerException ex) { // during addition return 0; } int n = 0; for (IAtomList pair = iter.next(); pair!=null; pair=iter.next()) { IAtom nbrj = pair.getAtom(0); if (nbrj==a) nbrj=pair.getAtom(1); dr.Ev1Mv2(pi, nbrj.getPosition()); boundary.nearestImage(dr); double r2 = dr.squared(); if (r2 < rc2) { n++; } } if (n < nmax) return 1.0; if (n == nmax) return 0.1; return 0.1; } }; // simGraphic.getDisplayBox(sim.box).setDiameterHash(dh); simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box)); simGraphic.makeAndDisplayFrame(APP_NAME); final AccumulatorHistory nHistory = new AccumulatorHistory(new HistoryCollapsingAverage()); DataSourceCountSteps timeDataSource = new DataSourceCountSteps(sim.integrator); nHistory.setTimeDataSource(timeDataSource); nHistory.setPushInterval(1); DataFork nFork = new DataFork(); nPump.setDataSink(nFork); nFork.addDataSink(nHistogram); nFork.addDataSink(nHistory); DisplayPlot nHistoryPlot = new DisplayPlot(); nHistoryPlot.setLabel("N history"); nHistoryPlot.setDoLegend(false); nHistory.setDataSink(nHistoryPlot.getDataSet().makeDataSink()); simGraphic.add(nHistoryPlot); DisplayPlot nPlot = new DisplayPlot(); nPlot.setLabel("N histogram"); nPlot.getPlot().setYLog(true); nHistogram.setDataSink(nPlot.getDataSet().makeDataSink()); nPlot.setLegend(new DataTag[]{nHistogram.getTag()}, "visited"); simGraphic.add(nPlot); final DataSourceFEHistogram feHistogram = new DataSourceFEHistogram(mcMoveOverlapMeter, mu); DataPumpListener feHistPump = new DataPumpListener(feHistogram, nPlot.getDataSet().makeDataSink(), numAtoms); sim.integrator.getEventManager().addListener(feHistPump); nPlot.setLegend(new DataTag[]{feHistogram.getTag()}, "measured"); final DataSourceImposedFEHistogram feHistogramImposed = new DataSourceImposedFEHistogram(mcMoveOverlapMeter, sim.mcMoveID, mu); DataPumpListener feHistImposedPump = new DataPumpListener(feHistogramImposed, nPlot.getDataSet().makeDataSink(), numAtoms); nPlot.setLegend(new DataTag[]{feHistogramImposed.getTag()}, "imposed"); sim.integrator.getEventManager().addListener(feHistImposedPump); final DataSourceImposedFEFit feHistogramFit = new DataSourceImposedFEFit(mcMoveOverlapMeter, sim.mcMoveID, mu); DataPumpListener feHistFitPump = new DataPumpListener(feHistogramFit, nPlot.getDataSet().makeDataSink(), numAtoms); nPlot.setLegend(new DataTag[]{feHistogramFit.getTag()}, "fit"); sim.integrator.getEventManager().addListener(feHistFitPump); DisplayPlot fePlot = new DisplayPlot(); final DataSourceFE dsfe = new DataSourceFE(mcMoveOverlapMeter); DataPumpListener fePump = new DataPumpListener(dsfe, fePlot.getDataSet().makeDataSink(), numAtoms); sim.integrator.getEventManager().addListener(fePump); fePlot.setLegend(new DataTag[]{dsfe.getTag()}, "FE"); final DataSourceFE dsfe2 = new DataSourceFE(mcMoveOverlapMeter); dsfe2.setSubtractComb(true); DataPumpListener fe2Pump = new DataPumpListener(dsfe2, fePlot.getDataSet().makeDataSink(), numAtoms); sim.integrator.getEventManager().addListener(fe2Pump); fePlot.setLegend(new DataTag[]{dsfe2.getTag()}, "FEdef"); final DataSourceFE dsfe3 = new DataSourceFE(mcMoveOverlapMeter); dsfe3.setSubtractComb(true); dsfe3.setAvgDef(true); DataPumpListener fe3Pump = new DataPumpListener(dsfe3, fePlot.getDataSet().makeDataSink(), numAtoms); sim.integrator.getEventManager().addListener(fe3Pump); fePlot.setLegend(new DataTag[]{dsfe3.getTag()}, "FEdefAvg"); fePlot.setLabel("FE"); simGraphic.add(fePlot); DisplayTextBox pDisplayBox = new DisplayTextBox(); pDisplayBox.setLabel("Measured pressure"); pDisplayBox.setPrecision(5); DisplayTextBox pDisplayBox2 = new DisplayTextBox(); pDisplayBox2.setLabel("Pressure"); pDisplayBox2.setPrecision(5); final DataSourceAvgPressure avgP = new DataSourceAvgPressure(pSplitter, mcMoveOverlapMeter, mu); DataPumpListener avgPPump = new DataPumpListener(avgP, pDisplayBox, numAtoms); sim.integrator.getEventManager().addListener(avgPPump); final DataSourceAvgPressure2 avgP2 = new DataSourceAvgPressure2(mcMoveOverlapMeter, mu, Alat, density, numAtoms/density); DataPumpListener avgPPump2 = new DataPumpListener(avgP2, pDisplayBox2, numAtoms); sim.integrator.getEventManager().addListener(avgPPump2); simGraphic.add(pDisplayBox); simGraphic.add(pDisplayBox2); DisplayPlot pmuPlot = new DisplayPlot(); pmuPlot.setDoLegend(false); pmuPlot.setLabel("dP vs. mu"); final DataSourcePMu pmu = new DataSourcePMu(mcMoveOverlapMeter, 0.2, 21, mu, pSplitter, Alat, density, numAtoms/density, false); DataPumpListener pmuPump = new DataPumpListener(pmu, pmuPlot.getDataSet().makeDataSink(), numAtoms); sim.integrator.getEventManager().addListener(pmuPump); simGraphic.add(pmuPlot); DisplayPlot muMuPlot = new DisplayPlot(); muMuPlot.setDoLegend(false); muMuPlot.setLabel("mu vs. mu"); final DataSourcePMu muMu = new DataSourcePMu(mcMoveOverlapMeter, 0.2, 21, mu, pSplitter, Alat, density, numAtoms/density, true); DataPumpListener muMuPump = new DataPumpListener(muMu, muMuPlot.getDataSet().makeDataSink(), numAtoms); sim.integrator.getEventManager().addListener(muMuPump); simGraphic.add(muMuPlot); DeviceBox muBox = new DeviceBox(); muBox.setPrecision(8); muBox.setEditable(true); muBox.setLabel("mu"); muBox.setModifier(new Modifier() { public void setValue(double newValue) { sim.mcMoveID.setMu(newValue); feHistogram.setMu(newValue); feHistogramImposed.setMu(newValue); avgP.setMu(newValue); avgP2.setBetaMu(newValue); pmu.setMu(newValue); mcMoveBiasAction.setMu(newValue); } public double getValue() { return sim.mcMoveID.getMu(); } public String getLabel() { return "your mom"; } public Dimension getDimension() { return Null.DIMENSION; } }); simGraphic.add(muBox); DataSourceMuRoot dsmr = new DataSourceMuRoot(mcMoveOverlapMeter, mu, pSplitter, Alat, density, numAtoms/density); final AccumulatorHistory dsmrHistory = new AccumulatorHistory(new HistoryCollapsingDiscard()); dsmrHistory.setTimeDataSource(timeDataSource); DataPumpListener dsmrPump = new DataPumpListener(dsmr, dsmrHistory, numAtoms); sim.integrator.getEventManager().addListener(dsmrPump); DisplayPlot dsmrPlot = new DisplayPlot(); dsmrPlot.setLabel("mu*"); dsmrPlot.setLegend(new DataTag[]{dsmr.getTag()},"avg"); dsmrHistory.setDataSink(dsmrPlot.getDataSet().makeDataSink()); simGraphic.add(dsmrPlot); DataSourceMuRoot1 dsmr1 = null; final AccumulatorHistory dsmr1History; dsmr1 = new DataSourceMuRoot1(mcMoveOverlapMeter, mu, pSplitter, Alat, density, numAtoms/density); dsmr1.setMinMu(10); dsmr1History = new AccumulatorHistory(new HistoryCollapsingDiscard()); dsmr1History.setTimeDataSource(timeDataSource); DataPumpListener dsmr1Pump = new DataPumpListener(dsmr1, dsmr1History, numAtoms); sim.integrator.getEventManager().addListener(dsmr1Pump); dsmr1History.setDataSink(dsmrPlot.getDataSet().makeDataSink()); dsmrPlot.setLegend(new DataTag[]{dsmr1.getTag()},"v1"); DataSourcePN dataSourcePN = new DataSourcePN(pSplitter, numAtoms); DisplayPlot plotPN = new DisplayPlot(); DataPumpListener pumpPN = new DataPumpListener(dataSourcePN, plotPN.getDataSet().makeDataSink(), numAtoms); sim.integrator.getEventManager().addListener(pumpPN); plotPN.setLabel("P vs. N"); plotPN.setDoLegend(false); simGraphic.add(plotPN); DataSourceMuRootVacancyConcentration dsmrvc = dsmr.new DataSourceMuRootVacancyConcentration(); final AccumulatorHistory dsmrvcHistory = new AccumulatorHistory(new HistoryCollapsingDiscard()); dsmrvcHistory.setTimeDataSource(timeDataSource); DataPumpListener dsmrvcPump = new DataPumpListener(dsmrvc, dsmrvcHistory, numAtoms); sim.integrator.getEventManager().addListener(dsmrvcPump); DisplayPlot vPlot = new DisplayPlot(); vPlot.setLabel("vacancies"); dsmrvcHistory.setDataSink(vPlot.getDataSet().makeDataSink()); vPlot.setLegend(new DataTag[]{dsmrvc.getTag()}, "avg"); simGraphic.add(vPlot); final AccumulatorHistory dsmrvc1History; DataSourceMuRoot1.DataSourceMuRootVacancyConcentration dsmrvc1 = dsmr1.new DataSourceMuRootVacancyConcentration(); dsmrvc1History = new AccumulatorHistory(new HistoryCollapsingDiscard()); dsmrvc1History.setTimeDataSource(timeDataSource); DataPumpListener dsmrvc1Pump = new DataPumpListener(dsmrvc1, dsmrvc1History, numAtoms); sim.integrator.getEventManager().addListener(dsmrvc1Pump); dsmrvc1History.setDataSink(vPlot.getDataSet().makeDataSink()); vPlot.setLegend(new DataTag[]{dsmrvc1.getTag()}, "v1"); final DeviceButton resetButton = new DeviceButton(sim.getController()); IAction resetAction = new IAction() { boolean enabled = true; public void actionPerformed() { if (enabled) { mcMoveOverlapMeter.reset(); sim.integrator.resetStepCount(); nHistogram.reset(); nHistory.reset(); dsmrHistory.reset(); if (dsmr1History != null) { dsmr1History.reset(); dsmrvc1History.reset(); } dsmrvcHistory.reset(); for (int i=0; i<pSplitter.getNumDataSinks(); i++) { AccumulatorAverageBlockless avg = (AccumulatorAverageBlockless)pSplitter.getDataSink(i); if (avg != null) avg.reset(); } sim.integrator.getEventManager().removeListener(mcMoveBiasListener); enabled = false; resetButton.setLabel("Reweight"); } else { sim.integrator.getEventManager().addListener(mcMoveBiasListener); enabled = true; resetButton.setLabel("Reset"); } } }; resetButton.setAction(resetAction); resetButton.setLabel("Reset"); simGraphic.getPanel().controlPanel.add(resetButton.graphic(),SimulationPanel.getVertGBC()); return; } final DataSourceFE dsfe3 = new DataSourceFE(mcMoveOverlapMeter); dsfe3.setSubtractComb(true); dsfe3.setAvgDef(true); // equilibrate off the lattice sim.ai.setMaxSteps(steps/40); sim.ai.actionPerformed(); IData dsfe3Data = dsfe3.getData(); if (dsfe3Data.getLength() == 0) { throw new RuntimeException("no data after initial equilibration"); } double daDefAvg = dsfe3Data.getValue(0); System.out.println("very initial daDef = "+daDefAvg); // throw away our data mcMoveOverlapMeter.reset(); sim.integrator.resetStepCount(); for (int i=0; i<pSplitter.getNumDataSinks(); i++) { AccumulatorAverageBlockless avg = (AccumulatorAverageBlockless)pSplitter.getDataSink(i); if (avg != null) avg.reset(); } sim.integrator.resetStepCount(); if (params.doReweight) { // update weights mcMoveBiasAction.actionPerformed(); // and stop adjusting them sim.integrator.getEventManager().removeListener(mcMoveBiasListener); } final long finalSteps = steps; sim.integrator.getEventManager().addListener(new IIntegratorListener() { boolean reenabled = false; public void integratorStepStarted(IIntegratorEvent e) {} public void integratorStepFinished(IIntegratorEvent e) { if (!reenabled && sim.integrator.getStepCount() >= finalSteps/40) { sim.integrator.getEventManager().addListener(mcMoveBiasListener); reenabled = true; } } public void integratorInitialized(IIntegratorEvent e) {} }); sim.ai.setMaxSteps(steps/10); sim.ai.actionPerformed(); if (params.doReweight) { dsfe3Data = dsfe3.getData(); daDefAvg = dsfe3Data.getValue(0); System.out.println("using daDef = "+daDefAvg); // update weights mcMoveBiasAction.actionPerformed(); // and stop adjusting them (permanently this time) sim.integrator.getEventManager().removeListener(mcMoveBiasListener); } // and throw away data again mcMoveOverlapMeter.reset(); for (int i=0; i<pSplitter.getNumDataSinks(); i++) { AccumulatorAverageBlockless avg = (AccumulatorAverageBlockless)pSplitter.getDataSink(i); if (avg != null) avg.reset(); } sim.integrator.resetStepCount(); sim.integrator.getMoveManager().setEquilibrating(false); // take real data long t1 = System.currentTimeMillis(); sim.ai.setMaxSteps(steps); sim.getController().actionPerformed(); long t2 = System.currentTimeMillis(); System.out.println(); DataSourceMuRoot dsmr = new DataSourceMuRoot(mcMoveOverlapMeter, mu, pSplitter, Alat, density, numAtoms/density); double muRoot = dsmr.getDataAsScalar(); // histogram of # of atoms based on free energy differences final DataSourceFEHistogram feHistogram = new DataSourceFEHistogram(mcMoveOverlapMeter, muRoot); // actual free energy differences final DataSourceFE dsfe = new DataSourceFE(mcMoveOverlapMeter); final DataSourceFE dsfe2 = new DataSourceFE(mcMoveOverlapMeter); // subtract off combinatorial entropy dsfe2.setSubtractComb(true); IData nData = feHistogram.getIndependentData(0); IData fenData = feHistogram.getData(); IData dsfeData = dsfe.getData(); IData dsfe2Data = dsfe2.getData(); dsfe3Data = dsfe3.getData(); double[] nHistogram = mcMoveOverlapMeter.getHistogram(); for (int i=0; i<nData.getLength(); i++) { int n = (int)Math.round(nData.getValue(i)); double pAvg = Double.NaN; if (numAtoms-n < pSplitter.getNumDataSinks()) { AccumulatorAverageBlockless pAcc = (AccumulatorAverageBlockless)pSplitter.getDataSink(numAtoms-n); pAvg = pAcc == null ? Double.NaN : pAcc.getData().getValue(pAcc.AVERAGE.index); } if (dsfeData.getLength() > i) { System.out.println(String.format("%6d %20.15e %20.15e %20.15e %20.15e %20.15e", n, nHistogram[i], fenData.getValue(i), pAvg, dsfeData.getValue(i), dsfe2Data.getValue(i))); } else { System.out.println(String.format("%6d %20.15e %20.15e %20.15e", n, nHistogram[i], fenData.getValue(i), pAvg)); } } double pAccept = sim.mcMoveID.getTracker().acceptanceProbability(); System.out.println("\nInsert/delete acceptance "+pAccept); System.out.println("final daDef: "+dsfe3Data.getValue(0)); System.out.println("mu: "+muRoot); double pRoot = dsmr.getLastPressure(); double vRoot = dsmr.getLastVacancyConcentration(); System.out.println("pressure: "+pRoot); double deltaP = dsmr.getLastDPressure(); System.out.println("delta P: "+deltaP); System.out.println("vacancy fraction: "+vRoot); double tot = dsmr.getLastTot(); double deltaA = -(1-vRoot)*Math.log(tot)/numAtoms - vRoot/density*deltaP/temperature; // free energy change per lattice site System.out.println("delta betaA: "+deltaA); System.out.println("time: "+(t2-t1)/1000.0+" seconds"); } public static class LJParams extends ParameterBase { public int numAtoms = 500; public double density = 1.0; public double temperature = 0.8; public long steps = 1000000; public boolean graphics = false; public double mu = Double.NaN; public double Alat = Double.NaN; public int numV = 5; public boolean doReweight = true; public double daDef = Double.NaN; public double rc = 3; } }
package etomica.virial.cluster; import etomica.math.SpecialFunctions; import etomica.utility.Arrays; import etomica.virial.Cluster; import etomica.virial.ClusterAbstract; import etomica.virial.ClusterSum; import etomica.virial.MayerFunction; import etomica.virial.Cluster.BondGroup; /** * @author kofke * * Class that provides some standard pair sets (via static methods or fields of * integer arrays) used in specification of clusters. */ public final class Standard { /** * Private constructor to prevent instantiation. */ private Standard() { super(); } /** * Returns a chain of bonds, {{0,1},{1,2},...{n-2,n-1}} * @param n number of points in chain * @return int[][] array describing chain of bonds */ public static int[][] chain(int n) { int[][] array = new int[n-1][]; for(int i=0; i<n-1; i++) { array[i] = new int[] {i,i+1}; } return array; } /** * Returns a ring of bonds, {{0,1},{1,2},...{n-2,n-1},{n-1,0}} * @param n number of points in ring * @return int[][] array describing ring of bonds */ public static int[][] ring(int n) { int[][] array = new int[n][]; for(int i=0; i<n-1; i++) { array[i] = new int[] {i,i+1}; } array[n-1] = new int[] {0,n-1}; return array; } /** * Returns a full set of bonds, such that each of the n points is joined to * each of the others. Starts labeling points at 0. */ public static int[][] full(int n) { return full(n, 0); } /** * Returns a full set of bonds, such that each of the n points is joined to * each of the others; starts labeling of point using the given index * <first>. For example, full(3,2) returns {{2,3},{2,4},{3,4}}, which can * be compared to full(3), which returns {{0,1},{0,2},{1,2}} */ public static int[][] full(int n, int first) { int[][] array = new int[n*(n-1)/2][]; int k = 0; for(int i=0; i<n-1; i++) { for(int j=i+1; j<n; j++) { array[k++] = new int[] {i+first,j+first}; } } return array; } /** Prepares a set of bond pairs for a clusters * formed from a disconnected set of fully connected subclusters. * @param iSet element [k] describes the number of subclusters having k * points * @return int[][] the bond array built to the given specification */ public static int[][] product(int[] iSet) { int n = 0; for(int i=1; i<=iSet.length; i++) n += iSet[i-1]*i*(i-1)/2; int[][] array = new int[n][]; int j = 0; int first = iSet[0];//only single points (Q1) (no integer pairs) for number of points equal to iSet[0] for(int i=2; i<=iSet.length; i++) { //{1, 2, 0, 0, 0} = {Q1, 2Q2, etc} start with Q2 for(int k=0; k<iSet[i-1]; k++) {//e.g. make 2 Q2 sets {0,1}, {2,3} int[][] a = full(i, first); for(int m=0; m<a.length; m++) array[j++] = a[m];//add integer pairs for this group to array of all pairs first += i; } } return array; } public static ClusterAbstract virialCluster(int nBody, MayerFunction f) { return virialCluster(nBody,f,true); } public static ClusterAbstract virialCluster(int nBody, MayerFunction f, boolean usePermutations) { ClusterDiagram clusterD = new ClusterDiagram(nBody,0); ClusterGenerator generator = new ClusterGenerator(clusterD); generator.setAllPermutations(!usePermutations); generator.setOnlyDoublyConnected(true); generator.setExcludeArticulationPoint(false); generator.setExcludeArticulationPair(false); generator.setExcludeNodalPoint(false); generator.reset(); ClusterAbstract[] clusters = new ClusterAbstract[0]; double[] weights = new double[0]; int fullSymmetry = usePermutations ? SpecialFunctions.factorial(nBody) : 1; double weightPrefactor = -fullSymmetry*nBody/(double)(nBody-1); do { int numBonds = clusterD.getNumConnections(); int[][] bondList = new int[numBonds][2]; int iBond = 0; for (int i = 0; i < nBody; i++) { int[] iConnections = clusterD.mConnections[i]; for (int j = 0; j < nBody - 1 && iConnections[j] != -1; j++) { if (i < iConnections[j]) { bondList[iBond][0] = i; bondList[iBond++][1] = iConnections[j]; } } } // only use permutations if the diagram has permutations boolean thisUsePermutations = usePermutations && clusterD.mNumIdenticalPermutations < fullSymmetry; clusters = (ClusterAbstract[])Arrays.addObject(clusters,new Cluster(nBody, new BondGroup[] {new BondGroup(f, bondList)}, thisUsePermutations)); double [] newWeights = new double[weights.length+1]; System.arraycopy(weights,0,newWeights,0,weights.length); newWeights[weights.length] = weightPrefactor/(usePermutations ? clusterD.mNumIdenticalPermutations : 1); weights = newWeights; } while (generator.advance()); if (clusters.length == 1) return clusters[0]; return new ClusterSum(clusters,weights); } public static final int[][] B2 = new int[][] {{0,1}}; public static final int[][] C3 = ring(3); public static final int[][] D4 = ring(4); public static final int[][] D5 = new int[][] {{0,1},{0,2},{0,3},{1,2},{2,3}}; public static final int[][] D6 = full(4); public static double B2HS(double sigma) { return 2.0*Math.PI/3.0 * sigma*sigma*sigma; } public static double C3HS(double sigma) { double b0 = B2HS(sigma); return 5./8. * b0 * b0; } public static double D4HS(double sigma) { double b0 = B2HS(sigma); return (219.0*Math.sqrt(2.0)/2240.0/Math.PI-89.0/280.0+4131.0/2240.0/Math.PI*Math.atan(Math.sqrt(2.0)))*b0*b0*b0; } public static Cluster[] B6Clusters(MayerFunction f) { int[][] FRH1 = new int[][] {{0,1},{0,2},{0,4},{0,5},{1,2},{1,3},{1,5} ,{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}}; int[][] FRH2 = new int[][] {{0,2},{0,3},{0,4},{0,5},{1,2},{1,3},{1,4},{1,5} ,{2,4},{2,5},{3,4},{3,5}}; int[][] FRH3 = new int[][] {{0,2},{0,3},{0,4},{1,2},{1,3},{1,4},{1,5} ,{2,3},{2,5},{3,4},{3,5},{4,5}}; int[][] FRH4 = new int[][] {{0,1},{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} ,{2,4},{2,5},{3,4},{3,5}}; int[][] FRH5 = new int[][] {{0,2},{0,3},{0,4},{0,5},{1,2},{1,3},{1,4},{1,5} ,{2,4},{2,5},{3,5}}; int[][] FRH6 = new int[][] {{0,1},{0,2},{0,3},{1,2},{1,4},{1,5} ,{2,3},{2,4},{2,5},{3,4},{3,5}}; int[][] FRH7 = new int[][] {{0,1},{0,3},{0,4},{0,5},{1,2},{1,3},{1,5} ,{2,3},{2,4},{2,5},{3,5}}; int[][] FRH8 = new int[][] {{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} ,{2,4},{2,5},{3,4},{3,5}}; int[][] FRH9 = new int[][] {{0,2},{0,3},{0,4},{0,5},{1,2},{1,3},{1,4},{1,5} ,{2,4},{3,5}}; int[][] FRH10 = new int[][] {{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} ,{2,3},{2,5},{3,4},{3,5}}; int[][] FRH11 = new int[][] {{0,1},{0,3},{0,4},{0,5},{1,2},{1,3},{1,5} ,{2,3},{2,4},{2,5}}; int[][] FRH12 = new int[][] {{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} ,{2,4},{2,5},{3,5}}; int[][] FRH13 = new int[][] {{0,2},{0,3},{1,3},{1,4},{1,5} ,{2,4},{2,5},{3,4},{3,5}}; int[][] FRH14 = new int[][] {{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} ,{2,5},{3,4},{3,5}}; int[][] FRH15 = new int[][] {{0,2},{0,3},{0,4},{1,4},{1,5} ,{2,4},{2,5},{3,5}}; int[][] FRH16 = new int[][] {{0,2},{0,3},{1,4},{1,5} ,{2,4},{2,5},{3,4},{3,5}}; //error int[][] FRH17 = new int[][] {{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} //error ,{2,5},{3,5}}; int[][] FRH17 = new int[][] {{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} ,{2,5},{3,4}}; int[][] FRH18 = new int[][] {{0,2},{0,3},{0,4},{1,3},{1,4},{1,5} ,{2,5}}; int[][] FRH19 = new int[][] {{0,2},{0,3},{1,4},{1,5} ,{2,4},{3,5}}; // rest which are negligible in hard spheres int[][] FRH20 = new int[][]{{0,1},{0,2},{0,3},{1,4},{1,5},{2,4},{2,5} ,{3,4},{3,5}}; int[][] FRH21 = new int[][]{{0,2},{0,3},{0,4},{0,5},{1,2},{1,3},{1,4},{1,5} ,{2,4}}; //error int[][] FRH22 = new int[][]{{0,2},{0,3},{0,4},{0,5},{1,3},{1,4},{1,5}}; int[][] FRH22 = new int[][]{{0,2},{0,3},{0,4},{0,5},{1,2},{1,3},{1,4},{1,5}}; Cluster f0 = new Cluster(6, new Cluster.BondGroup(f, Standard.full(6))); Cluster f1 = new ReeHoover(6, new Cluster.BondGroup(f, FRH1)); Cluster f2 = new ReeHoover(6, new Cluster.BondGroup(f, FRH2)); Cluster f3 = new ReeHoover(6, new Cluster.BondGroup(f, FRH3)); Cluster f4 = new ReeHoover(6, new Cluster.BondGroup(f, FRH4)); Cluster f5 = new ReeHoover(6, new Cluster.BondGroup(f, FRH5)); Cluster f6 = new ReeHoover(6, new Cluster.BondGroup(f, FRH6)); Cluster f7 = new ReeHoover(6, new Cluster.BondGroup(f, FRH7)); Cluster f8 = new ReeHoover(6, new Cluster.BondGroup(f, FRH8)); Cluster f9 = new ReeHoover(6, new Cluster.BondGroup(f, FRH9)); Cluster f10 = new ReeHoover(6, new Cluster.BondGroup(f, FRH10)); Cluster f11 = new ReeHoover(6, new Cluster.BondGroup(f, FRH11)); Cluster f12 = new ReeHoover(6, new Cluster.BondGroup(f, FRH12)); Cluster f13 = new ReeHoover(6, new Cluster.BondGroup(f, FRH13)); Cluster f14 = new ReeHoover(6, new Cluster.BondGroup(f, FRH14)); Cluster f15 = new ReeHoover(6, new Cluster.BondGroup(f, FRH15)); Cluster f16 = new ReeHoover(6, new Cluster.BondGroup(f, FRH16)); Cluster f17 = new ReeHoover(6, new Cluster.BondGroup(f, FRH17)); Cluster f18 = new ReeHoover(6, new Cluster.BondGroup(f, FRH18)); Cluster f19 = new ReeHoover(6, new Cluster.BondGroup(f, FRH19)); Cluster f20 = new ReeHoover(6, new Cluster.BondGroup(f, FRH20)); Cluster f21 = new ReeHoover(6, new Cluster.BondGroup(f, FRH21)); Cluster f22 = new ReeHoover(6, new Cluster.BondGroup(f, FRH22)); Cluster[] clusters = new Cluster[] {f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22}; for(int i=0; i<clusters.length; i++) clusters[i].setUsePermutations(true); return clusters; } public static double[] B6ClusterWeights() { double[] weights = new double[]{-24, -240, -1440, -360, 900, 240, 360, 360, -180, 288, -540, -240, -360, -1080, 720, 90, 360, -180, -60, -40, -180, -15}; for (int i=0; i<weights.length; i++) { weights[i] /= 144.0; } return weights; } public static void main(String[] args) { int[] iSet = new int[] {5,0,0,0,0}; int[][] array = product(iSet); int n = array.length; String string = "("; for(int i=0; i<n-1; i++) string += "{"+array[i][0]+","+array[i][1]+"}, "; if(n>0) string += "{"+array[n-1][0]+","+array[n-1][1]+"}"; string += ")"; System.out.println(string); } // 24 (5, 0, 0, 0, 0) // -60 (3, 1, 0, 0, 0) // 30 (1, 2, 0, 0, 0) // 20 (2, 0, 1, 0, 0) // -10 (0, 1, 1, 0, 0) // -5 (1, 0, 0, 1, 0) // 1 (0, 0, 0, 0, 1) }
package swarm.client.view.cell; import java.util.logging.Logger; import swarm.client.app.smClientAppConfig; import swarm.client.app.smAppContext; import swarm.client.entities.smCamera; import swarm.client.entities.smBufferCell; import swarm.client.entities.smE_CodeStatus; import swarm.client.input.smClickManager; import swarm.client.input.smI_ClickHandler; import swarm.client.managers.smCameraManager; import swarm.client.navigation.smBrowserNavigator; import swarm.client.navigation.smU_CameraViewport; import swarm.client.states.camera.Action_Camera_SnapToPoint; import swarm.client.states.camera.Action_Camera_SetViewSize; import swarm.client.states.camera.Action_Camera_SnapToAddress; import swarm.client.states.camera.Action_Camera_SnapToCoordinate; import swarm.client.states.camera.Action_ViewingCell_Refresh; import swarm.client.states.camera.StateMachine_Camera; import swarm.client.states.camera.State_CameraSnapping; import swarm.client.states.camera.State_ViewingCell; import swarm.client.states.code.Action_EditingCode_Preview; import swarm.client.states.code.Action_EditingCode_Save; import swarm.client.view.smE_ZIndex; import swarm.client.view.smI_UIElement; import swarm.client.view.smU_Css; import swarm.client.view.smViewContext; import swarm.client.view.tooltip.smE_ToolTipType; import swarm.client.view.tooltip.smToolTipConfig; import swarm.client.view.tooltip.smToolTipManager; import swarm.client.view.widget.smSpriteButton; import swarm.shared.app.smS_App; import swarm.shared.debugging.smU_Debug; import swarm.shared.entities.smA_Grid; import swarm.shared.entities.smE_CodeType; import swarm.shared.statemachine.smA_Action; import swarm.shared.statemachine.smA_State; import swarm.shared.statemachine.smE_StateTimeType; import swarm.shared.statemachine.smStateEvent; import swarm.shared.structs.smGridCoordinate; import swarm.shared.structs.smPoint; import swarm.shared.structs.smVector; import swarm.shared.utils.smU_Math; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant; public class smVisualCellHud extends FlowPanel implements smI_UIElement { private static final Logger s_logger = Logger.getLogger(smVisualCellHud.class.getName()); private static final smPoint s_utilPoint1 = new smPoint(); private static final smPoint s_utilPoint2 = new smPoint(); private static final smVector s_utilVector = new smVector(); private class smHudButton extends smSpriteButton { private smHudButton(String spriteId) { super(spriteId); this.addStyleName("sm_hud_button"); } } private final HorizontalPanel m_innerContainer = new HorizontalPanel(); private final HorizontalPanel m_leftDock = new HorizontalPanel(); private final HorizontalPanel m_rightDock = new HorizontalPanel(); private final smHudButton m_back = new smHudButton("back"); private final smHudButton m_forward = new smHudButton("forward"); private final smHudButton m_refresh = new smHudButton("refresh"); private final smHudButton m_close = new smHudButton("close"); private boolean m_waitingForBeingRefreshableAgain = false; private final smViewContext m_viewContext; private final smClientAppConfig m_appConfig; private final Action_Camera_SnapToPoint.Args m_args_SetCameraTarget = new Action_Camera_SnapToPoint.Args(); private final double m_minWidth = 169;// TODO: GHETTO private double m_width = 0; private double m_baseAlpha; private double m_alpha; private final double m_fadeOutTime_seconds; private String m_lastTranslation = ""; private final smPoint m_lastWorldPositionOnDoubleSnap = new smPoint(); private final smPoint m_lastWorldPosition = new smPoint(); private final smGridCoordinate m_lastSnapCoord = new smGridCoordinate(); private boolean m_performedDoubleSnap; public smVisualCellHud(smViewContext viewContext, smClientAppConfig appConfig) { m_viewContext = viewContext; m_appConfig = appConfig; m_fadeOutTime_seconds = m_viewContext.viewConfig.hudFadeOutTime_seconds; m_alpha = m_baseAlpha = 0.0; this.addStyleName("sm_cell_hud"); smE_ZIndex.CELL_HUD.assignTo(this); this.setVisible(false); m_innerContainer.setWidth("100%"); this.getElement().getStyle().setProperty("minWidth", m_minWidth + "px"); smU_Css.setTransformOrigin(this.getElement(), "0% 0%"); m_innerContainer.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); m_leftDock.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); m_rightDock.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); m_leftDock.add(m_back); m_leftDock.add(m_forward); m_leftDock.add(m_refresh); m_rightDock.add(m_close); m_innerContainer.add(m_leftDock); m_innerContainer.add(m_rightDock); m_innerContainer.setCellHorizontalAlignment(m_rightDock, HasHorizontalAlignment.ALIGN_RIGHT); this.add(m_innerContainer); m_viewContext.clickMngr.addClickHandler(m_back, new smI_ClickHandler() { @Override public void onClick(int x, int y) { if( !m_back.isEnabled() ) return; m_viewContext.browserNavigator.go(-1); } }); m_viewContext.clickMngr.addClickHandler(m_forward, new smI_ClickHandler() { @Override public void onClick(int x, int y) { if( !m_forward.isEnabled() ) return; m_viewContext.browserNavigator.go(1); } }); m_viewContext.clickMngr.addClickHandler(m_refresh, new smI_ClickHandler() { @Override public void onClick(int x, int y) { if( !m_refresh.isEnabled() ) return; smVisualCellHud.this.m_viewContext.cellMngr.clearAlerts(); m_viewContext.stateContext.performAction(Action_ViewingCell_Refresh.class); } }); m_viewContext.clickMngr.addClickHandler(m_close, new smI_ClickHandler() { @Override public void onClick(int x, int y) { if( !m_close.isEnabled() ) return; s_utilPoint1.copy(smVisualCellHud.this.m_viewContext.appContext.cameraMngr.getCamera().getPosition()); s_utilPoint1.incZ(m_appConfig.backOffDistance); m_args_SetCameraTarget.init(s_utilPoint1, false, true); m_viewContext.stateContext.performAction(Action_Camera_SnapToPoint.class, m_args_SetCameraTarget); } }); smToolTipManager toolTipper = m_viewContext.toolTipMngr; toolTipper.addTip(m_back, new smToolTipConfig(smE_ToolTipType.MOUSE_OVER, "Go back.")); toolTipper.addTip(m_forward, new smToolTipConfig(smE_ToolTipType.MOUSE_OVER, "Go forward.")); toolTipper.addTip(m_refresh, new smToolTipConfig(smE_ToolTipType.MOUSE_OVER, "Refresh this cell.")); toolTipper.addTip(m_close, new smToolTipConfig(smE_ToolTipType.MOUSE_OVER, "Back off.")); } private void setAlpha(double alpha) { m_alpha = alpha <= 0 ? 0 : alpha; //s_logger.severe(m_alpha + ""); this.getElement().getStyle().setOpacity(m_alpha); } private void updateCloseButton() { State_ViewingCell viewingState = m_viewContext.stateContext.getEnteredState(State_ViewingCell.class); State_CameraSnapping snappingState = m_viewContext.stateContext.getEnteredState(State_CameraSnapping.class); if( viewingState != null || snappingState != null && snappingState.getPreviousState() == State_ViewingCell.class ) { m_close.setEnabled(true); } else { m_close.setEnabled(false); } } private void updateRefreshButton() { boolean canRefresh = m_viewContext.stateContext.isActionPerformable(Action_ViewingCell_Refresh.class); m_refresh.setEnabled(canRefresh); if( !canRefresh ) { m_waitingForBeingRefreshableAgain = true; } else { m_waitingForBeingRefreshableAgain = false; } } private void updatePositionFromScreenPoint(smA_Grid grid, smPoint screenPoint) { smCamera camera = m_viewContext.appContext.cameraMngr.getCamera(); camera.calcWorldPoint(screenPoint, m_lastWorldPosition); boolean has3dTransforms = m_viewContext.appContext.platformInfo.has3dTransforms(); m_lastTranslation = smU_Css.createTranslateTransform(screenPoint.getX(), screenPoint.getY(), has3dTransforms); double scaling = m_viewContext.cellMngr.getLastScaling(); String scaleProperty = smU_Css.createScaleTransform(scaling, has3dTransforms); smU_Css.setTransform(this.getElement(), m_lastTranslation + " " + scaleProperty); } private void updateScalingOnly() { boolean has3dTransforms = m_viewContext.appContext.platformInfo.has3dTransforms(); double scaling = m_viewContext.cellMngr.getLastScaling(); String scaleProperty = smU_Css.createScaleTransform(scaling, has3dTransforms); smU_Css.setTransform(this.getElement(), m_lastTranslation + " " + scaleProperty); } private void updatePositionFromWorldPoint(smA_Grid grid, smPoint worldPoint) { smCamera camera = m_viewContext.appContext.cameraMngr.getCamera(); camera.calcScreenPoint(worldPoint, s_utilPoint2); this.updatePositionFromScreenPoint(grid, s_utilPoint2); } private void updatePosition(smA_Grid grid, smGridCoordinate coord) { this.calcScreenPositionFromCoord(grid, coord, s_utilPoint2); this.updatePositionFromScreenPoint(grid, s_utilPoint2); } private void calcScreenPositionFromCoord(smA_Grid grid, smGridCoordinate coord, smPoint point_out) { smCamera camera = m_viewContext.appContext.cameraMngr.getCamera(); coord.calcPoint(s_utilPoint1, grid.getCellWidth(), grid.getCellHeight(), grid.getCellPadding(), 1); camera.calcScreenPoint(s_utilPoint1, point_out); Element scrollElement = this.getParent().getElement(); double scrollX = scrollElement.getScrollLeft(); double scrollY = scrollElement.getScrollTop(); double x = point_out.getX() + scrollX*2; double viewWidth = getViewWidth(camera, grid); double hudWidth = Math.max(m_width, m_minWidth); if( hudWidth > viewWidth ) { double scrollWidth = scrollElement.getScrollWidth(); double clientWidth = scrollElement.getClientWidth(); double diff = (hudWidth - viewWidth) + smU_CameraViewport.getViewPadding(grid)/2.0; double scrollRatio = scrollX / (scrollWidth-clientWidth); x -= diff * scrollRatio; } double scaling = m_viewContext.cellMngr.getLastScaling(); double y = point_out.getY()-(m_appConfig.cellHudHeight+grid.getCellPadding())*scaling; y -= 1*scaling; // account for margin...sigh y += scrollY * scaling; point_out.set(x, y, 0); } private void updatePositionFromState(State_CameraSnapping state) { smA_Grid grid = m_viewContext.appContext.gridMngr.getGrid(); // TODO: Can be more than one grid in the future smGridCoordinate coord = state.getTargetCoordinate(); this.updatePosition(grid, coord); } private void updatePositionFromState(State_ViewingCell state) { smBufferCell cell = ((State_ViewingCell)state).getCell(); smA_Grid grid = cell.getGrid(); smGridCoordinate coord = cell.getCoordinate(); this.updatePosition(grid, coord); } private void updateHistoryButtons() { State_ViewingCell viewingState = m_viewContext.stateContext.getEnteredState(State_ViewingCell.class); State_CameraSnapping snappingState = m_viewContext.stateContext.getEnteredState(State_CameraSnapping.class); if( viewingState != null || snappingState != null && snappingState.getPreviousState() == State_ViewingCell.class ) { m_back.setEnabled(m_viewContext.browserNavigator.hasBack()); m_forward.setEnabled(m_viewContext.browserNavigator.hasForward()); } else { m_back.setEnabled(false); m_forward.setEnabled(false); } } private double getViewWidth(smCamera camera, smA_Grid grid) { double viewPadding = smU_CameraViewport.getViewPadding(grid); double viewWidth = camera.getViewWidth() - viewPadding*2; return viewWidth; } private void updateSize(State_ViewingCell state) { smA_Grid grid = state.getCell().getGrid(); smCamera camera = m_viewContext.appContext.cameraMngr.getCamera(); double viewWidth = getViewWidth(camera, grid); double cellWidth = grid.getCellWidth(); double hudWidth = Math.min(viewWidth, cellWidth); m_width = hudWidth - 9; // TODO: GHETTO...takes into account padding or something. //m_width = Math.max(m_width, m_minWidth); //s_logger.severe("hud width: " + m_width); this.getElement().getStyle().setWidth(m_width, Unit.PX); } private void onDoubleSnap() { m_lastWorldPositionOnDoubleSnap.copy(m_lastWorldPosition); m_performedDoubleSnap = true; } @Override public void onStateEvent(smStateEvent event) { switch( event.getType() ) { case DID_ENTER: { if( event.getState() instanceof State_ViewingCell ) { this.updateSize((State_ViewingCell) event.getState()); this.updatePositionFromState((State_ViewingCell) event.getState()); this.updateCloseButton(); this.updateHistoryButtons(); this.setAlpha(1); m_baseAlpha = m_alpha; } else if( event.getState() instanceof State_CameraSnapping ) { if( event.getState().getPreviousState() != State_ViewingCell.class ) { if( m_alpha <= 0 ) { this.updatePositionFromState((State_CameraSnapping)event.getState()); } this.setVisible(true); m_baseAlpha = m_alpha; // s_logger.severe("BASE ALPHA: " + m_baseAlpha); } this.updateCloseButton(); this.updateHistoryButtons(); m_performedDoubleSnap = false; } break; } case DID_FOREGROUND: { if( event.getState() instanceof State_ViewingCell ) { this.updateHistoryButtons(); this.updateRefreshButton(); } break; } case DID_UPDATE: { if( event.getState().getParent() instanceof StateMachine_Camera ) { if( event.getState() instanceof State_ViewingCell ) { State_ViewingCell viewingState = (State_ViewingCell) event.getState(); if( m_waitingForBeingRefreshableAgain ) { if( viewingState.isForegrounded() ) { updateRefreshButton(); } } } else if( event.getState() instanceof State_CameraSnapping ) { State_CameraSnapping cameraSnapping = m_viewContext.stateContext.getEnteredState(State_CameraSnapping.class); if( cameraSnapping != null ) { if( cameraSnapping.getPreviousState() != State_ViewingCell.class ) { //s_logger.severe(cameraSnapping.getOverallSnapProgress() + ""); this.setAlpha(m_baseAlpha + (1-m_baseAlpha) * cameraSnapping.getOverallSnapProgress()); //this.setAlpha((1 - m_baseAlpha) * (1 - )); } if( !m_performedDoubleSnap && cameraSnapping.getPreviousState() != State_ViewingCell.class) { this.updatePositionFromState((State_CameraSnapping)event.getState()); } else { smA_Grid grid = m_viewContext.appContext.gridMngr.getGrid(); smGridCoordinate coord = cameraSnapping.getTargetCoordinate(); smCameraManager cameraMngr = m_viewContext.appContext.cameraMngr; smCamera camera = cameraMngr.getCamera(); this.calcScreenPositionFromCoord(grid, coord, s_utilPoint2); camera.calcWorldPoint(s_utilPoint2, s_utilPoint2); s_utilPoint2.calcDifference(m_lastWorldPositionOnDoubleSnap, s_utilVector); double progress = cameraMngr.getSnapProgressRatio(); s_utilVector.scaleByNumber(progress); s_utilPoint2.copy(m_lastWorldPositionOnDoubleSnap); s_utilPoint2.translate(s_utilVector); this.updatePositionFromWorldPoint(grid, s_utilPoint2); } } } else if( !(event.getState() instanceof State_ViewingCell) ) { if( m_alpha <= 1 ) { if( event.getState().isEntered() ) { if( m_alpha > 0 ) { double timeMantissa = event.getState().getTimeInState(smE_StateTimeType.TOTAL) / m_fadeOutTime_seconds; timeMantissa = smU_Math.clamp(timeMantissa, 0, 1); this.setAlpha(m_baseAlpha * (1-timeMantissa)); smA_Grid grid = m_viewContext.appContext.gridMngr.getGrid(); this.updatePositionFromWorldPoint(grid, m_lastWorldPosition); if( m_alpha <= 0 ) { this.setVisible(false); } } } } } } break; } case DID_EXIT: { if( event.getState() instanceof State_ViewingCell || event.getState() instanceof State_CameraSnapping ) { m_baseAlpha = m_alpha; smCamera camera = m_viewContext.appContext.cameraMngr.getCamera(); if( event.getState() instanceof State_ViewingCell ) { m_waitingForBeingRefreshableAgain = false; this.updateCloseButton(); this.updateHistoryButtons(); this.updateRefreshButton(); } else if( event.getState() instanceof State_CameraSnapping ) { m_lastSnapCoord.set(-1, -1); } } break; } case DID_PERFORM_ACTION: { if( event.getAction() == Action_Camera_SetViewSize.class ) { State_ViewingCell state = event.getContext().getEnteredState(State_ViewingCell.class); if( state != null ) { this.updateSize(state); Action_Camera_SetViewSize.Args args = event.getActionArgs(); if( args.updateBuffer() ) { this.updatePositionFromState(state); } } else if( event.getContext().isEntered(State_CameraSnapping.class) ) { this.onDoubleSnap(); } } else if( event.getAction() == Action_Camera_SnapToPoint.class ) { State_ViewingCell state = event.getContext().getEnteredState(State_ViewingCell.class); if( state != null ) { Action_Camera_SnapToPoint.Args args = event.getActionArgs(); if( args.isInstant() ) { this.updatePositionFromState(state); } } } else if( event.getAction() == Action_Camera_SnapToCoordinate.class ) {s_logger.severe("snap to coord"); State_CameraSnapping state = event.getContext().getEnteredState(State_CameraSnapping.class); //if( state != null && (state.getUpdateCount() > 0 ) { //if( !m_lastSnapCoord.isEqualTo(state.getTargetCoordinate()) ) {s_logger.severe("double"); this.onDoubleSnap(); } } m_lastSnapCoord.copy(state.getTargetCoordinate()); } else if(( event.getAction() == Action_ViewingCell_Refresh.class || event.getAction() == Action_EditingCode_Save.class || event.getAction() == Action_EditingCode_Preview.class || event.getAction() == Action_Camera_SnapToAddress.class || event.getAction() == Action_Camera_SnapToCoordinate.class )) { updateRefreshButton(); } break; } } } }
import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class Game extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Puzzle"); GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(25,25,25,25)); String gridBName = ""; for (int i = 0; i<10; i++) { for (int j = 0; j<10; j++) { gridBName = "Button" + i + j; Button = new Button(gridBName); grid.add(); } } Button StartOver = new Button("Start Over"); Button Hint = new Button("Hint"); HBox hbBtn = new HBox(10); hbBtn.setAlignment(Pos.BASELINE_CENTER); hbBtn.getChildren().add(Hint); hbBtn.getChildren().add(StartOver); grid.add(hbBtn,1,10); primaryStage.setScene(new Scene(grid, 300, 300)); primaryStage.show(); } }
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.concurrent.TimeUnit; import static spark.Spark.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.philihp.weblabora.model.*; import org.apache.commons.codec.binary.Hex; public class Main { private static ObjectMapper objectMapper = new ObjectMapper(); private static Cache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100000) .expireAfterAccess(7, TimeUnit.DAYS) .build(); public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); get("/:hash", "application/json", (request, response) -> { String hash = request.params(":hash"); return cache.get(hash, () -> { response.status(404); return "{\"error\":\"Forgot state of board. Please retry.\"}"; }); }); get("/", "application/json", (request, response) -> {; return Boolean.FALSE; }); post("/", "application/json", (request, response) -> { String hash = hash(request.body()); Board board = new Board(); String[] tokens = request.body().split("\n+"); for (String token : tokens) { MoveProcessor.processMove(board, token); } cache.put(hash, objectMapper.valueToTree(board).toString()); response.redirect("/" + hash, 303); // very important to use 303 return null; });
import static javax.measure.unit.SI.KILOGRAM; import javax.measure.quantity.Mass; import org.jscience.physics.model.RelativisticModel; import org.jscience.physics.amount.Amount; import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/hello", (req, res) -> "Hello World"); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); } }
// import static javax.measure.unit.SI.KILOGRAM; // import javax.measure.quantity.Mass; // import org.jscience.physics.model.RelativisticModel; // import org.jscience.physics.amount.Amount; import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); // get("/hello", (req, res) -> { // RelativisticModel.select(); // String energy = System.getenv().get("ENERGY"); // Amount<Mass> m = Amount.valueOf(energy).to(KILOGRAM); // return "E=mc^2: " + energy + " = " + m.toString(); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); } }
package nl.cwi.monetdb.jdbc; import java.sql.*; import java.util.*; /** * A DatabaseMetaData object suitable for the Monet database * <br /><br /> * * @author Fabian Groffen <Fabian.Groffen@cwi.nl> * @version 0.3 (beta release) */ public class MonetDatabaseMetaData implements DatabaseMetaData { private Connection con; private Driver driver; private Statement stmt; private Map envs; public MonetDatabaseMetaData(Connection parent) { con = parent; driver = new MonetDriver(); } private synchronized Statement getStmt() throws SQLException { if (stmt == null) stmt = con.createStatement(); return(stmt); } private synchronized Map getEnvMap() throws SQLException { if (envs == null) { // make the env map envs = new HashMap(); ResultSet env = getStmt().executeQuery("SELECT * FROM env"); while (env.next()) { envs.put(env.getString("name"), env.getString("value")); } env.close(); } return(envs); } /** * Can all the procedures returned by getProcedures be called * by the current user? * * @return true if so */ public boolean allProceduresAreCallable() { return(true); } /** * Can all the tables returned by getTable be SELECTed by * the current user? * * @return true because we only have one user a.t.m. */ public boolean allTablesAreSelectable() { return(true); } /** * What is the URL for this database? * * @return a reconstructed connection string * @throws SQLException if a database access error occurs */ public String getURL() throws SQLException { Map env = getEnvMap(); return("jdbc:monetdb://" + (String)env.get("host") + ":" + (String)env.get("sql_port") + "/" + (String)env.get("gdk_dbname")); } /** * What is our user name as known to the database? * * @return sql user * @throws SQLException if a database access error occurs */ public String getUserName() throws SQLException { Map env = getEnvMap(); return((String)env.get("sql_user")); } /** * Is the database in read-only mode? * * @return always false for now */ public boolean isReadOnly() { return(false); } /** * Are NULL values sorted high? * * @return true because Monet puts NULL values on top upon ORDER BY */ public boolean nullsAreSortedHigh() { return(true); } /** * Are NULL values sorted low? * * @return negative of nullsAreSortedHigh() * @see #nullsAreSortedHigh() */ public boolean nullsAreSortedLow() { return(!nullsAreSortedHigh()); } /** * Are NULL values sorted at the start regardless of sort order? * * @return false, since Monet doesn't do this */ public boolean nullsAreSortedAtStart() { return(false); } /** * Are NULL values sorted at the end regardless of sort order? * * @return false, since Monet doesn't do this */ public boolean nullsAreSortedAtEnd() { return(false); } /** * What is the name of this database product - this should be MonetDB * of course, so we return that explicitly. * * @return the database product name */ public String getDatabaseProductName() { return "MonetDB"; } /** * What is the version of this database product. * * @return a fixed version number, yes it's quick and dirty * @throws SQLException if a database access error occurs */ public String getDatabaseProductVersion() throws SQLException { Map env = getEnvMap(); return((String)env.get("gdk_version")); } /** * What is the name of this JDBC driver? If we don't know this * we are doing something wrong! * * @return the JDBC driver name */ public String getDriverName() { return("MonetDB Native Driver"); } /** * What is the version string of this JDBC driver? Again, this is * static. * * @return the JDBC driver name. */ public String getDriverVersion() { return(((MonetDriver)driver).getDriverVersion()); } /** * What is this JDBC driver's major version number? * * @return the JDBC driver major version */ public int getDriverMajorVersion() { return(driver.getMajorVersion()); } /** * What is this JDBC driver's minor version number? * * @return the JDBC driver minor version */ public int getDriverMinorVersion() { return(driver.getMinorVersion()); } /** * Does the database store tables in a local file? No - it * stores them in a file on the server. * * @return false because that's what Monet is for */ public boolean usesLocalFiles() { return(false); } /** * Does the database use a local file for each table? Well, not really, * since it doesn't use local files. * * @return false for it doesn't */ public boolean usesLocalFilePerTable() { return(false); } /** * Does the database treat mixed case unquoted SQL identifiers * as case sensitive and as a result store them in mixed case? * A JDBC-Compliant driver will always return false. * * @return false */ public boolean supportsMixedCaseIdentifiers() { return(false); } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in upper case? * * @return true if so */ public boolean storesUpperCaseIdentifiers() { return(false); } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in lower case? * * @return true if so */ public boolean storesLowerCaseIdentifiers() { return(true); } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in mixed case? * * @return true if so */ public boolean storesMixedCaseIdentifiers() { return(false); } /** * Does the database treat mixed case quoted SQL identifiers as * case sensitive and as a result store them in mixed case? A * JDBC compliant driver will always return true. * * @return true if so */ public boolean supportsMixedCaseQuotedIdentifiers() { return(true); } /** * Does the database treat mixed case quoted SQL identifiers as * case insensitive and store them in upper case? * * @return true if so */ public boolean storesUpperCaseQuotedIdentifiers() { return(false); } /** * Does the database treat mixed case quoted SQL identifiers as case * insensitive and store them in lower case? * * @return true if so */ public boolean storesLowerCaseQuotedIdentifiers() { return(false); } /** * Does the database treat mixed case quoted SQL identifiers as case * insensitive and store them in mixed case? * * @return true if so */ public boolean storesMixedCaseQuotedIdentifiers() { return(false); } /** * What is the string used to quote SQL identifiers? This returns * a space if identifier quoting isn't supported. A JDBC Compliant * driver will always use a double quote character. * * @return the quoting string */ public String getIdentifierQuoteString() { return("\""); } /** * Get a comma separated list of all a database's SQL keywords that * are NOT also SQL92 keywords. * <br /><br /> * Wasn't MonetDB fully standards compliant? So no extra keywords... * * @return a comma separated list of keywords we use (none) */ public String getSQLKeywords() { return(""); } public String getNumericFunctions() { return(""); } public String getStringFunctions() { return(""); } public String getSystemFunctions() { return(""); } public String getTimeDateFunctions() { return(""); } /** * This is the string that can be used to escape '_' and '%' in * a search string pattern style catalog search parameters * * @return the string used to escape wildcard characters */ public String getSearchStringEscape() { return("\\"); } /** * Get all the "extra" characters that can be used in unquoted * identifier names (those beyond a-zA-Z0-9 and _) * Monet has no extras * * @return a string containing the extra characters */ public String getExtraNameCharacters() { return(""); } /** * Is "ALTER TABLE" with an add column supported? * * @return true if so */ public boolean supportsAlterTableWithAddColumn() { return(true); } /** * Is "ALTER TABLE" with a drop column supported? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsAlterTableWithDropColumn() { return(true); } public boolean supportsColumnAliasing() { return(true); } /** * Are concatenations between NULL and non-NULL values NULL? A * JDBC Compliant driver always returns true * * @return true if so * @throws SQLException if a database access error occurs */ public boolean nullPlusNonNullIsNull() { return(true); } public boolean supportsConvert() { return(false); } public boolean supportsConvert(int fromType, int toType) { return(false); } /** * Are table correlation names supported? A JDBC Compliant * driver always returns true. * * @return true if so */ public boolean supportsTableCorrelationNames() { return(true); } /** * If table correlation names are supported, are they restricted to * be different from the names of the tables? * * @return true if so; false otherwise */ public boolean supportsDifferentTableCorrelationNames() { return(false); } /** * Are expressions in "ORDER BY" lists supported? * * <br>e.g. select * from t order by a + b; * * MonetDB does not support this (yet?) * * @return true if so */ public boolean supportsExpressionsInOrderBy() { return(false); } /** * Can an "ORDER BY" clause use columns not in the SELECT? * Monet = SQL99 = false * * @return true if so */ public boolean supportsOrderByUnrelated() { return(false); } /** * Is some form of "GROUP BY" clause supported? * * @return true since MonetDB supports it * @exception SQLException if a database access error occurs */ public boolean supportsGroupBy() { return(true); } /** * Can a "GROUP BY" clause use columns not in the SELECT? * * @return true since that also is supported * @exception SQLException if a database access error occurs */ public boolean supportsGroupByUnrelated() { return(true); } /** * Can a "GROUP BY" clause add columns not in the SELECT provided * it specifies all the columns in the SELECT? * * (Monet already supports the more difficult supportsGroupByUnrelated(), * so this is a piece of cake) * * @return true if so */ public boolean supportsGroupByBeyondSelect() { return(true); } /** * Is the escape character in "LIKE" clauses supported? A * JDBC compliant driver always returns true. * * @return true if so */ public boolean supportsLikeEscapeClause() { return(true); } /** * Are multiple ResultSets from a single execute supported? * MonetDB probably supports it, but I don't * * @return true if so */ public boolean supportsMultipleResultSets() { return(false); } /** * Can we have multiple transactions open at once (on different * connections?) * This is the main idea behind the Connection, is it? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsMultipleTransactions() { return(true); } /** * Can columns be defined as non-nullable. A JDBC Compliant driver * always returns true. * * @return true if so */ public boolean supportsNonNullableColumns() { return(true); } public boolean supportsMinimumSQLGrammar() { return(true); } /** * Does this driver support the Core ODBC SQL grammar. We need * SQL-92 conformance for this. * * @return true if so */ public boolean supportsCoreSQLGrammar() { return(true); } /** * Does this driver support the Extended (Level 2) ODBC SQL * grammar. We don't conform to the Core (Level 1), so we can't * conform to the Extended SQL Grammar. * * @return true if so */ public boolean supportsExtendedSQLGrammar() { return(false); } /** * Does this driver support the ANSI-92 entry level SQL grammar? * All JDBC Compliant drivers must return true. We should be this * compliant, so let's 'act' like we are. * * @return true if so */ public boolean supportsANSI92EntryLevelSQL() { return(true); } /** * Does this driver support the ANSI-92 intermediate level SQL * grammar? * probably not * * @return true if so */ public boolean supportsANSI92IntermediateSQL() { return(false); } /** * Does this driver support the ANSI-92 full SQL grammar? * Would be good if it was like that * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsANSI92FullSQL() { return(false); } /** * Is the SQL Integrity Enhancement Facility supported? * Our best guess is that this means support for constraints * * @return true if so */ public boolean supportsIntegrityEnhancementFacility() { return(true); } /** * Is some form of outer join supported? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsOuterJoins(){ return(true); } /** * Are full nexted outer joins supported? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsFullOuterJoins() { return(true); } /** * Is there limited support for outer joins? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean supportsLimitedOuterJoins() { return(false); } /** * What is the database vendor's preferred term for "schema"? * MonetDB uses the term "schema". * * @return the vendor term */ public String getSchemaTerm() { return("schema"); } /** * What is the database vendor's preferred term for "procedure"? * Traditionally, "function" has been used. * * @return the vendor term */ public String getProcedureTerm() { return("function"); } /** * What is the database vendor's preferred term for "catalog"? * MonetDB doesn't really have them (from driver accessible) but * from the monetdb.conf file the term "database" sounds best * * @return the vendor term */ public String getCatalogTerm() { return("database"); } /** * Does a catalog appear at the start of a qualified table name? * (Otherwise it appears at the end). * Currently there is no catalog support at all in MonetDB * * @return true if so */ public boolean isCatalogAtStart() { // return true here; we return false for every other catalog function // so it won't matter what we return here return(true); } /** * What is the Catalog separator. * * @return the catalog separator string */ public String getCatalogSeparator() { // Give them something to work with here // everything else returns false so it won't matter what we return here return("."); } /** * Can a schema name be used in a data manipulation statement? * * @return true if so */ public boolean supportsSchemasInDataManipulation() { return(true); } /** * Can a schema name be used in a procedure call statement? * Ohw probably, but I don't know of procedures in Monet * * @return true if so */ public boolean supportsSchemasInProcedureCalls() { return(true); } /** * Can a schema be used in a table definition statement? * * @return true if so */ public boolean supportsSchemasInTableDefinitions() { return(true); } /** * Can a schema name be used in an index definition statement? * * @return true if so */ public boolean supportsSchemasInIndexDefinitions() { return(true); } /** * Can a schema name be used in a privilege definition statement? * * @return true if so */ public boolean supportsSchemasInPrivilegeDefinitions() { return(true); } /** * Can a catalog name be used in a data manipulation statement? * * @return true if so */ public boolean supportsCatalogsInDataManipulation() { return(false); } /** * Can a catalog name be used in a procedure call statement? * * @return true if so */ public boolean supportsCatalogsInProcedureCalls() { return(false); } /** * Can a catalog name be used in a table definition statement? * * @return true if so */ public boolean supportsCatalogsInTableDefinitions() { return(false); } /** * Can a catalog name be used in an index definition? * * @return true if so */ public boolean supportsCatalogsInIndexDefinitions() { return(false); } /** * Can a catalog name be used in a privilege definition statement? * * @return true if so */ public boolean supportsCatalogsInPrivilegeDefinitions() { return(false); } /** * MonetDB doesn't support positioned DELETEs I guess * * @return true if so */ public boolean supportsPositionedDelete() { return(false); } /** * Is positioned UPDATE supported? (same as above) * * @return true if so */ public boolean supportsPositionedUpdate() { return(false); } /** * Is SELECT FOR UPDATE supported? * My test resulted in a negative answer * * @return true if so; false otherwise */ public boolean supportsSelectForUpdate(){ return(false); } /** * Are stored procedure calls using the stored procedure escape * syntax supported? * * @return true if so; false otherwise */ public boolean supportsStoredProcedures() { return(false); } /** * Are subqueries in comparison expressions supported? A JDBC * Compliant driver always returns true. MonetDB also supports this * * @return true if so; false otherwise */ public boolean supportsSubqueriesInComparisons() { return(true); } /** * Are subqueries in 'exists' expressions supported? A JDBC * Compliant driver always returns true. * * @return true if so; false otherwise */ public boolean supportsSubqueriesInExists() { return(true); } /** * Are subqueries in 'in' statements supported? A JDBC * Compliant driver always returns true. * * @return true if so; false otherwise */ public boolean supportsSubqueriesInIns() { return(true); } /** * Are subqueries in quantified expressions supported? A JDBC * Compliant driver always returns true. * * (No idea what this is, but we support a good deal of * subquerying.) * * @return true if so; false otherwise */ public boolean supportsSubqueriesInQuantifieds() { return(true); } /** * Are correlated subqueries supported? A JDBC Compliant driver * always returns true. * * (a.k.a. subselect in from?) * * @return true if so; false otherwise */ public boolean supportsCorrelatedSubqueries() { return(true); } /** * Is SQL UNION supported? * since 2004-03-20 * * @return true if so */ public boolean supportsUnion() { return(true); } /** * Is SQL UNION ALL supported? * since 2004-03-20 * * @return true if so */ public boolean supportsUnionAll() { return(true); } /** * ResultSet objects (cursors) are not closed upon explicit or * implicit commit. * * @return true if so */ public boolean supportsOpenCursorsAcrossCommit() { return(true); } /** * Same as above * * @return true if so */ public boolean supportsOpenCursorsAcrossRollback() { return(true); } /** * Can statements remain open across commits? They may, but * this driver cannot guarentee that. In further reflection. * we are taking a Statement object here, so the answer is * yes, since the Statement is only a vehicle to execute some SQL * * @return true if they always remain open; false otherwise */ public boolean supportsOpenStatementsAcrossCommit() { return(true); } /** * Can statements remain open across rollbacks? They may, but * this driver cannot guarentee that. In further contemplation, * we are taking a Statement object here, so the answer is yes again. * * @return true if they always remain open; false otherwise */ public boolean supportsOpenStatementsAcrossRollback() { return(true); } /** * How many hex characters can you have in an inline binary literal * I honestly wouldn't know... * * @return the max literal length */ public int getMaxBinaryLiteralLength() { return(0); // no limit } /** * What is the maximum length for a character literal * Is there a max? * * @return the max literal length */ public int getMaxCharLiteralLength() { return(0); // no limit } /** * Whats the limit on column name length. * I take some safety here, but it's just a varchar in MonetDB * * @return the maximum column name length */ public int getMaxColumnNameLength() { return(256); } /** * What is the maximum number of columns in a "GROUP BY" clause? * * @return the max number of columns */ public int getMaxColumnsInGroupBy() { return(0); // no limit } /** * What's the maximum number of columns allowed in an index? * * @return max number of columns */ public int getMaxColumnsInIndex() { return(0); // unlimited I guess } /** * What's the maximum number of columns in an "ORDER BY clause? * * @return the max columns */ public int getMaxColumnsInOrderBy() { return(0); // unlimited I guess } /** * What is the maximum number of columns in a "SELECT" list? * * @return the max columns */ public int getMaxColumnsInSelect() { return(0); // unlimited I guess } /** * What is the maximum number of columns in a table? * wasn't Monet designed for datamining? (= much columns) * * @return the max columns */ public int getMaxColumnsInTable() { return(0); } /** * How many active connections can we have at a time to this * database? Well, since it depends on Mserver, which just listens * for new connections and creates a new thread for each connection, * this number can be very high, and theoretically till the system * runs out of resources. However, knowing Monet is knowing that you * should handle it a little bit with care, so I give a very minimalistic * number here. * * @return the maximum number of connections */ public int getMaxConnections() { return(16); } /** * What is the maximum cursor name length * Actually we do not do named cursors, so I keep the value small as * a precaution for maybe the future. * * @return max cursor name length in bytes */ public int getMaxCursorNameLength() { return(256); } /** * Retrieves the maximum number of bytes for an index, including all * of the parts of the index. * * @return max index length in bytes, which includes the composite * of all the constituent parts of the index; a result of zero * means that there is no limit or the limit is not known */ public int getMaxIndexLength() { return(0); // I assume it is large, but I don't know } /** * Retrieves the maximum number of characters that this database * allows in a schema name. * * @return the number of characters or 0 if there is no limit, or the * limit is unknown. */ public int getMaxSchemaNameLength() { return(0); // I don't know... } /** * What is the maximum length of a procedure name * * @return the max name length in bytes */ public int getMaxProcedureNameLength() { return(0); // unknown } /** * What is the maximum length of a catalog * * @return the max length */ public int getMaxCatalogNameLength() { return(0); } /** * What is the maximum length of a single row? * * @return max row size in bytes */ public int getMaxRowSize() { return(0); // very long I hope... } /** * Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY * blobs? * Yes I thought so... * * @return true if so */ public boolean doesMaxRowSizeIncludeBlobs() { return(true); } /** * What is the maximum length of a SQL statement? * Till a programmer makes a mistake and causes a segmentation fault * on a string overflow... * * @return max length in bytes */ public int getMaxStatementLength() { return(0); // actually whatever fits in size_t } /** * How many active statements can we have open at one time to * this database? Basically, since each Statement downloads * the results as the query is executed, we can have many. * * @return the maximum */ public int getMaxStatements() { return(0); } /** * What is the maximum length of a table name * * @return max name length in bytes */ public int getMaxTableNameLength() { return(0); } /** * What is the maximum number of tables that can be specified * in a SELECT? * * @return the maximum */ public int getMaxTablesInSelect() { return(0); // no limit } /** * What is the maximum length of a user name * * @return the max name length in bytes * @exception SQLException if a database access error occurs */ public int getMaxUserNameLength() { return(0); // no limit } /** * What is the database's default transaction isolation level? * We only see commited data, nonrepeatable reads and phantom * reads can occur. * * @return the default isolation level * @see Connection */ public int getDefaultTransactionIsolation() { return(Connection.TRANSACTION_SERIALIZABLE); } /** * Are transactions supported? If not, commit and rollback are noops * and the isolation level is TRANSACTION_NONE. We do support * transactions. * * @return true if transactions are supported */ public boolean supportsTransactions() { return(true); } /** * Does the database support the given transaction isolation level? * We only support TRANSACTION_READ_COMMITTED as far as I know * * @param level the values are defined in java.sql.Connection * @return true if so * @see Connection */ public boolean supportsTransactionIsolationLevel(int level) { return(level == Connection.TRANSACTION_SERIALIZABLE); } /** * Are both data definition and data manipulation transactions * supported? * Supposedly that data definition is like CREATE or ALTER TABLE * yes it is. * * @return true if so */ public boolean supportsDataDefinitionAndDataManipulationTransactions() { return(true); } /** * Are only data manipulation statements withing a transaction * supported? * * @return true if so */ public boolean supportsDataManipulationTransactionsOnly() { return(false); } /** * Does a data definition statement within a transaction force * the transaction to commit? I think this means something like: * * <p><pre> * CREATE TABLE T (A INT); * INSERT INTO T (A) VALUES (2); * BEGIN; * UPDATE T SET A = A + 1; * CREATE TABLE X (A INT); * SELECT A FROM T INTO X; * COMMIT; * </pre><p> * * does the CREATE TABLE call cause a commit? The answer is no. * * @return true if so */ public boolean dataDefinitionCausesTransactionCommit() { return(false); } /** * Is a data definition statement within a transaction ignored? * * @return true if so * @exception SQLException if a database access error occurs */ public boolean dataDefinitionIgnoredInTransactions() { return(false); } /** * Get a description of stored procedures available in a catalog * Currently not applicable and not implemented, returns null * * <p>Only procedure descriptions matching the schema and procedure * name criteria are returned. They are ordered by PROCEDURE_SCHEM * and PROCEDURE_NAME * * <p>Each procedure description has the following columns: * <ol> * <li><b>PROCEDURE_CAT</b> String => procedure catalog (may be null) * <li><b>PROCEDURE_SCHEM</b> String => procedure schema (may be null) * <li><b>PROCEDURE_NAME</b> String => procedure name * <li><b>Field 4</b> reserved (make it null) * <li><b>Field 5</b> reserved (make it null) * <li><b>Field 6</b> reserved (make it null) * <li><b>REMARKS</b> String => explanatory comment on the procedure * <li><b>PROCEDURE_TYPE</b> short => kind of procedure * <ul> * <li> procedureResultUnknown - May return a result * <li> procedureNoResult - Does not return a result * <li> procedureReturnsResult - Returns a result * </ul> * </ol> * * @param catalog - a catalog name; "" retrieves those without a * catalog; null means drop catalog name from criteria * @param schemaPattern - a schema name pattern; "" retrieves those * without a schema - we ignore this parameter * @param procedureNamePattern - a procedure name pattern * @return ResultSet - each row is a procedure description * @throws SQLException if a database access error occurs */ public ResultSet getProcedures( String catalog, String schemaPattern, String procedureNamePattern ) throws SQLException { String query = "SELECT null AS \"PROCEDURE_CAT\", null AS \"PROCEDURE_SCHEM\", " + "'' AS \"PROCEDURE_NAME\", null AS \"Field4\", " + "null AS \"Field5\", null AS \"Field6\", " + "'' AS \"REMARKS\", 0 AS \"PROCEDURE_TYPE\" " + "WHERE 1 = 0"; return(getStmt().executeQuery(query)); } /** * Get a description of a catalog's stored procedure parameters * and result columns. * Currently not applicable and not implemented, returns null * * <p>Only descriptions matching the schema, procedure and parameter * name criteria are returned. They are ordered by PROCEDURE_SCHEM * and PROCEDURE_NAME. Within this, the return value, if any, is * first. Next are the parameter descriptions in call order. The * column descriptions follow in column number order. * * <p>Each row in the ResultSet is a parameter description or column * description with the following fields: * <ol> * <li><b>PROCEDURE_CAT</b> String => procedure catalog (may be null) * <li><b>PROCEDURE_SCHEM</b> String => procedure schema (may be null) * <li><b>PROCEDURE_NAME</b> String => procedure name * <li><b>COLUMN_NAME</b> String => column/parameter name * <li><b>COLUMN_TYPE</b> Short => kind of column/parameter: * <ul><li>procedureColumnUnknown - nobody knows * <li>procedureColumnIn - IN parameter * <li>procedureColumnInOut - INOUT parameter * <li>procedureColumnOut - OUT parameter * <li>procedureColumnReturn - procedure return value * <li>procedureColumnResult - result column in ResultSet * </ul> * <li><b>DATA_TYPE</b> short => SQL type from java.sql.Types * <li><b>TYPE_NAME</b> String => Data source specific type name * <li><b>PRECISION</b> int => precision * <li><b>LENGTH</b> int => length in bytes of data * <li><b>SCALE</b> short => scale * <li><b>RADIX</b> short => radix * <li><b>NULLABLE</b> short => can it contain NULL? * <ul><li>procedureNoNulls - does not allow NULL values * <li>procedureNullable - allows NULL values * <li>procedureNullableUnknown - nullability unknown * <li><b>REMARKS</b> String => comment describing parameter/column * </ol> * @param catalog This is ignored in org.postgresql, advise this is set to null * @param schemaPattern * @param procedureNamePattern a procedure name pattern * @param columnNamePattern a column name pattern, this is currently ignored because postgresql does not name procedure parameters. * @return each row is a stored procedure parameter or column description * @throws SQLException if a database-access error occurs * @see #getSearchStringEscape */ public ResultSet getProcedureColumns( String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern ) throws SQLException { String query = "SELECT null AS \"PROCEDURE_CAT\", null AS \"PROCEDURE_SCHEM\", " + "'' AS \"PROCEDURE_NAME\", '' AS \"COLUMN_NAME\", " + "0 AS \"COLUMN_TYPE\", 0 AS \"DATA_TYPE\", " + "'' AS \"TYPE_NAME\", 0 AS \"PRECISION\", " + "0 AS \"LENGTH\", 0 AS \"SCALE\", 0 AS \"RADIX\", " + "0 AS \"NULLABLE\", '' AS \"REMARKS\" " + "WHERE 1 = 0"; return(getStmt().executeQuery(query)); } //== this is a helper method which does not belong to the interface /** * returns the given string where all slashes and single quotes are * escaped with a slash. * * @param in the string to escape * @return the escaped string */ private static String escapeQuotes(String in) { return(in.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'")); } /** * returns the given string between two double quotes for usage as * exact column or table name in SQL queries. * * @param in the string to quote * @return the quoted string */ private static String dq(String in) { return("\"" + in.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"") + "\""); } //== end helper methods /** * Get a description of tables available in a catalog. * * <p>Only table descriptions matching the catalog, schema, table * name and type criteria are returned. They are ordered by * TABLE_TYPE, TABLE_SCHEM and TABLE_NAME. * * <p>Each table description has the following columns: * * <ol> * <li><b>TABLE_CAT</b> String => table catalog (may be null) * <li><b>TABLE_SCHEM</b> String => table schema (may be null) * <li><b>TABLE_NAME</b> String => table name * <li><b>TABLE_TYPE</b> String => table type. Typical types are "TABLE", * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL * TEMPORARY", "ALIAS", "SYNONYM". * <li><b>REMARKS</b> String => explanatory comment on the table * </ol> * * <p>The valid values for the types parameter are: * "TABLE", "INDEX", "SEQUENCE", "VIEW", * "SYSTEM TABLE", "SYSTEM INDEX", "SYSTEM VIEW", * "SYSTEM TOAST TABLE", "SYSTEM TOAST INDEX", * "TEMPORARY TABLE", and "TEMPORARY VIEW" * * @param catalog a catalog name; this parameter is currently ignored * @param schemaPattern a schema name pattern * @param tableNamePattern a table name pattern. For all tables this should be "%" * @param types a list of table types to include; null returns all types; * this parameter is currently ignored * @return each row is a table description * @throws SQLException if a database-access error occurs. */ public ResultSet getTables( String catalog, String schemaPattern, String tableNamePattern, String types[] ) throws SQLException { String select; String orderby; String cat = (String)(getEnvMap().get("gdk_dbname")); select = "SELECT * FROM ( " + "SELECT '" + cat + "' AS \"TABLE_CAT\", \"schemas\".\"name\" AS \"TABLE_SCHEM\", \"tables\".\"name\" AS \"TABLE_NAME\", " + "CASE WHEN \"tables\".\"system\" = true AND \"tables\".\"istable\" = true THEN 'SYSTEM TABLE' " + " WHEN \"tables\".\"system\" = true AND \"tables\".\"istable\" = false THEN 'SYSTEM VIEW' " + " WHEN \"tables\".\"system\" = false AND \"tables\".\"istable\" = true THEN 'TABLE' " + " WHEN \"tables\".\"system\" = false AND \"tables\".\"istable\" = false THEN 'VIEW' " + "END AS \"TABLE_TYPE\", '' AS \"REMARKS\", null AS \"TYPE_CAT\", null AS \"TYPE_SCHEM\", " + "null AS \"TYPE_NAME\", 'rowid' AS \"SELF_REFERENCING_COL_NAME\", 'SYSTEM' AS \"REF_GENERATION\" " + "FROM \"tables\", \"schemas\" WHERE \"tables\".\"schema_id\" = \"schemas\".\"id\"" + "UNION ALL " + "SELECT '" + cat + "' AS \"TABLE_CAT\", \"schemas\".\"name\" AS \"TABLE_SCHEM\", \"tables\".\"name\" AS \"TABLE_NAME\", " + "CASE WHEN \"tables\".\"system\" = true AND \"tables\".\"istable\" = true THEN 'SYSTEM SESSION TABLE' " + " WHEN \"tables\".\"system\" = true AND \"tables\".\"istable\" = false THEN 'SYSTEM SESSION VIEW' " + " WHEN \"tables\".\"system\" = false AND \"tables\".\"istable\" = true THEN 'SESSION TABLE' " + " WHEN \"tables\".\"system\" = false AND \"tables\".\"istable\" = false THEN 'SESSION VIEW' " + "END AS \"TABLE_TYPE\", '' AS \"REMARKS\", null AS \"TYPE_CAT\", null AS \"TYPE_SCHEM\", " + "null AS \"TYPE_NAME\", 'rowid' AS \"SELF_REFERENCING_COL_NAME\", 'SYSTEM' AS \"REF_GENERATION\" " + "FROM \"tmp_tables\" AS \"tables\", \"schemas\" WHERE \"tables\".\"schema_id\" = \"schemas\".\"id\"" + ") AS \"tables\" WHERE 1 = 1 "; if (tableNamePattern != null) { select += "AND \"TABLE_NAME\" LIKE '" + escapeQuotes(tableNamePattern) + "' "; } if (schemaPattern != null) { select += "AND \"TABLE_SCHEM\" LIKE '" + escapeQuotes(schemaPattern) + "' "; } if (types != null) { select += "AND ("; for (int i = 0; i < types.length; i++) { select += (i == 0 ? "" : " OR ") + "\"TABLE_TYPE\" LIKE '" + escapeQuotes(types[i]) + "'"; } select += ") "; } orderby = "ORDER BY \"TABLE_TYPE\", \"TABLE_SCHEM\", \"TABLE_NAME\" "; return(getStmt().executeQuery(select + orderby)); } /** * Get the schema names available in this database. The results * are ordered by schema name. * * <P>The schema column is: * <OL> * <LI><B>TABLE_SCHEM</B> String => schema name * <LI><B>TABLE_CATALOG</B> String => catalog name (may be null) * </OL> * * @return ResultSet each row has a single String column that is a * schema name * @throws SQLException if a database error occurs */ public ResultSet getSchemas() throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = "SELECT \"name\" AS \"TABLE_SCHEM\", '" + cat + "' AS \"TABLE_CATALOG\" " + "FROM \"schemas\" " + "ORDER BY \"TABLE_SCHEM\""; return(getStmt().executeQuery(query)); } /** * Get the catalog names available in this database. The results * are ordered by catalog name. * * <P>The catalog column is: * <OL> * <LI><B>TABLE_CAT</B> String => catalog name * </OL> * * Note: this will return a resultset with 'default', since there are no catalogs * in Monet * * @return ResultSet each row has a single String column that is a * catalog name * @throws SQLException if a database error occurs */ public ResultSet getCatalogs() throws SQLException { Map env = getEnvMap(); String query = "SELECT '" + ((String)env.get("gdk_dbname")) + "' AS \"TABLE_CAT\""; // some applications need a database or catalog... return(getStmt().executeQuery(query)); } /** * Get the table types available in this database. The results * are ordered by table type. * * <P>The table type is: * <OL> * <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE", * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", * "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * </OL> * * @return ResultSet each row has a single String column that is a * table type * @throws SQLException if a database error occurs */ public ResultSet getTableTypes() throws SQLException { String[] columns, types; String[][] results; columns = new String[1]; types = new String[1]; results = new String[8][1]; columns[0] = "TABLE_TYPE"; types[0] = "varchar"; results[0][0] = "SYSTEM TABLE"; results[1][0] = "TABLE"; results[2][0] = "SYSTEM VIEW"; results[3][0] = "VIEW"; results[4][0] = "SYSTEM SESSION TABLE"; results[5][0] = "SESSION TABLE"; results[6][0] = "SYSTEM SESSION VIEW"; results[7][0] = "SESSION VIEW"; try { return(new MonetVirtualResultSet(columns, types, results)); } catch (IllegalArgumentException e) { throw new SQLException("Internal driver error: " + e.getMessage()); } } /** * Get a description of table columns available in a catalog. * * <P>Only column descriptions matching the catalog, schema, table * and column name criteria are returned. They are ordered by * TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION. * * <P>Each column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> short => SQL type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => column size. For char or date * types this is the maximum number of characters, for numeric or * decimal types this is precision. * <LI><B>BUFFER_LENGTH</B> is not used. * <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits * <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2) * <LI><B>NULLABLE</B> int => is NULL allowed? * <UL> * <LI> columnNoNulls - might not allow NULL values * <LI> columnNullable - definitely allows NULL values * <LI> columnNullableUnknown - nullability unknown * </UL> * <LI><B>REMARKS</B> String => comment describing column (may be null) * <LI><B>COLUMN_DEF</B> String => default value (may be null) * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the * maximum number of bytes in the column * <LI><B>ORDINAL_POSITION</B> int => index of column in table * (starting at 1) * <LI><B>IS_NULLABLE</B> String => "NO" means column definitely * does not allow NULL values; "YES" means the column might * allow NULL values. An empty string means nobody knows. * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog; * currently ignored * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern * @param columnNamePattern a column name pattern * @return ResultSet each row is a column description * @see #getSearchStringEscape * @throws SQLException if a database error occurs */ public ResultSet getColumns( String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern ) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = "SELECT '" + cat + "' AS \"TABLE_CAT\", \"schemas\".\"name\" AS \"TABLE_SCHEM\", " + "\"tables\".\"name\" AS \"TABLE_NAME\", \"columns\".\"name\" AS \"COLUMN_NAME\", " + "CASE \"columns\".\"type\" " + "WHEN 'table' THEN " + Types.ARRAY + " " + "WHEN 'boolean' THEN " + Types.BOOLEAN + " " + "WHEN 'bool' THEN " + Types.BOOLEAN + " " + "WHEN 'ubyte' THEN " + Types.CHAR + " " + "WHEN 'char' THEN " + Types.CHAR + " " + "WHEN 'character' THEN " + Types.CHAR + " " + "WHEN 'varchar' THEN " + Types.VARCHAR + " " + "WHEN 'text' THEN " + Types.LONGVARCHAR + " " + "WHEN 'tinytext' THEN " + Types.LONGVARCHAR + " " + "WHEN 'string' THEN " + Types.LONGVARCHAR + " " + "WHEN 'tinyint' THEN " + Types.TINYINT + " " + "WHEN 'smallint' THEN " + Types.SMALLINT + " " + "WHEN 'mediumint' THEN " + Types.INTEGER + " " + "WHEN 'oid' THEN " + Types.OTHER + " " + "WHEN 'int' THEN " + Types.INTEGER + " " + "WHEN 'integer' THEN " + Types.INTEGER + " " + "WHEN 'bigint' THEN " + Types.BIGINT + " " + "WHEN 'number' THEN " + Types.INTEGER + " " + "WHEN 'decimal' THEN " + Types.DECIMAL + " " + "WHEN 'numeric' THEN " + Types.NUMERIC + " " + "WHEN 'float' THEN " + Types.FLOAT + " " + "WHEN 'double' THEN " + Types.DOUBLE + " " + "WHEN 'real' THEN " + Types.DOUBLE + " " + "WHEN 'month_interval' THEN " + Types.INTEGER + " " + "WHEN 'sec_interval' THEN " + Types.BIGINT + " " + "WHEN 'date' THEN " + Types.DATE + " " + "WHEN 'time' THEN " + Types.TIME + " " + "WHEN 'datetime' THEN " + Types.TIMESTAMP + " " + "WHEN 'timestamp' THEN " + Types.TIMESTAMP + " " + "WHEN 'blob' THEN " + Types.BLOB + " " + "ELSE " + Types.OTHER + " " + "END AS \"DATA_TYPE\", " + "\"columns\".\"type\" AS \"TYPE_NAME\", \"columns\".\"type_digits\" AS \"COLUMN_SIZE\", " + "\"columns\".\"type_scale\" AS \"DECIMAL_DIGITS\", 0 AS \"BUFFER_LENGTH\", " + "10 AS \"NUM_PREC_RADIX\", " + "CASE \"null\" " + "WHEN true THEN " + ResultSetMetaData.columnNullable + " " + "WHEN false THEN " + ResultSetMetaData.columnNoNulls + " " + "END AS \"NULLABLE\", null AS \"REMARKS\", " + "\"columns\".\"default\" AS \"COLUMN_DEF\", 0 AS \"SQL_DATA_TYPE\", " + "0 AS \"SQL_DATETIME_SUB\", 0 AS \"CHAR_OCTET_LENGTH\", " + "\"columns\".\"number\" + 1 AS \"ORDINAL_POSITION\", null AS \"SCOPE_CATALOG\", " + "null AS \"SCOPE_SCHEMA\", null AS \"SCOPE_TABLE\", " + ((MonetDriver)driver).getJavaType("other") + " AS \"SOURCE_DATA_TYPE\", " + "CASE \"null\" " + "WHEN true THEN CAST ('YES' AS varchar) " + "WHEN false THEN CAST ('NO' AS varchar) " + "END AS \"IS_NULLABLE\" " + "FROM ( " + "SELECT * FROM \"columns\" " + "UNION ALL " + "SELECT * FROM \"tmp_columns\" " + ") AS \"columns\", ( " + "SELECT * FROM \"tables\" " + "UNION ALL " + "SELECT * FROM \"tmp_tables\" " + ") AS \"tables\", \"schemas\" " + "WHERE \"columns\".\"table_id\" = \"tables\".\"id\" " + "AND \"tables\".\"schema_id\" = \"schemas\".\"id\" "; if (schemaPattern != null) { query += "AND \"schemas\".\"name\" LIKE '" + escapeQuotes(schemaPattern) + "' "; } if (tableNamePattern != null) { query += "AND \"tables\".\"name\" LIKE '" + escapeQuotes(tableNamePattern) + "' "; } if (columnNamePattern != null) { query += "AND \"columns\".\"name\" LIKE '" + escapeQuotes(columnNamePattern) + "' "; } query += "ORDER BY \"TABLE_SCHEM\", \"TABLE_NAME\", \"ORDINAL_POSITION\""; return(getStmt().executeQuery(query)); } /** * Get a description of the access rights for a table's columns. * Not implemented since,Monet knows no access rights * * <P>Only privileges matching the column name criteria are * returned. They are ordered by COLUMN_NAME and PRIVILEGE. * * <P>Each privilige description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>GRANTOR</B> => grantor of access (may be null) * <LI><B>GRANTEE</B> String => grantee of access * <LI><B>PRIVILEGE</B> String => name of access (SELECT, * INSERT, UPDATE, REFRENCES, ...) * <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted * to grant to others; "NO" if not; null if unknown * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @param columnNamePattern a column name pattern * @return ResultSet each row is a column privilege description * @see #getSearchStringEscape * @throws SQLException if a database error occurs */ public ResultSet getColumnPrivileges( String catalog, String schema, String table, String columnNamePattern ) throws SQLException { String[] columns = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "GRANTOR", "GRANTEE", "PRIVILEGE", "IS_GRANTABLE" }; String[] types = { "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar" }; String[][] results = new String[0][columns.length]; try { return(new MonetVirtualResultSet(columns, types, results)); } catch (IllegalArgumentException e) { throw new SQLException("Internal driver error: " + e.getMessage()); } } /** * Get a description of the access rights for each table available * in a catalog. * Not implemented since Monet knows no access rights * * <P>Only privileges matching the schema and table name * criteria are returned. They are ordered by TABLE_SCHEM, * TABLE_NAME, and PRIVILEGE. * * <P>Each privilige description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>GRANTOR</B> => grantor of access (may be null) * <LI><B>GRANTEE</B> String => grantee of access * <LI><B>PRIVILEGE</B> String => name of access (SELECT, * INSERT, UPDATE, REFRENCES, ...) * <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted * to grant to others; "NO" if not; null if unknown * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern * @return ResultSet each row is a table privilege description * @see #getSearchStringEscape * @throws SQLException if a database error occurs */ public ResultSet getTablePrivileges( String catalog, String schemaPattern, String tableNamePattern ) throws SQLException { String[] columns = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "GRANTOR", "GRANTEE", "PRIVILEGE", "IS_GRANTABLE" }; String[] types = { "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar" }; String[][] results = new String[0][columns.length]; try { return(new MonetVirtualResultSet(columns, types, results)); } catch (IllegalArgumentException e) { throw new SQLException("Internal driver error: " + e.getMessage()); } } /** * Get a description of a table's optimal set of columns that * uniquely identifies a row. They are ordered by SCOPE. * * <P>Each column description has the following columns: * <OL> * <LI><B>SCOPE</B> short => actual scope of result * <UL> * <LI> bestRowTemporary - very temporary, while using row * <LI> bestRowTransaction - valid for remainder of current transaction * <LI> bestRowSession - valid for remainder of current session * </UL> * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => precision * <LI><B>BUFFER_LENGTH</B> int => not used * <LI><B>DECIMAL_DIGITS</B> short => scale * <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column * like an Oracle ROWID * <UL> * <LI> bestRowUnknown - may or may not be pseudo column * <LI> bestRowNotPseudo - is NOT a pseudo column * <LI> bestRowPseudo - is a pseudo column * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @param scope the scope of interest; use same values as SCOPE * @param nullable include columns that are nullable? * @return ResultSet each row is a column description * @throws SQLException if a database error occurs */ public ResultSet getBestRowIdentifier( String catalog, String schema, String table, int scope, boolean nullable ) throws SQLException { String query = "SELECT \"columns\".\"name\" AS \"COLUMN_NAME\", \"columns\".\"type\" AS \"TYPE_NAME\", " + "\"columns\".\"type_digits\" AS \"COLUMN_SIZE\", 0 AS \"BUFFER_LENGTH\", " + "\"columns\".\"type_scale\" AS \"DECIMAL_DIGITS\", \"keys\".\"type\" AS \"keytype\" " + "FROM \"keys\", \"keycolumns\", ( " + "SELECT * FROM \"columns\" " + "UNION ALL " + "SELECT * FROM \"tmp_columns\" " + ") AS \"columns\", ( " + "SELECT * FROM \"tables\" " + "UNION ALL " + "SELECT * FROM \"tmp_tables\" " + ") AS \"tables\", \"schemas\" " + "WHERE \"keys\".\"id\" = \"keycolumns\".\"id\" AND \"keys\".\"table_id\" = \"tables\".\"id\" " + "AND \"keys\".\"table_id\" = \"columns\".\"table_id\" " + "AND \"keycolumns\".\"column\" = \"columns\".\"name\" " + "AND \"tables\".\"schema_id\" = \"schemas\".\"id\" " + "AND \"keys\".\"type\" IN (0, 1) "; // SCOPE, DATA_TYPE, PSEUDO_COLUMN have to be generated with Java logic if (schema != null) { query += "AND \"schemas\".\"name\" LIKE '" + escapeQuotes(schema) + "' "; } if (table != null) { query += "AND \"tables\".\"name\" LIKE '" + escapeQuotes(table) + "' "; } if (!nullable) { query += "AND \"columns\".\"null\" = false "; } query += "ORDER BY \"keytype\""; String columns[] = { "SCOPE", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "PSEUDO_COLUMN" }; String types[] = { "mediumint", "varchar", "mediumint", "varchar", "mediumint", "mediumint", "mediumint", "mediumint" }; String[][] results; ArrayList tmpRes = new ArrayList(); ResultSet rs = getStmt().executeQuery(query); while (rs.next()) { String[] result = new String[8]; result[0] = "" + DatabaseMetaData.bestRowSession; result[1] = rs.getString("column_name"); result[2] = "" + ((MonetDriver)driver).getJavaType(rs.getString("type_name")); result[3] = rs.getString("type_name"); result[4] = rs.getString("column_size"); result[5] = rs.getString("buffer_length"); result[6] = rs.getString("decimal_digits"); result[7] = "" + DatabaseMetaData.bestRowNotPseudo; tmpRes.add(result); } rs.close(); results = (String[][])tmpRes.toArray(new String[tmpRes.size()][]); try { return(new MonetVirtualResultSet(columns, types, results)); } catch (IllegalArgumentException e) { throw new SQLException("Internal driver error: " + e.getMessage()); } } /** * Get a description of a table's columns that are automatically * updated when any value in a row is updated. They are * unordered. * * <P>Each column description has the following columns: * <OL> * <LI><B>SCOPE</B> short => is not used * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => precision * <LI><B>BUFFER_LENGTH</B> int => length of column value in bytes * <LI><B>DECIMAL_DIGITS</B> short => scale * <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column * like an Oracle ROWID * <UL> * <LI> versionColumnUnknown - may or may not be pseudo column * <LI> versionColumnNotPseudo - is NOT a pseudo column * <LI> versionColumnPseudo - is a pseudo column * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @return ResultSet each row is a column description * @throws SQLException if a database error occurs */ public ResultSet getVersionColumns( String catalog, String schema, String table ) throws SQLException { // I don't know of columns which update themselves, except maybe on the // system tables String columns[] = { "SCOPE", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "PSEUDO_COLUMN" }; String types[] = { "mediumint", "varchar", "mediumint", "varchar", "mediumint", "mediumint", "mediumint", "mediumint" }; String[][] results = new String[0][columns.length]; try { return(new MonetVirtualResultSet(columns, types, results)); } catch (IllegalArgumentException e) { throw new SQLException("Internal driver error: " + e.getMessage()); } } /** * Get a description of a table's primary key columns. They * are ordered by COLUMN_NAME. * * <P>Each column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>KEY_SEQ</B> short => sequence number within primary key * <LI><B>PK_NAME</B> String => primary key name (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet each row is a primary key column description * @throws SQLException if a database error occurs */ public ResultSet getPrimaryKeys( String catalog, String schema, String table ) throws SQLException { String query = "SELECT null AS \"TABLE_CAT\", \"schemas\".\"name\" AS \"TABLE_SCHEM\", " + "\"tables\".\"name\" AS \"TABLE_NAME\", \"keycolumns\".\"column\" AS \"COLUMN_NAME\", " + "\"keys\".\"type\" AS \"KEY_SEQ\", \"keys\".\"name\" AS \"PK_NAME\" " + "FROM \"keys\", \"keycolumns\", ( " + "SELECT * FROM \"tables\" " + "UNION ALL " + "SELECT * FROM \"tmp_tables\" " + ") AS \"tables\", \"schemas\" " + "WHERE \"keys\".\"id\" = \"keycolumns\".\"id\" AND \"keys\".\"table_id\" = \"tables\".\"id\" " + "AND \"tables\".\"schema_id\" = \"schemas\".\"id\" " + "AND \"keys\".\"type\" = 0 "; if (schema != null) { query += "AND \"schemas\".\"name\" LIKE '" + escapeQuotes(schema) + "' "; } if (table != null) { query += "AND \"tables\".\"name\" LIKE '" + escapeQuotes(table) + "' "; } query += "ORDER BY \"COLUMN_NAME\""; return(getStmt().executeQuery(query)); } final static String keyQuery = ", \"pkschema\".\"name\" AS \"PKTABLE_SCHEM\", " + "\"pktable\".\"name\" AS \"PKTABLE_NAME\", \"pkkeycol\".\"column\" AS \"PKCOLUMN_NAME\", " + "\"fkschema\".\"name\" AS \"FKTABLE_SCHEM\", " + "\"fktable\".\"name\" AS \"FKTABLE_NAME\", \"fkkeycol\".\"column\" AS \"FKCOLUMN_NAME\", " + "\"fkkey\".\"type\" AS \"KEY_SEQ\", " + DatabaseMetaData.importedKeyNoAction + " AS \"UPDATE_RULE\", " + "" + DatabaseMetaData.importedKeyNoAction + " AS \"DELETE_RULE\", " + "\"fkkey\".\"name\" AS \"FK_NAME\", \"pkkey\".\"name\" AS \"PK_NAME\", " + "" + DatabaseMetaData.importedKeyNotDeferrable + " AS \"DEFERRABILITY\" " + "FROM \"keys\" AS \"fkkey\", \"keys\" AS \"pkkey\", \"keycolumns\" AS \"fkkeycol\", " + "\"keycolumns\" AS \"pkkeycol\", ( " + "SELECT * FROM \"tables\" " + "UNION ALL " + "SELECT * FROM \"tmp_tables\" " + ") AS \"fktable\", ( " + "SELECT * FROM \"tables\" " + "UNION ALL " + "SELECT * FROM \"tmp_tables\" " + ") AS \"pktable\", " + "\"schemas\" AS \"fkschema\", \"schemas\" AS \"pkschema\" " + "WHERE \"fktable\".\"id\" = \"fkkey\".\"table_id\" AND \"pktable\".\"id\" = \"pkkey\".\"table_id\" AND " + "\"fkkey\".\"id\" = \"fkkeycol\".\"id\" AND \"pkkey\".\"id\" = \"pkkeycol\".\"id\" AND " + "\"fkschema\".\"id\" = \"fktable\".\"schema_id\" AND \"pkschema\".\"id\" = \"pktable\".\"schema_id\" AND " + "\"fkkey\".\"rkey\" > -1 AND \"fkkey\".\"rkey\" = \"pkkey\".\"id\" "; static String keyQuery(String cat) { return("SELECT '" + cat + "' AS \"PKTABLE_CAT\", '" + cat + "' AS \"FKTABLE_CAT\"" + keyQuery); } /** * Get a description of the primary key columns that are * referenced by a table's foreign key columns (the primary keys * imported by a table). They are ordered by PKTABLE_CAT, * PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ. * * <P>Each primary key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog * being imported (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema * being imported (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * being imported * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * being imported * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeyRestrict - do not allow update of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeyRestrict - do not allow delete of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key name (may be null) * <LI><B>PK_NAME</B> String => primary key name (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet each row is a primary key column description * @see #getExportedKeys * @throws SQLException if a database error occurs */ public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = keyQuery(cat); if (schema != null) { query += "AND \"fkschema\".\"name\" LIKE '" + escapeQuotes(schema) + "' "; } if (table != null) { query += "AND \"fktable\".\"name\" LIKE '" + escapeQuotes(table) + "' "; } query += "ORDER BY \"PKTABLE_CAT\", \"PKTABLE_SCHEM\", \"PKTABLE_NAME\", \"KEY_SEQ\""; return(getStmt().executeQuery(query)); } /** * Get a description of a foreign key columns that reference a * table's primary key columns (the foreign keys exported by a * table). They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, * FKTABLE_NAME, and KEY_SEQ. * * <P>Each foreign key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * being exported (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * being exported (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * being exported * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * being exported * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeyRestrict - do not allow update of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeyRestrict - do not allow delete of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key identifier (may be null) * <LI><B>PK_NAME</B> String => primary key identifier (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet each row is a foreign key column description * @see #getImportedKeys * @throws SQLException if a database error occurs */ public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = keyQuery(cat); if (schema != null) { query += "AND \"pkschema\".\"name\" LIKE '" + escapeQuotes(schema) + "' "; } if (table != null) { query += "AND \"pktable\".\"name\" LIKE '" + escapeQuotes(table) + "' "; } query += "ORDER BY \"FKTABLE_CAT\", \"FKTABLE_SCHEM\", \"FKTABLE_NAME\", \"KEY_SEQ\""; return(getStmt().executeQuery(query)); } /** * Get a description of the foreign key columns in the foreign key * table that reference the primary key columns of the primary key * table (describe how one table imports another's key.) This * should normally return a single foreign key/primary key pair * (most tables only import a foreign key from a table once.) They * are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and * KEY_SEQ. * * This method is currently unimplemented. * * <P>Each foreign key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * being exported (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * being exported (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * being exported * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * being exported * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeyRestrict - do not allow update of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeyRestrict - do not allow delete of primary * key if it has been imported * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key identifier (may be null) * <LI><B>PK_NAME</B> String => primary key identifier (may be null) * </OL> * * @param pcatalog primary key catalog name; "" retrieves those without a catalog * @param pschema primary key schema name pattern; "" retrieves those * without a schema * @param ptable primary key table name * @param fcatalog foreign key catalog name; "" retrieves those without a catalog * @param fschema foreign key schema name pattern; "" retrieves those * without a schema * @param ftable koreign key table name * @return ResultSet each row is a foreign key column description * @throws SQLException if a database error occurs * @see #getImportedKeys */ public ResultSet getCrossReference( String pcatalog, String pschema, String ptable, String fcatalog, String fschema, String ftable ) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = keyQuery(cat); if (pschema != null) { query += "AND \"pkschema\".\"name\" LIKE '" + escapeQuotes(pschema) + "' "; } if (ptable != null) { query += "AND \"pktable\".\"name\" LIKE '" + escapeQuotes(ptable) + "' "; } if (fschema != null) { query += "AND \"fkschema\".\"name\" LIKE '" + escapeQuotes(fschema) + "' "; } if (ftable != null) { query += "AND \"fktable\".\"name\" LIKE '" + escapeQuotes(ftable) + "' "; } query += "ORDER BY \"FKTABLE_CAT\", \"FKTABLE_SCHEM\", \"FKTABLE_NAME\", \"KEY_SEQ\""; return(getStmt().executeQuery(query)); } /** * Get a description of all the standard SQL types supported by * this database. They are ordered by DATA_TYPE and then by how * closely the data type maps to the corresponding JDBC SQL type. * * <P>Each type description has the following columns: * <OL> * <LI><B>TYPE_NAME</B> String => Type name * <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types * <LI><B>PRECISION</B> int => maximum precision * <LI><B>LITERAL_PREFIX</B> String => prefix used to quote a literal * (may be null) * <LI><B>LITERAL_SUFFIX</B> String => suffix used to quote a literal * (may be null) * <LI><B>CREATE_PARAMS</B> String => parameters used in creating * the type (may be null) * <LI><B>NULLABLE</B> short => can you use NULL for this type? * <UL> * <LI> typeNoNulls - does not allow NULL values * <LI> typeNullable - allows NULL values * <LI> typeNullableUnknown - nullability unknown * </UL> * <LI><B>CASE_SENSITIVE</B> boolean=> is it case sensitive? * <LI><B>SEARCHABLE</B> short => can you use "WHERE" based on this type: * <UL> * <LI> typePredNone - No support * <LI> typePredChar - Only supported with WHERE .. LIKE * <LI> typePredBasic - Supported except for WHERE .. LIKE * <LI> typeSearchable - Supported for all WHERE .. * </UL> * <LI><B>UNSIGNED_ATTRIBUTE</B> boolean => is it unsigned? * <LI><B>FIXED_PREC_SCALE</B> boolean => can it be a money value? * <LI><B>AUTO_INCREMENT</B> boolean => can it be used for an * auto-increment value? * <LI><B>LOCAL_TYPE_NAME</B> String => localized version of type name * (may be null) * <LI><B>MINIMUM_SCALE</B> short => minimum scale supported * <LI><B>MAXIMUM_SCALE</B> short => maximum scale supported * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>NUM_PREC_RADIX</B> int => usually 2 or 10 * </OL> * * @return ResultSet each row is a SQL type description * @throws Exception if the developer made a Boo-Boo */ public ResultSet getTypeInfo() throws SQLException { String columns[] = { "TYPE_NAME", "DATA_TYPE", "PRECISION", "LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS", "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE", "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_INCREMENT", "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "NUM_PREC_RADIX" }; String types[] = { "varchar", "mediumint", "mediumint", "varchar", "varchar", "varchar", "tinyint", "boolean", "tinyint", "boolean", "boolean", "boolean", "varchar", "tinyint", "tinyint", "mediumint", "mediumint", "mediumint" }; String results[][] = { // type_name data_type prec. pre suff crte nullable casesns searchable unsign fixprec autoinc name min max sql sql radix {"table", "" + Types.ARRAY, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredNone, "true", "false", "false", "bat", "0", "0", "0", "0", "0"}, {"boolean", "" + Types.BOOLEAN, "1", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "true", "false", "false", "bit", "0", "0", "0", "0", "2"}, {"bool", "" + Types.BOOLEAN, "1", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "true", "false", "false", "bit", "0", "0", "0", "0", "2"}, {"blob", "" + Types.BLOB, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredNone, "true", "false", "false", "blob", "0", "0", "0", "0", "0"}, {"char", "" + Types.CHAR, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredChar, "true", "false", "false", "str", "0", "0", "0", "0", "0"}, {"character", "" + Types.CHAR, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredChar, "true", "false", "false", "str", "0", "0", "0", "0", "0"}, {"ubyte", "" + Types.CHAR, "2", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredNone, "true", "false", "false", "uchr", "0", "0", "0", "0", "2"}, {"date", "" + Types.DATE, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "true", "false", "false", "date", "0", "0", "0", "0", "0"}, {"decimal", "" + Types.DECIMAL, "4", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "true", "false", "sht", "1", "0", "0", "0", "10"}, {"decimal", "" + Types.DECIMAL, "9", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "true", "false", "int", "1", "0", "0", "0", "10"}, {"decimal", "" + Types.DECIMAL,"19", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "true", "false", "lng", "1", "0", "0", "0", "10"}, {"double", "" + Types.DOUBLE, "51", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "dbl", "2", "0", "0", "0", "2"}, {"float", "" + Types.REAL, "23", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "flt", "2", "0", "0", "0", "2"}, {"float", "" + Types.FLOAT, "51", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "dbl", "2", "0", "0", "0", "2"}, {"integer", "" + Types.INTEGER, "9", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "int", "0", "0", "0", "0", "2"}, {"number", "" + Types.INTEGER, "9", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "int", "0", "0", "0", "0", "2"}, {"mediumint", "" + Types.INTEGER, "9", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "int", "0", "0", "0", "0", "2"}, {"int", "" + Types.INTEGER, "9", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "int", "0", "0", "0", "0", "2"}, {"tinyint", "" + Types.TINYINT, "2", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "sht", "0", "0", "0", "0", "2"}, {"smallint", "" + Types.SMALLINT,"4", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "sht", "0", "0", "0", "0", "2"}, {"int", "" + Types.INTEGER, "4", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "sht", "0", "0", "0", "0", "2"}, {"int", "" + Types.BIGINT, "19", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "lng", "0", "0", "0", "0", "2"}, {"bigint", "" + Types.BIGINT, "19", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "lng", "0", "0", "0", "0", "2"}, {"text", "" + Types.LONGVARCHAR,"0",null,null,null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredChar, "true", "false", "false", "str", "0", "0", "0", "0", "0"}, {"tinytext", "" + Types.LONGVARCHAR,"0",null,null,null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredChar, "true", "false", "false", "str", "0", "0", "0", "0", "0"}, {"string", "" + Types.LONGVARCHAR,"0",null,null,null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredChar, "true", "false", "false", "str", "0", "0", "0", "0", "0"}, {"numeric", "" + Types.NUMERIC, "4", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "sht", "1", "0", "0", "0", "10"}, {"numeric", "" + Types.NUMERIC, "9", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "int", "1", "0", "0", "0", "10"}, {"numeric", "" + Types.NUMERIC,"19", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "lng", "1", "0", "0", "0", "10"}, {"oid", "" + Types.OTHER, "9", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredNone, "true", "false", "true", "lng", "0", "0", "0", "0", "2"}, {"month_interval",""+Types.INTEGER,"0",null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredNone, "false", "false", "false", "int", "0", "0", "0", "0", "10"}, {"sec_interval",""+Types.BIGINT, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredNone, "false", "false", "false", "lng", "0", "0", "0", "0", "10"}, {"real", "" + Types.DOUBLE, "51", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "false", "false", "false", "dbl", "2", "0", "0", "0", "2"}, {"time", "" + Types.TIME, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "true", "false", "false", "daytime","0","0","0", "0", "0"}, {"datetime", "" + Types.TIMESTAMP,"0",null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "true", "false", "false", "timestamp","0","0","0","0", "0"}, {"timestamp", "" + Types.TIMESTAMP,"0",null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredBasic, "true", "false", "false", "timestamp","0","0","0","0", "0"}, {"varchar", "" + Types.VARCHAR, "0", null, null, null, "" + DatabaseMetaData.typeNullable, "false", "" + DatabaseMetaData.typePredChar, "true", "false", "false", "str", "0", "0", "0", "0", "0"} }; try { return(new MonetVirtualResultSet(columns, types, results)); } catch (IllegalArgumentException e) { throw new SQLException("Internal driver error: " + e.getMessage()); } } /** * Get a description of a table's indices and statistics. They are * ordered by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION. * * <P>Each index column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>NON_UNIQUE</B> boolean => Can index values be non-unique? * false when TYPE is tableIndexStatistic * <LI><B>INDEX_QUALIFIER</B> String => index catalog (may be null); * null when TYPE is tableIndexStatistic * <LI><B>INDEX_NAME</B> String => index name; null when TYPE is * tableIndexStatistic * <LI><B>TYPE</B> short => index type: * <UL> * <LI> tableIndexStatistic - this identifies table statistics that are * returned in conjuction with a table's index descriptions * <LI> tableIndexClustered - this is a clustered index * <LI> tableIndexHashed - this is a hashed index * <LI> tableIndexOther - this is some other style of index * </UL> * <LI><B>ORDINAL_POSITION</B> short => column sequence number * within index; zero when TYPE is tableIndexStatistic * <LI><B>COLUMN_NAME</B> String => column name; null when TYPE is * tableIndexStatistic * <LI><B>ASC_OR_DESC</B> String => column sort sequence, "A" => ascending * "D" => descending, may be null if sort sequence is not supported; * null when TYPE is tableIndexStatistic * <LI><B>CARDINALITY</B> int => When TYPE is tableIndexStatisic then * this is the number of rows in the table; otherwise it is the * number of unique values in the index. * <LI><B>PAGES</B> int => When TYPE is tableIndexStatisic then * this is the number of pages used for the table, otherwise it * is the number of pages used for the current index. * <LI><B>FILTER_CONDITION</B> String => Filter condition, if any. * (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a catalog * @param schema a schema name pattern; "" retrieves those without a schema * @param table a table name * @param unique when true, return only indices for unique values; * when false, return indices regardless of whether unique or not * @param approximate when true, result is allowed to reflect approximate * or out of data values; when false, results are requested to be * accurate * @return ResultSet each row is an index column description * @throws SQLException if a database occurs */ public ResultSet getIndexInfo( String catalog, String schema, String table, boolean unique, boolean approximate ) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = "SELECT * FROM ( " + "SELECT '" + cat + "' AS \"TABLE_CAT\", " + "\"idxs\".\"name\" AS \"INDEX_NAME\", " + "\"tables\".\"name\" AS \"TABLE_NAME\", " + "\"schemas\".\"name\" AS \"TABLE_SCHEM\", " + "CASE WHEN \"keys\".\"name\" IS NULL THEN true ELSE false END AS \"NON_UNIQUE\", " + "CASE \"idxs\".\"type\" WHEN 0 THEN " + DatabaseMetaData. tableIndexHashed + " ELSE " + DatabaseMetaData. tableIndexOther + " END AS \"TYPE\", " + "\"keycolumns\".\"nr\" AS \"ORDINAL_POSITION\", " + "\"columns\".\"name\" as \"COLUMN_NAME\", " + "null AS \"INDEX_QUALIFIER\", " + "null AS \"ASC_OR_DESC\", " + "0 AS \"PAGES\", " + "null AS \"FILTER_CONDITION\" " + "FROM \"idxs\" LEFT JOIN \"keys\" ON \"idxs\".\"name\" = \"keys\".\"name\", \"schemas\", \"keycolumns\", ( " + "SELECT * FROM \"columns\" " + "UNION ALL " + "SELECT * FROM \"tmp_columns\" " + ") AS \"columns\", ( " + "SELECT * FROM \"tables\" " + "UNION ALL " + "SELECT * FROM \"tmp_tables\" " + ") AS \"tables\" " + "WHERE \"idxs\".\"table_id\" = \"tables\".\"id\" " + "AND \"tables\".\"schema_id\" = \"schemas\".\"id\" " + "AND \"idxs\".\"id\" = \"keycolumns\".\"id\" " + "AND \"tables\".\"id\" = \"columns\".\"table_id\" " + "AND \"keycolumns\".\"column\" = \"columns\".\"name\" " + "AND (\"keys\".\"type\" IS NULL OR \"keys\".\"type\" = 1) " + ") AS jdbcquery " + "WHERE 1 = 1 "; if (schema != null) { query += "AND \"TABLE_SCHEM\" LIKE '" + escapeQuotes(schema) + "' "; } if (table != null) { query += "AND \"TABLE_NAME\" LIKE '" + escapeQuotes(table) + "' "; } if (unique) { query += "AND \"NON_UNIQUE\" = false "; } query += "ORDER BY \"NON_UNIQUE\", \"TYPE\", \"INDEX_NAME\", \"ORDINAL_POSITION\""; String columns[] = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "NON_UNIQUE", "INDEX_QUALIFIER", "INDEX_NAME", "TYPE", "ORDINAL_POSITION", "COLUMN_NAME", "ASC_OR_DESC", "CARDINALITY", "PAGES", "FILTER_CONDITION" }; String types[] = { "varchar", "varchar", "varchar", "boolean", "varchar", "varchar", "mediumint", "mediumint", "varchar", "varchar", "mediumint", "mediumint", "varchar" }; String[][] results; ArrayList tmpRes = new ArrayList(); Statement sub = null; if (!approximate) sub = con.createStatement(); ResultSet rs = getStmt().executeQuery(query); while (rs.next()) { String[] result = new String[13]; result[0] = null; result[1] = rs.getString("table_schem"); result[2] = rs.getString("table_name"); result[3] = rs.getString("non_unique"); result[4] = rs.getString("index_qualifier"); result[5] = rs.getString("index_name"); result[6] = rs.getString("type"); result[7] = rs.getString("ordinal_position"); result[8] = rs.getString("column_name"); result[9] = rs.getString("asc_or_desc"); if (approximate) { result[10] = "0"; } else { ResultSet count = sub.executeQuery("SELECT COUNT(*) AS \"CARDINALITY\" FROM \"" + rs.getString("table_schem") + "\".\"" + rs.getString("table_name") + "\""); if (count.next()) { result[10] = count.getString("cardinality"); } else { result[10] = "0"; } } result[11] = rs.getString("pages"); result[12] = rs.getString("filter_condition"); tmpRes.add(result); } if (!approximate) sub.close(); rs.close(); results = (String[][])tmpRes.toArray(new String[tmpRes.size()][]); try { return(new MonetVirtualResultSet(columns, types, results)); } catch (IllegalArgumentException e) { throw new SQLException("Internal driver error: " + e.getMessage()); } } // ** JDBC 2 Extensions ** /** * Does the database support the given result set type? * * @param type - defined in java.sql.ResultSet * @return true if so; false otherwise * @throws SQLException - if a database access error occurs */ public boolean supportsResultSetType(int type) throws SQLException { // The only type we don't support return(type != ResultSet.TYPE_SCROLL_SENSITIVE); } /** * Does the database support the concurrency type in combination * with the given result set type? * * @param type - defined in java.sql.ResultSet * @param concurrency - type defined in java.sql.ResultSet * @return true if so; false otherwise * @throws SQLException - if a database access error occurs */ public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { // These combinations are not supported! if (type == ResultSet.TYPE_SCROLL_SENSITIVE) return(false); // We do only support Read Only ResultSets if (concurrency != ResultSet.CONCUR_READ_ONLY) return(false); // Everything else we do (well, what's left of it :) ) return(true); } /* lots of unsupported stuff... (no updatable ResultSet!) */ public boolean ownUpdatesAreVisible(int type) { return(false); } public boolean ownDeletesAreVisible(int type) { return(false); } public boolean ownInsertsAreVisible(int type) { return(false); } public boolean othersUpdatesAreVisible(int type) { return(false); } public boolean othersDeletesAreVisible(int i) { return(false); } public boolean othersInsertsAreVisible(int type) { return(false); } public boolean updatesAreDetected(int type) { return(false); } public boolean deletesAreDetected(int i) { return(false); } public boolean insertsAreDetected(int type) { return(false); } /** * Indicates whether the driver supports batch updates. * Not yet, but I want to do them in the near future */ public boolean supportsBatchUpdates() { return(false); } /** * Return user defined types in a schema * Probably not possible within Monet * * @throws SQLException if I made a Boo-Boo */ public ResultSet getUDTs( String catalog, String schemaPattern, String typeNamePattern, int[] types ) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = "SELECT '" + cat + "' AS \"TYPE_CAT\", '' AS \"TYPE_SCHEM\", '' AS \"TYPE_NAME\", " + "'java.lang.Object' AS \"CLASS_NAME\", 0 AS \"DATA_TYPE\", " + "'' AS \"REMARKS\", 0 AS \"BASE_TYPE\" WHERE 1 = 0"; return(getStmt().executeQuery(query)); } /** * Retrieves the connection that produced this metadata object. * * @return the connection that produced this metadata object */ public Connection getConnection() { return(con); } /* I don't find these in the spec!?! */ public boolean rowChangesAreDetected(int type) { return(false); } public boolean rowChangesAreVisible(int type) { return(false); } // ** JDBC 3 extensions ** /** * Retrieves whether this database supports savepoints. * * @return <code>true</code> if savepoints are supported; * <code>false</code> otherwise */ public boolean supportsSavepoints() { return(true); } /** * Retrieves whether this database supports named parameters to callable * statements. * * @return <code>true</code> if named parameters are supported; * <code>false</code> otherwise */ public boolean supportsNamedParameters() { return(false); } /** * Retrieves whether it is possible to have multiple <code>ResultSet</code> objects * returned from a <code>CallableStatement</code> object * simultaneously. * * @return <code>true</code> if a <code>CallableStatement</code> object * can return multiple <code>ResultSet</code> objects * simultaneously; <code>false</code> otherwise */ public boolean supportsMultipleOpenResults() { return(false); } /** * Retrieves whether auto-generated keys can be retrieved after * a statement has been executed. * * @return <code>true</code> if auto-generated keys can be retrieved * after a statement has executed; <code>false</code> otherwise */ public boolean supportsGetGeneratedKeys() { return(false); } /** * Retrieves a description of the user-defined type (UDT) hierarchies defined in a * particular schema in this database. Only the immediate super type/ * sub type relationship is modeled. * <P> * Only supertype information for UDTs matching the catalog, * schema, and type name is returned. The type name parameter * may be a fully-qualified name. When the UDT name supplied is a * fully-qualified name, the catalog and schemaPattern parameters are * ignored. * <P> * If a UDT does not have a direct super type, it is not listed here. * A row of the <code>ResultSet</code> object returned by this method * describes the designated UDT and a direct supertype. A row has the following * columns: * <OL> * <LI><B>TYPE_CAT</B> String => the UDT's catalog (may be <code>null</code>) * <LI><B>TYPE_SCHEM</B> String => UDT's schema (may be <code>null</code>) * <LI><B>TYPE_NAME</B> String => type name of the UDT * <LI><B>SUPERTYPE_CAT</B> String => the direct super type's catalog * (may be <code>null</code>) * <LI><B>SUPERTYPE_SCHEM</B> String => the direct super type's schema * (may be <code>null</code>) * <LI><B>SUPERTYPE_NAME</B> String => the direct super type's name * </OL> * * <P><B>Note:</B> If the driver does not support type hierarchies, an * empty result set is returned. * * @param catalog a catalog name; "" retrieves those without a catalog; * <code>null</code> means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param typeNamePattern a UDT name pattern; may be a fully-qualified * name * @return a <code>ResultSet</code> object in which a row gives information * about the designated UDT * @throws SQLException if a database access error occurs */ public ResultSet getSuperTypes( String catalog, String schemaPattern, String typeNamePattern ) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = "SELECT '" + cat + "' AS \"TYPE_CAT\", '' AS \"TYPE_SCHEM\", '' AS \"TYPE_NAME\", " + "'' AS \"SUPERTYPE_CAT\", '' AS \"SUPERTYPE_SCHEM\", " + "'' AS \"SUPERTYPE_NAME\" WHERE 1 = 0"; return(getStmt().executeQuery(query)); } /** * Retrieves a description of the table hierarchies defined in a particular * schema in this database. * * <P>Only supertable information for tables matching the catalog, schema * and table name are returned. The table name parameter may be a fully- * qualified name, in which case, the catalog and schemaPattern parameters * are ignored. If a table does not have a super table, it is not listed here. * Supertables have to be defined in the same catalog and schema as the * sub tables. Therefore, the type description does not need to include * this information for the supertable. * * <P>Each type description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => the type's catalog (may be <code>null</code>) * <LI><B>TABLE_SCHEM</B> String => type's schema (may be <code>null</code>) * <LI><B>TABLE_NAME</B> String => type name * <LI><B>SUPERTABLE_NAME</B> String => the direct super type's name * </OL> * * <P><B>Note:</B> If the driver does not support type hierarchies, an * empty result set is returned. * * @param catalog a catalog name; "" retrieves those without a catalog; * <code>null</code> means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern; may be a fully-qualified * name * @return a <code>ResultSet</code> object in which each row is a type description * @throws SQLException if a database access error occurs */ public ResultSet getSuperTables( String catalog, String schemaPattern, String tableNamePattern ) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = "SELECT '" + cat + "' AS \"TABLE_CAT\", '' AS \"TABLE_SCHEM\", '' AS \"TABLE_NAME\", " + "'' AS \"SUPERTABLE_NAME\" WHERE 1 = 0"; return(getStmt().executeQuery(query)); } /** * Retrieves a description of the given attribute of the given type * for a user-defined type (UDT) that is available in the given schema * and catalog. * <P> * Descriptions are returned only for attributes of UDTs matching the * catalog, schema, type, and attribute name criteria. They are ordered by * TYPE_SCHEM, TYPE_NAME and ORDINAL_POSITION. This description * does not contain inherited attributes. * <P> * The <code>ResultSet</code> object that is returned has the following * columns: * <OL> * <LI><B>TYPE_CAT</B> String => type catalog (may be <code>null</code>) * <LI><B>TYPE_SCHEM</B> String => type schema (may be <code>null</code>) * <LI><B>TYPE_NAME</B> String => type name * <LI><B>ATTR_NAME</B> String => attribute name * <LI><B>DATA_TYPE</B> short => attribute type SQL type from java.sql.Types * <LI><B>ATTR_TYPE_NAME</B> String => Data source dependent type name. * For a UDT, the type name is fully qualified. For a REF, the type name is * fully qualified and represents the target type of the reference type. * <LI><B>ATTR_SIZE</B> int => column size. For char or date * types this is the maximum number of characters; for numeric or * decimal types this is precision. * <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits * <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2) * <LI><B>NULLABLE</B> int => whether NULL is allowed * <UL> * <LI> attributeNoNulls - might not allow NULL values * <LI> attributeNullable - definitely allows NULL values * <LI> attributeNullableUnknown - nullability unknown * </UL> * <LI><B>REMARKS</B> String => comment describing column (may be <code>null</code>) * <LI><B>ATTR_DEF</B> String => default value (may be <code>null</code>) * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the * maximum number of bytes in the column * <LI><B>ORDINAL_POSITION</B> int => index of column in table * (starting at 1) * <LI><B>IS_NULLABLE</B> String => "NO" means column definitely * does not allow NULL values; "YES" means the column might * allow NULL values. An empty string means unknown. * <LI><B>SCOPE_CATALOG</B> String => catalog of table that is the * scope of a reference attribute (<code>null</code> if DATA_TYPE isn't REF) * <LI><B>SCOPE_SCHEMA</B> String => schema of table that is the * scope of a reference attribute (<code>null</code> if DATA_TYPE isn't REF) * <LI><B>SCOPE_TABLE</B> String => table name that is the scope of a * reference attribute (<code>null</code> if the DATA_TYPE isn't REF) * <LI><B>SOURCE_DATA_TYPE</B> short => source type of a distinct type or user-generated * Ref type,SQL type from java.sql.Types (<code>null</code> if DATA_TYPE * isn't DISTINCT or user-generated REF) * </OL> * @param catalog a catalog name; must match the catalog name as it * is stored in the database; "" retrieves those without a catalog; * <code>null</code> means that the catalog name should not be used to narrow * the search * @param schemaPattern a schema name pattern; must match the schema name * as it is stored in the database; "" retrieves those without a schema; * <code>null</code> means that the schema name should not be used to narrow * the search * @param typeNamePattern a type name pattern; must match the * type name as it is stored in the database * @param attributeNamePattern an attribute name pattern; must match the attribute * name as it is declared in the database * @return a <code>ResultSet</code> object in which each row is an * attribute description * @throws SQLException if a database access error occurs */ public ResultSet getAttributes( String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern ) throws SQLException { String cat = (String)(getEnvMap().get("gdk_dbname")); String query = "SELECT '" + cat + "' AS \"TYPE_CAT\", '' AS \"TYPE_SCHEM\", '' AS \"TYPE_NAME\", " + "'' AS \"ATTR_NAME\", '' AS \"ATTR_TYPE_NAME\", 0 AS \"ATTR_SIZE\", " + "0 AS \"DECIMAL_DIGITS\", 0 AS \"NUM_PREC_RADIX\", 0 AS \"NULLABLE\", " + "'' AS \"REMARKS\", '' AS \"ATTR_DEF\", 0 AS \"SQL_DATA_TYPE\", " + "0 AS \"SQL_DATETIME_SUB\", 0 AS \"CHAR_OCTET_LENGTH\", " + "0 AS \"ORDINAL_POSITION\", 'YES' AS \"IS_NULLABLE\", " + "'' AS \"SCOPE_CATALOG\", '' AS \"SCOPE_SCHEMA\", '' AS \"SCOPE_TABLE\", " + "0 AS \"SOURCE_DATA_TYPE\" WHERE 1 = 0"; return(getStmt().executeQuery(query)); } /** * Retrieves whether this database supports the given result set holdability. * * @param holdability one of the following constants: * <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or * <code>ResultSet.CLOSE_CURSORS_AT_COMMIT<code> * @return <code>true</code> if so; <code>false</code> otherwise * @see Connection */ public boolean supportsResultSetHoldability(int holdability) { // we don't close ResultSets at commit; and we don't do updateable // result sets, so comes closest to hold cursors over commit return(holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT); } /** * Retrieves the default holdability of this <code>ResultSet</code> * object. * * @return the default holdability; either * <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or * <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code> */ public int getResultSetHoldability() { return(ResultSet.HOLD_CURSORS_OVER_COMMIT); } /** * Retrieves the major version number of the underlying database. * * @return the underlying database's major version * @throws SQLException if a database access error occurs */ public int getDatabaseMajorVersion() throws SQLException { Map env = getEnvMap(); String version = (String)env.get("gdk_version"); int major = 0; try { major = Integer.parseInt(version.substring(0, version.indexOf("."))); } catch (NumberFormatException e) { // baaaaaaaaaa } return(major); } /** * Retrieves the minor version number of the underlying database. * * @return underlying database's minor version * @throws SQLException if a database access error occurs */ public int getDatabaseMinorVersion() throws SQLException { Map env = getEnvMap(); String version = (String)env.get("gdk_version"); int minor = 0; try { int start = version.indexOf("."); minor = Integer.parseInt(version.substring(start + 1, version.indexOf(".", start + 1))); } catch (NumberFormatException e) { // baaaaaaaaaa } return(minor); } /** * Retrieves the major JDBC version number for this * driver. * * @return JDBC version major number */ public int getJDBCMajorVersion() { return(3); // This class implements JDBC 3.0 (at least we try to) } /** * Retrieves the minor JDBC version number for this * driver. * * @return JDBC version minor number */ public int getJDBCMinorVersion() { return(0); // This class implements JDBC 3.0 (at least we try to) } /** * Indicates whether the SQLSTATEs returned by <code>SQLException.getSQLState</code> * is X/Open (now known as Open Group) SQL CLI or SQL99. * @return the type of SQLSTATEs, one of: * sqlStateXOpen or * sqlStateSQL99 */ public int getSQLStateType() { // we conform to the SQL99 standard, so... return(DatabaseMetaData.sqlStateSQL99); } /** * Indicates whether updates made to a LOB are made on a copy or directly * to the LOB. * @return <code>true</code> if updates are made to a copy of the LOB; * <code>false</code> if updates are made directly to the LOB */ public boolean locatorsUpdateCopy() { // not that we have it, but in a transaction it will be copy-on-write return(true); } /** * Retrieves whether this database supports statement pooling. * * @return <code>true</code> is so; <code>false</code> otherwise */ public boolean supportsStatementPooling() { // For the moment, I don't think so return(false); } //== end methods interface DatabaseMetaData /** * make sure our related statement is closed upon garbage collect */ protected void finalize() throws Throwable { try { if (stmt != null) stmt.close(); } catch (SQLException e) { /* ignore */ } super.finalize(); } } /** * This class is not intended for normal use. Therefore it is restricted to * classes from the very same package only. Because it is used only in the * MonetDatabaseMetaData class it is placed here. * * Any use of this class is disencouraged. */ class MonetVirtualResultSet extends MonetResultSet { private String results[][]; private boolean closed; MonetVirtualResultSet( String[] columns, String[] types, String[][] results ) throws IllegalArgumentException { super(columns, types, results.length); this.results = results; closed = false; } /** * This method is overridden in order to let it use the results array * instead of the cache in the Statement object that created it. * * @param row the number of the row to which the cursor should move. A * positive number indicates the row number counting from the * beginning of the result set; a negative number indicates the row * number counting from the end of the result set * @return true if the cursor is on the result set; false otherwise * @throws SQLException if a database error occurs */ public boolean absolute(int row) throws SQLException { if (closed) throw new SQLException("ResultSet is closed!"); // first calculate what the JDBC row is if (row < 0) { // calculate the negatives... row = tupleCount + row + 1; } // now place the row not farther than just before or after the result if (row < 0) row = 0; // before first else if (row > tupleCount + 1) row = tupleCount + 1; // after last // store it curRow = row; // see if we have the row if (row < 1 || row > tupleCount) return(false); result = results[row - 1]; return(true); } /** * Mainly here to prevent errors when the close method is called. There * is no real need for this object to close it. We simply remove our * resultset data. */ public void close() { if (!closed) { closed = true; results = null; // types and columns are MonetResultSets private parts } } /** * Retrieves the fetch size for this ResultSet object, which will be * zero, since it's a virtual set. * * @return the current fetch size for this ResultSet object * @throws SQLException if a database access error occurs */ public int getFetchSize() throws SQLException { return(0); } }
public class Test{ //This is just a comment public static void main(String[] args){ System.out.println("Hello World!!"); } }
package com.experitest.auto; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.util.Properties; import org.openqa.selenium.Capabilities; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import io.appium.java_client.AppiumDriver; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; import io.appium.java_client.remote.IOSMobileCapabilityType; import io.appium.java_client.remote.MobileCapabilityType; public class BaseTest { public static String buildId = System.getenv("BUILD_NUMBER"); public static String accessKey = System.getenv("access.key"); public static String deviceQuery = System.getenv("device.query"); protected IOSDriver<IOSElement> driver = null; protected DesiredCapabilities dc = new DesiredCapabilities(); public void init(String deviceQuery) throws Exception { initCloudProperties(); dc.setCapability("deviceQuery", adhocDevice(deviceQuery)); String cname = className.split("\\.")[className.split("\\.").length - 1]; dc.setCapability("testName", cname + "." + testName); dc.setCapability("build", String.valueOf(getBuild())); dc.setCapability(MobileCapabilityType.ORIENTATION, "portrait"); //dc.setCapability(MobileCapabilityType.APP, "cloud:com.experitest.ExperiBank"); //dc.setCapability(IOSMobileCapabilityType.BUNDLE_ID, "com.experitest.ExperiBank"); dc.setCapability("accessKey", accessKey); dc.setCapability("autoAcceptAlerts", true); dc.setCapability("stream", "demo4"); dc.setCapability("reportDirectory", "reports"); dc.setCapability("reportFormat", "xml"); dc.setCapability("project", getProperty("project", cloudProperties)); dc.setCapability("instrumentApp", true); driver = new IOSDriver<>(new URL("https://stage.experitest.com/wd/hub"), dc); Thread.sleep(2000); driver.executeScript("client:client.install(\"cloud:com.experitest.ExperiBank\", true, false);"); driver.executeScript("client:client.launch(\"com.experitest.ExperiBank\", true, true);"); } protected String getProperty(String property, Properties props) throws FileNotFoundException, IOException { if (System.getProperty(property) != null) { return System.getProperty(property); } else if (System.getenv().containsKey(property)) { return System.getenv(property); } else if (props != null) { return props.getProperty(property); } return null; } protected Properties cloudProperties = new Properties(); String testName = "unknown"; String className = "unknown"; @BeforeMethod public void handleTestMethodName(Method method) { testName = method.getName(); } @BeforeClass public void beforeClass() { className = this.getClass().getName(); } private void initCloudProperties() throws FileNotFoundException, IOException { FileReader fr = new FileReader("cloud.properties"); cloudProperties.load(fr); fr.close(); } private static synchronized String adhocDevice(String deviceQuery) { try { File jarLocation = (System.getProperty("os.name").toUpperCase().contains("WIN")) ? new File(System.getenv("APPDATA"), ".mobiledata") : new File(System.getProperty("user.home") + "/Library/Application " + "Support", ".mobiledata"); File adhocProperties = new File(jarLocation, "adhoc.properties"); if (adhocProperties.exists()) { Properties prop = new Properties(); FileReader reader = new FileReader(adhocProperties); try { prop.load(reader); } finally { reader.close(); } adhocProperties.delete(); return "@serialnumber='" + prop.getProperty("serial") + "'"; } } catch (Exception e) { e.printStackTrace(); } return deviceQuery; } public synchronized static String getBuild() { if(buildId == null) { buildId = "-1"; } return buildId; } public void shouldFailTest(AppiumDriver<?> driver) { Capabilities c = driver.getCapabilities(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // if("11.x".equals(c.getCapability("device.majorVersion"))) {
package org.collectionspace.chain.csp.persistence.services.user; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.collectionspace.chain.csp.persistence.services.XmlJsonConversion; import org.collectionspace.chain.csp.persistence.services.connection.ConnectionException; import org.collectionspace.chain.csp.persistence.services.connection.RequestMethod; import org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument; import org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument; import org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL; import org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection; import org.collectionspace.chain.csp.persistence.services.vocab.URNProcessor; import org.collectionspace.chain.csp.schema.Field; import org.collectionspace.chain.csp.schema.FieldSet; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.csp.api.core.CSPRequestCache; import org.collectionspace.csp.api.core.CSPRequestCredentials; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.helper.persistence.ContextualisedStorage; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; /** Implements user service connection over service layer. Generally simply a much simpler version of regular record storage, but also uses non-multiparts. * * @author dan * */ public class UserStorage implements ContextualisedStorage { private static final Logger log=LoggerFactory.getLogger(UserStorage.class); private ServicesConnection conn; private Record r; private Map<String,String> view_good=new HashMap<String,String>(); private Map<String,String> view_map=new HashMap<String,String>(); private Set<String> xxx_view_deurn=new HashSet<String>(); public UserStorage(Record r,ServicesConnection conn) throws DocumentException, IOException { this.conn=conn; this.r=r; } private void setGleanedValue(CSPRequestCache cache,String path,String key,String value) { cache.setCached(getClass(),new String[]{"glean",path,key},value); } private String getGleanedValue(CSPRequestCache cache,String path,String key) { return (String)cache.getCached(getClass(),new String[]{"glean",path,key}); } private JSONObject correctPassword(JSONObject in) throws JSONException, UnderlyingStorageException { try { if(in.has("password")){ String password=in.getString("password"); in.remove("password"); password=Base64.encode(password.getBytes("UTF-8")); while(password.endsWith("\n") || password.endsWith("\r")) password=password.substring(0,password.length()-1); in.put("password",password); } return in; } catch (UnsupportedEncodingException e) { throw new UnderlyingStorageException("Error generating Base 64",e); } } /* XXX FIXME in here until we fix the UI layer to pass the data correctly */ private JSONObject correctScreenName(JSONObject in) throws JSONException, UnderlyingStorageException { if(in.has("userName") && !in.has("screenName")){ String username=in.getString("userName"); in.remove("userName"); in.put("screenName",username); } return in; } /* XXX FIXME in here until we fix the UI layer to pass the data correctly */ private JSONObject correctUserId(JSONObject in) throws JSONException, UnderlyingStorageException { if(!in.has("userId")){ String userId=in.getString("email"); in.remove("userId"); in.put("userId",userId); } return in; } public String autocreateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject) throws ExistException, UnimplementedException, UnderlyingStorageException { try { jsonObject=correctPassword(jsonObject); jsonObject= correctScreenName(jsonObject); jsonObject= correctUserId(jsonObject); Document doc=XmlJsonConversion.convertToXml(r,jsonObject,"common"); ReturnedURL url = conn.getURL(RequestMethod.POST,r.getServicesURL()+"/",doc,creds,cache); if(url.getStatus()>299 || url.getStatus()<200) throw new UnderlyingStorageException("Bad response "+url.getStatus()); return url.getURLTail(); } catch (ConnectionException e) { throw new UnderlyingStorageException("Service layer exception",e); } catch (JSONException e) { throw new UnimplementedException("JSONException",e); } } public void createJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject) throws ExistException, UnimplementedException, UnderlyingStorageException { throw new UnimplementedException("Cannot post to full path"); } public void deleteJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException { try { int status=conn.getNone(RequestMethod.DELETE,r.getServicesURL()+"/"+filePath,null,creds,cache); if(status>299 || status<200) // XXX CSPACE-73, should be 404 throw new UnderlyingStorageException("Service layer exception status="+status); } catch (ConnectionException e) { throw new UnderlyingStorageException("Service layer exception",e); } } @SuppressWarnings("unchecked") public String[] getPaths(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String rootPath,JSONObject restrictions) throws ExistException, UnimplementedException, UnderlyingStorageException { try { List<String> out=new ArrayList<String>(); Iterator rit=restrictions.keys(); StringBuffer args=new StringBuffer(); while(rit.hasNext()) { String key=(String)rit.next(); FieldSet fs=r.getField(key); if(!(fs instanceof Field)) continue; String filter=((Field)fs).getServicesFilterParam(); if(filter==null) continue; args.append('&'); args.append(filter); args.append('='); args.append(URLEncoder.encode(restrictions.getString(key),"UTF-8")); } //pagination String url=r.getServicesURL()+"/"; String postfix = "?"; String tail=args.toString(); if(tail.length()>0) { postfix += tail.substring(1) +"&"; } if(restrictions!=null){ if(restrictions.has("pageSize")){ postfix += "pgSz="+restrictions.getString("pageSize")+"&"; } if(restrictions.has("pageNum")){ postfix += "pgNum="+restrictions.getString("pageNum")+"&"; } } postfix = postfix.substring(0, postfix.length()-1); ReturnedDocument doc=conn.getXMLDocument(RequestMethod.GET,r.getServicesURL()+"/"+postfix,null,creds,cache); if(doc.getStatus()<200 || doc.getStatus()>399) throw new UnderlyingStorageException("Cannot retrieve account list"); Document list=doc.getDocument(); List<Node> objects=list.selectNodes(r.getServicesListPath()); for(Node object : objects) { List<Node> fields=object.selectNodes("*"); String csid=object.selectSingleNode("csid").getText(); for(Node field : fields) { if("csid".equals(field.getName())) { int idx=csid.lastIndexOf("/"); if(idx!=-1) csid=csid.substring(idx+1); out.add(csid); } else if("uri".equals(field.getName())) { // Skip! } else { String json_name=view_map.get(field.getName()); if(json_name!=null) { String value=field.getText(); // XXX hack to cope with multi values if(value==null || "".equals(value)) { List<Node> inners=field.selectNodes("*"); for(Node n : inners) { value+=n.getText(); } } setGleanedValue(cache,r.getServicesURL()+"/"+csid,json_name,value); } } } } return out.toArray(new String[0]); } catch (ConnectionException e) { throw new UnderlyingStorageException("Service layer exception",e); } catch (UnsupportedEncodingException e) { throw new UnderlyingStorageException("Exception building query",e); } catch (JSONException e) { throw new UnderlyingStorageException("Exception building query",e); } } // XXX support URNs for reference private JSONObject miniForURI(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String refname,String uri) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { return storage.retrieveJSON(storage,creds,cache,"direct/urn/"+uri+"/"+refname); } public JSONObject refViewRetrieveJSON(ContextualisedStorage storage,CSPRequestCredentials creds,CSPRequestCache cache,String filePath) throws ExistException,UnimplementedException, UnderlyingStorageException, JSONException { try { ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET,r.getServicesURL()+"/"+filePath+"/authorityrefs",null,creds,cache); if(all.getStatus()!=200) throw new ConnectionException("Bad request during identifier cache map update: status not 200"); Document list=all.getDocument(); JSONObject out=new JSONObject(); for(Object node : list.selectNodes("authority-ref-list/authority-ref-item")) { if(!(node instanceof Element)) continue; String key=((Element)node).selectSingleNode("sourceField").getText(); String uri=((Element)node).selectSingleNode("uri").getText(); String refname=((Element)node).selectSingleNode("refName").getText(); if(uri!=null && uri.startsWith("/")) uri=uri.substring(1); JSONObject data=miniForURI(storage,creds,cache,refname,uri); out.put(key,data); } return out; } catch (ConnectionException e) { throw new UnderlyingStorageException("Connection problem",e); } } public JSONObject retrieveJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException { try { ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET,r.getServicesURL()+"/"+filePath,null,creds,cache); JSONObject out=new JSONObject(); if((doc.getStatus()<200 || doc.getStatus()>=300)) throw new ExistException("Does not exist "+filePath); out=XmlJsonConversion.convertToJson(r,doc.getDocument()); return out; } catch (ConnectionException e) { throw new UnderlyingStorageException("Service layer exception",e); } catch (JSONException e) { throw new UnderlyingStorageException("Service layer exception",e); } } private JSONObject xxx_cspace1458_fix(String filePath,JSONObject in,CSPRequestCredentials creds,CSPRequestCache cache) throws ConnectionException, UnderlyingStorageException, JSONException { // We need to also specify status and createdAt (revealed by GET) because of CSPACE-1458. ReturnedDocument doc = conn.getXMLDocument(RequestMethod.GET,r.getServicesURL()+"/"+filePath,null,creds,cache); if(doc.getStatus()>299 || doc.getStatus()<200) throw new UnderlyingStorageException("Bad response "+doc.getStatus()); System.err.println(doc.getDocument().asXML()); String created_at=doc.getDocument().selectSingleNode("accounts_common/createdAt").getText(); String status=doc.getDocument().selectSingleNode("accounts_common/status").getText(); in.put("createdAt",created_at); if(!in.has("status")) in.put("status",status); //in.remove("password"); return in; } public void updateJSON(ContextualisedStorage root,CSPRequestCredentials creds,CSPRequestCache cache,String filePath, JSONObject jsonObject) throws ExistException, UnimplementedException, UnderlyingStorageException { try { // XXX when CSPACE-1458 is fixed, remove the call to xxx_cspace1458_fix, and just pass jsonObject as this arg. (fao Chris or somoeone else at CARET). jsonObject=correctPassword(jsonObject); Document in=XmlJsonConversion.convertToXml(r,xxx_cspace1458_fix(filePath,jsonObject,creds,cache),"common"); System.err.println("Sending: "+in.asXML()); ReturnedDocument doc = conn.getXMLDocument(RequestMethod.PUT,r.getServicesURL()+"/"+filePath,in,creds,cache); if(doc.getStatus()==404) throw new ExistException("Not found: "+r.getServicesURL()+"/"+filePath); if(doc.getStatus()>299 || doc.getStatus()<200) throw new UnderlyingStorageException("Bad response "+doc.getStatus()); } catch (ConnectionException e) { throw new UnderlyingStorageException("Service layer exception",e); } catch (JSONException e) { throw new UnimplementedException("JSONException",e); } } }
package gov.cdc.sdp.cbr; import static org.junit.Assert.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.sql.ResultSet; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.apache.camel.CamelContext; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultExchange; import org.apache.camel.impl.DefaultMessage; import org.apache.camel.test.spring.CamelSpringJUnit4ClassRunner; import org.apache.camel.test.spring.CamelTestContextBootstrapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.BootstrapWith; import org.springframework.test.context.ContextConfiguration; @RunWith(CamelSpringJUnit4ClassRunner.class) @BootstrapWith(CamelTestContextBootstrapper.class) @ContextConfiguration(locations = { "classpath:PhinMSDBTest-context.xml" }) @PropertySource("classpath:application.properties") public class PhinMSDBTest { @Autowired protected CamelContext camelContext; @EndpointInject(uri = "mock:phinmsDb") protected MockEndpoint phinMSDb; @Produce(uri = "direct:phinms") protected ProducerTemplate template; private final String file_name = "phinms_input.csv"; private final String input_file_path = "src/test/resources/" + file_name; @Test public void testPhinMSProducer() { MockEndpoint.resetMocks(camelContext); JdbcTemplate jdbcTemplate = null; int count = -1; try { DataSource ds = (DataSource) camelContext.getRegistry().lookupByName("phinMSDataSource"); jdbcTemplate = new JdbcTemplate(ds); count = jdbcTemplate.queryForObject("select count(*) from message_inq", Integer.class); Exchange exchange = new DefaultExchange(camelContext); Message msg = new DefaultMessage(); String expected_content = readFile(input_file_path); msg.setBody(expected_content); exchange.setIn(msg); phinMSDb.expectedMessageCount(1); template.send(exchange); MockEndpoint.assertIsSatisfied(camelContext); int linesInFile = getLinesInFile(input_file_path); int countDelta = jdbcTemplate.queryForObject("select count(*) from message_inq", Integer.class) - count; assertEquals(linesInFile-1, countDelta); } catch (IOException e) { fail("Could not read input file"); } catch (InterruptedException e) { fail("Interrupted Exception thrown"); } finally { if (jdbcTemplate != null) { jdbcTemplate.execute("DELETE from message_inq where fromPartyId='testPhinMS_Producer'"); if (count > 0) { assertEquals(count, (int)jdbcTemplate.queryForObject("select count(*) from message_inq", Integer.class)); } } } } @Test public void testPhinMSProducerMultiLine() { MockEndpoint.resetMocks(camelContext); JdbcTemplate jdbcTemplate = null; int count = -1; try { DataSource ds = (DataSource) camelContext.getRegistry().lookupByName("phinMSDataSource"); jdbcTemplate = new JdbcTemplate(ds); count = jdbcTemplate.queryForObject("select count(*) from message_inq", Integer.class); String fileName = "phinms_input_multi.csv"; String inputFilePath = "src/test/resources/" + fileName; Exchange exchange = new DefaultExchange(camelContext); Message msg = new DefaultMessage(); String expected_content = readFile(inputFilePath); msg.setBody(expected_content); exchange.setIn(msg); phinMSDb.expectedMessageCount(1); template.send(exchange); MockEndpoint.assertIsSatisfied(camelContext); int countDelta = jdbcTemplate.queryForObject("select count(*) from message_inq", Integer.class) - count; assertEquals(13, countDelta); } catch (IOException e) { fail("Could not read input file"); } catch (InterruptedException e) { fail("Interrupted Exception thrown"); } finally { if (jdbcTemplate != null) { jdbcTemplate.execute("DELETE from message_inq where fromPartyId='TEST'"); if (count > 0) { assertEquals(count, (int)jdbcTemplate.queryForObject("select count(*) from message_inq", Integer.class)); } } } } private String readFile(String file) throws IOException { return new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(file))); } private int getLinesInFile(String file) throws IOException { LineNumberReader lnr = null; try { lnr = new LineNumberReader(new FileReader(new File(file))); lnr.skip(Long.MAX_VALUE); int lines = lnr.getLineNumber(); return lines; } finally { if (lnr != null) lnr.close(); } } }
package jcifs.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.net.MalformedURLException; import java.net.UnknownHostException; import org.junit.Test; import jcifs.CIFSContext; import jcifs.CIFSException; import jcifs.DfsReferralData; import jcifs.SmbConstants; import jcifs.SmbResource; import jcifs.SmbResourceLocator; import jcifs.config.BaseConfiguration; import jcifs.context.BaseContext; import jcifs.smb.SmbFile; import jcifs.smb.SmbResourceLocatorInternal; /** * @author mbechler * */ @SuppressWarnings ( "javadoc" ) public class FileLocationTest { @Test public void testRoot () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://", getContext()) ) { SmbResourceLocator fl = p.getLocator(); assertNull(fl.getServer()); assertNull(fl.getShare()); assertEquals(SmbConstants.TYPE_WORKGROUP, fl.getType()); assertEquals("\\", fl.getUNCPath()); assertEquals("smb://", fl.getCanonicalURL()); assertEquals("/", fl.getURLPath()); } } @Test public void testEmpty () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb:", getContext()) ) { SmbResourceLocator fl = p.getLocator(); assertNull(fl.getServer()); assertNull(fl.getShare()); assertEquals(SmbConstants.TYPE_WORKGROUP, fl.getType()); assertEquals("\\", fl.getUNCPath()); assertEquals("smb://", fl.getCanonicalURL()); assertEquals("/", fl.getURLPath()); } } @Test public void testChildHost () throws MalformedURLException, CIFSException, UnknownHostException { try ( SmbFile p = new SmbFile("smb://", getContext()); SmbResource c = new SmbFile(p, "1.2.3.4") ) { SmbResourceLocator fl = c.getLocator(); assertEquals("1.2.3.4", fl.getServer()); assertEquals(SmbConstants.TYPE_SERVER, fl.getType()); assertNull(fl.getShare()); assertEquals("\\", fl.getUNCPath()); assertEquals("smb://1.2.3.4/", fl.getCanonicalURL()); assertEquals("/", fl.getURLPath()); } } @Test public void testChildShare () throws MalformedURLException, CIFSException, UnknownHostException { try ( SmbFile p = new SmbFile("smb://1.2.3.4/", getContext()); SmbResource c = new SmbFile(p, "share/") ) { SmbResourceLocator fl = c.getLocator(); assertEquals("1.2.3.4", fl.getServer()); assertEquals(SmbConstants.TYPE_SHARE, fl.getType()); assertEquals("share", fl.getShare()); assertEquals("\\", fl.getUNCPath()); assertEquals("smb://1.2.3.4/share/", fl.getCanonicalURL()); assertEquals("/share/", fl.getURLPath()); } } @Test public void testChildShareCombined () throws MalformedURLException, CIFSException, UnknownHostException { try ( SmbFile p = new SmbFile("smb://", getContext()); SmbResource c = new SmbFile(p, "1.2.3.4/share/") ) { SmbResourceLocator fl = c.getLocator(); assertEquals("1.2.3.4", fl.getServer()); assertEquals(SmbConstants.TYPE_SHARE, fl.getType()); assertEquals("share", fl.getShare()); assertEquals("\\", fl.getUNCPath()); assertEquals("smb://1.2.3.4/share/", fl.getCanonicalURL()); assertEquals("/share/", fl.getURLPath()); } } @Test public void testChildPath () throws MalformedURLException, CIFSException, UnknownHostException { try ( SmbFile p = new SmbFile("smb://1.2.3.4/share/", getContext()); SmbResource c = new SmbFile(p, "foo/") ) { SmbResourceLocator fl = c.getLocator(); assertEquals("1.2.3.4", fl.getServer()); assertEquals(SmbConstants.TYPE_FILESYSTEM, fl.getType()); assertEquals("share", fl.getShare()); assertEquals("\\foo\\", fl.getUNCPath()); assertEquals("smb://1.2.3.4/share/foo/", fl.getCanonicalURL()); assertEquals("/share/foo/", fl.getURLPath()); } } @Test public void testChildMultiPath () throws MalformedURLException, CIFSException, UnknownHostException { try ( SmbFile p = new SmbFile("smb://1.2.3.4/share/", getContext()); SmbResource c = new SmbFile(p, "foo/bar/") ) { SmbResourceLocator fl = c.getLocator(); assertEquals("1.2.3.4", fl.getServer()); assertEquals(SmbConstants.TYPE_FILESYSTEM, fl.getType()); assertEquals("share", fl.getShare()); assertEquals("\\foo\\bar\\", fl.getUNCPath()); assertEquals("smb://1.2.3.4/share/foo/bar/", fl.getCanonicalURL()); assertEquals("/share/foo/bar/", fl.getURLPath()); } } @Test public void testChildPathCombined () throws MalformedURLException, CIFSException, UnknownHostException { try ( SmbFile p = new SmbFile("smb://", getContext()); SmbResource c = new SmbFile(p, "1.2.3.4/share/foo/") ) { SmbResourceLocator fl = c.getLocator(); assertEquals("1.2.3.4", fl.getServer()); assertEquals(SmbConstants.TYPE_FILESYSTEM, fl.getType()); assertEquals("share", fl.getShare()); assertEquals("\\foo\\", fl.getUNCPath()); assertEquals("smb://1.2.3.4/share/foo/", fl.getCanonicalURL()); assertEquals("/share/foo/", fl.getURLPath()); } } @Test public void testParentRoot () throws MalformedURLException, CIFSException { try ( SmbFile p = new SmbFile("smb://", getContext()); SmbResource pp = new SmbFile(p.getParent(), getContext()) ) { assertEquals("smb://", p.getLocator().getParent()); assertEquals(SmbConstants.TYPE_WORKGROUP, pp.getLocator().getType()); assertNull(pp.getLocator().getServer()); assertNull(pp.getLocator().getShare()); } } @Test public void testParentServer () throws MalformedURLException, CIFSException { try ( SmbFile p = new SmbFile("smb://1.2.3.4/", getContext()); SmbResource pp = new SmbFile(p.getParent(), getContext()) ) { assertEquals("smb://", p.getLocator().getParent()); SmbResourceLocator fl = pp.getLocator(); assertEquals(SmbConstants.TYPE_WORKGROUP, fl.getType()); assertNull(fl.getServer()); assertNull(fl.getShare()); } } @Test public void testParentShare () throws MalformedURLException, CIFSException { try ( SmbFile p = new SmbFile("smb://1.2.3.4/share/", getContext()); SmbResource pp = new SmbFile(p.getParent(), getContext()) ) { assertEquals("smb://1.2.3.4/", p.getLocator().getParent()); SmbResourceLocator fl = pp.getLocator(); assertEquals(SmbConstants.TYPE_SERVER, fl.getType()); assertEquals("1.2.3.4", fl.getServer()); assertNull(fl.getShare()); assertEquals("\\", fl.getUNCPath()); assertEquals("/", fl.getURLPath()); } } @Test public void testParentPath1 () throws MalformedURLException, CIFSException { try ( SmbFile p = new SmbFile("smb://1.2.3.4/share/foo/", getContext()); SmbResource pp = new SmbFile(p.getParent(), getContext()) ) { assertEquals("smb://1.2.3.4/share/", p.getLocator().getParent()); SmbResourceLocator fl = pp.getLocator(); assertEquals(SmbConstants.TYPE_SHARE, fl.getType()); assertEquals("1.2.3.4", fl.getServer()); assertEquals("share", fl.getShare()); assertEquals("\\", fl.getUNCPath()); assertEquals("/share/", fl.getURLPath()); } } @Test public void testParentPath2 () throws MalformedURLException, CIFSException { try ( SmbFile p = new SmbFile("smb://1.2.3.4/share/foo/bar/", getContext()); SmbResource pp = new SmbFile(p.getParent(), getContext()) ) { assertEquals("smb://1.2.3.4/share/foo/", p.getLocator().getParent()); SmbResourceLocator fl = pp.getLocator(); assertEquals(SmbConstants.TYPE_FILESYSTEM, fl.getType()); assertEquals("1.2.3.4", fl.getServer()); assertEquals("share", fl.getShare()); assertEquals("\\foo\\", fl.getUNCPath()); assertEquals("/share/foo/", fl.getURLPath()); } } @Test public void testDfsReferralServer () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://1.2.3.4/share/foo/bar/", getContext()) ) { DfsReferralData dr = new TestDfsReferral("2.3.4.5", null, "", 0); String reqPath = "\\foo\\bar\\"; SmbResourceLocator fl = p.getLocator(); assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath)); assertEquals("1.2.3.4", fl.getServer()); assertEquals("2.3.4.5", fl.getServerWithDfs()); assertEquals("share", fl.getShare()); assertEquals("\\foo\\bar\\", fl.getUNCPath()); assertEquals("/share/foo/bar/", fl.getURLPath()); } } @Test public void testDfsReferralShare () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://1.2.3.4/share/foo/bar/", getContext()) ) { DfsReferralData dr = new TestDfsReferral("1.2.3.4", "other", "", 0); String reqPath = "\\foo\\bar\\"; SmbResourceLocator fl = p.getLocator(); assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath)); assertEquals("1.2.3.4", fl.getServer()); assertEquals("1.2.3.4", fl.getServerWithDfs()); assertEquals("other", fl.getShare()); assertEquals("\\foo\\bar\\", fl.getUNCPath()); // this intentionally sticks to the old name assertEquals("/share/foo/bar/", fl.getURLPath()); } } @Test public void testDfsReferralShareNested () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://1.2.3.4/dfs/share/bar/", getContext()) ) { DfsReferralData dr = new TestDfsReferral("1.2.3.4", "target", "", 6); // consumes the /share dfs root path String reqPath = "\\share\\bar\\"; SmbResourceLocator fl = p.getLocator(); assertEquals("\\bar\\", ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath)); assertEquals("1.2.3.4", fl.getServer()); assertEquals("1.2.3.4", fl.getServerWithDfs()); assertEquals("target", fl.getShare()); assertEquals("\\bar\\", fl.getUNCPath()); // this intentionally sticks to the old name assertEquals("/dfs/share/bar/", fl.getURLPath()); } } @Test public void testDfsReferralAfterUncPath () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://1.2.3.4/share/foo/bar/", getContext()) ) { p.getLocator().getUNCPath(); DfsReferralData dr = new TestDfsReferral("1.2.3.5", "other", "", 0); String reqPath = "\\foo\\bar\\"; SmbResourceLocator fl = p.getLocator(); assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath)); assertEquals("1.2.3.4", fl.getServer()); assertEquals("1.2.3.5", fl.getServerWithDfs()); assertEquals("other", fl.getShare()); assertEquals("\\foo\\bar\\", fl.getUNCPath()); // this intentionally sticks to the old name assertEquals("/share/foo/bar/", fl.getURLPath()); } } @Test public void testDfsReferralChildResource () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://1.2.3.4/share/foo/", getContext()) ) { DfsReferralData dr = new TestDfsReferral("1.2.3.5", "other", "", 0); String reqPath = "\\foo\\"; SmbResourceLocator fl = p.getLocator(); assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath)); assertEquals("1.2.3.4", fl.getServer()); assertEquals("1.2.3.5", fl.getServerWithDfs()); assertEquals("other", fl.getShare()); assertEquals("\\foo\\", fl.getUNCPath()); // this intentionally sticks to the old name assertEquals("/share/foo/", fl.getURLPath()); try ( SmbResource c = p.resolve("bar/") ) { SmbResourceLocator fl2 = c.getLocator(); reqPath = fl2.getUNCPath(); assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl2 ).handleDFSReferral(dr, reqPath)); } } } @Test public void testDfsReferralMultiLink () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://1.2.3.4/share/foo/", getContext()) ) { DfsReferralData dr = new TestDfsReferral("1.2.3.5", "otherdfs", "", 0); String reqPath = "\\foo\\"; SmbResourceLocator fl = p.getLocator(); assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl ).handleDFSReferral(dr, reqPath)); assertEquals("1.2.3.4", fl.getServer()); assertEquals("1.2.3.5", fl.getServerWithDfs()); assertEquals("otherdfs", fl.getShare()); assertEquals("\\foo\\", fl.getUNCPath()); // this intentionally sticks to the old name assertEquals("/share/foo/", fl.getURLPath()); try ( SmbResource c = p.resolve("bar/") ) { DfsReferralData dr2 = new TestDfsReferral("1.2.3.6", "target", "", 0); SmbResourceLocator fl2 = c.getLocator(); reqPath = fl2.getUNCPath(); assertEquals(reqPath, ( (SmbResourceLocatorInternal) fl2 ).handleDFSReferral(dr2, reqPath)); assertEquals("1.2.3.4", fl2.getServer()); assertEquals("1.2.3.6", fl2.getServerWithDfs()); assertEquals("target", fl2.getShare()); assertEquals("\\foo\\bar\\", fl2.getUNCPath()); // this intentionally sticks to the old name assertEquals("/share/foo/bar/", fl2.getURLPath()); } } } // test case for @Test ( expected = MalformedURLException.class ) public void testInvalid () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb:a", getContext()) ) { p.getType(); } } // @Test public void testGetName () throws MalformedURLException, CIFSException { try ( SmbResource p = new SmbFile("smb://MYSERVER/Public/MyVideo.mkv", getContext()) ) { SmbResourceLocator fl = p.getLocator(); assertEquals("MYSERVER", fl.getServer()); assertEquals("MYSERVER", fl.getServerWithDfs()); assertEquals("Public", fl.getShare()); assertEquals("\\MyVideo.mkv", fl.getUNCPath()); assertEquals("/Public/MyVideo.mkv", fl.getURLPath()); assertEquals("MyVideo.mkv", p.getName()); } } // @Test public void testGetNameShare () throws MalformedURLException, CIFSException { try ( SmbResource r = new SmbFile("smb://MYSERVER/Public/", getContext()); SmbResource p = r.resolve("MyVideo.mkv") ) { SmbResourceLocator fl = p.getLocator(); assertEquals("MYSERVER", fl.getServer()); assertEquals("MYSERVER", fl.getServerWithDfs()); assertEquals("Public", fl.getShare()); assertEquals("\\MyVideo.mkv", fl.getUNCPath()); assertEquals("/Public/MyVideo.mkv", fl.getURLPath()); assertEquals("MyVideo.mkv", p.getName()); } } // @Test public void testGetNameServer () throws MalformedURLException, CIFSException { try ( SmbResource r = new SmbFile("smb://0.0.0.0/", getContext()); SmbResource s = r.resolve("Public/"); SmbResource p = s.resolve("MyVideo.mkv"); ) { SmbResourceLocator fl = p.getLocator(); assertEquals("0.0.0.0", fl.getServer()); assertEquals("0.0.0.0", fl.getServerWithDfs()); assertEquals("Public", fl.getShare()); assertEquals("\\MyVideo.mkv", fl.getUNCPath()); assertEquals("/Public/MyVideo.mkv", fl.getURLPath()); assertEquals("MyVideo.mkv", p.getName()); } } // @Test public void testIPCHidden () throws MalformedURLException, CIFSException { try ( SmbResource r = new SmbFile("smb://0.0.0.0/IPC$/", getContext()) ) { assert ( r.isHidden() ); } } private static class TestDfsReferral implements DfsReferralData { private String server; private String share; private String path; private int pathConsumed; public TestDfsReferral ( String server, String share, String path, int pathConsumed ) { this.server = server; this.share = share; this.path = path; this.pathConsumed = pathConsumed; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#unwrap(java.lang.Class) */ @SuppressWarnings ( "unchecked" ) @Override public <T extends DfsReferralData> T unwrap ( Class<T> type ) { if ( type.isAssignableFrom(this.getClass()) ) { return (T) this; } throw new ClassCastException(); } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#getServer() */ @Override public String getServer () { return this.server; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#getDomain() */ @Override public String getDomain () { return null; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#getLink() */ @Override public String getLink () { return null; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#getShare() */ @Override public String getShare () { return this.share; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#getPathConsumed() */ @Override public int getPathConsumed () { return this.pathConsumed; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#getPath() */ @Override public String getPath () { return this.path; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#getExpiration() */ @Override public long getExpiration () { return 0; } /** * {@inheritDoc} * * @see jcifs.DfsReferralData#next() */ @Override public DfsReferralData next () { return this; } } /** * @return * @throws CIFSException */ private static CIFSContext getContext () throws CIFSException { return new BaseContext(new BaseConfiguration(true)); } }
package org.drools.benchmark.manners; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.StringTokenizer; import org.drools.KnowledgeBase; import org.drools.KnowledgeBaseFactory; import org.drools.builder.KnowledgeBuilder; import org.drools.builder.KnowledgeBuilderConfiguration; import org.drools.builder.KnowledgeBuilderFactory; import org.drools.builder.KnowledgeType; import org.drools.definition.KnowledgePackage; import org.drools.io.ResourceFactory; import org.drools.runtime.StatefulKnowledgeSession; public class MannersBenchmark { /** Number of guests at the dinner (default: 16). */ private static int numGuests = 16; /** Number of seats at the table (default: 16). */ private static int numSeats = 16; /** Minimum number of hobbies each guest should have (default: 2). */ private static int minHobbies = 2; /** Maximun number of hobbies each guest should have (default: 3). */ private static int maxHobbies = 3; public static void main(final String[] args) throws Exception { KnowledgeBuilderConfiguration kbuilderConfig = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( kbuilderConfig ); kbuilder.add( ResourceFactory.newClassPathResource( "manners.drl", MannersBenchmark.class ), KnowledgeType.DRL ); Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); // add the package to a rulebase final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages( pkgs ); for ( int i = 0; i < 10; i++ ) { StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); String filename; if ( args.length != 0 ) { String arg = args[0]; filename = arg; } else { filename = "manners128.dat"; } InputStream is = MannersBenchmark.class.getResourceAsStream( filename ); List list = getInputObjects( is ); for ( Iterator it = list.iterator(); it.hasNext(); ) { Object object = it.next(); ksession.insert( object ); } ksession.insert( new Count( 1 ) ); long start = System.currentTimeMillis(); ksession.fireAllRules(); System.err.println( System.currentTimeMillis() - start ); ksession.dispose(); } } /** * Convert the facts from the <code>InputStream</code> to a list of * objects. */ protected static List<Object> getInputObjects(InputStream inputStream) throws IOException { List<Object> list = new ArrayList<Object>(); BufferedReader br = new BufferedReader( new InputStreamReader( inputStream ) ); String line; while ( (line = br.readLine()) != null ) { if ( line.trim().length() == 0 || line.trim().startsWith( ";" ) ) { continue; } StringTokenizer st = new StringTokenizer( line, "() " ); String type = st.nextToken(); if ( "guest".equals( type ) ) { if ( !"name".equals( st.nextToken() ) ) { throw new IOException( "expected 'name' in: " + line ); } String name = st.nextToken(); if ( !"sex".equals( st.nextToken() ) ) { throw new IOException( "expected 'sex' in: " + line ); } String sex = st.nextToken(); if ( !"hobby".equals( st.nextToken() ) ) { throw new IOException( "expected 'hobby' in: " + line ); } String hobby = st.nextToken(); Guest guest = new Guest( name, Sex.resolve( sex ), Hobby.resolve( hobby ) ); list.add( guest ); } if ( "last_seat".equals( type ) ) { if ( !"seat".equals( st.nextToken() ) ) { throw new IOException( "expected 'seat' in: " + line ); } list.add( new LastSeat( new Integer( st.nextToken() ).intValue() ) ); } if ( "context".equals( type ) ) { if ( !"state".equals( st.nextToken() ) ) { throw new IOException( "expected 'state' in: " + line ); } list.add( new Context( st.nextToken() ) ); } } inputStream.close(); return list; } public static InputStream generateData() { final String LINE_SEPARATOR = System.getProperty( "line.separator" ); StringWriter writer = new StringWriter(); int maxMale = numGuests / 2; int maxFemale = numGuests / 2; int maleCount = 0; int femaleCount = 0; // init hobbies List<String> hobbyList = new ArrayList<String>(); for ( int i = 1; i <= maxHobbies; i++ ) { hobbyList.add( "h" + i ); } Random rnd = new Random(); for ( int i = 1; i <= numGuests; i++ ) { char sex = rnd.nextBoolean() ? 'm' : 'f'; if ( sex == 'm' && maleCount == maxMale ) { sex = 'f'; } if ( sex == 'f' && femaleCount == maxFemale ) { sex = 'm'; } if ( sex == 'm' ) { maleCount++; } if ( sex == 'f' ) { femaleCount++; } List<String> guestHobbies = new ArrayList<String>( hobbyList ); int numHobbies = minHobbies + rnd.nextInt( maxHobbies - minHobbies + 1 ); for ( int j = 0; j < numHobbies; j++ ) { int hobbyIndex = rnd.nextInt( guestHobbies.size() ); String hobby = (String) guestHobbies.get( hobbyIndex ); writer.write( "(guest (name n" + i + ") (sex " + sex + ") (hobby " + hobby + "))" + LINE_SEPARATOR ); guestHobbies.remove( hobbyIndex ); } } writer.write( "(last_seat (seat " + numSeats + "))" + LINE_SEPARATOR ); writer.write( LINE_SEPARATOR ); writer.write( "(context (state start))" + LINE_SEPARATOR ); return new ByteArrayInputStream( writer.getBuffer().toString().getBytes() ); } }
package net.pixelcop.sewer; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Properties; import net.pixelcop.sewer.node.AbstractNodeTest; import net.pixelcop.sewer.node.NodeConfig; import net.pixelcop.sewer.node.TestableNode; import net.pixelcop.sewer.sink.buffer.DisruptorSink; import net.pixelcop.sewer.source.debug.ThreadedEventGeneratorSource; import net.pixelcop.sewer.util.HdfsUtil; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.junit.Test; import org.junit.runner.JUnitCore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Benchmark extends AbstractNodeTest { class Result { double duration; double count; double opsPerSec; String source; String sink; String notes; } private static final long TEST_WARMUP = 10000; private static final long TEST_DURATION = 30000; protected static final Logger LOG = LoggerFactory.getLogger(Benchmark.class); protected static final List<String> waitStrategies = new ArrayList<>(); static { waitStrategies.add(DisruptorSink.WAIT_BLOCKING); waitStrategies.add(DisruptorSink.WAIT_BUSYSPIN); waitStrategies.add(DisruptorSink.WAIT_SLEEPING); waitStrategies.add(DisruptorSink.WAIT_TIMEOUT); waitStrategies.add(DisruptorSink.WAIT_YIELDING); } private String compressor = null; public static void main(String[] args) { JUnitCore.main(Benchmark.class.getName()); } @Test public void testPerf() throws InterruptedException, IOException { Properties props = new Properties(); props.setProperty(DisruptorSink.CONF_THREADS, "1"); props.setProperty(DisruptorSink.CONF_TIMEOUT_MS, "1"); String source = "tgen(256)"; List<Result> results = new ArrayList<>(); // null tests runAllTests(props, source, "null", results); // i/o tests List<Class<? extends CompressionCodec>> codecs = CompressionCodecFactory.getCodecClasses(loadTestConfig(false, "")); for (Class<? extends CompressionCodec> codec : codecs) { props.put(HdfsUtil.CONFIG_COMPRESSION, codec.getName()); compressor = codec.getSimpleName(); runAllTests(props, source, "seqfile('/tmp/sewer-bench')", results); } compressor = null; // print results NumberFormat f = DecimalFormat.getIntegerInstance(); System.err.println("\n\n\n\n\n\n"); System.err.println("sink\tmsgs\tops/sec\t\tnotes"); for (Result result : results) { System.err.print(result.sink); System.err.print("\t"); System.err.print(f.format(result.count)); System.err.print("\t"); System.err.print(f.format(result.opsPerSec)); System.err.print("\t\t"); System.err.print(result.notes); System.err.print("\n"); } System.err.println("\n\n\n\n\n\n"); } private void runAllTests(Properties props, String source, String dest, List<Result> results) throws InterruptedException, IOException { // basic tests results.add(runTest(source, dest)); results.add(runTest(source, "buffer > " + dest)); // disruptor > null runDisruptorTests(props, source, "disruptor > " + dest, results); // meter before results.add(runTest(source, "meter > " + dest)); results.add(runTest(source, "meter > buffer > " + dest)); runDisruptorTests(props, source, "meter > disruptor > " + dest, results); // meter after results.add(runTest(source, "buffer > meter > " + dest)); runDisruptorTests(props, source, "disruptor > meter > " + dest, results); // meter before & after results.add(runTest(source, "meter > buffer > meter > " + dest)); runDisruptorTests(props, source, "meter > disruptor > meter > " + dest, results); } private void runDisruptorTests(Properties props, String source, String sink, List<Result> results) throws InterruptedException, IOException { for (String strat : waitStrategies) { props.setProperty(DisruptorSink.CONF_WAIT_STRATEGY, strat); results.add(runTest(source, sink, props, strat)); } } private Result runTest(String source, String sink) throws InterruptedException, IOException { return runTest(source, sink, null, ""); } private Result runTest(String source, String sink, Properties props, String notes) throws InterruptedException, IOException { // add compressor to notes if (compressor != null) { if (notes == null) { notes = "" + compressor; } else { notes = notes + ", " + compressor; } } Result r = new Result(); r.source = source; r.sink = sink; r.notes = notes; NodeConfig conf = loadTestConfig(false, ""); if (props != null) { conf.addResource(props); } TestableNode node = createNode(source, sink, null, conf); // start node, opens source node.start(); LOG.info("warming up..."); Thread.sleep(TEST_WARMUP); double startTime = System.nanoTime(); ((ThreadedEventGeneratorSource) node.getSource()).resetCounters(); Thread.sleep(TEST_DURATION); node.await(); node.cleanup(); r.count = ((ThreadedEventGeneratorSource) node.getSource()).getTotalCount(); r.duration = System.nanoTime() - startTime; r.opsPerSec = (1000L * 1000L * 1000L * r.count) / r.duration; System.gc(); // why not return r; } }
package controller; import boundary.PlayerApplication; import boundary.PlayerLevelView; import java.awt.EventQueue; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import model.CellType; import model.Move; import model.PlayerModel; import model.PlayerState; import model.Point; /** * @author Eli Skeggs, Nick Chaput * * TODO: implement "Swap" special move, add validity checks to basic moves */ public class PlayerBoardMouseCtrl implements MouseListener, MouseMotionListener { PlayerApplication app; PlayerModel model; PlayerRemoveCtrl removeCtrl; PlayerSwapCtrl swapCtrl; PlayerExpandMoveCtrl expandMoveCtrl; PlayerFinishMoveCtrl finishMoveCtrl; PlayerStartMoveCtrl startMoveCtrl; public PlayerBoardMouseCtrl(PlayerApplication app, PlayerModel model) { this.app = app; this.model = model; removeCtrl = new PlayerRemoveCtrl(app, model); swapCtrl = new PlayerSwapCtrl(app, model); expandMoveCtrl = new PlayerExpandMoveCtrl(app, model); finishMoveCtrl = new PlayerFinishMoveCtrl(app, model); startMoveCtrl = new PlayerStartMoveCtrl(app, model); } Point identifyPoint(MouseEvent event) { PlayerLevelView view = (PlayerLevelView) app.getView(); return view.boardView.identifyPoint(event.getX(), event.getY()); } protected void fizzleMove() { // make the move fizzle model.playerState = PlayerState.NONE; model.move = new Move(); if (model.counter > 0) { model.counter } // ends the level from here if (model.counter == 0) { EventQueue.invokeLater(new PlayerEndLevelCtrl(app, model, true)); } } @Override public void mouseClicked(MouseEvent event) { Point point; if (event.getButton() != MouseEvent.BUTTON1 || (point = identifyPoint(event)) == null || isNullTile(point)){ return; } switch (model.playerState) { case REMOVE: removeCtrl.mouseClicked(point); break; case SWAP: swapCtrl.startSwap(point); break; default: // do nothing! } } @Override public void mouseEntered(MouseEvent event) {} @Override public void mouseExited(MouseEvent event) { if (model.playerState == PlayerState.SELECT) { fizzleMove(); ((PlayerLevelView) app.getView()).update(); } } @Override public void mousePressed(MouseEvent event) { Point point; if (event.getButton() == MouseEvent.BUTTON1 && model.playerState == PlayerState.NONE && (point = identifyPoint(event)) != null) { startMoveCtrl.startMove(point); } ((PlayerLevelView) app.getView()).repaint(); } @Override public void mouseReleased(MouseEvent event) { Point point; if (event.getButton() == MouseEvent.BUTTON1 && model.playerState == PlayerState.SELECT && (point = identifyPoint(event)) != null) { finishMoveCtrl.finishMove(point); } } @Override public void mouseDragged(MouseEvent event) { if (model.playerState == PlayerState.SELECT) { Point point = identifyPoint(event); if (point != null) { expandMoveCtrl.expandMove(point); } else { fizzleMove(); ((PlayerLevelView)app.getView()).update(); } } } @Override public void mouseMoved(MouseEvent event) {} public boolean isNullTile (Point point) { return (model.level.currentBoard.grid[point.x][point.y].tile == null || model.level.currentBoard.grid[point.x][point.y].type == CellType.BUCKET || model.level.currentBoard.grid[point.x][point.y].type == CellType.INERT); } }
package org.eclipse.birt.report.engine.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.report.engine.api.IParameterDefnBase; import org.eclipse.birt.report.engine.api.IScalarParameterDefn; import org.eclipse.birt.report.engine.api.impl.CascadingParameterGroupDefn; import org.eclipse.birt.report.engine.api.impl.ParameterGroupDefn; import org.eclipse.birt.report.engine.api.impl.ParameterSelectionChoice; import org.eclipse.birt.report.engine.api.impl.ScalarParameterDefn; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.css.dom.StyleDeclaration; import org.eclipse.birt.report.engine.css.engine.CSSEngine; import org.eclipse.birt.report.engine.ir.ActionDesign; import org.eclipse.birt.report.engine.ir.CellDesign; import org.eclipse.birt.report.engine.ir.ColumnDesign; import org.eclipse.birt.report.engine.ir.DataItemDesign; import org.eclipse.birt.report.engine.ir.DimensionType; import org.eclipse.birt.report.engine.ir.DrillThroughActionDesign; import org.eclipse.birt.report.engine.ir.EngineIRConstants; import org.eclipse.birt.report.engine.ir.Expression; import org.eclipse.birt.report.engine.ir.ExtendedItemDesign; import org.eclipse.birt.report.engine.ir.FreeFormItemDesign; import org.eclipse.birt.report.engine.ir.GraphicMasterPageDesign; import org.eclipse.birt.report.engine.ir.GridItemDesign; import org.eclipse.birt.report.engine.ir.GroupDesign; import org.eclipse.birt.report.engine.ir.HighlightDesign; import org.eclipse.birt.report.engine.ir.HighlightRuleDesign; import org.eclipse.birt.report.engine.ir.ImageItemDesign; import org.eclipse.birt.report.engine.ir.LabelItemDesign; import org.eclipse.birt.report.engine.ir.ListBandDesign; import org.eclipse.birt.report.engine.ir.ListGroupDesign; import org.eclipse.birt.report.engine.ir.ListItemDesign; import org.eclipse.birt.report.engine.ir.ListingDesign; import org.eclipse.birt.report.engine.ir.MapDesign; import org.eclipse.birt.report.engine.ir.MapRuleDesign; import org.eclipse.birt.report.engine.ir.MasterPageDesign; import org.eclipse.birt.report.engine.ir.MultiLineItemDesign; import org.eclipse.birt.report.engine.ir.PageSetupDesign; import org.eclipse.birt.report.engine.ir.Report; import org.eclipse.birt.report.engine.ir.ReportElementDesign; import org.eclipse.birt.report.engine.ir.ReportItemDesign; import org.eclipse.birt.report.engine.ir.RowDesign; import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign; import org.eclipse.birt.report.engine.ir.StylePropertyMapping; import org.eclipse.birt.report.engine.ir.StyledElementDesign; import org.eclipse.birt.report.engine.ir.TableBandDesign; import org.eclipse.birt.report.engine.ir.TableGroupDesign; import org.eclipse.birt.report.engine.ir.TableItemDesign; import org.eclipse.birt.report.engine.ir.TemplateDesign; import org.eclipse.birt.report.engine.ir.TextItemDesign; import org.eclipse.birt.report.engine.ir.VisibilityDesign; import org.eclipse.birt.report.engine.ir.VisibilityRuleDesign; import org.eclipse.birt.report.model.api.ActionHandle; import org.eclipse.birt.report.model.api.CascadingParameterGroupHandle; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.ColumnHandle; import org.eclipse.birt.report.model.api.DataItemHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.DesignVisitor; import org.eclipse.birt.report.model.api.DimensionHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.FactoryPropertyHandle; import org.eclipse.birt.report.model.api.FreeFormHandle; import org.eclipse.birt.report.model.api.GraphicMasterPageHandle; import org.eclipse.birt.report.model.api.GridHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.HideRuleHandle; import org.eclipse.birt.report.model.api.HighlightRuleHandle; import org.eclipse.birt.report.model.api.ImageHandle; import org.eclipse.birt.report.model.api.LabelHandle; import org.eclipse.birt.report.model.api.ListGroupHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.ListingHandle; import org.eclipse.birt.report.model.api.MapRuleHandle; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.MemberHandle; import org.eclipse.birt.report.model.api.ParamBindingHandle; import org.eclipse.birt.report.model.api.ParameterGroupHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.SelectionChoiceHandle; import org.eclipse.birt.report.model.api.SimpleMasterPageHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.StructureHandle; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.TableGroupHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.api.TemplateReportItemHandle; import org.eclipse.birt.report.model.api.TextDataHandle; import org.eclipse.birt.report.model.api.TextItemHandle; import org.eclipse.birt.report.model.api.core.UserPropertyDefn; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.structures.HighlightRule; import org.eclipse.birt.report.model.api.metadata.DimensionValue; import org.eclipse.birt.report.model.api.metadata.IPropertyType; import org.eclipse.birt.report.model.elements.Style; class EngineIRVisitor extends DesignVisitor { /** * logger used to log the error. */ protected static Logger logger = Logger.getLogger( EngineIRVisitor.class .getName( ) ); protected Object currentElement; /** * default unit used by this report */ protected String defaultUnit; protected Report report; /** * report design handle */ protected ReportDesignHandle handle; /** * the CSSEngine */ protected CSSEngine cssEngine; /** * the inheritable report style */ StyleDeclaration nonInheritableReportStyle; /** * the non-inheritable report style */ StyleDeclaration inheritableReportStyle; /** * constructor * * @param handle * the entry point to the DE report design IR * */ EngineIRVisitor( ReportDesignHandle handle ) { super( ); this.handle = handle; } /** * translate the DE's IR to FPE's IR. * * @return FPE's IR. */ public Report translate( ) { report = new Report( ); cssEngine = report.getCSSEngine( ); report.setReportDesign( handle ); apply( handle ); return report; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.DesignVisitor#visitReportDesign(org.eclipse.birt.report.model.api.ReportDesignHandle) */ public void visitReportDesign( ReportDesignHandle handle ) { report.setUnit( handle.getDefaultUnits( ) ); if ( handle.getBase( ) != null && !handle.getBase( ).equals( "" ) ) //$NON-NLS-1$ { report.setBasePath( handle.getBase( ) ); } defaultUnit = report.getUnit( ); setupNamedExpressions( handle, report.getNamedExpressions( ) ); // INCLUDE LIBRARY // INCLUDE SCRIPT // CODE MODULES // Sets the report default style StyleHandle defaultStyle = handle.findStyle( "report" );//$NON-NLS-1$ createReportDefaultStyles( defaultStyle ); // TODO: add report style // report.addStyle( ); // COLOR-PALETTE // METHOD // STYLES // We needn't handle the style slot, it will be handled for each // element. // Handle Master Page PageSetupDesign pageSetup = new PageSetupDesign( ); SlotHandle pageSlot = handle.getMasterPages( ); for ( int i = 0; i < pageSlot.getCount( ); i++ ) { apply( pageSlot.get( i ) ); if ( currentElement != null ) { pageSetup.addMasterPage( (MasterPageDesign) currentElement ); } } // FIXME: add page sequence support // Handle Page Sequence // SlotHandle seqSlot = handle.getPageSequences( ); // for ( int i = 0; i < seqSlot.getCount( ); i++ ) // apply( seqSlot.get( i ) ); // assert ( currentElement != null ); // pageSetup.addPageSequence( (PageSequenceDesign) currentElement ); report.setPageSetup( pageSetup ); // COMPONENTS // Handle Report Body SlotHandle bodySlot = handle.getBody( ); for ( int i = 0; i < bodySlot.getCount( ); i++ ) { apply( bodySlot.get( i ) ); if ( currentElement != null ) { report.addContent( (ReportItemDesign) currentElement ); } } // SCRATCH-PAD // CONFIG-VARS // TRANSLATIONS // IMAGES // CUSTOM } /** * setup the named expression map * * @param userProperties * user defined named expressions in design file * @param namedExpressions * the data structure that hold named expressions */ private void setupNamedExpressions( DesignElementHandle handle, Map namedExpressions ) { List userProperties = handle.getUserProperties( ); if ( userProperties == null || namedExpressions == null ) return; for ( int i = 0; i < userProperties.size( ); i++ ) { UserPropertyDefn userDef = (UserPropertyDefn) userProperties .get( i ); if ( userDef.getTypeCode( ) == IPropertyType.EXPRESSION_TYPE ) { String name = userDef.getName( ); String exprString = handle.getStringProperty( name ); if ( exprString != null && !exprString.trim( ).equals( "" ) ) { //Expression expression = new Expression( exprString ); namedExpressions.put( name, exprString ); } } } } /** * setup the master page object from the base master page handle. * * @param page * page object * @param handle * page handle */ private void setupMasterPage( MasterPageDesign page, MasterPageHandle handle ) { setupStyledElement( page, handle ); String styleName = setupBodyStyle( page ); if (styleName != null) { page.setBodyStyleName( styleName ); } page.setPageType( handle.getPageType( ) ); // Master page width and height DimensionValue effectWidth = handle.getEffectiveWidth( ); DimensionValue effectHeight = handle.getEffectiveHeight( ); DimensionType width = null; DimensionType height = null; if ( effectWidth != null ) { width = new DimensionType( effectWidth.getMeasure( ), effectWidth .getUnits( ) ); } if ( effectHeight != null ) { height = new DimensionType( effectHeight.getMeasure( ), effectHeight.getUnits( ) ); } page.setPageSize( width, height ); page.setOrientation( handle.getOrientation( ) ); // Master page margins DimensionType top = createDimension( handle.getTopMargin( ) ); DimensionType left = createDimension( handle.getLeftMargin( ) ); DimensionType bottom = createDimension( handle.getBottomMargin( ) ); DimensionType right = createDimension( handle.getRightMargin( ) ); page.setMargin( top, left, bottom, right ); } protected void visitDesignElement( DesignElementHandle obj ) { // any unsupported element currentElement = null; } public void visitGraphicMasterPage( GraphicMasterPageHandle handle ) { GraphicMasterPageDesign page = new GraphicMasterPageDesign( ); setupMasterPage( page, handle ); // Multi-column properties page.setColumns( handle.getColumnCount( ) ); DimensionType spacing = createDimension( handle.getColumnSpacing( ) ); page.setColumnSpacing( spacing ); // Master page content SlotHandle contentSlot = handle.getContent( ); for ( int i = 0; i < contentSlot.getCount( ); i++ ) { apply( contentSlot.get( i ) ); if ( currentElement != null ) { page.addContent( (ReportItemDesign) currentElement ); } } currentElement = page; } public void visitSimpleMasterPage( SimpleMasterPageHandle handle ) { SimpleMasterPageDesign page = new SimpleMasterPageDesign( ); // setup the base master page property. setupMasterPage( page, handle ); page.setHeaderHeight( createDimension( handle.getHeaderHeight( ) ) ); page.setFooterHeight( createDimension( handle.getFooterHeight( ) ) ); page.setShowFooterOnLast( handle.showFooterOnLast( ) ); page.setShowHeaderOnFirst( handle.showHeaderOnFirst( ) ); page.setFloatingFooter( handle.isFloatingFooter( ) ); SlotHandle headerSlot = handle.getPageHeader( ); for ( int i = 0; i < headerSlot.getCount( ); i++ ) { apply( headerSlot.get( i ) ); if ( currentElement != null ) { page.addHeader( (ReportItemDesign) currentElement ); } } SlotHandle footerSlot = handle.getPageFooter( ); for ( int i = 0; i < footerSlot.getCount( ); i++ ) { apply( footerSlot.get( i ) ); if ( currentElement != null ) { page.addFooter( (ReportItemDesign) currentElement ); } } currentElement = page; } public void visitList( ListHandle handle ) { // Create ListItem ListItemDesign listItem = new ListItemDesign( ); setupListingItem( listItem, handle ); // Header SlotHandle headerSlot = handle.getHeader( ); listItem.setHeader( createListBand( headerSlot ) ); // Multiple groups SlotHandle groupsSlot = handle.getGroups( ); for ( int i = 0; i < groupsSlot.getCount( ); i++ ) { apply( groupsSlot.get( i ) ); if ( currentElement != null ) { listItem.addGroup( (ListGroupDesign) currentElement ); } } // List detail SlotHandle detailSlot = handle.getDetail( ); listItem.setDetail( createListBand( detailSlot ) ); // List Footer SlotHandle footerSlot = handle.getFooter( ); listItem.setFooter( createListBand( footerSlot ) ); currentElement = listItem; } public void visitFreeForm( FreeFormHandle handle ) { // Create Free form element FreeFormItemDesign container = new FreeFormItemDesign( ); setupReportItem( container, handle ); // Set up each individual item in a free form container SlotHandle slot = handle.getReportItems( ); for ( int i = 0; i < slot.getCount( ); i++ ) { apply( slot.get( i ) ); if ( currentElement != null ) { container.addItem( (ReportItemDesign) currentElement ); } } currentElement = container; } public void visitTextDataItem( TextDataHandle handle ) { MultiLineItemDesign multiLineItem = new MultiLineItemDesign( ); setupReportItem( multiLineItem, handle ); String valueExpr = handle.getValueExpr( ); String contentType = handle.getContentType( ); multiLineItem.setContent( createExpression( valueExpr ) ); multiLineItem.setContentType( contentType ); setHighlight( multiLineItem, valueExpr ); setMap( multiLineItem, valueExpr ); currentElement = multiLineItem; } public void visitParameterGroup( ParameterGroupHandle handle ) { ParameterGroupDefn paramGroup = new ParameterGroupDefn( ); paramGroup.setHandle( handle ); paramGroup.setParameterType( IParameterDefnBase.PARAMETER_GROUP ); paramGroup.setName( handle.getName( ) ); paramGroup.setDisplayName( handle.getDisplayName( ) ); paramGroup.setDisplayNameKey( handle.getDisplayNameKey( ) ); paramGroup.setHelpText( handle.getHelpText( ) ); paramGroup.setHelpTextKey( handle.getHelpTextKey( ) ); SlotHandle parameters = handle.getParameters( ); // set custom properties List properties = handle.getUserProperties( ); for ( int i = 0; i < properties.size( ); i++ ) { UserPropertyDefn p = (UserPropertyDefn) properties.get( i ); paramGroup.addUserProperty( p.getName( ), handle.getProperty( p .getName( ) ) ); } int size = parameters.getCount( ); for ( int n = 0; n < size; n++ ) { apply( parameters.get( n ) ); if ( currentElement != null ) { paramGroup.addParameter( (IParameterDefnBase) currentElement ); } } currentElement = paramGroup; } public void visitCascadingParameterGroup( CascadingParameterGroupHandle handle ) { CascadingParameterGroupDefn paramGroup = new CascadingParameterGroupDefn( ); paramGroup.setHandle( handle ); paramGroup .setParameterType( IParameterDefnBase.CASCADING_PARAMETER_GROUP ); paramGroup.setName( handle.getName( ) ); paramGroup.setDisplayName( handle.getDisplayName( ) ); paramGroup.setDisplayNameKey( handle.getDisplayNameKey( ) ); paramGroup.setHelpText( handle.getHelpText( ) ); paramGroup.setHelpTextKey( handle.getHelpTextKey( ) ); DataSetHandle dset = handle.getDataSet( ); if ( dset != null ) { paramGroup.setDataSet( dset.getName( ) ); } SlotHandle parameters = handle.getParameters( ); // set custom properties List properties = handle.getUserProperties( ); for ( int i = 0; i < properties.size( ); i++ ) { UserPropertyDefn p = (UserPropertyDefn) properties.get( i ); paramGroup.addUserProperty( p.getName( ), handle.getProperty( p .getName( ) ) ); } int size = parameters.getCount( ); for ( int n = 0; n < size; n++ ) { apply( parameters.get( n ) ); if ( currentElement != null ) { paramGroup.addParameter( (IParameterDefnBase) currentElement ); } } currentElement = paramGroup; } public void visitScalarParameter( ScalarParameterHandle handle ) { assert ( handle.getName( ) != null ); // Create Parameter ScalarParameterDefn scalarParameter = new ScalarParameterDefn( ); scalarParameter.setHandle( handle ); scalarParameter.setParameterType( IParameterDefnBase.SCALAR_PARAMETER ); scalarParameter.setName( handle.getName( ) ); // set custom properties List properties = handle.getUserProperties( ); for ( int i = 0; i < properties.size( ); i++ ) { UserPropertyDefn p = (UserPropertyDefn) properties.get( i ); scalarParameter.addUserProperty( p.getName( ), handle .getProperty( p.getName( ) ) ); } String align = handle.getAlignment( ); if ( DesignChoiceConstants.SCALAR_PARAM_ALIGN_CENTER.equals( align ) ) scalarParameter.setAlignment( IScalarParameterDefn.CENTER ); else if ( DesignChoiceConstants.SCALAR_PARAM_ALIGN_LEFT.equals( align ) ) scalarParameter.setAlignment( IScalarParameterDefn.LEFT ); else if ( DesignChoiceConstants.SCALAR_PARAM_ALIGN_RIGHT.equals( align ) ) scalarParameter.setAlignment( IScalarParameterDefn.RIGHT ); else scalarParameter.setAlignment( IScalarParameterDefn.AUTO ); scalarParameter.setAllowBlank( handle.allowBlank( ) ); scalarParameter.setAllowNull( handle.allowNull( ) ); String controlType = handle.getControlType( ); if ( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX.equals( controlType ) ) scalarParameter.setControlType( IScalarParameterDefn.CHECK_BOX ); else if ( DesignChoiceConstants.PARAM_CONTROL_LIST_BOX .equals( controlType ) ) scalarParameter.setControlType( IScalarParameterDefn.LIST_BOX ); else if ( DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON .equals( controlType ) ) scalarParameter.setControlType( IScalarParameterDefn.RADIO_BUTTON ); else scalarParameter.setControlType( IScalarParameterDefn.TEXT_BOX ); scalarParameter.setDefaultValue( handle.getDefaultValue( ) ); scalarParameter.setDisplayName( handle.getDisplayName( ) ); scalarParameter.setDisplayNameKey( handle.getDisplayNameKey( ) ); scalarParameter.setFormat( handle.getFormat( ) ); scalarParameter.setHelpText( handle.getHelpText( ) ); scalarParameter.setHelpTextKey( handle.getHelpTextKey( ) ); scalarParameter.setPromptText( handle.getPromptText( ) ); scalarParameter.setIsHidden( handle.isHidden( ) ); scalarParameter.setName( handle.getName( ) ); String valueType = handle.getDataType( ); if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( valueType ) ) scalarParameter.setDataType( IScalarParameterDefn.TYPE_BOOLEAN ); else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( valueType ) ) scalarParameter.setDataType( IScalarParameterDefn.TYPE_DATE_TIME ); else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( valueType ) ) scalarParameter.setDataType( IScalarParameterDefn.TYPE_DECIMAL ); else if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( valueType ) ) scalarParameter.setDataType( IScalarParameterDefn.TYPE_FLOAT ); else if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( valueType ) ) scalarParameter.setDataType( IScalarParameterDefn.TYPE_STRING ); else scalarParameter.setDataType( IScalarParameterDefn.TYPE_ANY ); ArrayList values = new ArrayList( ); Iterator selectionIter = handle.choiceIterator( ); while ( selectionIter.hasNext( ) ) { SelectionChoiceHandle selection = (SelectionChoiceHandle) selectionIter .next( ); ParameterSelectionChoice selectionChoice = new ParameterSelectionChoice( this.handle ); selectionChoice.setLabel( selection.getLabelKey( ), selection .getLabel( ) ); selectionChoice.setValue( selection.getValue( ), scalarParameter .getDataType( ) ); values.add( selectionChoice ); } scalarParameter.setSelectionList( values ); scalarParameter.setAllowNewValues( !handle.isMustMatch( ) ); scalarParameter.setFixedOrder( handle.isFixedOrder( ) ); if ( scalarParameter.getSelectionList( ) != null && scalarParameter.getSelectionList( ).size( ) > 0 ) scalarParameter .setSelectionListType( IScalarParameterDefn.SELECTION_LIST_STATIC ); else scalarParameter .setSelectionListType( IScalarParameterDefn.SELECTION_LIST_NONE ); scalarParameter.setValueConcealed( handle.isConcealValue( ) ); currentElement = scalarParameter; } public void visitLabel( LabelHandle handle ) { // Create Label Item LabelItemDesign labelItem = new LabelItemDesign( ); setupReportItem( labelItem, handle ); // Text String text = handle.getText( ); String textKey = handle.getTextKey( ); labelItem.setText( textKey, text ); // Handle Action ActionHandle action = handle.getActionHandle( ); if ( action != null ) { labelItem.setAction( createAction( action ) ); } // Fill in help text labelItem.setHelpText( handle.getHelpTextKey( ), handle.getHelpText( ) ); currentElement = labelItem; } public void visitDataItem( DataItemHandle handle ) { // Create data item DataItemDesign data = new DataItemDesign( ); setupReportItem( data, handle ); data.setName( handle.getName( ) ); // Fill in data expression, //String expr = handle.getValueExpr( ); String expr = handle.getResultSetColumn( ); if (expr != null && expr.trim( ).length( ) > 0) { expr = "row[\"" + expr.replaceAll( "\"", "\\\\\"") + "\"]"; data.setValue( expr ); } // Handle Action ActionHandle action = handle.getActionHandle( ); if ( action != null ) { data.setAction( createAction( action ) ); } // Fill in help text data.setHelpText( handle.getHelpTextKey( ), handle.getHelpText( ) ); setHighlight( data, expr ); setMap( data, expr ); currentElement = data; } public void visitGrid( GridHandle handle ) { // Create Grid Item GridItemDesign grid = new GridItemDesign( ); setupReportItem( grid, handle ); // Handle Columns SlotHandle columnSlot = handle.getColumns( ); for ( int i = 0; i < columnSlot.getCount( ); i++ ) { ColumnHandle columnHandle = (ColumnHandle) columnSlot.get( i ); apply( columnHandle ); if ( currentElement != null ) { ColumnDesign columnDesign = (ColumnDesign) currentElement; for ( int j = 0; j < columnHandle.getRepeatCount( ); j++ ) { grid.addColumn( columnDesign ); } } } // Handle Rows SlotHandle rowSlot = handle.getRows( ); for ( int i = 0; i < rowSlot.getCount( ); i++ ) { apply( rowSlot.get( i ) ); if ( currentElement != null ) { grid.addRow( (RowDesign) currentElement ); } } new TableItemDesignLayout( ).layout( grid ); currentElement = grid; } public void visitImage( ImageHandle handle ) { // Create Image Item ImageItemDesign image = new ImageItemDesign( ); setupReportItem( image, handle ); // Handle Action ActionHandle action = handle.getActionHandle( ); if ( action != null ) { image.setAction( createAction( action ) ); } // Alternative text for image image.setAltText( handle.getAltTextKey( ), handle.getAltText( ) ); // Help text for image image.setHelpText( handle.getHelpTextKey( ), handle.getHelpText( ) ); // Handle Image Source String imageSrc = handle.getSource( ); if ( EngineIRConstants.IMAGE_REF_TYPE_URL.equals( imageSrc ) ) { image.setImageUri( createExpression( handle.getURI( ) ) ); } else if ( EngineIRConstants.IMAGE_REF_TYPE_EXPR.equals( imageSrc ) ) { String valueExpr = handle.getValueExpression( ); String typeExpr = handle.getTypeExpression( ); String imageValue = createExpression( valueExpr ); String imageType = createExpression( typeExpr ); image.setImageExpression( imageValue, imageType ); } else if ( EngineIRConstants.IMAGE_REF_TYPE_EMBED.equals( imageSrc ) ) { image.setImageName( handle.getImageName( ) ); } else if ( EngineIRConstants.IMAGE_REF_TYPE_FILE.equals( imageSrc ) ) { image.setImageFile( createExpression( handle.getURI( ) ) ); } else { assert false; } currentElement = image; } public void visitTable( TableHandle handle ) { // Create Table Item TableItemDesign table = new TableItemDesign( ); table.setRepeatHeader( handle.repeatHeader( ) ); setupListingItem( table, handle ); // Handle table caption String caption = handle.getCaption( ); String captionKey = handle.getCaptionKey( ); if ( caption != null || captionKey != null ) { table.setCaption( captionKey, caption ); } // Handle table Columns SlotHandle columnSlot = handle.getColumns( ); for ( int i = 0; i < columnSlot.getCount( ); i++ ) { ColumnHandle columnHandle = (ColumnHandle) columnSlot.get( i ); apply( columnHandle ); if ( currentElement != null ) { ColumnDesign columnDesign = (ColumnDesign) currentElement; for ( int j = 0; j < columnHandle.getRepeatCount( ); j++ ) { table.addColumn( columnDesign ); } } } // Handle Table Header SlotHandle headerSlot = handle.getHeader( ); TableBandDesign header = createTableBand( headerSlot ); table.setHeader( header ); // Handle grouping in table SlotHandle groupSlot = handle.getGroups( ); for ( int i = 0; i < groupSlot.getCount( ); i++ ) { apply( groupSlot.get( i ) ); if ( currentElement != null ) { table.addGroup( (TableGroupDesign) currentElement ); } } // Handle detail section SlotHandle detailSlot = handle.getDetail( ); TableBandDesign detail = createTableBand( detailSlot ); table.setDetail( detail ); // Handle table footer SlotHandle footerSlot = handle.getFooter( ); TableBandDesign footer = createTableBand( footerSlot ); table.setFooter( footer ); new TableItemDesignLayout( ).layout( table ); //setup the supressDuplicate property of the data items in the //detail band detail = table.getDetail( ); for ( int i = 0; i < detail.getRowCount( ); i++ ) { RowDesign row = detail.getRow(i); for (int j = 0; j < row.getCellCount( ); j++) { CellDesign cell = row.getCell( j ); ColumnDesign column = table.getColumn( cell.getColumn( ) ); if ( column.getSuppressDuplicate( ) ) { for ( int k = 0; k < cell.getContentCount( ); k++ ) { ReportItemDesign item = cell.getContent( k ); if ( item instanceof DataItemDesign ) { DataItemDesign dataItem = ( DataItemDesign )item; dataItem.setSuppressDuplicate( true ); } } } } } currentElement = table; } public void visitColumn( ColumnHandle handle ) { // Create a Column, mostly used in Table or Grid ColumnDesign col = new ColumnDesign( ); setupStyledElement( col, handle ); // Column Width DimensionType width = createDimension( handle.getWidth( ) ); col.setWidth( width ); boolean supress = handle.suppressDuplicates( ); col.setSuppressDuplicate( supress ); currentElement = col; } public void visitRow( RowHandle handle ) { // Create a Row, mostly used in Table and Grid Item RowDesign row = new RowDesign( ); setupStyledElement( row, handle ); // Row Height DimensionType height = createDimension( handle.getHeight( ) ); row.setHeight( height ); // Book mark String bookmark = handle.getBookmark( ); row.setBookmark( createExpression( bookmark ) ); // Visibility VisibilityDesign visibility = createVisibility( handle .visibilityRulesIterator( ) ); row.setVisibility( visibility ); // Cells in a row SlotHandle cellSlot = handle.getCells( ); for ( int i = 0; i < cellSlot.getCount( ); i++ ) { apply( cellSlot.get( i ) ); if ( currentElement != null ) { row.addCell( (CellDesign) currentElement ); } } String onCreate = handle.getOnCreate( ); row.setOnCreate( createExpression( onCreate ) ); row.setOnRender( ( (RowHandle) handle ).getOnRender( ) ); setHighlight( row, null ); currentElement = row; } private boolean isContainer( ReportElementHandle handle ) { if ( handle instanceof TextItemHandle ) { return false; } if ( handle instanceof DataItemHandle ) { return false; } if ( handle instanceof LabelHandle ) { return false; } if ( handle instanceof TextDataHandle ) { return false; } if ( handle instanceof ExtendedItemHandle ) { return false; } if ( handle instanceof ImageHandle ) { return false; } return true; } /** * Sets up cell element's style attribute. * * @param cell * engine's styled cell element. * @param handle * DE's styled cell element. */ protected void setupStyledElement( StyledElementDesign design, ReportElementHandle handle ) { // Styled element is a report element setupReportElement( design, handle ); StyleDeclaration style = createPrivateStyle( handle, isContainer( handle ) ); if ( style != null && !style.isEmpty( ) ) { design.setStyleName( assignStyleName( style ) ); } } public void visitCell( CellHandle handle ) { // Create a Cell CellDesign cell = new CellDesign( ); setupStyledElement( cell, handle ); // Cell contents SlotHandle contentSlot = handle.getContent( ); for ( int i = 0; i < contentSlot.getCount( ); i++ ) { apply( contentSlot.get( i ) ); if ( currentElement != null ) { cell.addContent( (ReportItemDesign) currentElement ); } } // Span, Drop properties of a cell // FIXME: change the colspan/rowspan after MODEL fix the bug // cell.setColSpan( LayoutUtil.getEffectiveColumnSpan( handle ) ); cell.setColSpan( handle.getColumnSpan( ) ); int columnId = handle.getColumn( ) - 1; if ( columnId < 0 ) { columnId = -1; } cell.setColumn( columnId ); // cell.setRowSpan( LayoutUtil.getEffectiveRowSpan( handle ) ); cell.setRowSpan( handle.getRowSpan( ) ); cell.setDrop( handle.getDrop( ) ); String onCreate = handle.getOnCreate( ); cell.setOnCreate( createExpression( onCreate ) ); cell.setOnRender( handle.getOnRender( ) ); setHighlight( cell, null ); currentElement = cell; } /** * create a list band using the items in slot. * * @param elements * items in DE's IR * @return ListBand. */ private ListBandDesign createListBand( SlotHandle elements ) { ListBandDesign band = new ListBandDesign( ); for ( int i = 0; i < elements.getCount( ); i++ ) { apply( elements.get( i ) ); if ( currentElement != null ) { band.addContent( (ReportItemDesign) currentElement ); } } return band; } /** * create a list group using the DE's ListGroup. * * @param handle * De's list group * @return engine's list group */ public void visitListGroup( ListGroupHandle handle ) { ListGroupDesign listGroup = new ListGroupDesign( ); setupGroup( listGroup, handle ); ListBandDesign header = createListBand( handle.getHeader( ) ); listGroup.setHeader( header ); // flatten TOC on group to the first report item in group header String tocExpr = handle.getTocExpression( ); if ( null != tocExpr && !"".equals( tocExpr.trim( ) ) ) //$NON-NLS-1$ { if ( header.getContentCount( ) > 0 ) { ReportItemDesign item = (ReportItemDesign) header .getContent( 0 ); item.setTOC( createExpression( tocExpr ) ); } } ListBandDesign footer = createListBand( handle.getFooter( ) ); listGroup.setFooter( footer ); boolean hideDetail = handle.hideDetail( ); listGroup.setHideDetail( hideDetail ); currentElement = listGroup; } /** * create a table group using the DE's TableGroup. * * @param handle * De's table group * @return engine's table group */ public void visitTableGroup( TableGroupHandle handle ) { TableGroupDesign tableGroup = new TableGroupDesign( ); setupGroup( tableGroup, handle ); TableBandDesign header = createTableBand( handle.getHeader( ) ); tableGroup.setHeader( header ); // flatten TOC on group to the first report item in group header String toc = handle.getTocExpression( ); if ( null != toc && !"".equals( toc.trim( ) ) ) //$NON-NLS-1$ { if ( header.getRowCount( ) > 0 ) { RowDesign row = header.getRow( 0 ); row.setTOC( createExpression( toc ) ); } } TableBandDesign footer = createTableBand( handle.getFooter( ) ); tableGroup.setFooter( footer ); boolean hideDetail = handle.hideDetail( ); tableGroup.setHideDetail( hideDetail ); currentElement = tableGroup; } public void visitTextItem( TextItemHandle handle ) { // Create Text Item TextItemDesign textItem = new TextItemDesign( ); setupReportItem( textItem, handle ); String contentType = handle.getContentType( ); if ( contentType != null ) { textItem.setTextType( contentType ); } textItem.setText( handle.getContentKey( ), handle.getContent( ) ); currentElement = textItem; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.DesignVisitor#visitExtendedItem(org.eclipse.birt.report.model.api.ExtendedItemHandle) */ protected void visitExtendedItem( ExtendedItemHandle obj ) { ExtendedItemDesign extendedItem = new ExtendedItemDesign( ); setupReportItem( extendedItem, obj ); currentElement = extendedItem; } public void visitTemplateReportItem( TemplateReportItemHandle obj ) { TemplateDesign template = new TemplateDesign( ); setupReportElement( template, obj ); template.setPromptText( obj.getDescription( ) ); template.setPromptTextKey( obj.getDescriptionKey( ) ); template.setAllowedType( obj.getAllowedType( ) ); currentElement = template; } protected void setupGroup( GroupDesign group, GroupHandle handle ) { // name group.setName( handle.getName( ) ); String pageBreakBefore = handle .getStringProperty( StyleHandle.PAGE_BREAK_BEFORE_PROP ); String pageBreakAfter = handle .getStringProperty( StyleHandle.PAGE_BREAK_AFTER_PROP ); group.setPageBreakBefore( pageBreakBefore ); group.setPageBreakAfter( pageBreakAfter ); } /** * create a table band using the items in slot. * * @param elements * items in DE's IR * @return TableBand. */ private TableBandDesign createTableBand( SlotHandle elements ) { TableBandDesign band = new TableBandDesign( ); for ( int i = 0; i < elements.getCount( ); i++ ) { apply( elements.get( i ) ); if ( currentElement != null ) { band.addRow( (RowDesign) currentElement ); } } return band; } /** * Creates the property visibility * * @param visibilityRulesIterator * the handle's rules iterator * @return null only if the iterator is null or it contains no rules, * otherwise VisibilityDesign */ protected VisibilityDesign createVisibility( Iterator visibilityRulesIterator ) { if ( visibilityRulesIterator != null ) { VisibilityDesign visibility = new VisibilityDesign( ); while ( visibilityRulesIterator.hasNext( ) ) { VisibilityRuleDesign hide = createHide( (HideRuleHandle) visibilityRulesIterator .next( ) ); visibility.addRule( hide ); } if ( visibility.count( ) == 0 ) { return null; } return visibility; } return null; } /** * Creates the visibility rule( i.e. the hide) * * @param handle * the DE's handle * @return the created visibility rule */ protected VisibilityRuleDesign createHide( HideRuleHandle handle ) { VisibilityRuleDesign rule = new VisibilityRuleDesign( ); rule.setExpression( createExpression( handle.getExpression( ) ) ); rule.setFormat( handle.getFormat( ) ); return rule; } /** * setup the attribute of report item * * @param item * Engine's Report Item * @param handle * DE's report item. */ private void setupReportItem( ReportItemDesign item, ReportItemHandle handle ) { setupStyledElement( item, handle ); // x, y, width & height DimensionType height = createDimension( handle.getHeight( ) ); DimensionType width = createDimension( handle.getWidth( ) ); DimensionType x = createDimension( handle.getX( ) ); DimensionType y = createDimension( handle.getY( ) ); item.setHeight( height ); item.setWidth( width ); item.setX( x ); item.setY( y ); // setup TOC expression String toc = handle.getTocExpression( ); item.setTOC( createExpression( toc ) ); // setup book mark String bookmark = handle.getBookmark( ); item.setBookmark( createExpression( bookmark ) ); String onCreate = handle.getOnCreate( ); item.setOnCreate( createExpression( onCreate ) ); item.setOnRender( handle.getOnRender( ) ); // Sets up the visibility Iterator visibilityIter = handle.visibilityRulesIterator( ); VisibilityDesign visibility = createVisibility( visibilityIter ); item.setVisibility( visibility ); setHighlight( item, null ); } /** * setup report element attribute * * @param elem * engine's report element * @param handle * DE's report element */ private void setupReportElement( ReportElementDesign element, DesignElementHandle handle ) { element.setHandle( handle ); element.setName( handle.getName( ) ); element.setID( handle.getID( ) ); DesignElementHandle extend = handle.getExtends( ); if ( extend != null ) { element.setExtends( extend.getName( ) ); } // handle the properties Iterator iter = handle.getPropertyIterator( ); if ( iter != null ) { PropertyHandle propHandle = (PropertyHandle) iter.next( ); if ( propHandle != null && propHandle.isSet( ) ) { String name = propHandle.getDefn( ).getName( ); Object value = propHandle.getValue( ); assert name != null; assert value != null; Map properties = element.getCustomProperties( ); assert properties != null; properties.put( name, value ); } } setupNamedExpressions( handle, element.getNamedExpressions( ) ); setupElementIDMap( element ); } protected String createExpression( String expr ) { if ( expr != null && !expr.trim( ).equals( "" ) ) { return expr; } return null; } /** * create a Action. * * @param handle * action in DE * @return action in Engine. */ protected ActionDesign createAction( ActionHandle handle ) { ActionDesign action = new ActionDesign( ); String linkType = handle.getLinkType( ); if ( EngineIRConstants.ACTION_LINK_TYPE_HYPERLINK.equals( linkType ) ) { action.setHyperlink( createExpression( handle.getURI( ) ) ); action.setTargetWindow( handle.getTargetWindow( ) ); } else if ( EngineIRConstants.ACTION_LINK_TYPE_BOOKMARK_LINK .equals( linkType ) ) { action .setBookmark( createExpression( handle.getTargetBookmark( ) ) ); } else if ( EngineIRConstants.ACTION_LINK_TYPE_DRILL_THROUGH .equals( linkType ) ) { action.setTargetWindow( handle.getTargetWindow( ) ); DrillThroughActionDesign drillThrough = new DrillThroughActionDesign( ); action.setDrillThrough( drillThrough ); drillThrough.setReportName( handle.getReportName( ) ); drillThrough.setFormat( handle.getFormatType( ) ); drillThrough.setBookmark( createExpression( handle .getTargetBookmark( ) ) ); Map params = new HashMap( ); Iterator paramIte = handle.paramBindingsIterator( ); while ( paramIte.hasNext( ) ) { ParamBindingHandle member = (ParamBindingHandle) paramIte .next( ); params.put( member.getParamName( ), createExpression( member .getExpression( ) ) ); } drillThrough.setParameters( params ); // XXX Search criteria is not supported yet. // Map search = new HashMap( ); // Iterator searchIte = handle.searchIterator( ); // while ( searchIte.hasNext( ) ) // SearchKeyHandle member = (SearchKeyHandle) paramIte.next( ); // params // .put( member., member // .getValue( ) ); // drillThrough.setSearch( search ); } else { assert ( false ); } return action; } /** * create a highlight rule from a structure handle. * * @param ruleHandle * rule in the MODEL. * @return rule design, null if exist any error. */ protected HighlightRuleDesign createHighlightRule( StructureHandle ruleHandle, String defaultStr ) { HighlightRuleDesign rule = new HighlightRuleDesign( ); MemberHandle hOperator = ruleHandle .getMember( HighlightRule.OPERATOR_MEMBER ); MemberHandle hValue1 = ruleHandle .getMember( HighlightRule.VALUE1_MEMBER ); MemberHandle hValue2 = ruleHandle .getMember( HighlightRule.VALUE2_MEMBER ); MemberHandle hTestExpr = ruleHandle .getMember( HighlightRule.TEST_EXPR_MEMBER ); String oper = hOperator.getStringValue( ); String value1 = hValue1.getStringValue( ); String value2 = hValue2.getStringValue( ); String testExpr = hTestExpr.getStringValue( ); rule.setExpression( oper, value1, value2 ); if ( testExpr != null && testExpr.length( ) > 0 ) { rule.setTestExpression( testExpr ); } else if ( ( defaultStr != null ) && defaultStr.length( ) > 0 ) { rule.setTestExpression( defaultStr ); } else { // test expression is null return null; } // all other properties are style properties, // copy those properties into a style design. StyleDeclaration style = new StyleDeclaration( cssEngine ); setupStyle( ruleHandle, style ); // this rule is empty, so we can drop it safely. if ( style.isEmpty( ) ) { return null; } rule.setStyle( style ); ConditionalExpression condExpr = new ConditionalExpression( rule .getTestExpression( ), toDteFilterOperator( rule.getOperator( ) ), rule.getValue1( ), rule.getValue2( ) ); rule.setConditionExpr( condExpr ); return rule; } /** * create highlight defined in the handle. * * @param item * styled item. */ protected void setHighlight( StyledElementDesign item, String defaultStr ) { StyleHandle handle = item.getHandle( ).getPrivateStyle( ); if ( handle == null ) { return; } // hightlight Rules Iterator iter = handle.highlightRulesIterator( ); if ( iter == null ) { return; } HighlightDesign highlight = new HighlightDesign( ); while ( iter.hasNext( ) ) { HighlightRuleHandle ruleHandle = (HighlightRuleHandle) iter.next( ); HighlightRuleDesign rule = createHighlightRule( ruleHandle, defaultStr ); if ( rule != null ) { highlight.addRule( rule ); } } if ( highlight.getRuleCount( ) > 0 ) { item.setHighlight( highlight ); } } /** * setup a Map. * * @param item * styled item; */ protected void setMap( StyledElementDesign item, String defaultStr ) { StyleHandle handle = item.getHandle( ).getPrivateStyle( ); if ( handle == null ) { return; } Iterator iter = handle.mapRulesIterator( ); if ( iter == null ) { return; } MapDesign map = new MapDesign( ); while ( iter.hasNext( ) ) { MapRuleHandle ruleHandle = (MapRuleHandle) iter.next( ); MapRuleDesign rule = createMapRule( ruleHandle, defaultStr ); if ( rule != null ) { map.addRule( rule ); } } if ( map.getRuleCount( ) > 0 ) { item.setMap( map ); } } /** * create a map rule. * * @param obj * map rule in DE. * @return map rule in ENGINE. */ protected MapRuleDesign createMapRule( MapRuleHandle handle, String defaultStr ) { MapRuleDesign rule = new MapRuleDesign( ); rule.setExpression( handle.getOperator( ), handle.getValue1( ), handle .getValue2( ) ); rule.setDisplayText( handle.getDisplayKey( ), handle.getDisplay( ) ); String testExpr = handle.getTestExpression( ); if ( testExpr != null && testExpr.length( ) > 0 ) { rule.setTestExpression( testExpr ); } else if ( ( defaultStr != null ) && defaultStr.length( ) > 0 ) { rule.setTestExpression( defaultStr ); } else { // test expression is null return null; } ConditionalExpression condExpr = new ConditionalExpression( rule .getTestExpression( ), toDteFilterOperator( rule.getOperator( ) ), rule.getValue1( ), rule.getValue2( ) ); rule.setConditionExpr( condExpr ); return rule; } /** * Checks if a given style is in report's style list, if not, assign a * unique name to it and then add it to the style list. * * @param style * The <code>StyleDeclaration</code> object. * @return the name of the style. */ private String assignStyleName( StyleDeclaration style ) { if ( style == null || style.isEmpty( ) ) { return null; } // Check if the style is already in report's style list for ( int i = 0; i < report.getStyleCount( ); i++ ) { // Cast the type mandatorily StyleDeclaration cachedStyle = (StyleDeclaration) report .getStyle( i ); if ( cachedStyle.equals( style ) ) { // There exist a style which has same properties with this // one, style = cachedStyle; return Report.PREFIX_STYLE_NAME + i; } } // the style is a new style, we need create a unique name for // it, and // add it into the report's style list. String styleName = Report.PREFIX_STYLE_NAME + report.getStyleCount( ); report.addStyle( styleName, style ); return styleName; } protected String getElementProperty( ReportElementHandle handle, String name ) { return getElementProperty( handle, name, false ); } protected String getElementProperty( ReportElementHandle handle, String name, boolean isColorProperty ) { FactoryPropertyHandle prop = handle.getFactoryPropertyHandle( name ); if ( prop != null && prop.isSet( ) ) { if ( isColorProperty ) { return prop.getColorValue( ); } return prop.getStringValue( ); } return null; } String getElementColorProperty( ReportElementHandle handle, String name ) { FactoryPropertyHandle prop = handle.getFactoryPropertyHandle( name ); if ( prop != null && prop.isSet( ) ) { return prop.getColorValue( ); } return null; } protected StyleDeclaration createPrivateStyle( ReportElementHandle handle ) { return createPrivateStyle( handle, true ); } protected String decodePageBreak( String pageBreak ) { if ( pageBreak == null ) { return null; } if ( DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS.equals( pageBreak ) ) { return IStyle.CSS_ALWAYS_VALUE; } if ( DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS_EXCLUDING_LAST .equals( pageBreak ) ) { return IStyle.CSS_ALWAYS_VALUE; } if ( DesignChoiceConstants.PAGE_BREAK_AFTER_AUTO.equals( pageBreak ) ) { return IStyle.CSS_AUTO_VALUE; } if ( DesignChoiceConstants.PAGE_BREAK_AFTER_AVOID.equals( pageBreak ) ) { return IStyle.CSS_AVOID_VALUE; } if ( DesignChoiceConstants.PAGE_BREAK_BEFORE_ALWAYS.equals( pageBreak ) ) { return IStyle.CSS_ALWAYS_VALUE; } if ( DesignChoiceConstants.PAGE_BREAK_BEFORE_ALWAYS_EXCLUDING_FIRST .equals( pageBreak ) ) { return IStyle.CSS_ALWAYS_VALUE; } if ( DesignChoiceConstants.PAGE_BREAK_BEFORE_AUTO.equals( pageBreak ) ) { return IStyle.CSS_AUTO_VALUE; } if ( DesignChoiceConstants.PAGE_BREAK_BEFORE_AVOID.equals( pageBreak ) ) { return IStyle.CSS_AVOID_VALUE; } return IStyle.CSS_AUTO_VALUE; } protected StyleDeclaration createPrivateStyle( ReportElementHandle handle, boolean isContainer ) { // Background StyleDeclaration style = new StyleDeclaration( cssEngine ); style.setBackgroundColor( getElementProperty( handle, Style.BACKGROUND_COLOR_PROP, true ) ); style.setBackgroundImage( getElementProperty( handle, Style.BACKGROUND_IMAGE_PROP ) ); style.setBackgroundPositionX( getElementProperty( handle, Style.BACKGROUND_POSITION_X_PROP ) ); style.setBackgroundPositionY( getElementProperty( handle, Style.BACKGROUND_POSITION_Y_PROP ) ); style.setBackgroundRepeat( getElementProperty( handle, Style.BACKGROUND_REPEAT_PROP ) ); // Text related style .setTextAlign( getElementProperty( handle, Style.TEXT_ALIGN_PROP ) ); style .setTextIndent( getElementProperty( handle, Style.TEXT_INDENT_PROP ) ); style.setTextUnderline( getElementProperty( handle, Style.TEXT_UNDERLINE_PROP ) ); style.setTextLineThrough( getElementProperty( handle, Style.TEXT_LINE_THROUGH_PROP ) ); style.setTextOverline( getElementProperty( handle, Style.TEXT_OVERLINE_PROP ) ); style.setLetterSpacing( getElementProperty( handle, Style.LETTER_SPACING_PROP ) ); style .setLineHeight( getElementProperty( handle, Style.LINE_HEIGHT_PROP ) ); style.setOrphans( getElementProperty( handle, Style.ORPHANS_PROP ) ); style.setTextTransform( getElementProperty( handle, Style.TEXT_TRANSFORM_PROP ) ); style.setVerticalAlign( getElementProperty( handle, Style.VERTICAL_ALIGN_PROP ) ); style .setWhiteSpace( getElementProperty( handle, Style.WHITE_SPACE_PROP ) ); style.setWidows( getElementProperty( handle, Style.WIDOWS_PROP ) ); style.setWordSpacing( getElementProperty( handle, Style.WORD_SPACING_PROP ) ); // Section properties style.setDisplay( getElementProperty( handle, Style.DISPLAY_PROP ) ); style .setMasterPage( getElementProperty( handle, Style.MASTER_PAGE_PROP ) ); String pageBreakAfter = getElementProperty(handle, StyleHandle.PAGE_BREAK_AFTER_PROP); style.setPageBreakAfter( decodePageBreak(pageBreakAfter) ); String pageBreakBefore = getElementProperty( handle, StyleHandle.PAGE_BREAK_BEFORE_PROP ); style.setPageBreakBefore( decodePageBreak(pageBreakBefore) ); style.setPageBreakInside( getElementProperty( handle, Style.PAGE_BREAK_INSIDE_PROP ) ); // Font related style .setFontFamily( getElementProperty( handle, Style.FONT_FAMILY_PROP ) ); style.setColor( getElementProperty( handle, Style.COLOR_PROP, true ) ); style.setFontSize( getElementProperty( handle, Style.FONT_SIZE_PROP ) ); style .setFontStyle( getElementProperty( handle, Style.FONT_STYLE_PROP ) ); style .setFontWeight( getElementProperty( handle, Style.FONT_WEIGHT_PROP ) ); style.setFontVariant( getElementProperty( handle, Style.FONT_VARIANT_PROP ) ); // Border style.setBorderBottomColor( getElementProperty( handle, Style.BORDER_BOTTOM_COLOR_PROP, true ) ); style.setBorderBottomStyle( getElementProperty( handle, Style.BORDER_BOTTOM_STYLE_PROP ) ); style.setBorderBottomWidth( getElementProperty( handle, Style.BORDER_BOTTOM_WIDTH_PROP ) ); style.setBorderLeftColor( getElementProperty( handle, Style.BORDER_LEFT_COLOR_PROP, true ) ); style.setBorderLeftStyle( getElementProperty( handle, Style.BORDER_LEFT_STYLE_PROP ) ); style.setBorderLeftWidth( getElementProperty( handle, Style.BORDER_LEFT_WIDTH_PROP ) ); style.setBorderRightColor( getElementProperty( handle, Style.BORDER_RIGHT_COLOR_PROP, true ) ); style.setBorderRightStyle( getElementProperty( handle, Style.BORDER_RIGHT_STYLE_PROP ) ); style.setBorderRightWidth( getElementProperty( handle, Style.BORDER_RIGHT_WIDTH_PROP ) ); style.setBorderTopColor( getElementProperty( handle, Style.BORDER_TOP_COLOR_PROP, true ) ); style.setBorderTopStyle( getElementProperty( handle, Style.BORDER_TOP_STYLE_PROP ) ); style.setBorderTopWidth( getElementProperty( handle, Style.BORDER_TOP_WIDTH_PROP ) ); // Margin style .setMarginTop( getElementProperty( handle, Style.MARGIN_TOP_PROP ) ); style .setMarginLeft( getElementProperty( handle, Style.MARGIN_LEFT_PROP ) ); style.setMarginBottom( getElementProperty( handle, Style.MARGIN_BOTTOM_PROP ) ); style.setMarginRight( getElementProperty( handle, Style.MARGIN_RIGHT_PROP ) ); // Padding style .setPaddingTop( getElementProperty( handle, Style.PADDING_TOP_PROP ) ); style.setPaddingLeft( getElementProperty( handle, Style.PADDING_LEFT_PROP ) ); style.setPaddingBottom( getElementProperty( handle, Style.PADDING_BOTTOM_PROP ) ); style.setPaddingRight( getElementProperty( handle, Style.PADDING_RIGHT_PROP ) ); // Data Formatting style.setNumberAlign( getElementProperty( handle, Style.NUMBER_ALIGN_PROP ) ); style.setDateFormat( getElementProperty( handle, Style.DATE_TIME_FORMAT_PROP ) ); style.setNumberFormat( getElementProperty( handle, Style.NUMBER_FORMAT_PROP ) ); style.setStringFormat( getElementProperty( handle, Style.STRING_FORMAT_PROP ) ); // Others style .setCanShrink( getElementProperty( handle, Style.CAN_SHRINK_PROP ) ); style.setShowIfBlank( getElementProperty( handle, Style.SHOW_IF_BLANK_PROP ) ); return style; } String getMemberProperty( StructureHandle handle, String name ) { MemberHandle prop = handle.getMember( name ); if ( prop != null ) { return prop.getStringValue( ); } return null; } IStyle setupStyle( StructureHandle highlight, IStyle style ) { // Background style.setBackgroundColor( getMemberProperty( highlight, HighlightRule.BACKGROUND_COLOR_MEMBER ) ); // style.setBackgroundPositionX(getMemberProperty(highlight, // HighlightRule.BACKGROUND_POSITION_X_MEMBER)); // style.setBackgroundPositionY(getMemberProperty(highlight, // HighlightRule.BACKGROUND_POSITION_Y_MEMBER)); // style.setBackgroundRepeat(getMemberProperty(highlight, // HighlightRule.BACKGROUND_REPEAT_MEMBER)); // Text related style.setTextAlign( getMemberProperty( highlight, HighlightRule.TEXT_ALIGN_MEMBER ) ); style.setTextIndent( getMemberProperty( highlight, HighlightRule.TEXT_INDENT_MEMBER ) ); style.setTextUnderline( getMemberProperty( highlight, Style.TEXT_UNDERLINE_PROP ) ); style.setTextLineThrough( getMemberProperty( highlight, Style.TEXT_LINE_THROUGH_PROP ) ); style.setTextOverline( getMemberProperty( highlight, Style.TEXT_OVERLINE_PROP ) ); // style.setLetterSpacing(getMemberProperty(highlight, // HighlightRule.LETTER_SPACING_MEMBER)); // style.setLineHeight(getMemberProperty(highlight, // HighlightRule.LINE_HEIGHT_MEMBER)); // style.setOrphans(getMemberProperty(highlight, // HighlightRule.ORPHANS_MEMBER)); style.setTextTransform( getMemberProperty( highlight, HighlightRule.TEXT_TRANSFORM_MEMBER ) ); // style.setVerticalAlign(getMemberProperty(highlight, // HighlightRule.VERTICAL_ALIGN_MEMBER)); // style.setWhiteSpace(getMemberProperty(highlight, // HighlightRule.WHITE_SPACE_MEMBER)); // style.setWidows(getMemberProperty(highlight, // HighlightRule.WIDOWS_MEMBER)); // style.setWordSpacing(getMemberProperty(highlight, // HighlightRule.WORD_SPACING_MEMBER)); // Section properties // style.setDisplay(getMemberProperty(highlight, // HighlightRule.DISPLAY_MEMBER)); // style.setMasterPage(getMemberProperty(highlight, // HighlightRule.MASTER_PAGE_MEMBER)); // style.setPageBreakAfter(getMemberProperty(highlight, // HighlightRule.PAGE_BREAK_AFTER_MEMBER)); // style.setPageBreakBefore(getMemberProperty(highlight, // HighlightRule.PAGE_BREAK_BEFORE_MEMBER)); // style.setPageBreakInside(getMemberProperty(highlight, // HighlightRule.PAGE_BREAK_INSIDE_MEMBER)); // Font related style.setFontFamily( getMemberProperty( highlight, HighlightRule.FONT_FAMILY_MEMBER ) ); style.setColor( getMemberProperty( highlight, HighlightRule.COLOR_MEMBER ) ); style.setFontSize( getMemberProperty( highlight, HighlightRule.FONT_SIZE_MEMBER ) ); style.setFontStyle( getMemberProperty( highlight, HighlightRule.FONT_STYLE_MEMBER ) ); style.setFontWeight( getMemberProperty( highlight, HighlightRule.FONT_WEIGHT_MEMBER ) ); style.setFontVariant( getMemberProperty( highlight, HighlightRule.FONT_VARIANT_MEMBER ) ); // Border style.setBorderBottomColor( getMemberProperty( highlight, HighlightRule.BORDER_BOTTOM_COLOR_MEMBER ) ); style.setBorderBottomStyle( getMemberProperty( highlight, HighlightRule.BORDER_BOTTOM_STYLE_MEMBER ) ); style.setBorderBottomWidth( getMemberProperty( highlight, HighlightRule.BORDER_BOTTOM_WIDTH_MEMBER ) ); style.setBorderLeftColor( getMemberProperty( highlight, HighlightRule.BORDER_LEFT_COLOR_MEMBER ) ); style.setBorderLeftStyle( getMemberProperty( highlight, HighlightRule.BORDER_LEFT_STYLE_MEMBER ) ); style.setBorderLeftWidth( getMemberProperty( highlight, HighlightRule.BORDER_LEFT_WIDTH_MEMBER ) ); style.setBorderRightColor( getMemberProperty( highlight, HighlightRule.BORDER_RIGHT_COLOR_MEMBER ) ); style.setBorderRightStyle( getMemberProperty( highlight, HighlightRule.BORDER_RIGHT_STYLE_MEMBER ) ); style.setBorderRightWidth( getMemberProperty( highlight, HighlightRule.BORDER_RIGHT_WIDTH_MEMBER ) ); style.setBorderTopColor( getMemberProperty( highlight, HighlightRule.BORDER_TOP_COLOR_MEMBER ) ); style.setBorderTopStyle( getMemberProperty( highlight, HighlightRule.BORDER_TOP_STYLE_MEMBER ) ); style.setBorderTopWidth( getMemberProperty( highlight, HighlightRule.BORDER_TOP_WIDTH_MEMBER ) ); // Margin // style.setMarginTop(getMemberProperty(highlight, // HighlightRule.MARGIN_TOP_MEMBER)); // style.setMarginLeft(getMemberProperty(highlight, // HighlightRule.MARGIN_LEFT_MEMBER)); // style.setMarginBottom(getMemberProperty(highlight, // HighlightRule.MARGIN_BOTTOM_MEMBER)); // style.setMarginRight(getMemberProperty(highlight, // HighlightRule.MARGIN_RIGHT_MEMBER)); // Padding // style.setPaddingTop(getMemberProperty(highlight, // HighlightRule.PADDING_TOP_MEMBER)); // style.setPaddingLeft(getMemberProperty(highlight, // HighlightRule.PADDING_LEFT_MEMBER)); // style.setPaddingBottom(getMemberProperty(highlight, // HighlightRule.PADDING_BOTTOM_MEMBER)); // style.setPaddingRight(getMemberProperty(highlight, // HighlightRule.PADDING_RIGHT_MEMBER)); // Data Formatting style.setNumberAlign( getMemberProperty( highlight, HighlightRule.NUMBER_ALIGN_MEMBER ) ); style.setDateFormat( getMemberProperty( highlight, HighlightRule.DATE_TIME_FORMAT_MEMBER ) ); style.setNumberFormat( getMemberProperty( highlight, HighlightRule.NUMBER_FORMAT_MEMBER ) ); style.setStringFormat( getMemberProperty( highlight, HighlightRule.STRING_FORMAT_MEMBER ) ); // Others // style.setCanShrink(getMemberProperty(highlight, // HighlightRule.CAN_SHRINK_MEMBER)); // style.setShowIfBlank(getMemberProperty(highlight, // HighlightRule.SHOW_IF_BLANK_MEMBER)); return style; } protected DimensionType createDimension( DimensionHandle handle ) { if ( handle == null || !handle.isSet( ) ) { return null; } // Extended Choice if ( handle.isKeyword( ) ) { return new DimensionType( handle.getStringValue( ) ); } // set measure and unit double measure = handle.getMeasure( ); String unit = handle.getUnits( ); if ( DimensionValue.DEFAULT_UNIT.equals( unit ) ) { unit = defaultUnit; } return new DimensionType( measure, unit ); } protected void setupListingItem( ListingDesign listing, ListingHandle handle ) { // setup related scripts setupReportItem( listing, handle ); listing.setPageBreakInterval( handle.getPageBreakInterval( ) ); // setup scripts // listing.setOnStart( handle.getOnStart( ) ); // listing.setOnRow( handle.getOnRow( ) ); // listing.setOnFinish( handle.getOnFinish( ) ); } // Convert model operator value to DtE IColumnFilter enum value protected int toDteFilterOperator( String modelOpr ) { if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_EQ ) ) return IConditionalExpression.OP_EQ; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NE ) ) return IConditionalExpression.OP_NE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_LT ) ) return IConditionalExpression.OP_LT; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_LE ) ) return IConditionalExpression.OP_LE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_GE ) ) return IConditionalExpression.OP_GE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_GT ) ) return IConditionalExpression.OP_GT; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_BETWEEN ) ) return IConditionalExpression.OP_BETWEEN; if ( modelOpr .equals( DesignChoiceConstants.FILTER_OPERATOR_NOT_BETWEEN ) ) return IConditionalExpression.OP_NOT_BETWEEN; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NULL ) ) return IConditionalExpression.OP_NULL; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NOT_NULL ) ) return IConditionalExpression.OP_NOT_NULL; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_TRUE ) ) return IConditionalExpression.OP_TRUE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_FALSE ) ) return IConditionalExpression.OP_FALSE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_LIKE ) ) return IConditionalExpression.OP_LIKE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_TOP_N ) ) return IConditionalExpression.OP_TOP_N; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_BOTTOM_N ) ) return IConditionalExpression.OP_BOTTOM_N; if ( modelOpr .equals( DesignChoiceConstants.FILTER_OPERATOR_TOP_PERCENT ) ) return IConditionalExpression.OP_TOP_PERCENT; if ( modelOpr .equals( DesignChoiceConstants.FILTER_OPERATOR_BOTTOM_PERCENT ) ) return IConditionalExpression.OP_BOTTOM_PERCENT; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NOT_LIKE )) return IConditionalExpression.OP_NOT_LIKE; if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_NOT_MATCH )) return IConditionalExpression.OP_NOT_MATCH; /* if ( modelOpr.equals( DesignChoiceConstants.FILTER_OPERATOR_ANY ) ) return IConditionalExpression.OP_ANY;*/ return IConditionalExpression.OP_NONE; } protected void addReportDefaultPropertyValue( String name, StyleHandle handle ) { addReportDefaultPropertyValue( name, handle, false ); } protected void addReportDefaultPropertyValue( String name, StyleHandle handle, boolean isColorProperty ) { Object value = null; int index = StylePropertyMapping.getPropertyID( name ); if ( StylePropertyMapping.canInherit( name ) ) { if ( handle != null ) { if ( isColorProperty ) { value = handle.getColorProperty( name ).getStringValue( ); } else { value = handle.getProperty( name ); } } if ( value == null ) { value = StylePropertyMapping.getDefaultValue( name ); } inheritableReportStyle.setCssText( index, value == null ? null : value.toString( ) ); } else { value = StylePropertyMapping.getDefaultValue( name ); nonInheritableReportStyle.setCssText( index, value == null ? null : value.toString( ) ); } } /** * Creates Report default styles */ protected void createReportDefaultStyles( StyleHandle handle ) { nonInheritableReportStyle = new StyleDeclaration( cssEngine ); inheritableReportStyle = new StyleDeclaration( cssEngine ); // Background addReportDefaultPropertyValue( Style.BACKGROUND_COLOR_PROP, handle, true ); addReportDefaultPropertyValue( Style.BACKGROUND_IMAGE_PROP, handle ); addReportDefaultPropertyValue( Style.BACKGROUND_POSITION_X_PROP, handle ); addReportDefaultPropertyValue( Style.BACKGROUND_POSITION_Y_PROP, handle ); addReportDefaultPropertyValue( Style.BACKGROUND_REPEAT_PROP, handle ); // Text related addReportDefaultPropertyValue( Style.TEXT_ALIGN_PROP, handle ); addReportDefaultPropertyValue( Style.TEXT_INDENT_PROP, handle ); addReportDefaultPropertyValue( Style.LETTER_SPACING_PROP, handle ); addReportDefaultPropertyValue( Style.LINE_HEIGHT_PROP, handle ); addReportDefaultPropertyValue( Style.ORPHANS_PROP, handle ); addReportDefaultPropertyValue( Style.TEXT_TRANSFORM_PROP, handle ); addReportDefaultPropertyValue( Style.VERTICAL_ALIGN_PROP, handle ); addReportDefaultPropertyValue( Style.WHITE_SPACE_PROP, handle ); addReportDefaultPropertyValue( Style.WIDOWS_PROP, handle ); addReportDefaultPropertyValue( Style.WORD_SPACING_PROP, handle ); // Section properties addReportDefaultPropertyValue( Style.DISPLAY_PROP, handle ); addReportDefaultPropertyValue( Style.MASTER_PAGE_PROP, handle ); addReportDefaultPropertyValue( Style.PAGE_BREAK_AFTER_PROP, handle ); addReportDefaultPropertyValue( Style.PAGE_BREAK_BEFORE_PROP, handle ); addReportDefaultPropertyValue( Style.PAGE_BREAK_INSIDE_PROP, handle ); // Font related addReportDefaultPropertyValue( Style.FONT_FAMILY_PROP, handle ); addReportDefaultPropertyValue( Style.COLOR_PROP, handle, true ); addReportDefaultPropertyValue( Style.FONT_SIZE_PROP, handle ); addReportDefaultPropertyValue( Style.FONT_STYLE_PROP, handle ); addReportDefaultPropertyValue( Style.FONT_WEIGHT_PROP, handle ); addReportDefaultPropertyValue( Style.FONT_VARIANT_PROP, handle ); // Text decoration addReportDefaultPropertyValue( Style.TEXT_LINE_THROUGH_PROP, handle ); addReportDefaultPropertyValue( Style.TEXT_OVERLINE_PROP, handle ); addReportDefaultPropertyValue( Style.TEXT_UNDERLINE_PROP, handle ); // Border addReportDefaultPropertyValue( Style.BORDER_BOTTOM_COLOR_PROP, handle, true ); addReportDefaultPropertyValue( Style.BORDER_BOTTOM_STYLE_PROP, handle ); addReportDefaultPropertyValue( Style.BORDER_BOTTOM_WIDTH_PROP, handle ); addReportDefaultPropertyValue( Style.BORDER_LEFT_COLOR_PROP, handle, true ); addReportDefaultPropertyValue( Style.BORDER_LEFT_STYLE_PROP, handle ); addReportDefaultPropertyValue( Style.BORDER_LEFT_WIDTH_PROP, handle ); addReportDefaultPropertyValue( Style.BORDER_RIGHT_COLOR_PROP, handle, true ); addReportDefaultPropertyValue( Style.BORDER_RIGHT_STYLE_PROP, handle ); addReportDefaultPropertyValue( Style.BORDER_RIGHT_WIDTH_PROP, handle ); addReportDefaultPropertyValue( Style.BORDER_TOP_COLOR_PROP, handle, true ); addReportDefaultPropertyValue( Style.BORDER_TOP_STYLE_PROP, handle ); addReportDefaultPropertyValue( Style.BORDER_TOP_WIDTH_PROP, handle ); // Margin addReportDefaultPropertyValue( Style.MARGIN_TOP_PROP, handle ); addReportDefaultPropertyValue( Style.MARGIN_LEFT_PROP, handle ); addReportDefaultPropertyValue( Style.MARGIN_BOTTOM_PROP, handle ); addReportDefaultPropertyValue( Style.MARGIN_RIGHT_PROP, handle ); // Padding addReportDefaultPropertyValue( Style.PADDING_TOP_PROP, handle ); addReportDefaultPropertyValue( Style.PADDING_LEFT_PROP, handle ); addReportDefaultPropertyValue( Style.PADDING_BOTTOM_PROP, handle ); addReportDefaultPropertyValue( Style.PADDING_RIGHT_PROP, handle ); report.setRootStyleName( assignStyleName( inheritableReportStyle ) ); if ( nonInheritableReportStyle.isEmpty( ) ) { nonInheritableReportStyle = null; } else { report.setDefaultStyle( nonInheritableReportStyle ); } } /** * Creates the body style for master page. * * @param design * the master page design * @return the content style */ protected String setupBodyStyle( MasterPageDesign design ) { String styleName = design.getStyleName( ); IStyle style = report.findStyle( styleName ); if ( style == null || style.isEmpty( ) ) { return null; } StyleDeclaration contentStyle = new StyleDeclaration( cssEngine ); contentStyle.setProperty( IStyle.STYLE_BACKGROUND_COLOR, style .getProperty( IStyle.STYLE_BACKGROUND_COLOR ) ); contentStyle.setProperty( IStyle.STYLE_BACKGROUND_IMAGE, style .getProperty( IStyle.STYLE_BACKGROUND_IMAGE ) ); contentStyle.setProperty( IStyle.STYLE_BACKGROUND_POSITION_Y, style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_Y ) ); contentStyle.setProperty( IStyle.STYLE_BACKGROUND_POSITION_X, style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_X ) ); contentStyle.setProperty( IStyle.STYLE_BACKGROUND_REPEAT, style .getProperty( IStyle.STYLE_BACKGROUND_REPEAT ) ); String bodyStyleName = assignStyleName( contentStyle ); return bodyStyleName; } private void setupElementIDMap( ReportElementDesign rptElement ) { report.setReportItemInstanceID( rptElement.getID( ), rptElement ); } }
package org.mariadb.jdbc; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLNonTransientConnectionException; import java.sql.Statement; import java.util.Random; import org.junit.Ignore; import org.junit.Test; public class TimeoutTest extends BaseTest { /** * CONJ-79 * * @throws SQLException */ @Test public void resultSetAfterSocketTimeoutTest() throws SQLException { setConnection("&connectTimeout=5&socketTimeout=5"); boolean bugReproduced = false; int exc = 0; int went = 0; for (int i = 0; i < 10000; i++) { try { int v1 = selectValue(connection, 1); int v2 = selectValue(connection, 2); if (v1 != 1 || v2 != 2) { bugReproduced = true; break; } assertTrue(v1 == 1 && v2 == 2); went++; } catch (Exception e) { exc++; } } assertFalse(bugReproduced); // either Exception or fine assertTrue(went > 0); assertTrue(went + exc == 10000); } private static int selectValue(Connection conn, int value) throws SQLException { Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("select " + value); rs.next(); return rs.getInt(1); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } } /** * CONJ-79 * * @throws SQLException */ @Test public void socketTimeoutTest() throws SQLException { int exceptionCount = 0; // set a short connection timeout setConnection("&connectTimeout=5&socketTimeout=5"); PreparedStatement ps = connection.prepareStatement("SELECT 1"); ResultSet rs = ps.executeQuery(); rs.next(); logInfo(rs.getString(1)); // wait for the connection to time out ps = connection.prepareStatement("SELECT sleep(1)"); // a timeout should occur here try { rs = ps.executeQuery(); } catch (SQLException e) { // check that it's a timeout that occurs if (e.getMessage().contains("timed out")) exceptionCount++; } ps = connection.prepareStatement("SELECT 2"); // connection should be closed here, exception expected try { rs = ps.executeQuery(); rs.next(); } catch (SQLException e) { // check that it's a execute "called on closed" exception that occurs if (e.getMessage().contains("called on closed")) exceptionCount++; } // the connection should be closed assertTrue(connection.isClosed()); // there should have been two exceptions assertTrue(exceptionCount == 2); } @Test public void waitTimeoutStatementTest() throws SQLException, InterruptedException { Statement statement = connection.createStatement(); statement.execute("set session wait_timeout=1"); Thread.sleep(3000); // Wait for the server to kill the connection logInfo(connection.toString()); // here a SQLNonTransientConnectionException is expected // "Could not read resultset: unexpected end of stream, ..." try { statement.execute("SELECT 1"); } catch (SQLException e) { // verify that the correct type of exception is thrown assertTrue(e.getMessage().contains("Could not read resultset")); } statement.close(); connection.close(); connection = null; } @Test public void waitTimeoutResultSetTest() throws SQLException, InterruptedException { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 1"); rs.next(); stmt.execute("set session wait_timeout=1"); Thread.sleep(3000); // Wait for the server to kill the connection // here a SQLNonTransientConnectionException is expected // "Could not read resultset: unexpected end of stream, ..." try { rs = stmt.executeQuery("SELECT 2"); rs.next(); } catch (SQLException e) { // verify that the correct type of exception is thrown assertTrue(e.getMessage().contains("Could not read resultset")); } } // CONJ-68 // TODO: this test is not yet able to repeat the bug. Ignore until then. @Ignore @Test public void lastPacketFailedTest() throws SQLException { Statement stmt = connection.createStatement(); stmt.execute("DROP TABLE IF EXISTS `pages_txt`"); stmt.execute("CREATE TABLE `pages_txt` (`id` INT(10) UNSIGNED NOT NULL, `title` TEXT NOT NULL, `txt` MEDIUMTEXT NOT NULL, PRIMARY KEY (`id`)) COLLATE='utf8_general_ci' ENGINE=MyISAM;"); //create arbitrary long strings String chars = "0123456789abcdefghijklmnopqrstuvwxyzåäöABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ,;.:-_*¨^+?!<> StringBuffer outputBuffer = null; Random r = null; for(int i = 1; i < 2001; i++) { r = new Random(); outputBuffer = new StringBuffer(i); for (int j = 0; j < i; j++){ outputBuffer.append(chars.charAt(r.nextInt(chars.length()))); } stmt.execute("insert into pages_txt values (" + i + ", '" + outputBuffer.toString() + "' , 'txt')"); } } }
package org.geomajas.gwt2.example.client.sample.general; import org.geomajas.command.dto.TransformGeometryRequest; import org.geomajas.command.dto.TransformGeometryResponse; import org.geomajas.geometry.Bbox; import org.geomajas.gwt.client.command.AbstractCommandCallback; import org.geomajas.gwt.client.command.GwtCommand; import org.geomajas.gwt2.client.GeomajasImpl; import org.geomajas.gwt2.client.GeomajasServerExtension; import org.geomajas.gwt2.client.event.MapInitializationEvent; import org.geomajas.gwt2.client.event.MapInitializationHandler; import org.geomajas.gwt2.client.map.MapConfiguration; import org.geomajas.gwt2.client.map.MapPresenter; import org.geomajas.gwt2.client.map.layer.Layer; import org.geomajas.gwt2.example.base.client.ExampleBase; import org.geomajas.gwt2.example.base.client.sample.SamplePanel; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.geolocation.client.Geolocation; import com.google.gwt.geolocation.client.Position; import com.google.gwt.geolocation.client.PositionError; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.ResizeLayoutPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * ContentPanel that demonstrates some options regarding map navigation. * * @author Pieter De Graef */ public class NavigationOptionPanel implements SamplePanel { /** * UI binder for this widget. * * @author Pieter De Graef */ interface MyUiBinder extends UiBinder<Widget, NavigationOptionPanel> { } private static final MyUiBinder UI_BINDER = GWT.create(MyUiBinder.class); private final int defaultMillis = 400; private final int defaultFadeInMillis = 250; private MapPresenter mapPresenter; @UiField protected TextBox millisBox; @UiField protected TextBox fadeInBox; @UiField protected CheckBox cancelAnimationSupport; @UiField protected VerticalPanel layerPanel; @UiField protected ResizeLayoutPanel mapPanel; public Widget asWidget() { Widget layout = UI_BINDER.createAndBindUi(this); // Initialize the map, and return the layout: mapPresenter = GeomajasImpl.getInstance().createMapPresenter(); mapPresenter.setSize(480, 480); mapPresenter.getEventBus().addMapInitializationHandler(new MyMapInitializationHandler()); GeomajasServerExtension.getInstance().initializeMap(mapPresenter, "gwt-app", "mapCountries"); DecoratorPanel mapDecorator = new DecoratorPanel(); mapDecorator.add(mapPresenter.asWidget()); mapPanel.add(mapDecorator); // Make sure the text box also reacts to the "Enter" key: millisBox.addKeyUpHandler(new KeyUpHandler() { public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { changeAnimationMillis(); } } }); fadeInBox.addKeyUpHandler(new KeyUpHandler() { public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { changeFadeInMillis(); } } }); cancelAnimationSupport.addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { mapPresenter.getConfiguration().setHintValue(MapConfiguration.ANIMATION_CANCEL_SUPPORT, cancelAnimationSupport.getValue()); } }); return layout; } @UiHandler("millisBtn") protected void onMillisButtonClicked(ClickEvent event) { changeAnimationMillis(); } @UiHandler("fadeInBtn") protected void onFadeInButtonClicked(ClickEvent event) { changeFadeInMillis(); } @UiHandler("currentLocationBtn") protected void onCurrentLocationButtonClicked(ClickEvent event) { if (Geolocation.isSupported()) { Geolocation.getIfSupported().getCurrentPosition(new Callback<Position, PositionError>() { @Override public void onSuccess(Position result) { TransformGeometryRequest request = new TransformGeometryRequest(); request.setBounds(new Bbox(result.getCoordinates().getLongitude(), result.getCoordinates() .getLatitude(), 0, 0)); request.setSourceCrs("EPSG:4326"); request.setTargetCrs(mapPresenter.getViewPort().getCrs()); GwtCommand command = new GwtCommand(TransformGeometryRequest.COMMAND); command.setCommandRequest(request); GeomajasServerExtension.getInstance().getCommandService() .execute(command, new AbstractCommandCallback<TransformGeometryResponse>() { @Override public void execute(TransformGeometryResponse response) { mapPresenter.getViewPort().applyBounds(response.getBounds()); } }); }; @Override public void onFailure(PositionError reason) { // TODO Auto-generated method stub } }); } } private void changeAnimationMillis() { String txt = millisBox.getValue(); int time = defaultMillis; try { time = Integer.parseInt(txt); } catch (Exception e) { // NOSONAR Window.alert("Could not parse milliseconds... Default value of " + defaultMillis + " is used"); mapPresenter.getConfiguration().setHintValue(MapConfiguration.ANIMATION_TIME, defaultMillis); millisBox.setValue(defaultMillis + ""); } mapPresenter.getConfiguration().setHintValue(MapConfiguration.ANIMATION_TIME, time); } private void changeFadeInMillis() { String txt = fadeInBox.getValue(); int time = defaultFadeInMillis; try { time = Integer.parseInt(txt); } catch (Exception e) { // NOSONAR Window.alert("Could not parse milliseconds... Default value of " + defaultFadeInMillis + " is used"); mapPresenter.getConfiguration().setHintValue(MapConfiguration.FADE_IN_TIME, defaultMillis); fadeInBox.setValue(defaultFadeInMillis + ""); } mapPresenter.getConfiguration().setHintValue(MapConfiguration.FADE_IN_TIME, time); } /** * Map initialization handler that adds checkboxes for every layer to enable/disable animated rendering for those * layers. * * @author Pieter De Graef */ private class MyMapInitializationHandler implements MapInitializationHandler { public void onMapInitialized(MapInitializationEvent event) { // Add layer specific animation CheckBoxes: for (int i = 0; i < mapPresenter.getLayersModel().getLayerCount(); i++) { final Layer layer = mapPresenter.getLayersModel().getLayer(i); CheckBox cb = new CheckBox("Animate: " + layer.getTitle()); cb.setValue(mapPresenter.getLayersModelRenderer().isAnimated(layer)); cb.addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { mapPresenter.getLayersModelRenderer().setAnimated(layer, event.getValue()); } }); layerPanel.add(cb); } // Zoom in (scale times 4), to get a better view: mapPresenter.getViewPort().applyBounds(ExampleBase.BBOX_AFRICA); } } }
package com.yox89.ld32.actors; import javax.swing.plaf.basic.BasicScrollPaneUI.HSBChangeListener; import box2dLight.PointLight; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Animation.PlayMode; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.yox89.ld32.Physics; import com.yox89.ld32.util.Collision; import com.yox89.ld32.util.Ui; public class PlayerActor extends PhysicsActor { private static final float ROTATION_UP = 90; private static final float ROTATION_DOWN = -90; private static final float ROTATION_RIGHT = 0; private static final float ROTATION_LEFT = 180; private static final float ANIMATION_START = 10f; private static final float ANIMATION_DURATION = 2.30f; private static final String MAP_PROPERTIES_FLUFF = "fluff"; private static final int URGE_TO_MUTTER = 70; private float speed; private float angularSpeed; private Animation animation; private float rotationPriority = 0f; private boolean moving; private float stateTime = ANIMATION_START; private PointLight mLight; private Ui ui; public boolean mBlockInput; private MapProperties mapProperties; private int urgeToMutter = 0; private boolean hasMuttered = false; public PlayerActor(Physics physics, Ui ui, MapProperties mapProperties) { setTouchable(Touchable.disabled); this.ui = ui; this.mapProperties = mapProperties; this.animation = setupAnimation(); this.speed = 5f; this.angularSpeed = 10f; setSize(1.3f, 1.3f); initPhysicsBody(createBody(physics, BodyType.DynamicBody, Collision.PLAYER, (short) (Collision.WORLD | Collision.GHOST_VISION))); mLight = new PointLight(physics.rayHandler, 10, new Color(1f, 1f, 1f, 0.5f), 1.5f, 0f, 0f); } private Animation setupAnimation() { int frameRows = 4; int frameColumns = 4; Texture walkSheet = new Texture( Gdx.files.internal("animation_sheet2.png")); TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth() / frameColumns, walkSheet.getHeight() / frameRows); TextureRegion[] walkFrames = new TextureRegion[frameColumns * frameRows]; int index = 0; for (int i = 0; i < frameRows; i++) { for (int j = 0; j < frameColumns; j++) { walkFrames[index++] = tmp[i][j]; } } animation = new Animation(ANIMATION_DURATION, walkFrames); animation.setPlayMode(PlayMode.LOOP); return animation; } @Override public void act(float delta) { super.act(delta); final Vector2 movement = new Vector2(); if (!mBlockInput) { if (Gdx.input.isKeyPressed(Keys.UP) || Gdx.input.isKeyPressed(Keys.W)) { movement.y++; rotationPriority = ROTATION_UP; } if (Gdx.input.isKeyPressed(Keys.DOWN) || Gdx.input.isKeyPressed(Keys.S)) { movement.y rotationPriority = ROTATION_DOWN; } if (Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D)) { movement.x++; rotationPriority = ROTATION_RIGHT; } if (Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A)) { movement.x rotationPriority = ROTATION_LEFT; } } if(movement.x != 0 || movement.y != 0){ moving = true; ui.removeFluffText(); mutter(); } else { moving = false; stateTime = ANIMATION_START; } movement.nor().scl(delta * speed); rotateTowards(rotationPriority, getCurrentRotationNegative180ToPositive180(), angularSpeed); moveBy(movement.x, movement.y); mLight.setPosition(getX(), getY()); } private void rotateTowards(float rotationGoal, float currentRotationNegative180ToPositive180, float rotationChange) { float currentRotation = currentRotationNegative180ToPositive180; boolean leftSemi = currentRotation < -90 || currentRotation > 90; boolean lowerSemi = currentRotation < 0; int clockWise = 1; if (rotationGoal == ROTATION_UP) { clockWise = leftSemi ? -1 : 1; } else if (rotationGoal == ROTATION_DOWN) { clockWise = leftSemi ? 1 : -1; } else if (rotationGoal == ROTATION_LEFT) { clockWise = lowerSemi ? -1 : 1; } else if (rotationGoal == ROTATION_RIGHT) { clockWise = lowerSemi ? 1 : -1; } rotationChange = (Math.abs(rotationGoal - currentRotation) < rotationChange) ? 0 : rotationChange; rotateBy(rotationChange * clockWise); } private float getCurrentRotationNegative180ToPositive180() { float currentRotation = getRotation() % 360; if (currentRotation > 180) { currentRotation = -180 + (currentRotation - 180); } else if (currentRotation < -180) { currentRotation = 180 + (currentRotation + 180); } return currentRotation; } private void mutter() { if(!hasMuttered ){ urgeToMutter++; if(urgeToMutter > URGE_TO_MUTTER){ if(urgeToMutter%URGE_TO_MUTTER == 0 && Math.random() < 0.4f){ ui.showMutter(mapProperties.containsKey(MAP_PROPERTIES_FLUFF)?""+mapProperties.get(MAP_PROPERTIES_FLUFF):"Urgh...", new Vector2(getX(),getY())); hasMuttered = true; } } } } @Override public void draw(Batch batch, float parentAlpha) { batch.draw(animation.getKeyFrame((moving ? ++stateTime : 10)), getX() - (getWidth() / 2), getY() - (getHeight() / 2), getOriginX() + (getWidth() / 2), getOriginY() + (getHeight() / 2), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation(), true); } public static Body createBody(Physics physics, BodyType bodyType, short collisionType, short collisionMask) { final BodyDef bd = new BodyDef(); bd.type = bodyType; bd.position.set(0.0f, 10.0f); bd.linearDamping = 0.2f; final Body body = physics.world.createBody(bd); final FixtureDef fd = new FixtureDef(); fd.density = 0.0f; fd.filter.categoryBits = collisionType; fd.filter.maskBits = collisionMask; fd.restitution = 0.0f; fd.friction = 0.0f; final CircleShape shape = new CircleShape(); shape.setRadius(0.4f); fd.shape = shape; body.createFixture(fd); shape.dispose(); return body; } }
//@@author A0144939R package seedu.task.testutil; import seedu.task.model.tag.UniqueTagList; import seedu.task.model.task.*; /** * A mutable task object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private DateTime openTime; private DateTime closeTime; private UniqueTagList tags; private boolean isImportant; private boolean isCompleted; public TestTask() { tags = new UniqueTagList(); } //@@author A0141052Y /** * Creates a duplicate (copy) of an existing TestTask * @param task the TestTask to copy from */ public TestTask(TestTask task) { this.name = task.getName(); this.openTime = task.getOpenTime(); this.closeTime = task.getCloseTime(); this.isCompleted = task.getComplete(); this.isImportant = task.getImportance(); this.tags = new UniqueTagList(task.getTags()); } //@@author public void setName(Name name) { this.name = name; } //@@author A0153467Y public void setIsImportant(boolean isImportant){ this.isImportant=isImportant; } //@@author public void setOpenTime(DateTime openTime) { this.openTime = openTime; } public void setCloseTime(DateTime closeTime) { this.closeTime = closeTime; } //@@author A0153467Y public void setIsCompleted(boolean isCompleted){ this.isCompleted = isCompleted; } @Override public Name getName() { return name; } //@@author A0153467Y @Override public boolean getComplete() { return isCompleted; } //@@author @Override public DateTime getOpenTime() { return openTime; } @Override public DateTime getCloseTime() { return closeTime; } @Override public UniqueTagList getTags() { return tags; } //@@author A0153467Y @Override public boolean getImportance() { return isImportant; } //@@author @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().taskName + " "); sb.append("starts " + this.getOpenTime().toPrettyString() + " "); sb.append("ends " + this.getCloseTime().toPrettyString() + " "); this.getTags().getInternalList().stream().forEach(s -> sb.append("tag " + s.tagName + " ")); System.out.println("COMMAND" +sb.toString()); return sb.toString(); } public String getArgs() { StringBuilder sb = new StringBuilder(); sb.append(" "+this.getName().taskName + " "); sb.append("starts " + this.getOpenTime().toPrettyString() + " "); sb.append("ends " + this.getCloseTime().toPrettyString() + " "); this.getTags().getInternalList().stream().forEach(s -> sb.append("tag " + s.tagName + " ")); return sb.toString(); } }
package org.monarchinitiative.exomiser.core.model.pathogenicity; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.util.*; public class ClinVarData { private static final ClinVarData EMPTY = new Builder().build(); public enum ClinSig { // ACMG/AMP-based BENIGN, BENIGN_OR_LIKELY_BENIGN, LIKELY_BENIGN, UNCERTAIN_SIGNIFICANCE, LIKELY_PATHOGENIC, PATHOGENIC_OR_LIKELY_PATHOGENIC, PATHOGENIC, CONFLICTING_PATHOGENICITY_INTERPRETATIONS, //Non-ACMG-based AFFECTS, ASSOCIATION, DRUG_RESPONSE, NOT_PROVIDED, OTHER, PROTECTIVE, RISK_FACTOR; } private final String alleleId; private final ClinSig primaryInterpretation; private final Set<ClinSig> secondaryInterpretations; private final String reviewStatus; private final Map<String, ClinSig> includedAlleles; private ClinVarData(Builder builder) { this.alleleId = builder.alleleId; this.primaryInterpretation = builder.primaryInterpretation; this.secondaryInterpretations = Sets.immutableEnumSet(builder.secondaryInterpretations); this.reviewStatus = builder.reviewStatus; this.includedAlleles = ImmutableMap.copyOf(builder.includedAlleles); } public static ClinVarData empty() { return EMPTY; } public boolean isEmpty() { return this.equals(EMPTY); } public String getAlleleId() { return alleleId; } public ClinSig getPrimaryInterpretation() { return primaryInterpretation; } public Set<ClinSig> getSecondaryInterpretations() { return secondaryInterpretations; } public String getReviewStatus() { return reviewStatus; } public Map<String, ClinSig> getIncludedAlleles() { return includedAlleles; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClinVarData that = (ClinVarData) o; return Objects.equals(alleleId, that.alleleId) && primaryInterpretation == that.primaryInterpretation && Objects.equals(secondaryInterpretations, that.secondaryInterpretations) && Objects.equals(reviewStatus, that.reviewStatus) && Objects.equals(includedAlleles, that.includedAlleles); } @Override public int hashCode() { return Objects.hash(alleleId, primaryInterpretation, secondaryInterpretations, reviewStatus, includedAlleles); } @Override public String toString() { return "ClinVarData{" + "alleleId='" + alleleId + '\'' + ", primaryInterpretation=" + primaryInterpretation + ", secondaryInterpretations=" + secondaryInterpretations + ", reviewStatus='" + reviewStatus + '\'' + ", includedAlleles=" + includedAlleles + '}'; } public static Builder builder() { return new Builder(); } public static class Builder { private String alleleId = ""; private ClinSig primaryInterpretation = ClinSig.NOT_PROVIDED; private Set<ClinSig> secondaryInterpretations = EnumSet.noneOf(ClinSig.class); private String reviewStatus = ""; private Map<String, ClinSig> includedAlleles = Collections.emptyMap(); public Builder alleleId(String alleleId) { Objects.requireNonNull(alleleId); this.alleleId = alleleId; return this; } public Builder primaryInterpretation(ClinSig primaryInterpretation) { Objects.requireNonNull(primaryInterpretation); this.primaryInterpretation = primaryInterpretation; return this; } public Builder secondaryInterpretations(Set<ClinSig> secondaryInterpretations) { Objects.requireNonNull(secondaryInterpretations); this.secondaryInterpretations = secondaryInterpretations; return this; } public Builder reviewStatus(String reviewStatus) { Objects.requireNonNull(reviewStatus); this.reviewStatus = reviewStatus; return this; } public Builder includedAlleles(Map<String, ClinSig> includedAlleles) { Objects.requireNonNull(includedAlleles); this.includedAlleles = includedAlleles; return this; } public ClinVarData build() { return new ClinVarData(this); } } }
package org.eclipse.persistence.config; import org.eclipse.persistence.descriptors.ClassDescriptor; /** * PUBLIC: * This interface is to allow extra customization on a EclipseLink Session */ public interface DescriptorCustomizer { public void customize(ClassDescriptor descriptor) throws Exception; }
package de.stefanocke.japkit.roo.japkit; import java.util.Date; import javax.lang.model.element.Modifier; import javax.validation.constraints.NotNull; import de.stefanocke.japkit.annotations.RuntimeMetadata; import de.stefanocke.japkit.metaannotations.Annotation; import de.stefanocke.japkit.metaannotations.Case; import de.stefanocke.japkit.metaannotations.CodeFragment; import de.stefanocke.japkit.metaannotations.Constructor; import de.stefanocke.japkit.metaannotations.Field; import de.stefanocke.japkit.metaannotations.Getter; import de.stefanocke.japkit.metaannotations.InnerClass; import de.stefanocke.japkit.metaannotations.Matcher; import de.stefanocke.japkit.metaannotations.Method; import de.stefanocke.japkit.metaannotations.ParamNames; import de.stefanocke.japkit.metaannotations.Setter; import de.stefanocke.japkit.metaannotations.Template; import de.stefanocke.japkit.metaannotations.Var; import de.stefanocke.japkit.metaannotations.classselectors.ClassSelector; import de.stefanocke.japkit.metaannotations.classselectors.ClassSelectorKind; import de.stefanocke.japkit.metaannotations.classselectors.GeneratedClass; import de.stefanocke.japkit.metaannotations.classselectors.SrcType; @RuntimeMetadata @Template(vars = { @Var(name = "validationFragment", code = @CodeFragment(activation = @Matcher(annotations = NotNull.class), code = "if(#{src.simpleName}==null){\n" + " throw new IllegalArgumentException(\"#{src.simpleName} must not be null.\");\n" + "}")), @Var(name = "defensiveCopyFragment", code = @CodeFragment(imports = Date.class, cases = { @Case(matcher = @Matcher( type = Date.class), expr = "new Date(#{surrounded}.getTime())") }, linebreak = false)) // @Var(name = "tryFinallyTest", code = @CodeFragment(expr="try {\n" + // "#{surrounded}" + // "} finally {\n" + }) public abstract class ValueObjectTemplate { @InnerClass(fields = @Field(src = "#{properties}", modifiers = Modifier.PRIVATE, annotations = @Annotation(copyAnnotationsFromPackages = { "javax.persistence", "javax.validation.constraints", "org.springframework.format.annotation" }), getter = @Getter(fluent = true), setter = @Setter(fluent = true, chain = true), commentFromSrc = true)) @ClassSelector(kind = ClassSelectorKind.INNER_CLASS_NAME, enclosing = GeneratedClass.class) public static abstract class Builder { @ClassSelector(kind = ClassSelectorKind.EXPR, expr = "#{currentGenClass.enclosingElement.asType()}") abstract static class EnclosingClass { } @Method(bodyCode = "return new #{genElement.returnType.code}(this);") public abstract EnclosingClass build(); } @Field(src = "#{properties}", annotations = @Annotation(copyAnnotationsFromPackages = { "javax.persistence", "javax.validation.constraints", "org.springframework.format.annotation" }), commentFromSrc = true, getter = @Getter( fluent = true, surroundReturnExprFragments = "defensiveCopyFragment", commentExpr = "Getter for #{src.simpleName}. \n@returns #{src.simpleName}\n")) private SrcType $srcElementName$; @Constructor(bodyCode = "//Some ctor code") private ValueObjectTemplate() { }; @Constructor(vars = { @Var(name = "rhs", code = @CodeFragment(code = "builder.#{src.simpleName}", surroundingFragments = "defensiveCopyFragment", linebreak = false)), @Var(name = "assignment", code = @CodeFragment(code = "this.#{src.simpleName} = #{rhs.code()};", beforeFragments = "validationFragment")) }, bodyIterator = "properties", bodyCode = "assignment") @ParamNames("builder") private ValueObjectTemplate(Builder builder) { } }
package com.intellij.psi.impl.source.resolve.graphInference; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.Function; public class PsiPolyExpressionUtil { public static boolean hasStandaloneForm(PsiExpression expression) { return !(expression instanceof PsiFunctionalExpression) && !(expression instanceof PsiParenthesizedExpression) && !(expression instanceof PsiConditionalExpression) && !(expression instanceof PsiSwitchExpression) && !(expression instanceof PsiCallExpression); } public static boolean isPolyExpression(final PsiExpression expression) { if (expression instanceof PsiFunctionalExpression) { return true; } if (expression instanceof PsiParenthesizedExpression) { return isPolyExpression(((PsiParenthesizedExpression)expression).getExpression()); } if (expression instanceof PsiNewExpression && PsiDiamondType.hasDiamond((PsiNewExpression)expression)) { return isInAssignmentOrInvocationContext(expression); } if (expression instanceof PsiMethodCallExpression) { return isMethodCallPolyExpression(expression, expr -> ((PsiMethodCallExpression)expr).resolveMethod()); } if (expression instanceof PsiConditionalExpression) { final ConditionalKind conditionalKind = isBooleanOrNumeric(expression); if (conditionalKind == null) { return isInAssignmentOrInvocationContext(expression); } } if (expression instanceof PsiSwitchExpression) { return isInAssignmentOrInvocationContext(expression); } return false; } public static boolean isMethodCallPolyExpression(PsiExpression expression, final PsiMethod method) { return isMethodCallPolyExpression(expression, e -> method); } private static boolean isMethodCallPolyExpression(PsiExpression expression, Function<? super PsiExpression, ? extends PsiMethod> methodResolver) { if (isInAssignmentOrInvocationContext(expression) && ((PsiCallExpression)expression).getTypeArguments().length == 0) { PsiMethod method = methodResolver.apply(expression); return method == null || isMethodCallTypeDependsOnInference(expression, method); } return false; } private static boolean isMethodCallTypeDependsOnInference(PsiExpression expression, PsiMethod method) { final Set<PsiTypeParameter> typeParameters = new HashSet<>(Arrays.asList(method.getTypeParameters())); if (!typeParameters.isEmpty()) { final PsiType returnType = method.getReturnType(); if (returnType != null) { return mentionsTypeParameters(returnType, typeParameters); } } else if (method.isConstructor() && expression instanceof PsiNewExpression && PsiDiamondType.hasDiamond((PsiNewExpression)expression)) { return true; } return false; } public static Boolean mentionsTypeParameters(@Nullable PsiType returnType, final Set<PsiTypeParameter> typeParameters) { if (returnType == null) return false; return returnType.accept(new PsiTypeVisitor<Boolean>() { @NotNull @Override public Boolean visitType(PsiType type) { return false; } @Nullable @Override public Boolean visitWildcardType(PsiWildcardType wildcardType) { final PsiType bound = wildcardType.getBound(); if (bound != null) { return bound.accept(this); } return false; } @NotNull @Override public Boolean visitClassType(PsiClassType classType) { PsiClassType.ClassResolveResult result = classType.resolveGenerics(); final PsiClass psiClass = result.getElement(); if (psiClass != null) { PsiSubstitutor substitutor = result.getSubstitutor(); for (PsiTypeParameter parameter : PsiUtil.typeParametersIterable(psiClass)) { PsiType type = substitutor.substitute(parameter); if (type != null && type.accept(this)) return true; } } return psiClass instanceof PsiTypeParameter && typeParameters.contains(psiClass); } @Nullable @Override public Boolean visitArrayType(PsiArrayType arrayType) { return arrayType.getComponentType().accept(this); } }); } private static boolean isInAssignmentOrInvocationContext(PsiExpression expr) { final PsiElement context = PsiUtil.skipParenthesizedExprUp(expr.getParent()); return context instanceof PsiExpressionList || context instanceof PsiArrayInitializerExpression || context instanceof PsiConditionalExpression && (expr instanceof PsiCallExpression || isPolyExpression((PsiExpression)context)) || isSwitchExpressionAssignmentOrInvocationContext(expr) || isAssignmentContext(expr, context); } private static boolean isSwitchExpressionAssignmentOrInvocationContext(PsiExpression expr) { PsiElement parent = PsiUtil.skipParenthesizedExprUp(expr).getParent(); if (parent instanceof PsiExpressionStatement && parent.getParent() instanceof PsiSwitchLabeledRuleStatement || parent instanceof PsiBreakStatement || parent instanceof PsiThrowStatement) { PsiSwitchExpression switchExpression = PsiTreeUtil.getParentOfType(expr, PsiSwitchExpression.class, true, PsiMember.class, PsiLambdaExpression.class); return switchExpression != null && PsiUtil.getSwitchResultExpressions(switchExpression).contains(expr) && isInAssignmentOrInvocationContext(switchExpression); } return false; } private static boolean isAssignmentContext(PsiExpression expr, PsiElement context) { return PsiUtil.isCondition(expr, context) || context instanceof PsiReturnStatement || context instanceof PsiAssignmentExpression && ((PsiAssignmentExpression)context).getOperationTokenType() == JavaTokenType.EQ || context instanceof PsiVariable && !isVarContext((PsiVariable)context) || context instanceof PsiLambdaExpression; } private static boolean isVarContext(PsiVariable variable) { if (PsiUtil.isLanguageLevel10OrHigher(variable)) { PsiTypeElement typeElement = variable.getTypeElement(); if (typeElement != null && typeElement.isInferredType()) { return true; } } return false; } public static boolean isExpressionOfPrimitiveType(@Nullable PsiExpression arg) { if (arg != null && !isPolyExpression(arg)) { final PsiType type = arg.getType(); return type instanceof PsiPrimitiveType && type != PsiType.NULL; } else if (arg instanceof PsiNewExpression || arg instanceof PsiFunctionalExpression) { return false; } else if (arg instanceof PsiParenthesizedExpression) { return isExpressionOfPrimitiveType(((PsiParenthesizedExpression)arg).getExpression()); } else if (arg instanceof PsiConditionalExpression) { return isBooleanOrNumeric(arg) != null; } else if (arg instanceof PsiMethodCallExpression) { final PsiMethod method = ((PsiMethodCallExpression)arg).resolveMethod(); return method != null && method.getReturnType() instanceof PsiPrimitiveType; } else if (arg instanceof PsiSwitchExpression) { return isBooleanOrNumeric(arg) != null; } else { assert false : arg; return false; } } private enum ConditionalKind { BOOLEAN, NUMERIC, NULL } private static ConditionalKind isBooleanOrNumeric(PsiExpression expr) { if (expr instanceof PsiParenthesizedExpression) { return isBooleanOrNumeric(((PsiParenthesizedExpression)expr).getExpression()); } if (expr == null) return null; PsiType type = null; //A class instance creation expression (p15.9) for a class that is convertible to a numeric type. //As numeric classes do not have type parameters, at this point expressions with diamonds could be ignored if (expr instanceof PsiNewExpression && !PsiDiamondType.hasDiamond((PsiNewExpression)expr) || hasStandaloneForm(expr)) { type = expr.getType(); } else if (expr instanceof PsiMethodCallExpression) { final PsiMethod method = ((PsiMethodCallExpression)expr).resolveMethod(); if (method != null) { type = method.getReturnType(); } } final ConditionalKind kind = isBooleanOrNumericType(type); if (kind != null) { return kind; } if (expr instanceof PsiConditionalExpression) { final PsiExpression thenExpression = ((PsiConditionalExpression)expr).getThenExpression(); final PsiExpression elseExpression = ((PsiConditionalExpression)expr).getElseExpression(); final ConditionalKind thenKind = isBooleanOrNumeric(thenExpression); final ConditionalKind elseKind = isBooleanOrNumeric(elseExpression); if (thenKind == elseKind || elseKind == ConditionalKind.NULL) return thenKind; if (thenKind == ConditionalKind.NULL) return elseKind; } if (expr instanceof PsiSwitchExpression) { ConditionalKind switchKind = null; for (PsiExpression resultExpression : PsiUtil.getSwitchResultExpressions((PsiSwitchExpression)expr)) { ConditionalKind resultKind = isBooleanOrNumeric(resultExpression); if (resultKind == null) return null; if (switchKind == null) { switchKind = resultKind; } else if (switchKind != resultKind) { if (switchKind == ConditionalKind.NULL) { switchKind = resultKind; } else if (resultKind != ConditionalKind.NULL) { return null; } } } } return null; } @Nullable private static ConditionalKind isBooleanOrNumericType(PsiType type) { if (type == PsiType.NULL) { return ConditionalKind.NULL; } final PsiClass psiClass = PsiUtil.resolveClassInClassTypeOnly(type); if (TypeConversionUtil.isNumericType(type)) return ConditionalKind.NUMERIC; if (TypeConversionUtil.isBooleanType(type)) return ConditionalKind.BOOLEAN; if (psiClass instanceof PsiTypeParameter) { for (PsiClassType classType : psiClass.getExtendsListTypes()) { final ConditionalKind kind = isBooleanOrNumericType(classType); if (kind != null) { return kind; } } } return null; } }
package com.ore.infinium; import com.badlogic.ashley.core.ComponentMapper; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.core.PooledEngine; import com.badlogic.ashley.utils.ImmutableArray; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.ore.infinium.components.*; import com.ore.infinium.systems.*; import java.util.HashMap; public class World implements Disposable { public static final float PIXELS_PER_METER = 50.0f; public static final float GRAVITY_ACCEL = 9.8f / PIXELS_PER_METER / 3.0f; public static final float GRAVITY_ACCEL_CLAMP = 9.8f / PIXELS_PER_METER / 3.0f; public static final float BLOCK_SIZE = (16.0f / PIXELS_PER_METER); public static final float BLOCK_SIZE_PIXELS = 16.0f; public static final int WORLD_COLUMNCOUNT = 1000; //2400 public static final int WORLD_ROWCOUNT = 1000; //8400 public static final int WORLD_SEA_LEVEL = 50; public static final HashMap<Block.BlockType, BlockStruct> blockTypes = new HashMap<>(); static { blockTypes.put(Block.BlockType.NullBlockType, new BlockStruct("", false)); blockTypes.put(Block.BlockType.DirtBlockType, new BlockStruct("dirt", true)); blockTypes.put(Block.BlockType.StoneBlockType, new BlockStruct("stone", true)); } private static final int zoomInterval = 50; private static OreTimer m_zoomTimer = new OreTimer(); public Block[] blocks; public PooledEngine engine; public Array<Entity> m_players = new Array<>(); public Entity m_mainPlayer; public OreServer m_server; public AssetManager assetManager; public OreClient m_client; public OrthographicCamera m_camera; //fixme remove in favor of the render system public TextureAtlas m_atlas; protected TileRenderer m_tileRenderer; PowerOverlayRenderSystem m_powerOverlaySystem; private ComponentMapper<PlayerComponent> playerMapper = ComponentMapper.getFor(PlayerComponent.class); private ComponentMapper<SpriteComponent> spriteMapper = ComponentMapper.getFor(SpriteComponent.class); private ComponentMapper<ControllableComponent> controlMapper = ComponentMapper.getFor(ControllableComponent.class); private ComponentMapper<ItemComponent> itemMapper = ComponentMapper.getFor(ItemComponent.class); private ComponentMapper<VelocityComponent> velocityMapper = ComponentMapper.getFor(VelocityComponent.class); private ComponentMapper<JumpComponent> jumpMapper = ComponentMapper.getFor(JumpComponent.class); private ComponentMapper<BlockComponent> blockMapper = ComponentMapper.getFor(BlockComponent.class); private ComponentMapper<AirGeneratorComponent> airGeneratorMapper = ComponentMapper.getFor(AirGeneratorComponent.class); private ComponentMapper<ToolComponent> toolMapper = ComponentMapper.getFor(ToolComponent.class); private ComponentMapper<AirComponent> airMapper = ComponentMapper.getFor(AirComponent.class); private ComponentMapper<TagComponent> tagMapper = ComponentMapper.getFor(TagComponent.class); private ComponentMapper<HealthComponent> healthMapper = ComponentMapper.getFor(HealthComponent.class); private ComponentMapper<TorchComponent> torchMapper = ComponentMapper.getFor(TorchComponent.class); private boolean m_noClipEnabled; private Entity m_blockPickingCrosshair; private Entity m_itemPlacementGhost; private com.artemis.World artemisWorld; public World(OreClient client, OreServer server) { m_client = client; m_server = server; if (isClient()) { float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); } blocks = new Block[WORLD_ROWCOUNT * WORLD_COLUMNCOUNT]; // assetManager = new AssetManager(); // TextureAtlas m_blockAtlas = assetManager.get("data/", TextureAtlas.class); // assetManager.finishLoading(); engine = new PooledEngine(2000, 2000, 2000, 2000); engine.addSystem(new MovementSystem(this)); engine.addSystem(new PlayerSystem(this)); m_camera = new OrthographicCamera(1600 / World.PIXELS_PER_METER, 900 / World.PIXELS_PER_METER);//30, 30 * (h / w)); m_camera.setToOrtho(true, 1600 / World.PIXELS_PER_METER, 900 / World.PIXELS_PER_METER); // m_camera.position.set(m_camera.viewportWidth / 2f, m_camera.viewportHeight / 2f, 0); assert isClient() ^ isServer(); if (isClient()) { m_atlas = new TextureAtlas(Gdx.files.internal("packed/entities.atlas")); initializeWorld(); m_blockPickingCrosshair = engine.createEntity(); TagComponent tagComponent = engine.createComponent(TagComponent.class); tagComponent.tag = "crosshair"; m_blockPickingCrosshair.add(tagComponent); SpriteComponent spriteComponent = engine.createComponent(SpriteComponent.class); m_blockPickingCrosshair.add(spriteComponent); spriteComponent.sprite.setSize(BLOCK_SIZE, BLOCK_SIZE); spriteComponent.sprite.setRegion(m_atlas.findRegion("crosshair-blockpicking")); } if (isServer()) { generateWorld(); } } protected void clientInventoryItemSelected() { assert !isServer(); PlayerComponent playerComponent = playerMapper.get(m_mainPlayer); Entity entity = playerComponent.equippedPrimaryItem(); if (entity == null) { return; } if (m_itemPlacementGhost != null) { engine.removeEntity(m_itemPlacementGhost); } //this item is placeable, show a ghost of it so we can see where we're going to place it m_itemPlacementGhost = cloneEntity(entity); ItemComponent itemComponent = itemMapper.get(m_itemPlacementGhost); itemComponent.state = ItemComponent.State.InWorldState; SpriteComponent spriteComponent = spriteMapper.get(m_itemPlacementGhost); TagComponent tag = engine.createComponent(TagComponent.class); tag.tag = "itemPlacementGhost"; m_itemPlacementGhost.add(tag); engine.addEntity(m_itemPlacementGhost); } public void initServer() { } public void initClient(Entity mainPlayer) { m_mainPlayer = mainPlayer; // velocityMapper.get(m_mainPlayer); engine.addSystem(m_tileRenderer = new TileRenderer(m_camera, this, 1f / 60f)); engine.addSystem(new SpriteRenderSystem(this)); engine.addSystem(m_powerOverlaySystem = new PowerOverlayRenderSystem(this)); SpriteComponent playerSprite = spriteMapper.get(m_mainPlayer); playerSprite.sprite.setRegion(m_atlas.findRegion("player-32x64")); playerSprite.sprite.flip(false, true); } /** * adding entity to the world is callers responsibility * * @param playerName * @param connectionId * @return */ public Entity createPlayer(String playerName, int connectionId) { Entity player = engine.createEntity(); SpriteComponent playerSprite = engine.createComponent(SpriteComponent.class); player.add(playerSprite); player.add(engine.createComponent(VelocityComponent.class)); PlayerComponent playerComponent = engine.createComponent(PlayerComponent.class); playerComponent.connectionId = connectionId; playerComponent.noClip = m_noClipEnabled; playerComponent.playerName = playerName; playerComponent.loadedViewport.setRect(new Rectangle(0, 0, LoadedViewport.MAX_VIEWPORT_WIDTH, LoadedViewport.MAX_VIEWPORT_HEIGHT)); playerComponent.loadedViewport.centerOn(new Vector2(playerSprite.sprite.getX(), playerSprite.sprite.getY())); player.add(playerComponent); playerSprite.sprite.setSize(World.BLOCK_SIZE * 2, World.BLOCK_SIZE * 3); player.add(engine.createComponent(ControllableComponent.class)); playerSprite.textureName = "player1Standing1"; playerSprite.category = SpriteComponent.EntityCategory.Character; player.add(engine.createComponent(JumpComponent.class)); HealthComponent healthComponent = engine.createComponent(HealthComponent.class); healthComponent.health = healthComponent.maxHealth; player.add(healthComponent); AirComponent airComponent = engine.createComponent(AirComponent.class); airComponent.air = airComponent.maxAir; player.add(airComponent); return player; } private void generateWorld() { generateOres(); } private void initializeWorld() { for (int x = 0; x < WORLD_COLUMNCOUNT; ++x) { for (int y = 0; y < WORLD_ROWCOUNT; ++y) { int index = x * WORLD_ROWCOUNT + y; blocks[index] = new Block(); blocks[index].blockType = Block.BlockType.StoneBlockType; } } } private void generateOres() { for (int x = 0; x < WORLD_COLUMNCOUNT; ++x) { for (int y = 0; y < WORLD_ROWCOUNT; ++y) { int index = x * WORLD_ROWCOUNT + y; //java wants me to go through each and every block and initialize them.. blocks[index] = new Block(); blocks[index].blockType = Block.BlockType.NullBlockType; //create some sky if (y <= seaLevel()) { continue; } switch (MathUtils.random(0, 3)) { case 0: blocks[index].blockType = Block.BlockType.NullBlockType; break; case 1: blocks[index].blockType = Block.BlockType.DirtBlockType; break; case 2: blocks[index].blockType = Block.BlockType.StoneBlockType; break; } // blocks[dragSourceIndex].wallType = Block::Wall } } // for (int x = 0; x < WORLD_COLUMNCOUNT; ++x) { // for (int y = seaLevel(); y < WORLD_ROWCOUNT; ++y) { // Block block = blockAt(x, y); // block.blockType = Block.BlockType.DirtBlockType; } public boolean isServer() { return m_server != null; } public boolean isClient() { return m_client != null; } public Block blockAtPosition(Vector2 pos) { return blockAt((int) (pos.x / BLOCK_SIZE), (int) (pos.y / BLOCK_SIZE)); } public Block blockAt(int x, int y) { assert x >= 0 && y >= 0 && x <= WORLD_COLUMNCOUNT && y <= WORLD_ROWCOUNT; return blocks[x * WORLD_ROWCOUNT + y]; } public boolean isBlockSolid(int x, int y) { boolean solid = true; Block.BlockType type = blockAt(x, y).blockType; if (type == Block.BlockType.NullBlockType) { solid = false; } return solid; } public boolean canPlaceBlock(int x, int y) { boolean canPlace = blockAt(x, y).blockType == Block.BlockType.NullBlockType; //TODO: check collision with other entities... return canPlace; } public void dispose() { } public void zoom(float factor) { m_camera.zoom *= factor; } public void update(double elapsed) { if (isClient()) { if (m_mainPlayer == null) { return; } // playerSprite.sprite.setOriginCenter(); // m_camera.position.set(playerSprite.sprite.getX() + playerSprite.sprite.getWidth() * 0.5f, playerSprite.sprite.getY() + playerSprite.sprite.getHeight() * 0.5f, 0); final float zoomAmount = 0.004f; if (Gdx.input.isKeyPressed(Input.Keys.MINUS)) { if (m_zoomTimer.milliseconds() >= zoomInterval) { //zoom out zoom(1.0f + zoomAmount); m_zoomTimer.reset(); } } if (Gdx.input.isKeyPressed(Input.Keys.EQUALS)) { if (m_zoomTimer.milliseconds() >= zoomInterval) { zoom(1.0f - zoomAmount); m_zoomTimer.reset(); } } updateCrosshair(); updateItemPlacementGhost(); } if (isServer()) { } //todo explicitly call update on systems, me thinks...otherwise the render and update steps are coupled engine.update((float) elapsed); } private void handleLeftMousePrimaryAttack() { Vector2 mouse = mousePositionWorldCoords(); PlayerComponent playerComponent = playerMapper.get(m_mainPlayer); Entity item = playerComponent.equippedPrimaryItem(); if (item == null) { return; } ToolComponent toolComponent = toolMapper.get(item); if (toolComponent != null) { if (toolComponent.type != ToolComponent.ToolType.Drill) { return; } int x = (int) (mouse.x / BLOCK_SIZE); int y = (int) (mouse.y / BLOCK_SIZE); Block block = blockAt(x, y); //attempt to destroy it if it's not already destroyed... if (block.blockType != Block.BlockType.NullBlockType) { block.blockType = Block.BlockType.NullBlockType; m_client.sendBlockPick(x, y); } //action performed return; } BlockComponent blockComponent = blockMapper.get(item); if (blockComponent != null) { int x = (int) (mouse.x / BLOCK_SIZE); int y = (int) (mouse.y / BLOCK_SIZE); Block block = blockAt(x, y); //attempt to place one if the area is empty if (block.blockType == Block.BlockType.NullBlockType) { block.blockType = blockComponent.blockType; m_client.sendBlockPlace(x, y); } //action performed return; } ItemComponent itemComponent = itemMapper.get(item); if (itemComponent != null) { //place the item Entity placedItem = cloneEntity(playerComponent.equippedPrimaryItem()); ItemComponent placedItemComponent = itemMapper.get(placedItem); placedItemComponent.state = ItemComponent.State.InWorldState; SpriteComponent spriteComponent = spriteMapper.get(placedItem); spriteComponent.sprite.setPosition(mouse.x, mouse.y); engine.addEntity(placedItem); //hack, do more validation.. m_client.sendItemPlace(mouse.x, mouse.y); } } public void render(double elapsed) { if (m_mainPlayer == null) { return; } // m_camera.zoom *= 0.9; //m_lightRenderer->renderToFBO(); if (m_client.m_renderTiles) { //m_tileRenderer.render(elapsed); } else { } //FIXME: incorporate entities into the pre-lit gamescene FBO, then render lighting as last pass //m_lightRenderer->renderToBackbuffer(); //FIXME: take lighting into account, needs access to fbos though. // m_fluidRenderer->render(); // m_particleRenderer->render(); //FIXME unused m_quadTreeRenderer->render(); updateCrosshair(); updateItemPlacementGhost(); } private void updateCrosshair() { //PlayerComponent playerComponent = playerMapper.get(m_mainPlayer); //playerComponent SpriteComponent spriteComponent = spriteMapper.get(m_blockPickingCrosshair); Vector2 mouse = mousePositionWorldCoords(); Vector2 crosshairPosition = new Vector2(BLOCK_SIZE * MathUtils.floor(mouse.x / BLOCK_SIZE), BLOCK_SIZE * MathUtils.floor(mouse.y / BLOCK_SIZE)); Vector2 crosshairOriginOffset = new Vector2(spriteComponent.sprite.getWidth() * 0.5f, spriteComponent.sprite.getHeight() * 0.5f); Vector2 crosshairFinalPosition = crosshairPosition.add(crosshairOriginOffset); spriteComponent.sprite.setPosition(crosshairFinalPosition.x, crosshairFinalPosition.y); } private Vector2 mousePositionWorldCoords() { Vector3 mouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0f); Vector3 finalMouse = m_camera.unproject(mouse); return new Vector2(finalMouse.x, finalMouse.y); } private void updateItemPlacementGhost() { if (m_itemPlacementGhost == null) { return; } Vector2 mouse = mousePositionWorldCoords(); alignPositionToBlocks(mouse); SpriteComponent spriteComponent = spriteMapper.get(m_itemPlacementGhost); spriteComponent.sprite.setPosition(mouse.x, mouse.y); spriteComponent.placementValid = isPlacementValid(m_itemPlacementGhost); } private void alignPositionToBlocks(Vector2 pos) { pos.set(BLOCK_SIZE * MathUtils.floor(pos.x / BLOCK_SIZE), BLOCK_SIZE * MathUtils.floor(pos.y / BLOCK_SIZE)); } public int seaLevel() { return WORLD_SEA_LEVEL; } public void createBlockItem(Entity block) { block.add(engine.createComponent(VelocityComponent.class)); BlockComponent blockComponent = engine.createComponent(BlockComponent.class); blockComponent.blockType = Block.BlockType.StoneBlockType; block.add(blockComponent); SpriteComponent blockSprite = engine.createComponent(SpriteComponent.class); blockSprite.textureName = blockTypes.get(blockComponent.blockType).textureName; //warning fixme size is fucked blockSprite.sprite.setSize(32 / World.PIXELS_PER_METER, 32 / World.PIXELS_PER_METER); block.add(blockSprite); ItemComponent itemComponent = engine.createComponent(ItemComponent.class); itemComponent.stackSize = 800; itemComponent.maxStackSize = 900; block.add(itemComponent); } public Entity createAirGenerator() { Entity air = engine.createEntity(); ItemComponent itemComponent = engine.createComponent(ItemComponent.class); itemComponent.stackSize = 800; itemComponent.maxStackSize = 900; air.add(itemComponent); SpriteComponent airSprite = engine.createComponent(SpriteComponent.class); airSprite.textureName = "air-generator-64x64"; //warning fixme size is fucked airSprite.sprite.setSize(BLOCK_SIZE * 4, BLOCK_SIZE * 4); air.add(airSprite); AirGeneratorComponent airComponent = engine.createComponent(AirGeneratorComponent.class); airComponent.airOutputRate = 100; air.add(airComponent); return air; } private boolean isPlacementValid(Entity entity) { SpriteComponent spriteComponent = spriteMapper.get(entity); Vector2 pos = new Vector2(spriteComponent.sprite.getX(), spriteComponent.sprite.getY()); Vector2 size = new Vector2(spriteComponent.sprite.getWidth(), spriteComponent.sprite.getHeight()); float epsilon = 0.001f; int startX = (int) ((pos.x - (size.x * 0.5f)) / BLOCK_SIZE + epsilon); int startY = (int) ((pos.y - (size.y * 0.5f)) / BLOCK_SIZE + epsilon); int endX = (int) ((pos.x + (size.x * 0.5f)) / BLOCK_SIZE + 0); int endY = (int) ((pos.y + (size.y * 0.5f - epsilon)) / BLOCK_SIZE + 1); if (!(startX >= 0 && startY >= 0 && endX <= WORLD_COLUMNCOUNT && endY <= WORLD_ROWCOUNT)) { //fixme //not sure why, but this ends up giving me some way way invalid values. likely due to mouse being outside //of valid range, *somehow*. sometimes does it on startup etc return false; } for (int column = startX; column < endX; ++column) { for (int row = startY; row < endY; ++row) { if (blockAt(column, row).blockType != Block.BlockType.NullBlockType) { return false; } } } //float x = Math.min(pos.x - (BLOCK_SIZE * 20), 0.0f); //float y = Math.min(pos.y - (BLOCK_SIZE * 20), 0.0f); //float x2 = Math.min(pos.x + (BLOCK_SIZE * 20), WORLD_COLUMNCOUNT * BLOCK_SIZE); //float y2 = Math.min(pos.y + (BLOCK_SIZE * 20), WORLD_ROWCOUNT * BLOCK_SIZE); ImmutableArray<Entity> entities = engine.getEntitiesFor(Family.all(SpriteComponent.class).get()); for (int i = 0; i < entities.size(); ++i) { //it's us, don't count a collision with ourselves if (entities.get(i) == entity) { continue; } //ignore players, aka don't count them as colliding when placing static objects. // if (e.has_component<PlayerComponent>()) { // continue; ItemComponent itemComponent = itemMapper.get(entities.get(i)); if (itemComponent != null) { if (itemComponent.state == ItemComponent.State.DroppedInWorld) { continue; } } if (entityCollides(entities.get(i), entity)) { return false; } } return true; } private boolean entityCollides(Entity first, Entity second) { SpriteComponent spriteComponent1 = spriteMapper.get(first); SpriteComponent spriteComponent2 = spriteMapper.get(second); Vector2 pos1 = new Vector2(spriteComponent1.sprite.getX(), spriteComponent1.sprite.getY()); Vector2 pos2 = new Vector2(spriteComponent2.sprite.getX(), spriteComponent2.sprite.getY()); Vector2 size1 = new Vector2(spriteComponent1.sprite.getWidth(), spriteComponent1.sprite.getHeight()); Vector2 size2 = new Vector2(spriteComponent2.sprite.getWidth(), spriteComponent2.sprite.getHeight()); float epsilon = 0.0001f; float left1 = pos1.x - (size1.x * 0.5f) + epsilon; float right1 = pos1.x + (size1.x * 0.5f) - epsilon; float top1 = pos1.y - (size1.y * 0.5f) + epsilon; float bottom1 = pos1.y + (size1.y * 0.5f) - epsilon; float left2 = pos2.x - (size2.x * 0.5f) + epsilon; float right2 = pos2.x + (size2.x * 0.5f) - epsilon; float top2 = pos2.y - (size2.y * 0.5f) + epsilon; float bottom2 = pos2.y + (size2.y * 0.5f) - epsilon; boolean collides = !(left2 > right1 || right2 < left1 || top2 > bottom1 || bottom2 < top1); return collides; } public void loadBlockRegion(Network.BlockRegion region) { int sourceIndex = 0; for (int row = region.y; row < region.y2; ++row) { for (int col = region.x; col < region.x2; ++col) { int index = col * WORLD_ROWCOUNT + row; Block origBlock = blocks[index]; Network.SingleBlock srcBlock = region.blocks.get(sourceIndex); origBlock.blockType = srcBlock.blockType; //fixme wall type as well ++sourceIndex; } } } /** * Clone everything about the entity. Does *not* add it to the engine * * @param entity to clone * @return the cloned entity */ public Entity cloneEntity(Entity entity) { Entity clonedEntity = engine.createEntity(); //sorted alphabetically for your pleasure AirComponent airComponent = airMapper.get(entity); if (airComponent != null) { AirComponent clonedComponent = new AirComponent(airComponent); clonedEntity.add(clonedComponent); } AirGeneratorComponent airGeneratorComponent = airGeneratorMapper.get(entity); if (airGeneratorComponent != null) { AirGeneratorComponent clonedComponent = new AirGeneratorComponent(airGeneratorComponent); clonedEntity.add(clonedComponent); } BlockComponent blockComponent = blockMapper.get(entity); if (blockComponent != null) { BlockComponent clonedComponent = new BlockComponent(blockComponent); clonedEntity.add(clonedComponent); } ControllableComponent controllableComponent = controlMapper.get(entity); if (controllableComponent != null) { ControllableComponent clonedComponent = new ControllableComponent(controllableComponent); clonedEntity.add(clonedComponent); } HealthComponent healthComponent = healthMapper.get(entity); if (healthComponent != null) { HealthComponent clonedComponent = new HealthComponent(healthComponent); clonedEntity.add(clonedComponent); } ItemComponent itemComponent = itemMapper.get(entity); if (itemComponent != null) { ItemComponent clonedComponent = new ItemComponent(itemComponent); clonedEntity.add(clonedComponent); } JumpComponent jumpComponent = jumpMapper.get(entity); if (jumpComponent != null) { JumpComponent clonedComponent = new JumpComponent(jumpComponent); clonedEntity.add(clonedComponent); } //player, unneeded assert playerMapper.get(entity) == null; SpriteComponent spriteComponent = spriteMapper.get(entity); if (spriteComponent != null) { SpriteComponent clonedComponent = new SpriteComponent(spriteComponent); clonedEntity.add(clonedComponent); } TagComponent tagComponent = tagMapper.get(entity); if (tagComponent != null) { TagComponent clonedComponent = new TagComponent(tagComponent); clonedEntity.add(clonedComponent); } ToolComponent toolComponent = toolMapper.get(entity); if (toolComponent != null) { ToolComponent clonedComponent = new ToolComponent(toolComponent); clonedEntity.add(clonedComponent); } TorchComponent torchComponent = torchMapper.get(entity); if (torchComponent != null) { TorchComponent clonedComponent = new TorchComponent(torchComponent); clonedEntity.add(clonedComponent); } VelocityComponent velocityComponent = velocityMapper.get(entity); if (velocityComponent != null) { VelocityComponent clonedComponent = new VelocityComponent(velocityComponent); clonedEntity.add(clonedComponent); } return clonedEntity; } public void addPlayer(Entity player) { m_players.add(player); } public Entity playerForID(int playerIdWhoDropped) { assert !isClient(); ImmutableArray<Entity> entities = engine.getEntitiesFor(Family.all(PlayerComponent.class).get()); PlayerComponent playerComponent; for (int i = 0; i < entities.size(); ++i) { playerComponent = playerMapper.get(entities.get(i)); if (playerComponent.connectionId == playerIdWhoDropped) { return entities.get(i); } } throw new IllegalStateException("player id attempted to be obtained from item, but this player does not exist"); } public boolean touchDown(int screenX, int screenY, int pointer, int button) { if (button != Input.Buttons.LEFT) { return false; } if (m_powerOverlaySystem.overlayVisible) { m_powerOverlaySystem.leftMouseReleased(); return true; } else { handleLeftMousePrimaryAttack(); return true; } //return false; } public boolean touchUp(int screenX, int screenY, int pointer, int button) { if (button != Input.Buttons.LEFT) { return false; } if (m_powerOverlaySystem.overlayVisible) { m_powerOverlaySystem.leftMouseReleased(); return true; } else { } return false; } public static class BlockStruct { public String textureName; //e.g. "dirt", "stone", etc. boolean collides; BlockStruct(String _textureName, boolean _collides) { textureName = _textureName; collides = _collides; } } }
package com.ch; import com.ch.components.FreeLook; import com.ch.components.FreeMove; import com.ch.components.GameComponent; import com.ch.core.renderer.Renderer3D; import com.ch.core.scene.Scene; import com.ch.core.GameObject; import com.ch.core.Window; import com.ch.math.Matrix4f; import com.ch.math.Quaternion; import com.ch.math.Vector3f; import com.ch.rendering.Material; import com.ch.rendering.Mesh; import com.ch.rendering.Texture; import com.ch.rendering.components.Camera; import com.ch.rendering.components.Camera3D; import com.ch.rendering.components.MeshRenderer; import com.ch.rendering.components.light.DirectionalLight; import com.ch.rendering.components.light.PointLight; import com.ch.rendering.light.Attenuation; import com.tp.physics.RigidBody; public class TestGame extends Scene { public void init() { setMainRenderer(new Renderer3D()); Mesh mesh = new Mesh("plane3.obj"); Material material2 = new Material(new Texture("crate.png"), 1f, 1, new Texture("crate_normal.png"), new Texture("default_disp.png"), 0.03f, -0.5f); Material material1 = new Material(new Texture("bricks2.jpg"), .3f, 1, new Texture("bricks2_normal.jpg"), new Texture("bricks2_disp.jpg"), .03f, -.50f); Material material = new Material(new Texture("bricks.jpg"), .3f, 1, new Texture("bricks_normal.jpg"), new Texture("bricks_disp.png"), 0.04f, -1.0f); Mesh tempMesh = new Mesh("crate.obj"); MeshRenderer meshRenderer = new MeshRenderer(mesh, material1); GameObject planeObject = new GameObject(); planeObject.addComponent(meshRenderer); planeObject.getTransform().getPos().set(0, 0, 0); // planeObject.getTransform().getScale().set(3, 3, 3); GameObject directionalLightObject = new GameObject(); DirectionalLight directionalLight = new DirectionalLight(new Vector3f(1f, 1f, 1f), 1f); directionalLightObject.addComponent(directionalLight); directionalLight.getTransform().rotate(new Vector3f(0, 0, 1), (float) Math.toRadians(0)); addObject(directionalLightObject); // GameObject pointLightObject = new GameObject(); // PointLight l = new PointLight(new Vector3f(1, 1, 0.7f), 400f, new Attenuation(0, 0, 1f)) { // @Override // public void update(float dt) { // this.color = this.color.lerp(new Vector3f((float) Math.random(), (float) Math.random(), (float) Math.random()), .1f); // super.update(dt); // pointLightObject.addComponent(l); // addObject(pointLightObject); // pointLightObject.getTransform().getPos().set(0, 10, 0); GameObject pointLightObject = new GameObject(); pointLightObject.addComponent(new PointLight(new Vector3f(0, 0.4f, .9f), .4f, new Attenuation(0, 0, .1f))); addObject(pointLightObject); pointLightObject.getTransform().getPos().set(0, 2, 0); // GameObject pointLightObject1 = new GameObject(); // pointLightObject1.addComponent(new PointLight(new Vector3f(1, .7f, 0), .4f, new Attenuation(0, 0, .1f))); // addObject(pointLightObject1); // pointLightObject1.getTransform().getPos().set(3, 2, 0); // GameObject pointLightObject2 = new GameObject(); // pointLightObject2.addComponent(new PointLight(new Vector3f(0, 0, 1), .4f, new Attenuation(0, 0, .1f))); // addObject(pointLightObject2); // pointLightObject2.getTransform().getPos().set(-3, 2f, 0); // GameObject pointLightObject3 = new GameObject(); // pointLightObject3.addComponent(new PointLight(new Vector3f(1, 0.4f, 0), .4f, new Attenuation(0, 0, .1f))); // addObject(pointLightObject3); // pointLightObject3.getTransform().getPos().set(6, 2, 0); // GameObject pointLightObject4 = new GameObject(); // pointLightObject4.addComponent(new PointLight(new Vector3f(1, 0.1f, 0.9f), .4f, new Attenuation(0, 0, .1f))); // addObject(pointLightObject4); // pointLightObject4.getTransform().getPos().set(-6, 2, 0); // SpotLight spotLight = new SpotLight(new Vector3f(1, 0.6f, 0.0f), 10f, new Attenuation(0, 0, 1f), .8f); // GameObject spotLightObject = new GameObject(); // spotLightObject.addComponent(spotLight); // spotLightObject.getTransform().getPos().set(0, 2, 5); // spotLightObject.getTransform().setRot(new Quaternion(new Vector3f(1, 0, 0), (float) Math.toRadians(90.0f))); // spotLightObject.getTransform().rotate(new Vector3f(0, 0, 1), (float) Math.toRadians(-30.0f)); // spotLightObject.addComponent(new GameComponent() { // float time = 0; // @Override // public void update(float dt) { // // time += dt; // getTransform().rotate(new Vector3f(0, 0, 1), 2 * dt); // addObject(spotLightObject); // SpotLight spotLight1 = new SpotLight(new Vector3f(0, 0.6f, 0.8f), 10f, new Attenuation(0, 0, 1f), .8f); // GameObject spotLightObject1 = new GameObject(); // spotLightObject1.addComponent(spotLight1); // spotLightObject1.getTransform().getPos().set(0, 2, 5); // spotLightObject1.getTransform().setRot(new Quaternion(new Vector3f(1, 0, 0), (float) Math.toRadians(90.0f))); // spotLightObject1.getTransform().rotate(new Vector3f(0, 0, 1), (float) Math.toRadians(30.0f)); // spotLightObject1.addComponent(new GameComponent() { // float time = 0; // @Override // public void update(float dt) { // // time += dt; // getTransform().rotate(new Vector3f(0, 0, 1), 2f * dt); // addObject(spotLightObject1); // SpotLight spotLight2 = new SpotLight(new Vector3f(0.9f, 0.3f, 0.2f), 10f, new Attenuation(0, 0, 1f), .8f); // GameObject spotLightObject2 = new GameObject(); // spotLightObject2.addComponent(spotLight2); // spotLightObject2.getTransform().getPos().set(0, 2, 5); // spotLightObject2.getTransform().setRot(new Quaternion(new Vector3f(1, 0, 0), (float) Math.toRadians(90.0f))); // spotLightObject2.getTransform().rotate(new Vector3f(0, 0, 1), (float) Math.toRadians(-90.0f)); // spotLightObject2.addComponent(new GameComponent() { // float time = 0; // @Override // public void update(float dt) { // // time += dt; // getTransform().rotate(new Vector3f(0, 0, 1), 2f * dt); // addObject(spotLightObject2); // SpotLight spotLight3 = new SpotLight(new Vector3f(0.2f, 0.9f, 0.3f), 10f, new Attenuation(0, 0, 1f), .8f); // GameObject spotLightObject3 = new GameObject(); // spotLightObject3.addComponent(spotLight3); // spotLightObject3.getTransform().getPos().set(0, 2, 5); // spotLightObject3.getTransform().setRot(new Quaternion(new Vector3f(1, 0, 0), (float) Math.toRadians(90.0f))); // spotLightObject3.getTransform().rotate(new Vector3f(0, 0, 1), (float) Math.toRadians(-90.0f - 60.0f)); // spotLightObject3.addComponent(new GameComponent() { // float time = 0; // @Override // public void update(float dt) { // // time += dt; // getTransform().rotate(new Vector3f(0, 0, 1), 2f * dt); // addObject(spotLightObject3); addObject(planeObject); GameObject testMesh3 = new GameObject() // .addComponent(new LookAtComponent()) .addComponent(new MeshRenderer(tempMesh, material2)); addObject(new GameObject().addComponent(new FreeLook(0.3f)).addComponent(new FreeMove(6.0f)) .addComponent(new Camera3D((float) Math.toRadians(70.0f), (float) Window.getWidth() / (float) Window.getHeight(), 0.01f, 1000.0f))); // AddObject( // addObject(new GameObject().addComponent(new FreeLook(0.3f)).addComponent(new FreeMove(6.0f)) // .addComponent(new Camera2D(Window.getWidth() / 100, Window.getHeight() / 100, 100, -100))); addObject(testMesh3); testMesh3.getTransform().getPos().set(2, 0, 2); // testMesh3.getTransform().getScale().set(.3f, .3f, .3f); testMesh3.getTransform().setRot(new Quaternion(new Vector3f(0, 1, 0), (float) Math.toRadians(-70.0f))); // int i; // for (i = 0; i < 7; i++) { for (int i = 0; i < 1; i++) { MeshRenderer r = new MeshRenderer(new Mesh("cube.obj"), material2); //5629 GameObject go = new GameObject().addComponent(r); go.getTransform().getPos().set(0, 10.0f, 0); go.addComponent(new RigidBody()); addObject(go); } GameComponent c; // final int offset = i = 0; // final Vector3f posI = new Vector3f(0, -2, 0); // go.addComponent(new GameComponent() { // float time = 0; // @Override // public void update(float dt) { // time += 3 * dt; // getTransform().getPos().set(posI.add((new Vector3f(8 * (float) // Math.cos(time + offset), 0, 2 * (float) Math.sin(time + // offset))).mul(0.2f))); // r.getTransform().getScale().set(.1f, .1f, .1f); } }
package manager; import java.awt.Point; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import backend.Board; import backend.Box; import backend.Content; import backend.Floor; import backend.Ice; import backend.Interruptor; import backend.Player; import backend.Target; import backend.Tree; import exceptions.ParsingException; public class Parser { private int columns = 0; private int rows = 0; private Board board; boolean playerExists = false; private static final char PLAYER = '@'; private static final char BOX = 'B'; private static final char TARGET = 'G'; private static final char TREE = 'T'; private static final char WATER = ' private static final char ICE = 'C'; private static final char INTERRUPTOR = 'K'; /** * This method parses a file to check if all the data is correct. * * @param file * An input file where to obtain the data from. * @return A board created with the data from the file. * @throws IOException * If the file couldn't be opened. */ public Board parse(File file) throws IOException { String line; BufferedReader buffer = null; try { buffer = new BufferedReader(new FileReader(file)); while ((line = (buffer.readLine())) != null) { line = deleteTabs(line); if (line.length() > 1) { if (columns == 0) { columns = line.length(); } if (line.length() != columns) { throw new ParsingException(); } rows++; } } System.out.println(rows); System.out.println(columns); board = new Board(rows, columns); if (buffer != null) { buffer.close(); } buffer = new BufferedReader(new FileReader(file)); rows = 0; while ((line = (buffer.readLine())) != null) { line = deleteTabs(line); checkElementsValues(line, rows); rows++; } return board; } finally { if (buffer != null) { buffer.close(); } } } /** * This method deletes every tab from a string. * * @param line * A string representing a line of the file. * @return A new string without tabs. */ private String deleteTabs(String line) { char aux; String resp = new String(); for (int i = 0; i < line.length(); i++) { if ((aux = line.charAt(i)) != '\t') resp += aux; } return resp; } /** * This method checks each element values to see if they are correct. * * @param line * An array of strings representing each of the parameters of a * line separated by a comma. */ private void checkElementsValues(String line, int rowActual) { int index = 0; Content element = null; Point p; char symbol; if (line.length() != columns) { throw new ParsingException(); } while (index < columns) { p = new Point(rowActual, index); symbol = line.charAt(index); checkSymbolExistance(symbol); switch (symbol) { case PLAYER: { board.putCell(new Floor(), p); element = new Player(p, board); board.putContent(element, p); board.setPlayer((Player) element); playerExists = true; break; } case BOX: { board.putCell(new Floor(), p); element = new Box(p, board); board.putContent(element, p); break; } case TARGET: { board.putCell(new Target(), p); break; } case TREE: { board.putCell(new Tree(), p); break; } case WATER: { board.putCell(new Tree(), p); break; } case ICE: { board.putCell(new Floor(), p); element = new Ice(p, board); board.putContent(element, p); break; } case INTERRUPTOR: { board.putCell(new Interruptor(), p); break; } } index++; } } /** * This method checks if the element is an existing type of element. * * @param symbol * A char representing the type of element. */ public void checkSymbolExistance(char symbol) { System.out.println(symbol); if (symbol != 'G' && symbol != 'T' && symbol != '#' && symbol != 'B' && symbol != 'C' && symbol != ' ' && symbol != '@' && symbol != 'K') { throw new ParsingException(); } } }
package bartMachine; import gnu.trove.list.array.TDoubleArrayList; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import OpenSourceExtensions.UnorderedPair; /** * This class handles the parallelization of many Gibbs chains over many CPU cores * to create one BART regression model. It also handles all operations on the completed model. * * @author Adam Kapelner and Justin Bleich */ public class bartMachineRegressionMultThread extends Classifier implements Serializable { /** the number of CPU cores to build many different Gibbs chain within a BART model */ protected int num_cores = 1; //default /** the number of trees in this BART model on all Gibbs chains */ protected int num_trees = 50; //default /** the collection of <code>num_cores</code> BART models which will run separate Gibbs chains */ protected bartMachineRegression[] bart_gibbs_chain_threads; /** this is the combined gibbs samples after burn in from all of the <code>num_cores</code> chains */ protected bartMachineTreeNode[][] gibbs_samples_of_bart_trees_after_burn_in; /** the estimate of some upper limit of the variance of the response which is usually the MSE from a a linear regression */ private Double sample_var_y; /** the number of burn-in samples in each Gibbs chain */ protected int num_gibbs_burn_in = 250; //default /** the total number of gibbs samples where each chain gets a number of burn-in and then the difference from the total divided by <code>num_cores</code> */ protected int num_gibbs_total_iterations = 1250; //default /** the total number of Gibbs samples for each of the <code>num_cores</code> chains */ protected int total_iterations_multithreaded; /** The probability vector that samples covariates for selecting split rules */ protected double[] cov_split_prior; /** A hyperparameter that controls how easy it is to grow new nodes in a tree independent of depth */ protected Double alpha = 0.95; /** A hyperparameter that controls how easy it is to grow new nodes in a tree dependent on depth which makes it more difficult as the tree gets deeper */ protected Double beta = 2.0; /** this controls where to set <code>hyper_sigsq_mu</code> by forcing the variance to be this number of standard deviations on the normal CDF */ protected Double hyper_k = 2.0; /** At a fixed <code>hyper_nu</code>, this controls where to set <code>hyper_lambda</code> by forcing q proportion to be at that value in the inverse gamma CDF */ protected Double hyper_q = 0.9; /** half the shape parameter and half the multiplicand of the scale parameter of the inverse gamma prior on the variance */ protected Double hyper_nu = 3.0; /** the hyperparameter of the probability of picking a grow step during the Metropolis-Hastings tree proposal */ protected Double prob_grow = 2.5 / 9.0; /** the hyperparameter of the probability of picking a prune step during the Metropolis-Hastings tree proposal */ protected Double prob_prune = 2.5 / 9.0; /** should we print select messages to the screen */ protected boolean verbose = true; /** * whether or not we use the memory cache feature * * @see Section 3.1 of Kapelner, A and Bleich, J. bartMachine: A Powerful Tool for Machine Learning in R. ArXiv e-prints, 2013 */ protected boolean mem_cache_for_speed = true; /** the default constructor sets the number of total iterations each Gibbs chain is charged with sampling */ public bartMachineRegressionMultThread(){ setNumGibbsTotalIterations(num_gibbs_total_iterations); } /** * This is a simple setter for the number of total Gibbs samples and * it also sets the total iterations per Gibbs chain running on each CPU * core (see formula in the code) * * @param num_gibbs_total_iterations The number of total Gibbs iterations to set */ public void setNumGibbsTotalIterations(int num_gibbs_total_iterations){ this.num_gibbs_total_iterations = num_gibbs_total_iterations; total_iterations_multithreaded = num_gibbs_burn_in + (int)Math.ceil((num_gibbs_total_iterations - num_gibbs_burn_in) / (double) num_cores); } /** The number of samples after burning is simply the title minus the burn-in */ public int numSamplesAfterBurning(){ return num_gibbs_total_iterations - num_gibbs_burn_in; } /** Set up an array of regression BARTs with length equal to <code>num_cores</code>, the number of CPU cores requested */ protected void SetupBARTModels() { bart_gibbs_chain_threads = new bartMachineRegression[num_cores]; for (int t = 0; t < num_cores; t++){ bartMachineRegression bart = new bartMachineRegression(); SetupBartModel(bart, t); } } /** * Initialize one of the <code>num_cores</code> BART models by setting * all its custom parameters * * @param bart The BART model to initialize * @param t The number of the core this BART model corresponds to */ protected void SetupBartModel(bartMachineRegression bart, int t) { bart.setVerbose(verbose); //now set specs on each of the bart models bart.num_trees = num_trees; bart.num_gibbs_total_iterations = total_iterations_multithreaded; bart.num_gibbs_burn_in = num_gibbs_burn_in; bart.sample_var_y = sample_var_y; //now some hyperparams bart.setAlpha(alpha); bart.setBeta(beta); bart.setK(hyper_k); bart.setProbGrow(prob_grow); bart.setProbPrune(prob_prune); //set thread num and data bart.setThreadNum(t); bart.setTotalNumThreads(num_cores); bart.setMemCacheForSpeed(mem_cache_for_speed); //set features if (cov_split_prior != null){ bart.setCovSplitPrior(cov_split_prior); } //do special stuff for regression model if (!(bart instanceof bartMachineClassification)){ bart.setNu(hyper_nu); bart.setQ(hyper_q); } //once the params are set, now you can set the data bart.setData(X_y); bart_gibbs_chain_threads[t] = bart; } /** * Takes a library of standard normal samples provided external and caches them * * @param norm_samples The externally provided cache */ public void setNormSamples(double[] norm_samples){ bartMachine_b_hyperparams.samps_std_normal = norm_samples; bartMachine_b_hyperparams.samps_std_normal_length = norm_samples.length; } /** * Takes a library of chi-squared samples provided external and caches them * * @param gamma_samples The externally provided cache */ public void setGammaSamples(double[] gamma_samples){ bartMachine_b_hyperparams.samps_chi_sq_df_eq_nu_plus_n = gamma_samples; bartMachine_b_hyperparams.samps_chi_sq_df_eq_nu_plus_n_length = gamma_samples.length; } /** This function actually initiates the Gibbs sampling to build all the BART models */ public void Build() { SetupBARTModels(); //run a build on all threads long t0 = System.currentTimeMillis(); if (verbose){ System.out.println("building BART " + (mem_cache_for_speed ? "with" : "without") + " mem-cache speedup..."); } BuildOnAllThreads(); long t1 = System.currentTimeMillis(); if (verbose){ System.out.println("done building BART in " + ((t1 - t0) / 1000.0) + " sec \n"); } //once it's done, now put together the chains ConstructBurnedChainForTreesAndOtherInformation(); } /** Create a post burn-in chain for ease of manipulation later */ protected void ConstructBurnedChainForTreesAndOtherInformation() { gibbs_samples_of_bart_trees_after_burn_in = new bartMachineTreeNode[numSamplesAfterBurning()][num_trees]; if (verbose){ System.out.print("burning and aggregating chains from all threads... "); } //go through each thread and get the tail and put them together for (int t = 0; t < num_cores; t++){ bartMachineRegression bart_model = bart_gibbs_chain_threads[t]; for (int i = num_gibbs_burn_in; i < total_iterations_multithreaded; i++){ int offset = t * (total_iterations_multithreaded - num_gibbs_burn_in); int g = offset + (i - num_gibbs_burn_in); if (g >= numSamplesAfterBurning()){ break; } gibbs_samples_of_bart_trees_after_burn_in[g] = bart_model.gibbs_samples_of_bart_trees[i]; } } if (verbose){ System.out.print("done\n"); } } /** This is the core of BART's parallelization for model creation: build one BART model on each CPU core in parallel */ private void BuildOnAllThreads(){ ExecutorService bart_gibbs_chain_pool = Executors.newFixedThreadPool(num_cores); for (int t = 0; t < num_cores; t++){ final int tf = t; bart_gibbs_chain_pool.execute(new Runnable(){ public void run() { bart_gibbs_chain_threads[tf].Build(); } }); } bart_gibbs_chain_pool.shutdown(); try { bart_gibbs_chain_pool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); //effectively infinity } catch (InterruptedException ignored){} } /** * Return the predictions from each tree for each burned-in Gibbs sample * * @param records the observations / records for which to return predictions * @param num_cores_evaluate The number of CPU cores to use during evaluation * @return Predictions for all records further indexed by Gibbs sample */ protected double[][] getGibbsSamplesForPrediction(final double[][] records, final int num_cores_evaluate){ final int num_samples_after_burn_in = numSamplesAfterBurning(); final bartMachineRegression first_bart = bart_gibbs_chain_threads[0]; final int n = records.length; final double[][] y_hats = new double[n][records[0].length]; //this is really ugly, but it's faster (we've checked in a Profiler) if (num_cores_evaluate == 1){ for (int i = 0; i < n; i++){ double[] y_gibbs_samples = new double[num_samples_after_burn_in]; for (int g = 0; g < num_samples_after_burn_in; g++){ bartMachineTreeNode[] trees = gibbs_samples_of_bart_trees_after_burn_in[g]; double yt_i = 0; for (int m = 0; m < num_trees; m++){ yt_i += trees[m].Evaluate(records[i]); //sum of trees, right? } //just make sure we switch it back to really what y is for the user y_gibbs_samples[g] = first_bart.un_transform_y(yt_i); } y_hats[i] = y_gibbs_samples; } } else { Thread[] fixed_thread_pool = new Thread[num_cores_evaluate]; for (int t = 0; t < num_cores_evaluate; t++){ final int final_t = t; Thread thread = new Thread(){ public void run(){ for (int i = 0; i < n; i++){ if (i % num_cores_evaluate == final_t){ double[] y_gibbs_samples = new double[num_samples_after_burn_in]; for (int g = 0; g < num_samples_after_burn_in; g++){ bartMachineTreeNode[] trees = gibbs_samples_of_bart_trees_after_burn_in[g]; double yt_i = 0; for (int m = 0; m < num_trees; m++){ //sum of trees right? yt_i += trees[m].Evaluate(records[i]); } //just make sure we switch it back to really what y is for the user y_gibbs_samples[g] = first_bart.un_transform_y(yt_i); } y_hats[i] = y_gibbs_samples; } } } }; thread.start(); fixed_thread_pool[t] = thread; } for (int t = 0; t < num_cores_evaluate; t++){ try { fixed_thread_pool[t].join(); } catch (InterruptedException e) {} } } return y_hats; } /** * Using the {@link #getGibbsSamplesForPrediction} function, return a credible interval at a specified * level of coverage * * @param record The record for which to obtain an interval * @param coverage The desired coverage * @param num_cores_evaluate The number of CPU cores to use during evaluation * @return A double pair which represents the upper and lower bound of coverage */ protected double[] getPostPredictiveIntervalForPrediction(double[] record, double coverage, int num_cores_evaluate){ double[][] data = new double[1][record.length]; data[0] = record; //get all gibbs samples sorted double[][] y_gibbs_samples_sorted_matrix = getGibbsSamplesForPrediction(data, num_cores_evaluate); double[] y_gibbs_samples_sorted = y_gibbs_samples_sorted_matrix[0]; Arrays.sort(y_gibbs_samples_sorted); //calculate index of the CI_a and CI_b int n_bottom = (int)Math.round((1 - coverage) / 2 * y_gibbs_samples_sorted.length) - 1; //-1 because arrays start at zero int n_top = (int)Math.round(((1 - coverage) / 2 + coverage) * y_gibbs_samples_sorted.length) - 1; //-1 because arrays start at zero double[] conf_interval = {y_gibbs_samples_sorted[n_bottom], y_gibbs_samples_sorted[n_top]}; return conf_interval; } /** * Using the {@link #getPostPredictiveIntervalForPrediction} function, return a 95\% credible interval * * @param record The record for which to obtain an interval * @param num_cores_evaluate The number of CPU cores to use during evaluation * @return A double pair which represents the upper and lower bound of coverage */ protected double[] get95PctPostPredictiveIntervalForPrediction(double[] record, int num_cores_evaluate){ return getPostPredictiveIntervalForPrediction(record, 0.95, num_cores_evaluate); } public double[] getGibbsSamplesSigsqs(){ TDoubleArrayList sigsqs_to_export = new TDoubleArrayList(num_gibbs_total_iterations); for (int t = 0; t < num_cores; t++){ TDoubleArrayList sigsqs_to_export_by_thread = new TDoubleArrayList(bart_gibbs_chain_threads[t].getGibbsSamplesSigsqs()); if (t == 0){ sigsqs_to_export.addAll(sigsqs_to_export_by_thread); } else { sigsqs_to_export.addAll(sigsqs_to_export_by_thread.subList(num_gibbs_burn_in, total_iterations_multithreaded)); } } return sigsqs_to_export.toArray(); } /** * Returns a record of Metropolis-Hastings acceptances or rejections for all trees during burn-in * * @return Yes/No's for acceptances for all Gibbs samples further indexed by tree */ public boolean[][] getAcceptRejectMHsBurnin(){ boolean[][] accept_reject_mh_first_thread = bart_gibbs_chain_threads[0].getAcceptRejectMH(); boolean[][] accept_reject_mh_burn_ins = new boolean[num_gibbs_burn_in][num_trees]; for (int g = 1; g < num_gibbs_burn_in + 1; g++){ accept_reject_mh_burn_ins[g - 1] = accept_reject_mh_first_thread[g]; } return accept_reject_mh_burn_ins; } /** * Returns a record of Metropolis-Hastings acceptances or rejections for all trees after burn-in * * @param thread_num Which CPU core's acceptance / rejection record should be returned * @return Yes/No's for acceptances for all Gibbs samples further indexed by tree */ public boolean[][] getAcceptRejectMHsAfterBurnIn(int thread_num){ boolean[][] accept_reject_mh_by_core = bart_gibbs_chain_threads[thread_num - 1].getAcceptRejectMH(); boolean[][] accept_reject_mh_after_burn_ins = new boolean[total_iterations_multithreaded - num_gibbs_burn_in][num_trees]; for (int g = num_gibbs_burn_in; g < total_iterations_multithreaded; g++){ accept_reject_mh_after_burn_ins[g - num_gibbs_burn_in] = accept_reject_mh_by_core[g]; } return accept_reject_mh_after_burn_ins; } /** * Return the number of times each of the attributes were used during the construction of the sum-of-trees * by Gibbs sample. * * @param type Either "splits" or "trees" ("splits" means total number and "trees" means sum of binary values of whether or not it has appeared in the tree) * @return The counts for all Gibbs samples further indexed by the attribute 1, ..., p */ public int[][] getCountsForAllAttribute(final String type) { final int[][] variable_counts_all_gibbs = new int[num_gibbs_total_iterations - num_gibbs_burn_in][p]; for (int g = 0; g < num_gibbs_total_iterations - num_gibbs_burn_in; g++){ final bartMachineTreeNode[] trees = gibbs_samples_of_bart_trees_after_burn_in[g]; int[] variable_counts_one_gibbs = new int[p]; for (bartMachineTreeNode tree : trees){ if (type.equals("splits")){ variable_counts_one_gibbs = Tools.add_arrays(variable_counts_one_gibbs, tree.attribute_split_counts); } else if (type.equals("trees")){ variable_counts_one_gibbs = Tools.binary_add_arrays(variable_counts_one_gibbs, tree.attribute_split_counts); } } variable_counts_all_gibbs[g] = variable_counts_one_gibbs; } return variable_counts_all_gibbs; } /** * Return the proportion of times each of the attributes were used (count over total number of splits) * during the construction of the sum-of-trees by Gibbs sample. * * @param type Either "splits" or "trees" ("splits" means total number and "trees" means sum of binary values of whether or not it has appeared in the tree) * @return The proportion of splits for all Gibbs samples further indexed by the attribute 1, ..., p */ public double[] getAttributeProps(final String type) { int[][] variable_counts_all_gibbs = getCountsForAllAttribute(type); double[] attribute_counts = new double[p]; for (int g = 0; g < num_gibbs_total_iterations - num_gibbs_burn_in; g++){ attribute_counts = Tools.add_arrays(attribute_counts, variable_counts_all_gibbs[g]); } Tools.normalize_array(attribute_counts); //will turn it into proportions return attribute_counts; } /** * For all Gibbs samples after burn in, calculate the set of interaction counts (consider a split on x_j * and a daughter node splits on x_k and that would be considered an "interaction") * * @return A matrix of size p x p where the row is top split and the column is a bottom split. It is recommended to triangularize the matrix after ignoring the order. */ public int[][] getInteractionCounts(){ int[][] interaction_count_matrix = new int[p][p]; for (int g = 0; g < gibbs_samples_of_bart_trees_after_burn_in.length; g++){ bartMachineTreeNode[] trees = gibbs_samples_of_bart_trees_after_burn_in[g]; for (bartMachineTreeNode tree : trees){ //get the set of pairs of interactions HashSet<UnorderedPair<Integer>> set_of_interaction_pairs = new HashSet<UnorderedPair<Integer>>(p * p); //find all interactions tree.findInteractions(set_of_interaction_pairs); //now tabulate these interactions in our count matrix for (UnorderedPair<Integer> pair : set_of_interaction_pairs){ interaction_count_matrix[pair.getFirst()][pair.getSecond()]++; } } } return interaction_count_matrix; } /** Flush all unnecessary data from the Gibbs chains to conserve RAM */ protected void FlushData() { for (int t = 0; t < num_cores; t++){ bart_gibbs_chain_threads[t].FlushData(); } } /** * The default BART evaluation of a new observations is done via sample average of the * posterior predictions. Other functions can be used here such as median, mode, etc. * Default is to use one CPU core. * * @param record The observation to be evaluated / predicted */ public double Evaluate(double[] record) { return EvaluateViaSampAvg(record, 1); } /** * The default BART evaluation of a new observations is done via sample average of the * posterior predictions. Other functions can be used here such as median, mode, etc. * * @param record The observation to be evaluated / predicted * @param num_cores_evaluate The number of CPU cores to use during evaluation */ public double Evaluate(double[] record, int num_cores_evaluate) { return EvaluateViaSampAvg(record, num_cores_evaluate); } /** * Evaluates a new observations via sample average of the posterior predictions. * * @param record The observation to be evaluated / predicted * @param num_cores_evaluate The number of CPU cores to use during evaluation */ public double EvaluateViaSampAvg(double[] record, int num_cores_evaluate) { double[][] data = new double[1][record.length]; data[0] = record; double[][] gibbs_samples = getGibbsSamplesForPrediction(data, num_cores_evaluate); return StatToolbox.sample_average(gibbs_samples[0]); } /** * Evaluates a new observations via sample median of the posterior predictions. * * @param record The observation to be evaluated / predicted * @param num_cores_evaluate The number of CPU cores to use during evaluation */ public double EvaluateViaSampMed(double[] record, int num_cores_evaluate) { double[][] data = new double[1][record.length]; data[0] = record; double[][] gibbs_samples = getGibbsSamplesForPrediction(data, num_cores_evaluate); return StatToolbox.sample_median(gibbs_samples[0]); } /** * After burn in, find the depth (greatest generation of a terminal node) of each tree for each Gibbs sample * * @param thread_num which CPU core (which Gibbs chain) to return results for * @return for each Gibbs chain return a vector of depths for all <code>num_trees</code> chains */ public int[][] getDepthsForTreesInGibbsSampAfterBurnIn(int thread_num){ return bart_gibbs_chain_threads[thread_num - 1].getDepthsForTrees(num_gibbs_burn_in, total_iterations_multithreaded); } /** * After burn in, return the number of total nodes (internal plus terminal) of each tree for each Gibbs sample * * @param thread_num which CPU core (which Gibbs chain) to return results for * @return for each Gibbs chain return a vector of number of nodes for all <code>num_trees</code> chains */ public int[][] getNumNodesAndLeavesForTreesInGibbsSampAfterBurnIn(int thread_num){ return bart_gibbs_chain_threads[thread_num - 1].getNumNodesAndLeavesForTrees(num_gibbs_burn_in, total_iterations_multithreaded); } public void setData(ArrayList<double[]> X_y){ this.X_y = X_y; n = X_y.size(); p = X_y.get(0).length - 1; } public void setCovSplitPrior(double[] cov_split_prior){ this.cov_split_prior = cov_split_prior; } public void setNumGibbsBurnIn(int num_gibbs_burn_in){ this.num_gibbs_burn_in = num_gibbs_burn_in; } public void setNumTrees(int num_trees){ this.num_trees = num_trees; } public void setSampleVarY(double sample_var_y){ this.sample_var_y = sample_var_y; } public void setAlpha(double alpha){ this.alpha = alpha; } public void setBeta(double beta){ this.beta = beta; } public void setK(double hyper_k) { this.hyper_k = hyper_k; } public void setQ(double hyper_q) { this.hyper_q = hyper_q; } public void setNU(double hyper_nu) { this.hyper_nu = hyper_nu; } public void setProbGrow(double prob_grow) { this.prob_grow = prob_grow; } public void setProbPrune(double prob_prune) { this.prob_prune = prob_prune; } public void setVerbose(boolean verbose){ this.verbose = verbose; } public void setNumCores(int num_cores){ this.num_cores = num_cores; } public void setMemCacheForSpeed(boolean mem_cache_for_speed){ this.mem_cache_for_speed = mem_cache_for_speed; } /** Must be implemented, but does nothing */ public void StopBuilding() {} }
package org.multibit.hd.ui.views.components.enter_recipient; import com.google.common.base.Optional; import net.miginfocom.swing.MigLayout; import org.multibit.hd.core.dto.Recipient; import org.multibit.hd.ui.gravatar.Gravatars; import org.multibit.hd.ui.utils.ClipboardUtils; import org.multibit.hd.ui.views.components.*; import org.multibit.hd.ui.views.components.auto_complete.AutoCompleteFilter; import org.multibit.hd.ui.views.components.auto_complete.AutoCompleteFilters; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; /** * <p>View to provide the following to UI:</p> * <ul> * <li>Presentation of a dual-purpose combobox</li> * <li>Support for locating contacts by name</li> * <li>Support for entering recipient Bitcoin address representations (address, seed, key etc)</li> * </ul> * * @since 0.0.1 * */ public class EnterRecipientView extends AbstractComponentView<EnterRecipientModel> { // View components private JComboBox<Recipient> recipientComboBox; private JLabel imageLabel; private JButton pasteButton; /** * @param model The model backing this view */ public EnterRecipientView(EnterRecipientModel model) { super(model); } @Override public JPanel newComponentPanel() { AutoCompleteFilter<Recipient> filter = AutoCompleteFilters.newRecipientFilter(); // Bind a key listener to allow instant update of UI to matched passwords recipientComboBox = ComboBoxes.newRecipientComboBox(filter); recipientComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateModelFromView(); } }); pasteButton = Buttons.newPasteButton(getPasteAction()); JPanel panel = Panels.newPanel(new MigLayout( "fillx,insets 0", // Layout "[][][][]", // Columns "[]" // Rows )); // Start with an invisible label imageLabel = Labels.newImageLabel(Optional.<BufferedImage>absent()); imageLabel.setVisible(false); panel.add(Labels.newRecipient()); // Specify minimum width for consistent appearance across contact names and locales panel.add(recipientComboBox, "growx,w min:350:,push"); panel.add(pasteButton, "shrink"); panel.add(imageLabel, "shrink,wrap"); return panel; } @Override public void updateModelFromView() { Object selectedItem = recipientComboBox.getSelectedItem(); Optional<Recipient> currentRecipient = getModel().get().getRecipient(); boolean showGravatar = false; if (selectedItem instanceof Recipient) { // We have a select from the drop down Recipient selectedRecipient = (Recipient) selectedItem; // Avoid double events triggering calls if (currentRecipient.isPresent() && currentRecipient.get().equals(selectedRecipient)) { return; } // Update the current with the selected currentRecipient = Optional.of(selectedRecipient); getModel().get().setValue(selectedRecipient); // Display a gravatar if we have a contact if (selectedRecipient.getContact().isPresent()) { if (selectedRecipient.getContact().get().getEmail().isPresent()) { // We have an email address String emailAddress = selectedRecipient.getContact().get().getEmail().get(); Optional<BufferedImage> image = Gravatars.retrieveGravatar(emailAddress); if (image.isPresent()) { imageLabel.setIcon(new ImageIcon(image.get())); imageLabel.setVisible(true); showGravatar = true; } } } } else { // Create a recipient based on the text entry currentRecipient = Optional.of(new Recipient((String) selectedItem)); } // There is no gravatar to show if (!showGravatar) { imageLabel.setVisible(false); } // Update the model getModel().get().setValue(currentRecipient.get()); } /** * @return A new action for pasting the recipient information */ private Action getPasteAction() { // Show or hide the seed phrase return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { Optional<String> pastedText = ClipboardUtils.pasteStringFromClipboard(); if (pastedText.isPresent()) { recipientComboBox.getEditor().setItem(pastedText.get()); } } }; } }
package org.n52.movingcode.runtime.coderepository; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.jackrabbit.uuid.UUID; import org.apache.xmlbeans.XmlException; import org.joda.time.DateTime; import org.n52.movingcode.runtime.codepackage.Constants; import org.n52.movingcode.runtime.codepackage.MovingCodePackage; import org.n52.movingcode.runtime.codepackage.PackageID; import de.tudresden.gis.geoprocessing.movingcode.schema.PackageDescriptionDocument; /** * This class implements an {@link IMovingCodeRepository} for local (unzipped) packages, stored * in a flat folder structure. This folder structure shall have the following appearance: * * <absPath>-<folder1>-<packagedescription.xml> * | \<package.id> * | \<workspacefolder1> * | * -<folder2>-<packagedescription.xml> * | \<package.id> * | \<workspacefolder2> * | * -<folder3>-<packagedescription.xml> * | \<package.id> * | \<workspacefolder3> * | * ... * | * -<folderN>-<processdescriptionN> * \<package.id> * \<workspacefolderN> * * For any sub-folders found in <absPath> it will be assumed that it contains a plain (unzipped) * Moving Code package. * * The file <packagedescription.xml> contains the description of the MovingCode package. * * The file <package.id> contains the hierarchical ID of that package, usually a URL path or path fragment. * The following layout / mapping is used: * (mapping to {@link PackageID}) * * <packageroot>/<username>/<collectionname>/<packagename>/<timestamp> * * pageroot => namespace * identifier => <username>/<collectionname>/<packagename> * timestamp => version * * Performs occasional checks for updated content. * (Interval for periodical checks is given by {@link IMovingCodeRepository#localPollingInterval}) * * @author Matthias Mueller, TU Dresden * */ public class LocalVersionedFileRepository extends AbstractRepository { private final File directory; private String fingerprint; private Timer timerDaemon; private static final HashMap<PackageID,String> packageFolders = new HashMap<PackageID,String>(); /** * * Constructor for file system based repositories. Scans all sub-directories of a given sourceDirectory * for valid workspaces and attempt to interpret them as MovingCodePackages. * Incomplete or malformed packages will be ignored. * * @param sourceDirectory {@link File} - the directory to be scanned for Moving Code Packages. * */ public LocalVersionedFileRepository(File sourceDirectory) { this.directory = sourceDirectory; // compute directory fingerprint fingerprint = RepositoryUtils.directoryFingerprint(directory); // load packages from folder load(); // start timer daemon timerDaemon = new Timer(true); timerDaemon.scheduleAtFixedRate(new CheckFolder(), 0, IMovingCodeRepository.localPollingInterval); } public synchronized void addPackage(File workspace, PackageDescriptionDocument pd, PackageID pid){ // 1. create moving code packe object // 2. make new directory with UUID // 3. put packagedescription XML in place // 4. dump workspace to repo // 5. dump packageid to repo MovingCodePackage mcp = new MovingCodePackage(workspace, pd, new DateTime(pid.getVersion())); File targetDir = makeNewDirectory(); mcp.dumpWorkspace(targetDir); mcp.dumpDescription(new File(targetDir.getAbsolutePath() + File.separator + Constants.PACKAGE_DESCRIPTION_XML)); pid.dump(targetDir); // 6. register package register(mcp, pid); packageFolders.put(pid, targetDir.getAbsolutePath()); } public synchronized void addPackage(MovingCodePackage mcp, PackageID pid){ File targetDir = makeNewDirectory(); mcp.dumpWorkspace(targetDir); mcp.dumpDescription(new File(targetDir.getAbsolutePath() + File.separator + Constants.PACKAGE_DESCRIPTION_XML)); pid.dump(targetDir); // finally: register package register(mcp, pid); } /** * Remove a package with a given ID from this repository * * @param pid * @return */ public boolean removePackage(PackageID pid){ // 1. unregister package, so it cannot be found any longer // 2. remove directory // 3. TODO: care for errors in case something goes wrong to make sure we are // not left in an undefined state unregister(pid); File packageDir = new File(packageFolders.get(pid)); try { FileUtils.cleanDirectory(packageDir); FileUtils.deleteDirectory(packageDir); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } // 4. remove folder from inventory packageFolders.remove(pid); return true; } /** * private method that encapsulates the logic for loading zipped * MovingCode packages from a local folder. */ private final void load(){ // recursively obtain all zipfiles in sourceDirectory Collection<File> packageFolders = scanForFolders(directory); logger.info("Scanning directory: " + directory.getAbsolutePath()); for (File currentFolder : packageFolders) { // attempt to read packageDescription XML File packageDescriptionFile = new File(currentFolder, Constants.PACKAGE_DESCRIPTION_XML); if (!packageDescriptionFile.exists()){ continue; // skip this and immediately jump to the next iteration } PackageDescriptionDocument pd; try { pd = PackageDescriptionDocument.Factory.parse(packageDescriptionFile); } catch (XmlException e) { // silently skip this and immediately jump to the next iteration continue; } catch (IOException e) { // silently skip this and immediately jump to the next iteration continue; } // attempt to read package.id File packageIdFile = new File(currentFolder, Constants.PACKAGE_ID_FILE); PackageID packageId = PackageID.parse(packageIdFile); // packageID = absolute path logger.info("Found package: " + currentFolder + "; using ID: " + packageId.toString()); // attempt to access workspace root folder String workspace = pd.getPackageDescription().getWorkspace().getWorkspaceRoot(); if (workspace.startsWith("./")){ workspace = workspace.substring(2); // remove leading "./" if it exists } File workspaceDir = new File(currentFolder, workspace); if (!workspaceDir.exists()){ continue; // skip this and immediately jump to the next iteration } MovingCodePackage mcPackage = new MovingCodePackage(workspaceDir, pd, null); // validate // and add to package map // and add current file to zipFiles map if (mcPackage.isValid()) { register(mcPackage, packageId); } else { logger.error(currentFolder.getAbsolutePath() + " is an invalid package."); } } } /** * Scans a directory for subfolders (i.e. immediate child folders) and adds them * to the resulting Collection. * * @param directory {@link File} - parent directory to scan. * @return {@link Collection} of {@link File} - the directories found */ private static final Collection<File> scanForFolders(File directory) { return FileUtils.listFiles(directory, FileFilterUtils.directoryFileFilter(), null); } /** * Generate a new directory. * * @return */ private final File makeNewDirectory(){ String dirName = directory.getAbsolutePath() + File.separator + UUID.randomUUID().toString(); File newDir = new File(dirName); newDir.mkdirs(); return newDir; } /** * A task which re-computes the directory's fingerprint and * triggers a content reload if required. * * @author Matthias Mueller * */ private final class CheckFolder extends TimerTask { @Override public void run() { String newFingerprint = RepositoryUtils.directoryFingerprint(directory); if (!newFingerprint.equals(fingerprint)){ logger.info("Repository content has silently changed. Running update ..."); // set new fingerprint fingerprint = newFingerprint; // clear an reload clear(); load(); logger.info("Reload finished. Calling Repository Change Listeners."); informRepositoryChangeListeners(); } } } }
package main; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Collection of Options * * @author nhan * */ public class Options implements Iterable<Option> { private Map<OptionType, Collection<Option>> optionTable; public boolean add(Option opt) { OptionType optType = OptionType.fromOption(opt); Collection<Option> options = null; if (optionTable.containsKey(optType)) { options = optionTable.get(optType); } else { options = new ArrayList<Option>(); } options.add(opt); optionTable.put(optType, options); return true; } /** * Query if this collection contains a particular option * * @param opt the Option to query * @return boolean flag if the matching option exists in the collection */ public boolean hasOption(Option opt) { OptionType optType = OptionType.fromOption(opt); if (optionTable.containsKey(optType)) { Collection<Option> options = optionTable.get(optType); return options.contains(opt); } else { return false; } } /** * Query if this collection contains an option name * * @param optName String name for the option * @return boolean flag if a certain option type exists. */ public boolean hasOption(String optName) { return optionTable.containsKey(OptionType.fromString(optName)); } /** * Retrieve a passed Option if it exists in this collection * * @param opt an Option to search for in the collection * @return an Option object that exists in the collection */ public Option getOption(Option opt) { OptionType optType = OptionType.fromOption(opt); for (Option o: optionTable.get(optType)) { if (opt.equals(o)) { return o; } } return null; } /** * Retrieve the collection of Option that has the same type * * @param optName an alias of the option to specify OptionType * @return a collection of all the options of that OptionType */ public Collection<Option> getOptions(String optName) { OptionType optType = OptionType.fromString(optName); return optionTable.get(optType); } public boolean hasAmbiguity() { return false; } @Override public Iterator<Option> iterator() { // TODO Auto-generated method stub return null; } }
package org.kevoree.modeling.abs; import org.kevoree.modeling.KCallback; import org.kevoree.modeling.KObject; import org.kevoree.modeling.KObjectInfer; import org.kevoree.modeling.defer.KDefer; import org.kevoree.modeling.memory.manager.KMemoryManager; import org.kevoree.modeling.meta.*; import org.kevoree.modeling.traversal.KTraversalIndexResolver; public class AbstractKObjectInfer extends AbstractKObject implements KObjectInfer { public AbstractKObjectInfer(long p_universe, long p_time, long p_uuid, KMetaClass p_metaClass, KMemoryManager p_manager) { super(p_universe, p_time, p_uuid, p_metaClass, p_manager); } @Override public void train(KObject[] dependencies, Object[] expectedOutputs, KCallback callback) { final KObjectInfer selfObject = this; if (dependencies.length != _metaClass.dependencies().dependencies().length || expectedOutputs.length != _metaClass.outputs().length) { throw new RuntimeException("Bad number of arguments for dependencies"); } KDefer waiter = this.manager().model().defer(); KTraversalIndexResolver resolver = new KTraversalIndexResolver() { @Override public KObject[] resolve(String indexName) { KMetaDependency dependency = _metaClass.dependencies().dependencyByName(indexName); if (dependency != null) { KObject[] single = new KObject[1]; single[0] = dependencies[dependency.index()]; return single; } return null; } }; for (int i = 0; i < _metaClass.inputs().length; i++) { _metaClass.inputs()[i].extractor().exec(null, resolver, waiter.wait("" + i)); } waiter.then(new KCallback() { @Override public void on(Object o) { double[][] extractedInputs = new double[1][_metaClass.inputs().length]; for (int i = 0; i < _metaClass.inputs().length; i++) { try { extractedInputs[0][i] = (double) waiter.getResult("" + i); } catch (Exception e) { e.printStackTrace(); } } double[][] extractedOutputs = new double[1][_metaClass.outputs().length]; for (int i = 0; i < _metaClass.outputs().length; i++) { KMetaInferOutput metaInferOutput = _metaClass.outputs()[i]; extractedOutputs[0][i] = internalConvertOutput(expectedOutputs[i], metaInferOutput); } _metaClass.inferAlg().train(extractedInputs, extractedOutputs, selfObject); if (callback != null) { callback.on(null); } } }); } private double internalConvertOutput(Object output, KMetaInferOutput metaOutput) { if (metaOutput.type().equals(KPrimitiveTypes.BOOL)) { if (output.equals(true)) { return 1.0; } else { return 0.0; } } else { //TODO implement here all the case study //default case return 0; } } @Override public void trainAll(KObject[][] p_trainingSet, Object[][] p_expectedResultSet, KCallback callback) { //if(p_trainingSet) } @Override public void infer(KObject[] features, KCallback<Object[]> callback) { //TODO } @Override public void inferAll(KObject[][] features, KCallback<Object[][]> callback) { } @Override public void resetLearning() { //TODO throw new RuntimeException("Not Implemented Yet!"); } }
package com.intellij.openapi.roots.ui.configuration.projectRoot; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl; import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.MasterDetailsComponent; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.Consumer; import com.intellij.util.EventDispatcher; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; /** * @author anna */ public class ProjectSdksModel implements SdkModel { private static final Logger LOG = Logger.getInstance(ProjectSdksModel.class); private final HashMap<Sdk, Sdk> myProjectSdks = new HashMap<>(); private final EventDispatcher<Listener> mySdkEventsDispatcher = EventDispatcher.create(Listener.class); private boolean myModified; private Sdk myProjectSdk; private boolean myInitialized; @NotNull @Override public Listener getMulticaster() { return mySdkEventsDispatcher.getMulticaster(); } @NotNull @Override public Sdk[] getSdks() { return myProjectSdks.values().toArray(new Sdk[0]); } @Override @Nullable public Sdk findSdk(@NotNull String sdkName) { for (Sdk projectJdk : myProjectSdks.values()) { if (sdkName.equals(projectJdk.getName())) return projectJdk; } return null; } @Override public void addListener(@NotNull Listener listener) { mySdkEventsDispatcher.addListener(listener); } @Override public void removeListener(@NotNull Listener listener) { mySdkEventsDispatcher.removeListener(listener); } public void reset(@Nullable Project project) { myProjectSdks.clear(); final Sdk[] projectSdks = ProjectJdkTable.getInstance().getAllJdks(); for (Sdk sdk : projectSdks) { try { Sdk editable = (Sdk)sdk.clone(); myProjectSdks.put(sdk, editable); SdkDownloadTracker.getInstance().registerEditableSdk(sdk, editable); } catch (CloneNotSupportedException e) { LOG.error(e); } } if (project != null) { String sdkName = ProjectRootManager.getInstance(project).getProjectSdkName(); myProjectSdk = sdkName == null ? null : findSdk(sdkName); } myModified = false; myInitialized = true; } public void disposeUIResources() { myProjectSdks.clear(); myInitialized = false; } @NotNull public HashMap<Sdk, Sdk> getProjectSdks() { return myProjectSdks; } public boolean isModified() { return myModified; } public void apply() throws ConfigurationException { apply(null); } public void apply(@Nullable MasterDetailsComponent configurable) throws ConfigurationException { apply(configurable, false); } public void apply(@Nullable MasterDetailsComponent configurable, boolean addedOnly) throws ConfigurationException { String[] errorString = new String[1]; if (!canApply(errorString, configurable, addedOnly)) { throw new ConfigurationException(errorString[0]); } doApply(); myModified = false; } private void doApply() { ApplicationManager.getApplication().runWriteAction(() -> { final ArrayList<Sdk> itemsInTable = new ArrayList<>(); final ProjectJdkTable jdkTable = ProjectJdkTable.getInstance(); final Sdk[] allFromTable = jdkTable.getAllJdks(); // Delete removed and fill itemsInTable for (final Sdk tableItem : allFromTable) { if (myProjectSdks.containsKey(tableItem)) { itemsInTable.add(tableItem); } else { jdkTable.removeJdk(tableItem); } } // Now all removed items are deleted from table, itemsInTable contains all items in table for (Sdk originalJdk : itemsInTable) { final Sdk modifiedJdk = myProjectSdks.get(originalJdk); LOG.assertTrue(modifiedJdk != null); LOG.assertTrue(originalJdk != modifiedJdk); jdkTable.updateJdk(originalJdk, modifiedJdk); } // Add new items to table final Sdk[] allJdks = jdkTable.getAllJdks(); for (final Sdk projectJdk : myProjectSdks.keySet()) { LOG.assertTrue(projectJdk != null); if (ArrayUtilRt.find(allJdks, projectJdk) == -1) { jdkTable.addJdk(projectJdk); jdkTable.updateJdk(projectJdk, myProjectSdks.get(projectJdk)); } } }); } private boolean canApply(@NotNull String[] errorString, @Nullable MasterDetailsComponent rootConfigurable, boolean addedOnly) throws ConfigurationException { Map<Sdk, Sdk> sdks = new LinkedHashMap<>(myProjectSdks); if (addedOnly) { Sdk[] allJdks = ProjectJdkTable.getInstance().getAllJdks(); for (Sdk jdk : allJdks) { sdks.remove(jdk); } } ArrayList<String> allNames = new ArrayList<>(); Sdk itemWithError = null; for (Sdk currItem : sdks.values()) { String currName = currItem.getName(); if (currName.isEmpty()) { itemWithError = currItem; errorString[0] = ProjectBundle.message("sdk.list.name.required.error"); break; } if (allNames.contains(currName)) { itemWithError = currItem; errorString[0] = ProjectBundle.message("sdk.list.unique.name.required.error"); break; } final SdkAdditionalData sdkAdditionalData = currItem.getSdkAdditionalData(); if (sdkAdditionalData instanceof ValidatableSdkAdditionalData) { try { ((ValidatableSdkAdditionalData)sdkAdditionalData).checkValid(this); } catch (ConfigurationException e) { if (rootConfigurable != null) { final Object projectJdk = rootConfigurable.getSelectedObject(); if (!(projectJdk instanceof Sdk) || !Comparing.strEqual(((Sdk)projectJdk).getName(), currName)) { //do not leave current item with current name rootConfigurable.selectNodeInTree(currName); } } throw new ConfigurationException(ProjectBundle.message("sdk.configuration.exception", currName) + " " + e.getMessage()); } } allNames.add(currName); } if (itemWithError == null) return true; if (rootConfigurable != null) { rootConfigurable.selectNodeInTree(itemWithError.getName()); } return false; } public void removeSdk(@NotNull Sdk editableObject) { Sdk projectJdk = null; for (Sdk jdk : myProjectSdks.keySet()) { if (myProjectSdks.get(jdk) == editableObject) { projectJdk = jdk; break; } } if (projectJdk != null) { myProjectSdks.remove(projectJdk); SdkDownloadTracker.getInstance().onSdkRemoved(projectJdk); mySdkEventsDispatcher.getMulticaster().beforeSdkRemove(projectJdk); myModified = true; } } public void createAddActions(@NotNull DefaultActionGroup group, @NotNull final JComponent parent, @NotNull final Consumer<? super Sdk> updateTree, @Nullable Condition<? super SdkTypeId> filter) { createAddActions(group, parent, null, updateTree, filter); } @NotNull private static List<SdkType> getAddableSdkTypes(@Nullable Condition<? super SdkTypeId> filter) { return ContainerUtil.filter(SdkType.getAllTypes(), type -> type.allowCreationByUser() && (filter == null || filter.value(type)) ); } public void createAddActions(@NotNull DefaultActionGroup group, @NotNull final JComponent parent, @Nullable final Sdk selectedSdk, @NotNull final Consumer<? super Sdk> updateTree, @Nullable Condition<? super SdkTypeId> filter) { Map<SdkType, NewSdkAction> downloadActions = createDownloadActions(parent, selectedSdk, updateTree, filter); Map<SdkType, NewSdkAction> defaultAddActions = createAddActions(parent, selectedSdk, updateTree, filter); for (SdkType type : getAddableSdkTypes(filter)) { AnAction downloadAction = downloadActions.get(type); if (downloadAction != null) { group.add(downloadAction); } AnAction defaultAction = defaultAddActions.get(type); if (defaultAction != null) { group.add(defaultAction); } } } public static abstract class NewSdkAction extends DumbAwareAction { private final SdkType mySdkType; private NewSdkAction(@NotNull SdkType sdkType, @Nls(capitalization = Nls.Capitalization.Title) @Nullable String text, @Nullable Icon icon) { super(text, null, icon); mySdkType = sdkType; } @NotNull public SdkType getSdkType() { return mySdkType; } } @NotNull public Map<SdkType, NewSdkAction> createDownloadActions(@NotNull final JComponent parent, @Nullable final Sdk selectedSdk, @NotNull final Consumer<? super Sdk> updateTree, @Nullable Condition<? super SdkTypeId> filter) { Map<SdkType, NewSdkAction> result = new LinkedHashMap<>(); for (final SdkType type : getAddableSdkTypes(filter)) { SdkDownload downloadExtension = SdkDownload.EP_NAME.findFirstSafe(it -> it.supportsDownload(type)); if (downloadExtension == null) continue; String downloadText = ProjectBundle.message("sdk.configure.download.action", type.getPresentableName()); NewSdkAction downloadAction = new NewSdkAction(type, downloadText, downloadExtension.getIconForDownloadAction(type)) { @Override public void actionPerformed(@NotNull AnActionEvent e) { doDownload(downloadExtension, parent, selectedSdk, type, updateTree); } }; result.put(type, downloadAction); } return result; } @NotNull public Map<SdkType, NewSdkAction> createAddActions(@NotNull final JComponent parent, @Nullable final Sdk selectedSdk, @NotNull final Consumer<? super Sdk> updateTree, @Nullable Condition<? super SdkTypeId> filter) { Map<SdkType, NewSdkAction> result = new LinkedHashMap<>(); for (final SdkType type : getAddableSdkTypes(filter)) { String addOnDiskText = ProjectBundle.message("sdk.configure.add.default.action", type.getPresentableName()); NewSdkAction addAction = new NewSdkAction(type, addOnDiskText, type.getIconForAddAction()) { @Override public void actionPerformed(@NotNull AnActionEvent e) { if (type.supportsCustomCreateUI()) { type.showCustomCreateUI(ProjectSdksModel.this, parent, selectedSdk, sdk -> setupSdk(sdk, updateTree)); } else { SdkConfigurationUtil.selectSdkHome(type, home -> addSdk(type, home, updateTree)); } } }; result.put(type, addAction); } return result; } public void doAdd(@NotNull JComponent parent, @NotNull final SdkType type, @NotNull final Consumer<? super Sdk> callback) { doAdd(parent, null, type, callback); } public void doDownload(@NotNull SdkDownload downloadExtension, @NotNull JComponent parent, @Nullable final Sdk selectedSdk, @NotNull final SdkType type, @NotNull final Consumer<? super Sdk> callback) { LOG.assertTrue(downloadExtension.supportsDownload(type)); myModified = true; downloadExtension.showDownloadUI(type, this, parent, selectedSdk, sdk -> setupInstallableSdk(type, sdk, callback)); } public void doAdd(@NotNull JComponent parent, @Nullable final Sdk selectedSdk, @NotNull final SdkType type, @NotNull final Consumer<? super Sdk> callback) { myModified = true; if (type.supportsCustomCreateUI()) { type.showCustomCreateUI(this, parent, selectedSdk, sdk -> setupSdk(sdk, callback)); } else { SdkConfigurationUtil.selectSdkHome(type, home -> addSdk(type, home, callback)); } } public void addSdk(@NotNull SdkType type, @NotNull String home, @Nullable Consumer<? super Sdk> callback) { final Sdk newJdk = createSdk(type, home); setupSdk(newJdk, callback); } @NotNull public Sdk createSdk(@NotNull SdkType type, @NotNull String home) { String newSdkName = SdkConfigurationUtil.createUniqueSdkName(type, home, myProjectSdks.values()); return createSdkInternal(type, newSdkName, home); } @NotNull public Sdk createSdk(@NotNull SdkType type, @NotNull String suggestedName, @NotNull String home) { String newSdkName = SdkConfigurationUtil.createUniqueSdkName(suggestedName, myProjectSdks.values()); return createSdkInternal(type, newSdkName, home); } @NotNull private static Sdk createSdkInternal(@NotNull SdkType type, @NotNull String newSdkName, @NotNull String home) { final ProjectJdkImpl newJdk = new ProjectJdkImpl(newSdkName, type); newJdk.setHomePath(home); return newJdk; } public void setupInstallableSdk(@NotNull SdkType type, @NotNull SdkDownloadTask item, @Nullable Consumer<? super Sdk> callback) { // we do not ask the SdkType to set up the SDK for us, instead, we return an incomplete SDK to the // model with an expectation it would be updated later on String suggestedName = item.getSuggestedSdkName(); String homeDir = FileUtil.toSystemIndependentName(item.getPlannedHomeDir()); Sdk sdk = createSdk(type, suggestedName, homeDir); SdkDownloadTracker.configureSdk(sdk, item); SdkDownloadTracker tracker = SdkDownloadTracker.getInstance(); tracker.registerSdkDownload(sdk, item); Sdk editableSdk = doAddInternal(sdk, callback); if (editableSdk != null) { tracker.registerEditableSdk(sdk, editableSdk); } tracker.startSdkDownloadIfNeeded(sdk); } private void setupSdk(@NotNull Sdk newJdk, @Nullable Consumer<? super Sdk> callback) { String home = newJdk.getHomePath(); SdkType sdkType = (SdkType)newJdk.getSdkType(); if (!sdkType.setupSdkPaths(newJdk, this)) return; if (newJdk.getVersionString() == null) { String message = ProjectBundle.message("sdk.java.corrupt.error", home); Messages.showMessageDialog(message, ProjectBundle.message("sdk.java.corrupt.title"), Messages.getErrorIcon()); } doAdd(newJdk, callback); } @Override public void addSdk(@NotNull Sdk sdk) { doAdd(sdk, null); } public void doAdd(@NotNull Sdk newSdk, @Nullable Consumer<? super Sdk> updateTree) { doAddInternal(newSdk, updateTree); } @Nullable private Sdk doAddInternal(@NotNull Sdk newSdk, @Nullable Consumer<? super Sdk> updateTree) { myModified = true; try { Sdk editableCopy = (Sdk)newSdk.clone(); myProjectSdks.put(newSdk, editableCopy); if (updateTree != null) { updateTree.consume(editableCopy); } mySdkEventsDispatcher.getMulticaster().sdkAdded(editableCopy); return editableCopy; } catch (CloneNotSupportedException e) { LOG.error(e); return null; } } @Nullable public Sdk findSdk(@Nullable final Sdk modelJdk) { for (Map.Entry<Sdk, Sdk> entry : myProjectSdks.entrySet()) { Sdk jdk = entry.getKey(); if (Comparing.equal(entry.getValue(), modelJdk)) { return jdk; } } return null; } @Nullable public Sdk getProjectSdk() { if (!myProjectSdks.containsValue(myProjectSdk)) return null; return myProjectSdk; } public void setProjectSdk(final Sdk projectSdk) { myProjectSdk = projectSdk; } public boolean isInitialized() { return myInitialized; } }
package uk.ac.horizon.observer.vc; import java.util.List; import uk.ac.horizon.observer.model.Places; import uk.ac.horizon.observer.model.Task; import uk.ac.horizon.observer.model.TaskBin; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; /** * A fragment representing a single Place's tasks. This fragment is either * contained in a {@link PlacesActivity} in two-pane mode (on tablets) or a * {@link TasksActivity} on handsets. */ public class TaskFragment extends ListFragment { /** * The fragment argument representing the Place ID that the tasks are for. */ public static final String ARG_ITEM_ID = "item_id"; /** * The tasks */ private List<Task> myTasks = null; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public TaskFragment() { } /* * @Override public void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * * if (getArguments().containsKey(ARG_ITEM_ID)) { // Load the dummy content * specified by the fragment // arguments. In a real-world scenario, use a * Loader // to load content from a content provider. mItem = * DummyContent.ITEM_MAP.get(getArguments().getString( ARG_ITEM_ID)); } } * * @Override public View onCreateView(LayoutInflater inflater, ViewGroup * container, Bundle savedInstanceState) { View rootView = * inflater.inflate(R.layout.fragment_place_detail, container, false); * * // Show the dummy content as text in a TextView. if (mItem != null) { * ((TextView) rootView.findViewById(R.id.place_detail)) * .setText(mItem.content); } * * return rootView; } */ /** * On create set the tasks to the ones for the corresponding Place * @author Jesse */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); myTasks = Places.getTasksforCurrentPlace(); // can be null } /** * Display a multipe choice selection list of the tasks available for the given Place * @author Jesse */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if(null != myTasks){ if(myTasks.isEmpty()){ Toast.makeText(this.getActivity(), String.valueOf("No tasks to select for " + Places.getCurrentPlaceName()), Toast.LENGTH_LONG).show(); } ArrayAdapter<Task> adapter = new ArrayAdapter<Task>( this.getActivity(), android.R.layout.simple_list_item_activated_1, myTasks); setListAdapter(adapter); ListView lv = getListView(); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { getListView().getChildAt(0).setEnabled(false); } }); } } /** * Add values of clicked items to the click queue */ @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Task tmp = myTasks.get(position); Task task = new Task(tmp.getName(), Places.getCurrentPlace()); TaskBin.getInstance().addTask(task); //task.addObservation(this.getActivity()); //Log the insertion of the new row //long lastobs = task.addObservation(this.getActivity()); //Toast.makeText(this.getActivity(), "lastobs: " + lastobs, Toast.LENGTH_SHORT) // .show(); } }
package edu.umd.cs.findbugs; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.apache.bcel.classfile.ClassFormatException; import org.dom4j.DocumentException; import edu.umd.cs.findbugs.asm.FBClassReader; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.AnalysisFeatures; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.SourceInfoMap; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierAnnotation; import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierApplications; import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierValue; import edu.umd.cs.findbugs.bugReporter.BugReporterDecorator; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.IAnalysisCache; import edu.umd.cs.findbugs.classfile.IAnalysisEngineRegistrar; import edu.umd.cs.findbugs.classfile.IClassFactory; import edu.umd.cs.findbugs.classfile.IClassObserver; import edu.umd.cs.findbugs.classfile.IClassPath; import edu.umd.cs.findbugs.classfile.IClassPathBuilder; import edu.umd.cs.findbugs.classfile.ICodeBase; import edu.umd.cs.findbugs.classfile.ICodeBaseEntry; import edu.umd.cs.findbugs.classfile.MissingClassException; import edu.umd.cs.findbugs.classfile.impl.ClassFactory; import edu.umd.cs.findbugs.config.AnalysisFeatureSetting; import edu.umd.cs.findbugs.config.UserPreferences; import edu.umd.cs.findbugs.detect.NoteSuppressedWarnings; import edu.umd.cs.findbugs.filter.FilterException; import edu.umd.cs.findbugs.log.Profiler; import edu.umd.cs.findbugs.log.YourKitController; import edu.umd.cs.findbugs.plan.AnalysisPass; import edu.umd.cs.findbugs.plan.ExecutionPlan; import edu.umd.cs.findbugs.plan.OrderingConstraintException; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.TopologicalSort.OutEdges; /** * FindBugs driver class. Orchestrates the analysis of a project, collection of * results, etc. * * @author David Hovemeyer */ public class FindBugs2 implements IFindBugsEngine { private static final boolean LIST_ORDER = SystemProperties.getBoolean("findbugs.listOrder"); private static final boolean VERBOSE = SystemProperties.getBoolean("findbugs.verbose"); public static final boolean DEBUG = VERBOSE || SystemProperties.getBoolean("findbugs.debug"); public static final boolean PROGRESS = DEBUG || SystemProperties.getBoolean("findbugs.progress"); private static final boolean SCREEN_FIRST_PASS_CLASSES = SystemProperties.getBoolean("findbugs.screenFirstPass"); public static final String PROP_FINDBUGS_HOST_APP = "findbugs.hostApp"; public static final String PROP_FINDBUGS_HOST_APP_VERSION = "findbugs.hostAppVersion"; private int rankThreshold; private List<IClassObserver> classObserverList; private BugReporter bugReporter; private ErrorCountingBugReporter errorCountingBugReporter; private Project project; private IClassFactory classFactory; private IClassPath classPath; private List<ClassDescriptor> appClassList; private Collection<ClassDescriptor> referencedClassSet; private DetectorFactoryCollection detectorFactoryCollection; private ExecutionPlan executionPlan; private final YourKitController yourkitController = new YourKitController(); private String currentClassName; private FindBugsProgress progress; private IClassScreener classScreener; private final AnalysisOptions analysisOptions = new AnalysisOptions(true); /** * Constructor. */ public FindBugs2() { this.classObserverList = new LinkedList<IClassObserver>(); this.analysisOptions.analysisFeatureSettingList = FindBugs.DEFAULT_EFFORT; this.progress = new NoOpFindBugsProgress(); // By default, do not exclude any classes via the class screener this.classScreener = new IClassScreener() { /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IClassScreener#matches(java.lang.String) */ public boolean matches(String fileName) { return true; } public boolean vacuous() { return true; } }; String hostApp = System.getProperty(PROP_FINDBUGS_HOST_APP); String hostAppVersion = null; if (hostApp == null || hostApp.trim().length() <= 0) { hostApp = "FindBugs TextUI"; hostAppVersion = System.getProperty(PROP_FINDBUGS_HOST_APP_VERSION); } if (hostAppVersion == null) hostAppVersion = ""; Version.registerApplication(hostApp, hostAppVersion); // By default, we do not want to scan nested archives this.analysisOptions.scanNestedArchives = false; // bug 2815983: no bugs are reported anymore // there is no info which value should be default, so using the any one rankThreshold = BugRanker.VISIBLE_RANK_MAX; } /** * Set the detector factory collection to be used by this FindBugs2 engine. * This method should be called before the execute() method is called. * * @param detectorFactoryCollection * The detectorFactoryCollection to set. */ public void setDetectorFactoryCollection(DetectorFactoryCollection detectorFactoryCollection) { this.detectorFactoryCollection = detectorFactoryCollection; } /** * Execute the analysis. For obscure reasons, CheckedAnalysisExceptions are * re-thrown as IOExceptions. However, these can only happen during the * setup phase where we scan codebases for classes. * * @throws IOException * @throws InterruptedException */ public void execute() throws IOException, InterruptedException { if (FindBugs.isNoAnalysis()) throw new UnsupportedOperationException("This FindBugs invocation was started without analysis capabilities"); Profiler profiler = bugReporter.getProjectStats().getProfiler(); try { try { // Get the class factory for creating classpath/codebase/etc. classFactory = ClassFactory.instance(); // The class path object createClassPath(); progress.reportNumberOfArchives(project.getFileCount() + project.getNumAuxClasspathEntries()); profiler.start(this.getClass()); // The analysis cache object createAnalysisCache(); // Create BCEL compatibility layer createAnalysisContext(project, appClassList, analysisOptions.sourceInfoFileName); // Discover all codebases in classpath and // enumerate all classes (application and non-application) buildClassPath(); // Build set of classes referenced by application classes buildReferencedClassSet(); // Create BCEL compatibility layer setAppClassList(appClassList); // Configure the BugCollection (if we are generating one) FindBugs.configureBugCollection(this); // Enable/disabled relaxed reporting mode FindBugsAnalysisFeatures.setRelaxedMode(analysisOptions.relaxedReportingMode); FindBugsDisplayFeatures.setAbridgedMessages(analysisOptions.abridgedMessages); // Configure training databases FindBugs.configureTrainingDatabases(this); // Configure analysis features configureAnalysisFeatures(); // Create the execution plan (which passes/detectors to execute) createExecutionPlan(); for (Plugin p : detectorFactoryCollection.plugins()) { for (ComponentPlugin<BugReporterDecorator> brp : p.getComponentPlugins(BugReporterDecorator.class)) { if (brp.isEnabledByDefault() && !brp.isNamed(explicitlyDisabledBugReporterDecorators) || brp.isNamed(explicitlyEnabledBugReporterDecorators)) bugReporter = BugReporterDecorator.construct(brp, bugReporter); } } if (!classScreener.vacuous()) { bugReporter = new DelegatingBugReporter(bugReporter) { @Override public void reportBug(@Nonnull BugInstance bugInstance) { String className = bugInstance.getPrimaryClass().getClassName(); String resourceName = className.replace('.', '/') + ".class"; if (classScreener.matches(resourceName)) { this.getDelegate().reportBug(bugInstance); } } }; } if (executionPlan.isActive(NoteSuppressedWarnings.class)) { SuppressionMatcher m = AnalysisContext.currentAnalysisContext().getSuppressionMatcher(); bugReporter = new FilterBugReporter(bugReporter, m, false); } if (appClassList.size() == 0) { Map<String, ICodeBaseEntry> codebase = classPath.getApplicationCodebaseEntries(); if (analysisOptions.noClassOk) { System.err.println("No classfiles specified; output will have no warnings"); } else if (codebase.isEmpty()) { throw new IOException("No files to analyze could be opened"); } else { throw new NoClassesFoundToAnalyzeException(classPath); } } // Analyze the application analyzeApplication(); } catch (CheckedAnalysisException e) { IOException ioe = new IOException("IOException while scanning codebases"); ioe.initCause(e); throw ioe; } catch (OutOfMemoryError e) { System.err.println("Out of memory"); System.err.println("Total memory: " + Runtime.getRuntime().maxMemory() / 1000000 + "M"); System.err.println(" free memory: " + Runtime.getRuntime().freeMemory() / 1000000 + "M"); for (String s : project.getFileList()) { System.err.println("Analyzed: " + s); } for (String s : project.getAuxClasspathEntryList()) { System.err.println(" Aux: " + s); } throw e; } finally { clearCaches(); profiler.end(this.getClass()); profiler.report(); } } catch (IOException e) { bugReporter.reportQueuedErrors(); throw e; } } /** * Protected to allow Eclipse plugin remember some cache data for later reuse */ protected void clearCaches() { DescriptorFactory.clearInstance(); ObjectTypeFactory.clearInstance(); TypeQualifierApplications.clearInstance(); TypeQualifierAnnotation.clearInstance(); TypeQualifierValue.clearInstance(); // Make sure the codebases on the classpath are closed AnalysisContext.removeCurrentAnalysisContext(); Global.removeAnalysisCacheForCurrentThread(); if (classPath != null) { classPath.close(); } } /** * To avoid cyclic cross-references and allow GC after engine is not more * needed. (used by Eclipse plugin) */ public void dispose() { if (executionPlan != null) executionPlan.dispose(); if (appClassList != null) appClassList.clear(); if (classObserverList != null) classObserverList.clear(); if (referencedClassSet != null) referencedClassSet.clear(); analysisOptions.analysisFeatureSettingList = null; bugReporter = null; classFactory = null; classPath = null; classScreener = null; detectorFactoryCollection = null; executionPlan = null; progress = null; project = null; analysisOptions.userPreferences = null; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getBugReporter() */ public BugReporter getBugReporter() { return bugReporter; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getProject() */ public Project getProject() { return project; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#addClassObserver(edu.umd.cs.findbugs * .classfile.IClassObserver) */ public void addClassObserver(IClassObserver classObserver) { classObserverList.add(classObserver); } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#addFilter(java.lang.String, * boolean) */ public void addFilter(String filterFileName, boolean include) throws IOException, FilterException { bugReporter = FindBugs.configureFilter(bugReporter, filterFileName, include); } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#addBaselineBugs(java.lang.String) */ public void excludeBaselineBugs(String baselineBugs) throws IOException, DocumentException { bugReporter = FindBugs.configureBaselineFilter(bugReporter, baselineBugs); } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#enableTrainingInput(java.lang.String) */ public void enableTrainingInput(String trainingInputDir) { this.analysisOptions.trainingInputDir = trainingInputDir; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#enableTrainingOutput(java.lang.String * ) */ public void enableTrainingOutput(String trainingOutputDir) { this.analysisOptions.trainingOutputDir = trainingOutputDir; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getBugCount() */ public int getBugCount() { return errorCountingBugReporter.getBugCount(); } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getCurrentClass() */ public String getCurrentClass() { return currentClassName; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getErrorCount() */ public int getErrorCount() { return errorCountingBugReporter.getErrorCount(); } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getMissingClassCount() */ public int getMissingClassCount() { return errorCountingBugReporter.getMissingClassCount(); } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getReleaseName() */ public String getReleaseName() { return analysisOptions.releaseName; } public String getProjectName() { return analysisOptions.projectName; } public void setProjectName(String name) { analysisOptions.projectName = name; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#setAnalysisFeatureSettings(edu.umd * .cs.findbugs.config.AnalysisFeatureSetting[]) */ public void setAnalysisFeatureSettings(AnalysisFeatureSetting[] settingList) { this.analysisOptions.analysisFeatureSettingList = settingList; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#setBugReporter(edu.umd.cs.findbugs * .BugReporter) */ public void setBugReporter(BugReporter bugReporter) { this.bugReporter = this.errorCountingBugReporter = new ErrorCountingBugReporter(bugReporter); addClassObserver(bugReporter); } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#setClassScreener(edu.umd.cs.findbugs * .ClassScreener) */ public void setClassScreener(IClassScreener classScreener) { this.classScreener = classScreener; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#setProgressCallback(edu.umd.cs.findbugs * .FindBugsProgress) */ public void setProgressCallback(FindBugsProgress progressCallback) { this.progress = progressCallback; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#setProject(edu.umd.cs.findbugs.Project * ) */ public void setProject(Project project) { this.project = project; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#setRelaxedReportingMode(boolean) */ public void setRelaxedReportingMode(boolean relaxedReportingMode) { this.analysisOptions.relaxedReportingMode = relaxedReportingMode; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#setReleaseName(java.lang.String) */ public void setReleaseName(String releaseName) { this.analysisOptions.releaseName = releaseName; } /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.IFindBugsEngine#setSourceInfoFile(java.lang.String) */ public void setSourceInfoFile(String sourceInfoFile) { this.analysisOptions.sourceInfoFileName = sourceInfoFile; } public void setUserPreferences(UserPreferences userPreferences) { this.analysisOptions.userPreferences = userPreferences; // TODO should set it here too, but gui2 seems to have issues with it // setAnalysisFeatureSettings(userPreferences.getAnalysisFeatureSettings()); configureFilters(userPreferences); } protected void configureFilters(UserPreferences userPreferences) { IllegalArgumentException deferredError = null; Set<Entry<String, Boolean>> excludeBugFiles = userPreferences.getExcludeBugsFiles().entrySet(); for (Entry<String, Boolean> entry : excludeBugFiles) { if (entry.getValue() == null || !entry.getValue()) { continue; } try { excludeBaselineBugs(entry.getKey()); } catch (Exception e) { String message = "Unable to read filter: " + entry.getKey() + " : " + e.getMessage(); if (getBugReporter() != null) { getBugReporter().logError(message, e); } else if (deferredError == null){ deferredError = new IllegalArgumentException(message, e); } } } Set<Entry<String, Boolean>> includeFilterFiles = userPreferences.getIncludeFilterFiles().entrySet(); for (Entry<String, Boolean> entry : includeFilterFiles) { if (entry.getValue() == null || !entry.getValue()) { continue; } try { addFilter(entry.getKey(), true); } catch (Exception e) { String message = "Unable to read filter: " + entry.getKey() + " : " + e.getMessage(); if (getBugReporter() != null) { getBugReporter().logError(message, e); } else if (deferredError == null){ deferredError = new IllegalArgumentException(message, e); } } } Set<Entry<String, Boolean>> excludeFilterFiles = userPreferences.getExcludeFilterFiles().entrySet(); for (Entry<String, Boolean> entry : excludeFilterFiles) { Boolean value = entry.getValue(); if (value == null || !value) { continue; } String excludeFilterFile = entry.getKey(); try { addFilter(excludeFilterFile, false); } catch (Exception e) { String message = "Unable to read filter: " + excludeFilterFile + " : " + e.getMessage(); if (getBugReporter() != null) { getBugReporter().logError(message, e); } else if (deferredError == null){ deferredError = new IllegalArgumentException(message, e); } } } if (deferredError != null) throw deferredError; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#emitTrainingOutput() */ public boolean emitTrainingOutput() { return analysisOptions.trainingOutputDir != null; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getUserPreferences() */ public UserPreferences getUserPreferences() { return analysisOptions.userPreferences; } /** * Create the classpath object. */ private void createClassPath() { classPath = classFactory.createClassPath(); } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getTrainingInputDir() */ public String getTrainingInputDir() { return analysisOptions.trainingInputDir; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#getTrainingOutputDir() */ public String getTrainingOutputDir() { return analysisOptions.trainingOutputDir; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#useTrainingInput() */ public boolean useTrainingInput() { return analysisOptions.trainingInputDir != null; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#setScanNestedArchives(boolean) */ public void setScanNestedArchives(boolean scanNestedArchives) { this.analysisOptions.scanNestedArchives = scanNestedArchives; } /* * (non-Javadoc) * * @see edu.umd.cs.findbugs.IFindBugsEngine#setNoClassOk(boolean) */ public void setNoClassOk(boolean noClassOk) { this.analysisOptions.noClassOk = noClassOk; } /** * Create the analysis cache object and register it for current execution thread. * <p> * This method is protected to allow clients override it and possibly reuse * some previous analysis data (for Eclipse interactive re-build) * * @throws IOException * if error occurs registering analysis engines in a plugin */ protected IAnalysisCache createAnalysisCache() throws IOException { IAnalysisCache analysisCache = ClassFactory.instance().createAnalysisCache(classPath, bugReporter); // Register the "built-in" analysis engines registerBuiltInAnalysisEngines(analysisCache); // Register analysis engines in plugins registerPluginAnalysisEngines(detectorFactoryCollection, analysisCache); // Install the DetectorFactoryCollection as a database analysisCache.eagerlyPutDatabase(DetectorFactoryCollection.class, detectorFactoryCollection); Global.setAnalysisCacheForCurrentThread(analysisCache); return analysisCache; } /** * Register the "built-in" analysis engines with given IAnalysisCache. * * @param analysisCache * an IAnalysisCache */ @SuppressWarnings({"UnusedDeclaration"}) public static void registerBuiltInAnalysisEngines(IAnalysisCache analysisCache) { new edu.umd.cs.findbugs.classfile.engine.EngineRegistrar().registerAnalysisEngines(analysisCache); new edu.umd.cs.findbugs.classfile.engine.asm.EngineRegistrar().registerAnalysisEngines(analysisCache); new edu.umd.cs.findbugs.classfile.engine.bcel.EngineRegistrar().registerAnalysisEngines(analysisCache); } /** * Register all of the analysis engines defined in the plugins contained in * a DetectorFactoryCollection with an IAnalysisCache. * * @param detectorFactoryCollection * a DetectorFactoryCollection * @param analysisCache * an IAnalysisCache * @throws IOException */ @SuppressWarnings({"UnusedDeclaration"}) public static void registerPluginAnalysisEngines(DetectorFactoryCollection detectorFactoryCollection, IAnalysisCache analysisCache) throws IOException { for (Iterator<Plugin> i = detectorFactoryCollection.pluginIterator(); i.hasNext();) { Plugin plugin = i.next(); Class<? extends IAnalysisEngineRegistrar> engineRegistrarClass = plugin.getEngineRegistrarClass(); if (engineRegistrarClass != null) { try { IAnalysisEngineRegistrar engineRegistrar = engineRegistrarClass.newInstance(); engineRegistrar.registerAnalysisEngines(analysisCache); } catch (InstantiationException e) { IOException ioe = new IOException("Could not create analysis engine registrar for plugin " + plugin.getPluginId()); ioe.initCause(e); throw ioe; } catch (IllegalAccessException e) { IOException ioe = new IOException("Could not create analysis engine registrar for plugin " + plugin.getPluginId()); ioe.initCause(e); throw ioe; } } } } /** * Build the classpath from project codebases and system codebases. * * @throws InterruptedException * if the analysis thread is interrupted * @throws IOException * if an I/O error occurs * @throws CheckedAnalysisException */ private void buildClassPath() throws InterruptedException, IOException, CheckedAnalysisException { IClassPathBuilder builder = classFactory.createClassPathBuilder(bugReporter); for (String path : project.getFileArray()) { builder.addCodeBase(classFactory.createFilesystemCodeBaseLocator(path), true); } for (String path : project.getAuxClasspathEntryList()) { builder.addCodeBase(classFactory.createFilesystemCodeBaseLocator(path), false); } builder.scanNestedArchives(analysisOptions.scanNestedArchives); builder.build(classPath, progress); appClassList = builder.getAppClassList(); if (PROGRESS) { System.out.println(appClassList.size() + " classes scanned"); } // If any of the application codebases contain source code, // add them to the source path. // Also, use the last modified time of application codebases // to set the project timestamp. for (Iterator<? extends ICodeBase> i = classPath.appCodeBaseIterator(); i.hasNext();) { ICodeBase appCodeBase = i.next(); if (appCodeBase.containsSourceFiles()) { String pathName = appCodeBase.getPathName(); if (pathName != null) { project.addSourceDir(pathName); } } project.addTimestamp(appCodeBase.getLastModifiedTime()); } } private void buildReferencedClassSet() throws CheckedAnalysisException, InterruptedException { // XXX: should drive progress dialog (scanning phase)? if (PROGRESS) { System.out.println("Adding referenced classes"); } Set<String> referencedPackageSet = new HashSet<String>(); LinkedList<ClassDescriptor> workList = new LinkedList<ClassDescriptor>(); workList.addAll(appClassList); Set<ClassDescriptor> seen = new HashSet<ClassDescriptor>(); Set<ClassDescriptor> appClassSet = new HashSet<ClassDescriptor>(appClassList); Set<ClassDescriptor> badAppClassSet = new HashSet<ClassDescriptor>(); HashSet<ClassDescriptor> knownDescriptors = new HashSet<ClassDescriptor>(DescriptorFactory.instance() .getAllClassDescriptors()); int count = 0; Set<ClassDescriptor> addedToWorkList = new HashSet<ClassDescriptor>(appClassList); // add fields //noinspection ConstantIfStatement if (false) for (ClassDescriptor classDesc : appClassList) { try { XClass classNameAndInfo = Global.getAnalysisCache().getClassAnalysis(XClass.class, classDesc); for (XField f : classNameAndInfo.getXFields()) { String sig = f.getSignature(); ClassDescriptor d = DescriptorFactory.createClassDescriptorFromFieldSignature(sig); if (d != null && addedToWorkList.add(d)) workList.addLast(d); } } catch (RuntimeException e) { bugReporter.logError("Error scanning " + classDesc + " for referenced classes", e); if (appClassSet.contains(classDesc)) { badAppClassSet.add(classDesc); } } catch (MissingClassException e) { // Just log it as a missing class bugReporter.reportMissingClass(e.getClassDescriptor()); if (appClassSet.contains(classDesc)) { badAppClassSet.add(classDesc); } } } while (!workList.isEmpty()) { if (Thread.interrupted()) { throw new InterruptedException(); } ClassDescriptor classDesc = workList.removeFirst(); if (seen.contains(classDesc)) { continue; } seen.add(classDesc); if (!knownDescriptors.contains(classDesc)) { count++; if (PROGRESS && count % 5000 == 0) { System.out.println("Adding referenced class " + classDesc); } } referencedPackageSet.add(classDesc.getPackageName()); // Get list of referenced classes and add them to set. // Add superclasses and superinterfaces to worklist. try { XClass classNameAndInfo = Global.getAnalysisCache().getClassAnalysis(XClass.class, classDesc); ClassDescriptor superclassDescriptor = classNameAndInfo.getSuperclassDescriptor(); if (superclassDescriptor != null && addedToWorkList.add(superclassDescriptor)) { workList.addLast(superclassDescriptor); } for (ClassDescriptor ifaceDesc : classNameAndInfo.getInterfaceDescriptorList()) { if (addedToWorkList.add(ifaceDesc)) workList.addLast(ifaceDesc); } ClassDescriptor enclosingClass = classNameAndInfo.getImmediateEnclosingClass(); if (enclosingClass != null && addedToWorkList.add(enclosingClass)) workList.addLast(enclosingClass); } catch (RuntimeException e) { bugReporter.logError("Error scanning " + classDesc + " for referenced classes", e); if (appClassSet.contains(classDesc)) { badAppClassSet.add(classDesc); } } catch (MissingClassException e) { // Just log it as a missing class bugReporter.reportMissingClass(e.getClassDescriptor()); if (appClassSet.contains(classDesc)) { badAppClassSet.add(classDesc); } } catch (CheckedAnalysisException e) { // continue bugReporter.logError("Error scanning " + classDesc + " for referenced classes", e); if (appClassSet.contains(classDesc)) { badAppClassSet.add(classDesc); } } } // Delete any application classes that could not be read appClassList.removeAll(badAppClassSet); DescriptorFactory.instance().purge(badAppClassSet); for (ClassDescriptor d : DescriptorFactory.instance().getAllClassDescriptors()) { referencedPackageSet.add(d.getPackageName()); } referencedClassSet = new ArrayList<ClassDescriptor>(DescriptorFactory.instance().getAllClassDescriptors()); // Based on referenced packages, add any resolvable package-info classes // to the set of referenced classes. if (PROGRESS) { referencedPackageSet.remove(""); System.out.println("Added " + count + " referenced classes"); System.out.println("Total of " + referencedPackageSet.size() + " packages"); for (ClassDescriptor d : referencedClassSet) System.out.println(" " + d); } } public List<ClassDescriptor> sortByCallGraph(Collection<ClassDescriptor> classList, OutEdges<ClassDescriptor> outEdges) { List<ClassDescriptor> evaluationOrder = edu.umd.cs.findbugs.util.TopologicalSort.sortByCallGraph(classList, outEdges); edu.umd.cs.findbugs.util.TopologicalSort.countBadEdges(evaluationOrder, outEdges); return evaluationOrder; } @SuppressWarnings({"UnusedDeclaration"}) public static void clearAnalysisContext() { AnalysisContext.removeCurrentAnalysisContext(); } /** * Create the AnalysisContext that will serve as the BCEL-compatibility * layer over the AnalysisCache. * * @param project * The project * @param appClassList * list of ClassDescriptors identifying application classes * @param sourceInfoFileName * name of source info file (null if none) */ @SuppressWarnings({"UnusedDeclaration"}) public static void createAnalysisContext(Project project, List<ClassDescriptor> appClassList, @CheckForNull String sourceInfoFileName) throws IOException { AnalysisContext analysisContext = new AnalysisContext(); // Make this the current analysis context AnalysisContext.setCurrentAnalysisContext(analysisContext); // Make the AnalysisCache the backing store for // the BCEL Repository analysisContext.clearRepository(); // If needed, load SourceInfoMap if (sourceInfoFileName != null) { SourceInfoMap sourceInfoMap = analysisContext.getSourceInfoMap(); sourceInfoMap.read(new FileInputStream(sourceInfoFileName)); } analysisContext.setProject(project); } public static void setAppClassList(List<ClassDescriptor> appClassList) { AnalysisContext analysisContext = AnalysisContext .currentAnalysisContext(); analysisContext.setAppClassList(appClassList); } /** * Configure analysis feature settings. */ private void configureAnalysisFeatures() { for (AnalysisFeatureSetting setting : analysisOptions.analysisFeatureSettingList) { setting.configure(AnalysisContext.currentAnalysisContext()); } AnalysisContext.currentAnalysisContext().setBoolProperty(AnalysisFeatures.MERGE_SIMILAR_WARNINGS, analysisOptions.mergeSimilarWarnings); } /** * Create an execution plan. * * @throws OrderingConstraintException * if the detector ordering constraints are inconsistent */ private void createExecutionPlan() throws OrderingConstraintException { executionPlan = new ExecutionPlan(); // Use user preferences to decide which detectors are enabled. DetectorFactoryChooser detectorFactoryChooser = new DetectorFactoryChooser() { HashSet<DetectorFactory> forcedEnabled = new HashSet<DetectorFactory>(); /* * (non-Javadoc) * * @see * edu.umd.cs.findbugs.DetectorFactoryChooser#choose(edu.umd.cs. * findbugs.DetectorFactory) */ public boolean choose(DetectorFactory factory) { boolean result = FindBugs.isDetectorEnabled(FindBugs2.this, factory, rankThreshold) || forcedEnabled.contains(factory); if (ExecutionPlan.DEBUG) System.out.printf(" %6s %s %n", result, factory.getShortName()); return result; } public void enable(DetectorFactory factory) { forcedEnabled.add(factory); factory.setEnabledButNonReporting(true); } }; executionPlan.setDetectorFactoryChooser(detectorFactoryChooser); if (ExecutionPlan.DEBUG) System.out.println("rank threshold is " + rankThreshold); // Add plugins for (Iterator<Plugin> i = detectorFactoryCollection.pluginIterator(); i.hasNext();) { Plugin plugin = i.next(); if (DEBUG) { System.out.println("Adding plugin " + plugin.getPluginId() + " to execution plan"); } executionPlan.addPlugin(plugin); } // Build the execution plan executionPlan.build(); // Stash the ExecutionPlan in the AnalysisCache. Global.getAnalysisCache().eagerlyPutDatabase(ExecutionPlan.class, executionPlan); if (PROGRESS) { System.out.println(executionPlan.getNumPasses() + " passes in execution plan"); } } /** * Analyze the classes in the application codebase. */ private void analyzeApplication() throws InterruptedException { int passCount = 0; Profiler profiler = bugReporter.getProjectStats().getProfiler(); profiler.start(this.getClass()); AnalysisContext.currentXFactory().canonicalizeAll(); try { boolean multiplePasses = executionPlan.getNumPasses() > 1; if (executionPlan.getNumPasses() == 0) { throw new AssertionError("no analysis passes"); } int[] classesPerPass = new int[executionPlan.getNumPasses()]; classesPerPass[0] = referencedClassSet.size(); for (int i = 0; i < classesPerPass.length; i++) { classesPerPass[i] = i == 0 ? referencedClassSet.size() : appClassList.size(); } progress.predictPassCount(classesPerPass); XFactory factory = AnalysisContext.currentXFactory(); Collection<ClassDescriptor> badClasses = new LinkedList<ClassDescriptor>(); for (ClassDescriptor desc : referencedClassSet) { try { XClass info = Global.getAnalysisCache().getClassAnalysis(XClass.class, desc); factory.intern(info); } catch (CheckedAnalysisException e) { AnalysisContext.logError("Couldn't get class info for " + desc, e); badClasses.add(desc); } catch (RuntimeException e) { AnalysisContext.logError("Couldn't get class info for " + desc, e); badClasses.add(desc); } } if (!badClasses.isEmpty()) { referencedClassSet = new LinkedHashSet<ClassDescriptor>(referencedClassSet); referencedClassSet.removeAll(badClasses); } long startTime = System.currentTimeMillis(); bugReporter.getProjectStats().setReferencedClasses(referencedClassSet.size()); for (Iterator<AnalysisPass> passIterator = executionPlan.passIterator(); passIterator.hasNext();) { AnalysisPass pass = passIterator.next(); yourkitController.advanceGeneration("Pass " + passCount); // The first pass is generally a non-reporting pass which // gathers information about referenced classes. boolean isNonReportingFirstPass = multiplePasses && passCount == 0; // Instantiate the detectors Detector2[] detectorList = pass.instantiateDetector2sInPass(bugReporter); // If there are multiple passes, then on the first pass, // we apply detectors to all classes referenced by the // application classes. // On subsequent passes, we apply detector only to application // classes. Collection<ClassDescriptor> classCollection = (isNonReportingFirstPass) ? referencedClassSet : appClassList; AnalysisContext.currentXFactory().canonicalizeAll(); if (PROGRESS || LIST_ORDER) { System.out.printf("%6d : Pass %d: %d classes%n", (System.currentTimeMillis() - startTime)/1000, passCount, classCollection.size()); if (DEBUG) XFactory.profile(); } if (!isNonReportingFirstPass) { OutEdges<ClassDescriptor> outEdges = new OutEdges<ClassDescriptor>() { public Collection<ClassDescriptor> getOutEdges(ClassDescriptor e) { try { XClass classNameAndInfo = Global.getAnalysisCache().getClassAnalysis(XClass.class, e); return classNameAndInfo.getCalledClassDescriptors(); } catch (CheckedAnalysisException e2) { AnalysisContext.logError("error while analyzing " + e.getClassName(), e2); return Collections.emptyList(); } } }; classCollection = sortByCallGraph(classCollection, outEdges); } if (LIST_ORDER) { System.out.println("Analysis order:"); for (ClassDescriptor c : classCollection) { System.out.println(" " + c); } } AnalysisContext currentAnalysisContext = AnalysisContext.currentAnalysisContext(); currentAnalysisContext.updateDatabases(passCount); progress.startAnalysis(classCollection.size()); int count = 0; Global.getAnalysisCache().purgeAllMethodAnalysis(); Global.getAnalysisCache().purgeClassAnalysis(FBClassReader.class); for (ClassDescriptor classDescriptor : classCollection) { long classStartNanoTime = 0; if (PROGRESS) { classStartNanoTime = System.nanoTime(); System.out.printf("%6d %d/%d %d/%d %s%n", (System.currentTimeMillis() - startTime)/1000, passCount, executionPlan.getNumPasses(), count, classCollection.size(), classDescriptor); } count++; // Check to see if class is excluded by the class screener. // In general, we do not want to screen classes from the // first pass, even if they would otherwise be excluded. if ((SCREEN_FIRST_PASS_CLASSES || !isNonReportingFirstPass) && !classScreener.matches(classDescriptor.toResourceName())) { if (DEBUG) { System.out.println("*** Excluded by class screener"); } continue; } boolean isHuge = currentAnalysisContext.isTooBig(classDescriptor); if (isHuge && currentAnalysisContext.isApplicationClass(classDescriptor)) { bugReporter.reportBug(new BugInstance("SKIPPED_CLASS_TOO_BIG", Priorities.NORMAL_PRIORITY) .addClass(classDescriptor)); } currentClassName = ClassName.toDottedClassName(classDescriptor.getClassName()); notifyClassObservers(classDescriptor); profiler.startContext(currentClassName); currentAnalysisContext.setClassBeingAnalyzed(classDescriptor); try { for (Detector2 detector : detectorList) { if (Thread.interrupted()) { throw new InterruptedException(); } if (isHuge && !FirstPassDetector.class.isAssignableFrom(detector.getClass())) { continue; } if (DEBUG) { System.out.println("Applying " + detector.getDetectorClassName() + " to " + classDescriptor); // System.out.println("foo: " + // NonReportingDetector.class.isAssignableFrom(detector.getClass()) // + ", bar: " + detector.getClass().getName()); } try { profiler.start(detector.getClass()); detector.visitClass(classDescriptor); } catch (ClassFormatException e) { logRecoverableException(classDescriptor, detector, e); } catch (MissingClassException e) { Global.getAnalysisCache().getErrorLogger().reportMissingClass(e.getClassDescriptor()); } catch (CheckedAnalysisException e) { logRecoverableException(classDescriptor, detector, e); } catch (RuntimeException e) { logRecoverableException(classDescriptor, detector, e); } finally { profiler.end(detector.getClass()); } } } finally { progress.finishClass(); profiler.endContext(currentClassName); currentAnalysisContext.clearClassBeingAnalyzed(); if (PROGRESS) { long usecs = (System.nanoTime() - classStartNanoTime)/1000; if (usecs > 15000) { int classSize = currentAnalysisContext.getClassSize(classDescriptor); long speed = usecs /classSize; if (speed > 15) System.out.printf(" %6d usecs/byte %6d msec %6d bytes %d pass %s%n", speed, usecs/1000, classSize, passCount, classDescriptor); } } } } if (!passIterator.hasNext()) yourkitController.captureMemorySnapshot(); // Call finishPass on each detector for (Detector2 detector : detectorList) { detector.finishPass(); } progress.finishPerClassAnalysis(); passCount++; } } finally { bugReporter.finish(); bugReporter.reportQueuedErrors(); profiler.end(this.getClass()); if (PROGRESS) System.out.println("Analysis completed"); } } /** * Notify all IClassObservers that we are visiting given class. * * @param classDescriptor * the class being visited */ private void notifyClassObservers(ClassDescriptor classDescriptor) { for (IClassObserver observer : classObserverList) { observer.observeClass(classDescriptor); } } /** * Report an exception that occurred while analyzing a class with a * detector. * * @param classDescriptor * class being analyzed * @param detector * detector doing the analysis * @param e * the exception */ private void logRecoverableException(ClassDescriptor classDescriptor, Detector2 detector, Throwable e) { bugReporter.logError( "Exception analyzing " + classDescriptor.toDottedClassName() + " using detector " + detector.getDetectorClassName(), e); } public static void main(String[] args) throws Exception { // Sanity-check the loaded BCEL classes if (!CheckBcel.check()) { System.exit(1); } // Create FindBugs2 engine FindBugs2 findBugs = new FindBugs2(); // Parse command line and configure the engine TextUICommandLine commandLine = new TextUICommandLine(); FindBugs.processCommandLine(commandLine, args, findBugs); boolean justPrintConfiguration = commandLine.justPrintConfiguration(); if (justPrintConfiguration || commandLine.justPrintVersion()) { Version.printVersion(justPrintConfiguration); return; } // Away we go! FindBugs.runMain(findBugs, commandLine); } public void setAbridgedMessages(boolean xmlWithAbridgedMessages) { analysisOptions.abridgedMessages = xmlWithAbridgedMessages; } public void setMergeSimilarWarnings(boolean mergeSimilarWarnings) { this.analysisOptions.mergeSimilarWarnings = mergeSimilarWarnings; } public void setApplySuppression(boolean applySuppression) { this.analysisOptions.applySuppression = applySuppression; } public void setRankThreshold(int rankThreshold) { this.rankThreshold = rankThreshold; } public void finishSettings() { if (analysisOptions.applySuppression) { bugReporter = new FilterBugReporter(bugReporter, getProject().getSuppressionFilter(), false); } } @Nonnull Set<String> explicitlyEnabledBugReporterDecorators = Collections.emptySet(); @Nonnull Set<String> explicitlyDisabledBugReporterDecorators = Collections.emptySet(); public void setBugReporterDecorators(Set<String> explicitlyEnabled, Set<String> explicitlyDisabled) { explicitlyEnabledBugReporterDecorators = explicitlyEnabled; explicitlyDisabledBugReporterDecorators = explicitlyDisabled; } }
package uk.co.johnjtaylor.events.generic; import java.util.EventObject; import uk.co.johnjtaylor.events.EventImportance; import uk.co.johnjtaylor.events.EventType; /** * Base representation of an Event; extended * into either a SortEvent type or Tester event to * then be further defined into an individual event class. * * @author John */ public abstract class Event extends EventObject { private static final long serialVersionUID = -8983402706390183976L; private EventType type; private EventImportance importance; /** * @param source Source creating this event (EventObject constr.) * @param type EventType (enum) of the event instance * @param importance EventImportance (enum) of the event significance */ public Event(Object source, EventType type, EventImportance importance) { super(source); this.type = type; this.importance = importance; } /** * @return EventType (enum) representation of which Event this is */ public EventType getEventType() { return type; } /** * @return EventImportance (enum) representation of the significance of the occuring event */ public EventImportance getEventImportance() { return importance; } /** * @return A string representing the name of this event instance */ public abstract String getEventName(); }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-02-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag TLS_SIZE_FRACTION = defineDoubleFlag( "tls-size-fraction", 0.07, List.of("baldersheim"), "2021-12-20", "2022-02-01", "Fraction of disk available for transaction log", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "LATENCY", List.of("baldersheim"), "2020-12-02", "2022-02-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_TASK_LIMIT = defineIntFlag( "feed-task-limit", 1000, List.of("geirst, baldersheim"), "2021-10-14", "2022-02-01", "The task limit used by the executors handling feed in proton", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_MASTER_TASK_LIMIT = defineIntFlag( "feed-master-task-limit", 0, List.of("geirst, baldersheim"), "2021-11-18", "2022-02-01", "The task limit used by the master thread in each document db in proton. Ignored when set to 0.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag SHARED_FIELD_WRITER_EXECUTOR = defineStringFlag( "shared-field-writer-executor", "NONE", List.of("geirst, baldersheim"), "2021-11-05", "2022-02-01", "Whether to use a shared field writer executor for the document database(s) in proton. " + "Valid values: NONE, INDEX, INDEX_AND_ATTRIBUTE, DOCUMENT_DB", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2022-02-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-02-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-02-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-02-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-02-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-02-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2022-02-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag( "hide-shared-routing-endpoint", false, List.of("tokle", "bjormel"), "2020-12-02", "2022-02-01", "Whether the controller should hide shared routing layer endpoint", "Takes effect immediately", APPLICATION_ID ); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-02-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-02-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DISK_BLOAT_FACTOR = defineDoubleFlag( "disk-bloat-factor", 0.2, List.of("baldersheim"), "2021-10-08", "2022-02-01", "Amount of bloat allowed before compacting file", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag DOCSTORE_COMPRESSION_LEVEL = defineIntFlag( "docstore-compression-level", 3, List.of("baldersheim"), "2021-10-08", "2022-02-01", "Default compression level used for document store", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag NUM_DEPLOY_HELPER_THREADS = defineIntFlag( "num-model-builder-threads", -1, List.of("balder"), "2021-09-09", "2022-02-01", "Number of threads used for speeding up building of models.", "Takes effect on first (re)start of config server"); public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag( "enable-feed-block-in-distributor", true, List.of("geirst"), "2021-01-27", "2022-01-31", "Enables blocking of feed in the distributor if resource usage is above limit on at least one content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2022-02-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2022-02-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-02-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag( "generate-non-mtls-endpoint", true, List.of("tokle"), "2021-02-18", "2022-02-01", "Whether to generate the non-mtls endpoint", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-02-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 128, List.of("balder", "vekterli"), "2021-06-06", "2022-02-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 1024, List.of("balder", "vekterli"), "2021-06-06", "2022-02-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag IGNORE_MERGE_QUEUE_LIMIT = defineFeatureFlag( "ignore-merge-queue-limit", false, List.of("vekterli", "geirst"), "2021-10-06", "2022-03-01", "Specifies if merges that are forwarded (chained) from another content node are always " + "allowed to be enqueued even if the queue is otherwise full.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag LARGE_RANK_EXPRESSION_LIMIT = defineIntFlag( "large-rank-expression-limit", 8192, List.of("baldersheim"), "2021-06-09", "2022-02-01", "Limit for size of rank expressions distributed by filedistribution", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-03-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag( "metricsproxy-num-threads", 2, List.of("balder"), "2021-09-01", "2022-02-01", "Number of threads for metrics proxy", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2022-02-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag ENABLE_ONPREM_TENANT_S3_ARCHIVE = defineFeatureFlag( "enable-onprem-tenant-s3-archive", false, List.of("bjorncs"), "2021-09-14", "2022-02-01", "Enable tenant S3 buckets in cd/main. Must be set on controller cluster only.", "Takes effect immediately", ZONE_ID, TENANT_ID ); public static final UnboundBooleanFlag DELETE_UNMAINTAINED_CERTIFICATES = defineFeatureFlag( "delete-unmaintained-certificates", false, List.of("andreer"), "2021-09-23", "2022-02-01", "Whether to delete certificates that are known by provider but not by controller", "Takes effect on next run of EndpointCertificateMaintainer" ); public static final UnboundBooleanFlag USE_NEW_ENDPOINT_CERTIFICATE_PROVIDER_URL = defineFeatureFlag( "use-new-endpoint-certificate-provider-url", true, List.of("andreer"), "2021-12-14", "2022-01-14", "Use the new URL for the endpoint certificate provider API", "Takes effect immediately" ); public static final UnboundBooleanFlag ENABLE_TENANT_DEVELOPER_ROLE = defineFeatureFlag( "enable-tenant-developer-role", false, List.of("bjorncs"), "2021-09-23", "2022-02-01", "Enable tenant developer Athenz role in cd/main. Must be set on controller cluster only.", "Takes effect immediately", TENANT_ID ); public static final UnboundBooleanFlag ENABLE_ROUTING_REUSE_PORT = defineFeatureFlag( "enable-routing-reuse-port", true, List.of("mortent"), "2021-09-29", "2022-02-01", "Enable reuse port in routing configuration", "Takes effect on container restart", HOSTNAME ); public static final UnboundBooleanFlag ENABLE_TENANT_OPERATOR_ROLE = defineFeatureFlag( "enable-tenant-operator-role", false, List.of("bjorncs"), "2021-09-29", "2022-02-01", "Enable tenant specific operator roles in public systems. For controllers only.", "Takes effect on subsequent maintainer invocation", TENANT_ID ); public static final UnboundIntFlag DISTRIBUTOR_MERGE_BUSY_WAIT = defineIntFlag( "distributor-merge-busy-wait", 10, List.of("geirst", "vekterli"), "2021-10-04", "2022-03-01", "Number of seconds that scheduling of new merge operations in the distributor should be inhibited " + "towards a content node that has indicated merge busy", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag DISTRIBUTOR_ENHANCED_MAINTENANCE_SCHEDULING = defineFeatureFlag( "distributor-enhanced-maintenance-scheduling", false, List.of("vekterli", "geirst"), "2021-10-14", "2022-01-31", "Enable enhanced maintenance operation scheduling semantics on the distributor", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ASYNC_APPLY_BUCKET_DIFF = defineFeatureFlag( "async-apply-bucket-diff", false, List.of("geirst", "vekterli"), "2021-10-22", "2022-01-31", "Whether portions of apply bucket diff handling will be performed asynchronously", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag( "unordered-merge-chaining", false, List.of("vekterli", "geirst"), "2021-11-15", "2022-03-01", "Enables the use of unordered merge chains for data merge operations", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag JDK_VERSION = defineStringFlag( "jdk-version", "11", List.of("hmusum"), "2021-10-25", "2022-03-01", "JDK version to use on host and inside containers. Note application-id dimension only applies for container, " + "while hostname and node type applies for host.", "Takes effect on restart for Docker container and on next host-admin tick for host", APPLICATION_ID, TENANT_ID, HOSTNAME, NODE_TYPE); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-01-31", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", false, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_LEGACY_LB_SERVICES = defineFeatureFlag( "use-legacy-lb-services", false, List.of("tokle"), "2021-11-22", "2022-02-01", "Whether to generate routing table based on legacy lb-services config", "Takes effect on container reboot", ZONE_ID, HOSTNAME); public static final UnboundBooleanFlag USE_V8_DOC_MANAGER_CFG = defineFeatureFlag( "use-v8-doc-manager-cfg", false, List.of("arnej", "baldersheim"), "2021-12-09", "2022-12-31", "Use new (preparing for Vespa 8) section in documentmanager.def", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2022-03-31", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag FAIL_DEPLOYMENT_WITH_INVALID_JVM_OPTIONS = defineFeatureFlag( "fail-deployment-with-invalid-jvm-options", false, List.of("hmusum"), "2021-12-20", "2022-01-20", "Whether to fail deployments with invalid JVM options in services.xml", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package us.kbase.userprofile; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import us.kbase.common.service.JsonServerMethod; import us.kbase.common.service.JsonServerServlet; //BEGIN_HEADER import java.util.ArrayList; import us.kbase.auth.AuthService; import us.kbase.auth.AuthToken; import us.kbase.auth.UserDetail; import org.ini4j.Ini; import java.io.File; //END_HEADER /** * <p>Original spec-file module name: UserProfile</p> * <pre> * </pre> */ public class UserProfileServer extends JsonServerServlet { private static final long serialVersionUID = 1L; //BEGIN_CLASS_HEADER public static final String VERSION = "0.1.0"; public static final String SYS_PROP_KB_DEPLOYMENT_CONFIG = "KB_DEPLOYMENT_CONFIG"; public static final String SERVICE_DEPLOYMENT_NAME = "UserProfile"; public static final String CFG_MONGO_HOST = "mongodb-host"; public static final String CFG_MONGO_DB = "mongodb-database"; public static final String CFG_MONGO_USER = "mongodb-user"; public static final String CFG_MONGO_PSWD = "mongodb-pwd"; public static final String CFG_MONGO_RETRY = "mongodb-retry"; public static final String CFG_ADMIN = "admin"; private static Throwable configError = null; private static Map<String, String> config = null; public static Map<String, String> config() { if (config != null) return config; if (configError != null) throw new IllegalStateException("There was an error while loading configuration", configError); String configPath = System.getProperty(SYS_PROP_KB_DEPLOYMENT_CONFIG); if (configPath == null) configPath = System.getenv(SYS_PROP_KB_DEPLOYMENT_CONFIG); if (configPath == null) { configError = new IllegalStateException("Configuration file was not defined"); } else { System.out.println(UserProfileServer.class.getName() + ": Deployment config path was defined: " + configPath); try { config = new Ini(new File(configPath)).get(SERVICE_DEPLOYMENT_NAME); } catch (Throwable ex) { System.out.println(UserProfileServer.class.getName() + ": Error loading deployment config-file: " + ex.getMessage()); configError = ex; } } if (config == null) throw new IllegalStateException("There was unknown error in service initialization when checking" + "the configuration: is the ["+SERVICE_DEPLOYMENT_NAME+"] config group defined?"); return config; } private String getConfig(String configName) { String ret = config().get(configName); if (ret == null) throw new IllegalStateException("Parameter " + configName + " is not defined in configuration"); return ret; } private final MongoController db; //END_CLASS_HEADER public UserProfileServer() throws Exception { super("UserProfile"); //BEGIN_CONSTRUCTOR System.out.println(UserProfileServer.class.getName() + ": " + CFG_MONGO_HOST +" = " + getConfig(CFG_MONGO_HOST)); System.out.println(UserProfileServer.class.getName() + ": " + CFG_MONGO_DB +" = " + getConfig(CFG_MONGO_DB)); System.out.println(UserProfileServer.class.getName() + ": " + CFG_MONGO_RETRY +" = " + getConfig(CFG_MONGO_RETRY)); System.out.println(UserProfileServer.class.getName() + ": " + CFG_ADMIN +" = " + getConfig(CFG_ADMIN)); String mongoUser = ""; boolean useMongoAuth = true; try{ mongoUser = getConfig(CFG_MONGO_USER); } catch (Exception e) { useMongoAuth = false; } if(useMongoAuth) { db = new MongoController( getConfig(CFG_MONGO_HOST), getConfig(CFG_MONGO_DB), Integer.parseInt(getConfig(CFG_MONGO_RETRY)), mongoUser, getConfig(CFG_MONGO_PSWD) ); } else { db = new MongoController( getConfig(CFG_MONGO_HOST), getConfig(CFG_MONGO_DB), Integer.parseInt(getConfig(CFG_MONGO_RETRY))); } //END_CONSTRUCTOR } /** * <p>Original spec-file function name: ver</p> * <pre> * </pre> * @return instance of String */ @JsonServerMethod(rpc = "UserProfile.ver") public String ver() throws Exception { String returnVal = null; //BEGIN ver returnVal = VERSION; //END ver return returnVal; } /** * <p>Original spec-file function name: filter_users</p> * <pre> * Returns a list of users matching the filter. If the 'filter' field * is empty or null, then this will return all Users. The filter will * match substrings in usernames and realnames. * </pre> * @param p instance of type {@link us.kbase.userprofile.FilterParams FilterParams} * @return parameter "users" of list of type {@link us.kbase.userprofile.User User} */ @JsonServerMethod(rpc = "UserProfile.filter_users") public List<User> filterUsers(FilterParams p) throws Exception { List<User> returnVal = null; //BEGIN filter_users returnVal = db.filterUsers(p.getFilter()); //END filter_users return returnVal; } /** * <p>Original spec-file function name: get_user_profile</p> * <pre> * Given a list of usernames, returns a list of UserProfiles in the same order. * If no UserProfile was found for a username, the UserProfile at that position will * be null. * </pre> * @param usernames instance of list of original type "username" * @return parameter "profiles" of list of type {@link us.kbase.userprofile.UserProfile UserProfile} */ @JsonServerMethod(rpc = "UserProfile.get_user_profile") public List<UserProfile> getUserProfile(List<String> usernames) throws Exception { List<UserProfile> returnVal = null; //BEGIN get_user_profile returnVal = new ArrayList<UserProfile>(); for(int k=0; k<usernames.size(); k++) { // todo: make this one single batch query returnVal.add(db.getProfile(usernames.get(k))); } //END get_user_profile return returnVal; } /** * <p>Original spec-file function name: set_user_profile</p> * <pre> * Set the UserProfile for the user indicated in the User field of the UserProfile * object. This operation can only be performed if authenticated as the user in * the UserProfile or as the admin account of this service. * If the profile does not exist, one will be created. If it does already exist, * then the entire user profile will be replaced with the new profile. * </pre> * @param p instance of type {@link us.kbase.userprofile.SetUserProfileParams SetUserProfileParams} */ @JsonServerMethod(rpc = "UserProfile.set_user_profile") public void setUserProfile(SetUserProfileParams p, AuthToken authPart) throws Exception { //BEGIN set_user_profile if(p.getProfile()==null) throw new Exception("'profile' field must be set."); if(p.getProfile().getUser()==null) throw new Exception("'profile.user' field must be set."); if(p.getProfile().getUser().getUsername()==null) throw new Exception("'profile.user.username' field must be set."); if(!authPart.getUserName().equals(p.getProfile().getUser().getUsername()) && !authPart.getUserName().equals(getConfig(CFG_ADMIN))) { throw new Exception("only the user '"+p.getProfile().getUser().getUsername()+ "'or an admin can update this profile"); } db.setProfile(p.getProfile()); //END set_user_profile } /** * <p>Original spec-file function name: update_user_profile</p> * <pre> * Update the UserProfile for the user indicated in the User field of the UserProfile * object. This operation can only be performed if authenticated as the user in * the UserProfile or as the admin account of this service. * If the profile does not exist, one will be created. If it does already exist, * then the specified top-level fields in profile will be updated. * todo: add some way to remove fields. Fields in profile can only be modified or added. * </pre> * @param p instance of type {@link us.kbase.userprofile.SetUserProfileParams SetUserProfileParams} */ @JsonServerMethod(rpc = "UserProfile.update_user_profile") public void updateUserProfile(SetUserProfileParams p, AuthToken authPart) throws Exception { //BEGIN update_user_profile if(p.getProfile()==null) throw new Exception("'profile' field must be set."); if(p.getProfile().getUser()==null) throw new Exception("'profile.user' field must be set."); if(p.getProfile().getUser().getUsername()==null) throw new Exception("'profile.user.username' field must be set."); if(!authPart.getUserName().equals(p.getProfile().getUser().getUsername()) && !authPart.getUserName().equals(getConfig(CFG_ADMIN))) { throw new Exception("only the user '"+p.getProfile().getUser().getUsername()+ "'or an admin can update this profile"); } db.updateProfile(p.getProfile()); //END update_user_profile } /** * <p>Original spec-file function name: lookup_globus_user</p> * <pre> * </pre> * @param usernames instance of list of original type "username" * @return parameter "users" of mapping from original type "username" to type {@link us.kbase.userprofile.GlobusUser GlobusUser} */ @JsonServerMethod(rpc = "UserProfile.lookup_globus_user") public Map<String,GlobusUser> lookupGlobusUser(List<String> usernames, AuthToken authPart) throws Exception { Map<String,GlobusUser> returnVal = null; //BEGIN lookup_globus_user Map<String, UserDetail> data = AuthService.fetchUserDetail(usernames, authPart); Map<String, GlobusUser> ret = new HashMap<String, GlobusUser>(data.size()); for (UserDetail ud : data.values()) { ret.put(ud.getUserName(), new GlobusUser() .withEmail(ud.getEmail()) .withFullName(ud.getFullName()) .withUserName(ud.getUserName())); } //END lookup_globus_user return returnVal; } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <program> <server_port>"); return; } new UserProfileServer().startupServer(Integer.parseInt(args[0])); } }
package com.psddev.dari.util; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; /** * Skeletal runnable implementation that contains basic execution control * and status methods. Subclasses must implement: * * <ul> * <li>{@link #doTask} * </ul> */ public abstract class Task implements Comparable<Task>, Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Task.class); private final TaskExecutor executor; private final String name; private final AtomicReference<Future<?>> future = new AtomicReference<Future<?>>(); private final AtomicBoolean isRunning = new AtomicBoolean(); private final AtomicBoolean isPauseRequested = new AtomicBoolean(); private final AtomicBoolean isStopRequested = new AtomicBoolean(); private volatile Thread thread; private volatile long lastRunBegin = -1; private volatile long lastRunEnd = -1; private volatile String progress; private volatile long progressIndex; private volatile long progressTotal = -1; private volatile Throwable lastException; private final AtomicLong runCount = new AtomicLong(); /** * Creates an instance that will run in the given * {@code initialExecutor} with the given {@code initialName}. * * @param initialExecutor If {@code null}, this task will run in the * default executor. * @param initialName If blank, this task will be named based on its * class name and the count of all instances created so far. */ protected Task(String initialExecutor, String initialName) { executor = TaskExecutor.Static.getInstance(initialExecutor); if (ObjectUtils.isBlank(initialName)) { initialName = getClass().getName(); } name = initialName + " #" + TASK_INDEXES.getUnchecked(initialName).incrementAndGet(); } private static final LoadingCache<String, AtomicLong> TASK_INDEXES = CacheBuilder. newBuilder(). build(new CacheLoader<String, AtomicLong>() { @Override public AtomicLong load(String name) { return new AtomicLong(); } }); /** * Creates an instance that will run in the default executor * anonymously. */ protected Task() { this(null); } /** * Returns the executor that will run this task. * * @return Never {@code null}. */ public TaskExecutor getExecutor() { return executor; } /** * Returns the name. * * @return Never blank. */ public String getName() { return name; } /** * Returns the future. * * @return {@code null} if this task hasn't been started or scheduled. */ public Future<?> getFuture() { return future.get(); } private boolean isSubmittable() { Future<?> future = getFuture(); return future == null || future.isDone(); } private static long nano(double seconds) { return (long) (seconds * 1e9); } /** * Submits this task to run immediately. Does nothing if this task is * already scheduled to run. */ public void submit() { synchronized (future) { if (isSubmittable()) { future.set(getExecutor().submit(this)); } } } /** * Schedule this task to run after the given {@code initialDelay}. * Does nothing if this task is already scheduled to run. * * @param initialDelay In seconds. */ public void schedule(double initialDelay) { synchronized (future) { if (isSubmittable()) { future.set(getExecutor().schedule(this, nano(initialDelay), TimeUnit.NANOSECONDS)); } } } /** * Schedule this task to run after the given {@code initialDelay} and * forever after. Each subsequent runs will be scheduled to execute after * the given {@code periodicDelay} once the current one finishes. Does * nothing if this task is already scheduled to run. * * @param initialDelay In seconds. * @param periodicDelay In seconds. */ public void scheduleWithFixedDelay(double initialDelay, double periodicDelay) { synchronized (future) { if (isSubmittable()) { future.set(getExecutor().scheduleWithFixedDelay(this, nano(initialDelay), nano(periodicDelay), TimeUnit.NANOSECONDS)); } } } /** * Schedule this task to run after the given {@code initialDelay} and * forever after every given {@code periodicDelay}. Does nothing if this * task is already scheduled to run. * * @param initialDelay In seconds. * @param periodicDelay In seconds. */ public void scheduleAtFixedRate(double initialDelay, double periodicDelay) { synchronized (future) { if (isSubmittable()) { future.set(getExecutor().scheduleAtFixedRate(this, nano(initialDelay), nano(periodicDelay), TimeUnit.NANOSECONDS)); } } } /** * Returns the thread where this task is running. * * @return {@code null} if this task isn't running. */ public Thread getThread() { return thread; } /** * Returns {@code true} if the thread running this task has been * interrupted. * * @return Always {@code false} if this task isn't running. */ public boolean isInterrupted() { Thread thread = getThread(); return thread != null && thread.isInterrupted(); } /** Returns {@code true} if this task is currently running. */ public boolean isRunning() { return isRunning.get(); } /** * Returns {@code true} if {@link #pause} has been called on this * task. */ public boolean isPauseRequested() { return isPauseRequested.get(); } /** Tries to pause this task. */ public void pause() { if (isPauseRequested.compareAndSet(false, true)) { LOGGER.debug("Pausing [{}]", getName()); } } /** Resumes this task if it's paused. */ public void resume() { if (isPauseRequested.compareAndSet(true, false)) { LOGGER.debug("Resuming [{}]", getName()); synchronized (isPauseRequested) { isPauseRequested.notifyAll(); } } } /** * Returns {@code true} if {@link #stop} has been called on this * task. */ public boolean isStopRequested() { return isStopRequested.get(); } /** Tries to stop this task. */ public void stop() { if (isStopRequested.compareAndSet(false, true)) { LOGGER.debug("Stopping [{}]", getName()); synchronized (future) { Future<?> f = getFuture(); if (f != null && f.cancel(true)) { return; } } Thread t = getThread(); if (t != null) { t.interrupt(); } } } /** * Returns the time when the last run of this task began. * * @return Milliseconds since the epoch. {@code -1} if this task * never ran. */ public long getLastRunBegin() { return lastRunBegin; } /** * Returns the time when the last run of this task ended. * * @return Milliseconds since the epoch. {@code -1} if this task * is currenting running. */ public long getLastRunEnd() { return lastRunEnd; } /** * Returns the run duration for this task. If it's not currently * running, this method returns the measurement from the last run. * * @return In milliseconds. {@code -1} if this task never ran. */ public long getRunDuration() { long runBegin = getLastRunBegin(); if (runBegin < 0) { return -1; } else { long lastRunEnd = getLastRunEnd(); long runEnd = lastRunEnd > 0 ? lastRunEnd : System.currentTimeMillis(); return runEnd - runBegin; } } /** * Returns the progress. * * @return {@code null} if the progress isn't available. */ public String getProgress() { return progress; } /** * Sets the progress. For numeric progress, consider using * {@link #setProgressIndex} and {@link #setProgressTotal} instead. */ public void setProgress(String newProgress) { progress = newProgress; } /** * Returns the progress index. * * @return {@code -1} if the progress index isn't available. */ public long getProgressIndex() { return progressIndex; } /** Sets the progress index. Also updates the progress string. */ public void setProgressIndex(long newProgressIndex) { progressIndex = newProgressIndex; setProgressAutomatically(); } /** * Adds the given {@code amount} to the progress index. Also updates * the progress string. */ public void addProgressIndex(long amount) { setProgressIndex(getProgressIndex() + amount); } /** * Returns the progress total. * * @return {@code -1} if the progress total isn't available. */ public long getProgressTotal() { return progressTotal; } /** Sets the progress total. Also updates the progress string. */ public void setProgressTotal(long newProgressTotal) { progressTotal = newProgressTotal; setProgressAutomatically(); } private void setProgressAutomatically() { StringBuilder progress = new StringBuilder(); long index = getProgressIndex(); progress.append(index); progress.append('/'); long total = getProgressTotal(); if (total < 0) { progress.append('?'); } else { progress.append(total); progress.append(" ("); progress.append(index / (double) total * 100.0); progress.append(')'); } setProgress(progress.toString()); } /** * Returns the exception thrown from the last run of this task. * * @return {@code null} if there wasn't an error. */ public Throwable getLastException() { return lastException; } /** Returns the number of times that this task ran. */ public long getRunCount() { return runCount.get(); } @Override public int compareTo(Task other) { return getName().compareTo(other.getName()); } /** Returns {@code true} if this task should continue running. */ protected boolean shouldContinue() { if (isInterrupted() || isStopRequested()) { return false; } synchronized (isPauseRequested) { while (isPauseRequested()) { try { isPauseRequested.wait(); } catch (InterruptedException ex) { return false; } } } return true; } /** Called by {@link #run} to execute the actual task logic. */ protected abstract void doTask() throws Exception; @Override public final void run() { if (!isRunning.compareAndSet(false, true)) { LOGGER.debug("[{}] already running!", getName()); return; } // If running in Tomcat and this task belongs to an undeployed // application, stop running immediately. ClassLoader loader = getClass().getClassLoader(); Class<?> loaderClass = loader.getClass(); String loaderClassName = loaderClass.getName(); if ("org.apache.catalina.loader.WebappClassLoader".equals(loaderClassName)) { try { Field startedField = loaderClass.getDeclaredField("started"); startedField.setAccessible(true); if (Boolean.FALSE.equals(startedField.get(loader))) { stop(); return; } } catch (IllegalAccessException error) { // This should never happen since #setAccessible is called // on the field. } catch (NoSuchFieldException error) { // In case this code is used on future versions of Tomcat that // doesn't use the field any more. } } try { LOGGER.debug("Begin running [{}]", getName()); thread = Thread.currentThread(); lastRunBegin = System.currentTimeMillis(); lastRunEnd = -1; progress = null; progressIndex = 0; progressTotal = -1; lastException = null; if (shouldContinue()) { doTask(); } } catch (Throwable ex) { LOGGER.warn(String.format("Error running [%s]!", getName()), ex); lastException = ex; } finally { LOGGER.debug("End running [{}]", getName()); thread = null; lastRunEnd = System.currentTimeMillis(); runCount.incrementAndGet(); isRunning.set(false); isPauseRequested.set(false); isStopRequested.set(false); } } /** * @deprecated Use {@link TaskExecutor.Static#getAll} and * {@link TaskExecutor#getTasks} instead. */ @Deprecated public static List<Task> getInstances() { List<Task> tasks = new ArrayList<Task>(); for (TaskExecutor executor : TaskExecutor.Static.getAll()) { for (Object taskObject : executor.getTasks()) { if (taskObject instanceof Task) { tasks.add((Task) taskObject); } } } return tasks; } /** * Creates an instance that will run in the default executor * with the given {@code name}. * * @param name If blank, this task will be named based on its * class name and the count of all instances created so far. * * @deprecated Use {@link #Task(String, String)} instead. */ @Deprecated protected Task(String name) { this(null, name); } /** @deprecated Use {@link #getLastRunBegin} instead. */ @Deprecated public Date getStartTime() { return new Date(lastRunBegin); } /** @deprecated Use {@link #getLastRunEnd} instead. */ @Deprecated public Date getStopTime() { return new Date(lastRunEnd); } /** @deprecated Use {@link #getRunDuration} instead. */ @Deprecated public Long getDuration() { long runDuration = getRunDuration(); return runDuration > 0 ? runDuration : null; } /** @deprecated Use {@link #getRunCount} instead. */ @Deprecated public long getCount() { return runCount.get(); } /** @deprecated Use {@link #submit} instead. */ @Deprecated public void start() { submit(); } /** @deprecated Use {@link #schedule(double)} instead. */ @Deprecated public void scheduleOnce(double initialDelay) { schedule(initialDelay); } /** @deprecated Use {@link #scheduleWithFixedDelay} instead. */ @Deprecated public void schedule(double initialDelay, double periodicDelay) { scheduleWithFixedDelay(initialDelay, periodicDelay); } }
package main; public class BlankClass { public static void main(String[] args) { } }
import java.util.* ; import java.io.* ; import java.lang.* ; public class PlayGame { public static int nodes ; /** * print the possible actions */ public static void printActions ( Vector v ) { Iterator< int [] > itSucc = v.iterator () ; for ( ; itSucc.hasNext () ; ) { int [] pair = itSucc.next () ; System.out.println ( pair [ 0 ] + ", " + pair [ 1 ] ) ; } } /** * testPlay: this test the actions, the */ public static void testPlay () { State board = new State () ; Vector actions = new Vector< int [] > () ; System.out.println ( board.toString () ) ; while ( board.terminal () == false ) { System.out.println ( board.toString () ) ; System.out.println ( "Player " + board.getPlayer () ) ; actions = board.action () ; Iterator< int [] > itSucc = actions.iterator () ; printActions ( actions ) ; int [] a = new int [ 2 ] ; int player = board.getPlayer () ; a = itSucc.next () ; // play the first available move State c = board.result ( player , a [ 0 ] , a [ 1 ] ) ; board = c ; } System.out.println ( "Final? " + board.terminal () ) ; System.out.println ( "Value? " + board.utility () ) ; } public static void testPlayOptimal () { // State board = new State(); //State board = new State ( 2 , 1 , 0 , 0 , 1 , 0 , 0 , 2 , 0 ) ; nodes = 0 ; State board = new State ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) ; while ( board.terminal () == false ) { int [] move = minimax ( board ) ; System.out.println ( "Player: " + board.getPlayer () + "\nMove: (" + move [ 0 ] + "," + move [ 1 ] + ") => value " + move [ 2 ] ) ; State c = board.result ( board.getPlayer () , move [ 0 ] , move [ 1 ] ) ; board = c.copy () ; System.out.println ( "Board \n" + board.toString () ) ; } System.out.println ( "Final? " + board.terminal () ) ; System.out.println ( "Value? " + board.utility () ) ; System.out.println ( "Nodes created: " + nodes ) ; System.out.println ( "\n\n\n\n" ) ; nodes = 0 ; board = new State ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) ; //board = new State ( 2 , 1 , 0 , 0 , 1 , 0 , 0 , 2 , 0 ) ; while ( board.terminal () == false ) { int [] move = alphabeta ( board ) ; System.out.println ( "Player: " + board.getPlayer () + "\nMove: (" + move [ 0 ] + "," + move [ 1 ] + ") => value " + move [ 2 ] ) ; State c = board.result ( board.getPlayer () , move [ 0 ] , move [ 1 ] ) ; board = c.copy () ; System.out.println ( "Board \n" + board.toString () ) ; } System.out.println ( "Final? " + board.terminal () ) ; System.out.println ( "Value? " + board.utility () ) ; System.out.println ( "Nodes created: " + nodes ) ; } /** * testAction used for testing the computation of * possible actions in a given configuration */ public static void testAction () { State board = new State () ; Vector actions = new Vector<int[]> () ; System.out.println ( board.toString () ) ; actions = board.action () ; printActions ( actions ) ; System.out.println ( "After setting 1 at 0 0" ) ; board.setAt ( 1 , 0 , 0 ) ; actions = board.action () ; printActions ( actions ) ; } /** * Test the utility function */ public static void testUtility () { State board = new State ( 1 , 1 , 1 , 2 , 2 , 0 , 0 , 0 , 0 ) ; System.out.println ( board.toString () ) ; System.out.println ( "Final? " + board.terminal () ) ; System.out.println ( "Value? " + board.utility () ) ; board = new State ( 1 , 1 , 0 , 2 , 2 , 2 , 1 , 0 , 0 ) ; System.out.println ( board.toString () ) ; System.out.println ( "Final? " + board.terminal () ) ; System.out.println ( "Value? " + board.utility () ) ; board = new State ( 1 , 1 , 2 , 2 , 2 , 2 , 1 , 1 , 0 ) ; System.out.println ( board.toString () ) ; System.out.println ( "Final? " + board.terminal () ) ; System.out.println ( "Value? " + board.utility () ) ; board = new State ( 1 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 ) ; System.out.println ( board.toString () ) ; System.out.println ( "Final? " + board.terminal () ) ; System.out.println ( "Value? " + board.utility () ) ; } /** * Minimax * * This generates a gametree that calculates every possible move recursively * to discover the move which is most beneficial to make. This will block a * move that exists and allows the opposing player to win the game as well * as win the game if a game winning move exists. * * @param s state the current state of the board * @return returns the result of the serach. * move[0]: the row to make the move * move[1]: the column to make the move * move[2]: the utility cost of the move */ public static int [] minimax ( State s ) { Vector< int [] > actions = s.action () ; int [] result = new int [ 3 ] ; // start the result at "negative infinity" result [ 2 ] = Integer.MIN_VALUE ; for ( int i = 0 ; i < actions.size () ; i ++ ) { nodes ++ ; // track nodes created, used for testing int [] move = actions.elementAt ( i ) ; int value = minvalue ( s.result ( s.getPlayer () , move [ 0 ] , move [ 1 ] ) ) ; if ( value > result [ 2 ] ) { result [ 0 ] = move [ 0 ] ; result [ 1 ] = move [ 1 ] ; result [ 2 ] = value ; } } return result ; } /** * MinValue * * Recursively finds the minimum maximum value from available actions. * * @param s state the current state of the board * @return the utility score of the best move */ public static int minvalue ( State s ) { if ( s.terminal () == true ) { // if player 1, negate the result to get the MIN perspective if ( s.getPlayer () == 1 ) return -s.utility () ; return s.utility () ; } Vector< int [] > actions = s.action () ; // start score at "possitive infinity" int score = Integer.MAX_VALUE ; int [] move = new int [ 2 ] ; for ( int i = 0 ; i < actions.size () ; i ++ ) { nodes ++ ; // track nodes created, used for testing move = actions.elementAt ( i ) ; score = Math.min ( score, maxvalue ( s.result ( s.getPlayer () , move [ 0 ] , move [ 1 ] ) ) ) ; } return score ; } /** * MaxValue * * Recursively finds the maximum minimum value from available actions. * * @param s state the current state of the board * @return the utility score of the best move */ public static int maxvalue ( State s ) { if ( s.terminal () == true ) { if ( s.getPlayer () == 1 ) return s.utility () ; // if player 2, negate the result to get MIN perspective return -s.utility () ; } Vector< int [] > actions = s.action () ; // start score at "negative infinity" int score = Integer.MIN_VALUE ; int [] move = new int [ 2 ] ; for ( int i = 0 ; i < actions.size () ; i ++ ) { nodes ++ ; // track nodes created, used for testing move = actions.elementAt ( i ) ; score = Math.max ( score , minvalue ( s.result ( s.getPlayer () , move [ 0 ] , move [ 1 ] ) ) ) ; } return score ; } /** * Alpha-Beta Pruning * * This generates a gametree that prunes the results as soon as it has found * a minimum that is lower than another branch of the subtree. * * @param s state the current state of the board * @return returns the result of the serach. * move[0]: the row to make the move * move[1]: the column to make the move * move[2]: the utility cost of the move */ public static int [] alphabeta ( State s ) { Vector< int [] > actions = s.action () ; int [] result = new int [ 3 ] ; // start score at "negative infinity" result [ 2 ] = Integer.MIN_VALUE ; for ( int i = 0 ; i < actions.size () ; i ++ ) { nodes ++ ; // track nodes created, used for testing int [] move = actions.elementAt ( i ) ; int value = abMinValue ( s.result ( s.getPlayer () , move [ 0 ] , move [ 1 ] ) , Integer.MIN_VALUE , Integer.MAX_VALUE ) ; if ( value > result [ 2 ] ) { result [ 0 ] = move [ 0 ] ; result [ 1 ] = move [ 1 ] ; result [ 2 ] = value ; } } return result ; } /** * Alpha-Beta MaxValue * * Recursively finds the maximum minimum value from available actions. * * @param s state the current state of the board * @param a alpha the maximum value found in the chains * @param b beta the minimum value found in the chains * @return the utility score of the best move */ public static int abMaxValue ( State s , int a , int b ) { if ( s.terminal () == true ) { if ( s.getPlayer () == 1 ) return s.utility () ; // if player 2, negate the result to get MIN perspective return -s.utility () ; } Vector< int [] > actions = s.action () ; // start score at "negative infinity" int score = Integer.MIN_VALUE ; int [] move = new int [ 2 ] ; for ( int i = 0 ; i < actions.size () ; i ++ ) { nodes ++ ; // track nodes created, used for testing move = actions.elementAt ( i ) ; score = Math.max ( score , abMinValue ( s.result ( s.getPlayer () , move [ 0 ] , move [ 1 ] ) , a , b ) ) ; if ( score >= b ) return score ; a = Math.max ( a , score ) ; } return score ; } /** * Alpha-Beta MinValue * * Recursively finds the minimum maximum value from available actions. * * @param s state the current state of the board * @param a alpha the maximum value found in the chains * @param b beta the minimum value found in the chains * @return the utility score of the best move */ public static int abMinValue ( State s , int a , int b ) { if ( s.terminal () == true ) { // if player 1, negate the result to get the MIN perspective if ( s.getPlayer () == 1 ) return -s.utility () ; return s.utility () ; } Vector< int [] > actions = s.action () ; // start score at "possitive infinity" int score = Integer.MAX_VALUE ; int [] move = new int [ 2 ] ; for ( int i = 0 ; i < actions.size () ; i ++ ) { nodes ++ ; // track nodes created, used for testing move = actions.elementAt ( i ) ; score = Math.min ( score, abMaxValue ( s.result ( s.getPlayer () , move [ 0 ] , move [ 1 ] ) , a , b ) ) ; if ( score <= a ) return score ; b = Math.min ( b , score ) ; } return score ; } /** * @param args */ public static void main ( String [] args ) { //testAction(); //testUtility(); testPlayOptimal(); /*State board = new State(2,1,1,0,1,0,0,2,0); board.setPlayer(2); int[] move = minvalue(board); System.out.println(board.toString()); System.out.println("Move: ("+move[0]+","+move[1]+") => value " + move[2]); */ } }
import java.awt.Image; import java.net.URL; public class MediaCheck { public static void media(URL url) { Image image = null; } }
package cpw.mods.fml.server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.IOUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.MapDifference; import net.minecraft.entity.Entity; import net.minecraft.network.INetworkManager; import net.minecraft.network.packet.NetHandler; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.Packet131MapData; import net.minecraft.server.MinecraftServer; import net.minecraft.util.StringTranslate; import net.minecraft.world.World; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.IFMLSidedHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.common.ObfuscationReflectionHelper; import cpw.mods.fml.common.network.EntitySpawnAdjustmentPacket; import cpw.mods.fml.common.network.EntitySpawnPacket; import cpw.mods.fml.common.network.ModMissingPacket; import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.ItemData; import cpw.mods.fml.common.registry.LanguageRegistry; import cpw.mods.fml.relauncher.Side; /** * Handles primary communication from hooked code into the system * * The FML entry point is {@link #beginServerLoading(MinecraftServer)} called from * {@link net.minecraft.server.dedicated.DedicatedServer} * * Obfuscated code should focus on this class and other members of the "server" * (or "client") code * * The actual mod loading is handled at arms length by {@link Loader} * * It is expected that a similar class will exist for each target environment: * Bukkit and Client side. * * It should not be directly modified. * * @author cpw * */ public class FMLServerHandler implements IFMLSidedHandler { /** * The singleton */ private static final FMLServerHandler INSTANCE = new FMLServerHandler(); /** * A reference to the server itself */ private MinecraftServer server; private FMLServerHandler() { FMLCommonHandler.instance().beginLoading(this); } /** * Called to start the whole game off from * {@link MinecraftServer#startServer} * * @param minecraftServer */ public void beginServerLoading(MinecraftServer minecraftServer) { server = minecraftServer; Loader.instance().loadMods(); } /** * Called a bit later on during server initialization to finish loading mods */ public void finishServerLoading() { Loader.instance().initializeMods(); LanguageRegistry.reloadLanguageTable(); GameData.initializeServerGate(1); } @Override public void haltGame(String message, Throwable exception) { throw new RuntimeException(message, exception); } /** * Get the server instance */ public MinecraftServer getServer() { return server; } /** * @return the instance */ public static FMLServerHandler instance() { return INSTANCE; } /* (non-Javadoc) * @see cpw.mods.fml.common.IFMLSidedHandler#getAdditionalBrandingInformation() */ @Override public List<String> getAdditionalBrandingInformation() { return ImmutableList.<String>of(); } /* (non-Javadoc) * @see cpw.mods.fml.common.IFMLSidedHandler#getSide() */ @Override public Side getSide() { return Side.SERVER; } @Override public void showGuiScreen(Object clientGuiElement) { } @Override public Entity spawnEntityIntoClientWorld(EntityRegistration er, EntitySpawnPacket packet) { // NOOP return null; } @Override public void adjustEntityLocationOnClient(EntitySpawnAdjustmentPacket entitySpawnAdjustmentPacket) { // NOOP } @Override public void sendPacket(Packet packet) { throw new RuntimeException("You cannot send a bare packet without a target on the server!"); } @Override public void displayMissingMods(ModMissingPacket modMissingPacket) { // NOOP on server } @Override public void handleTinyPacket(NetHandler handler, Packet131MapData mapData) { // NOOP on server } @Override public void setClientCompatibilityLevel(byte compatibilityLevel) { // NOOP on server } @Override public byte getClientCompatibilityLevel() { return 0; } @Override public boolean shouldServerShouldBeKilledQuietly() { return false; } @Override public void disconnectIDMismatch(MapDifference<Integer, ItemData> s, NetHandler handler, INetworkManager mgr) { } @Override public void addModAsResource(ModContainer container) { File source = container.getSource(); try { if (source.isDirectory()) { searchDirForENUSLanguage(source,""); } else { searchZipForENUSLanguage(source); } } catch (IOException ioe) { } } private static final Pattern assetENUSLang = Pattern.compile("assets/(.*)/lang/en_US.lang"); private void searchZipForENUSLanguage(File source) throws IOException { ZipFile zf = new ZipFile(source); for (ZipEntry ze : Collections.list(zf.entries())) { Matcher matcher = assetENUSLang.matcher(ze.getName()); if (matcher.matches()) { FMLLog.fine("Injecting found translation data in zip file %s at %s into language system", source.getName(), ze.getName()); StringTranslate.inject(zf.getInputStream(ze)); } } zf.close(); } private void searchDirForENUSLanguage(File source, String path) throws IOException { for (File file : source.listFiles()) { String currPath = path+file.getName(); if (file.isDirectory()) { searchDirForENUSLanguage(file, currPath+'/'); } Matcher matcher = assetENUSLang.matcher(currPath); if (matcher.matches()) { FMLLog.fine("Injecting found translation data at %s into language system", currPath); StringTranslate.inject(new FileInputStream(file)); } } } @Override public void updateResourcePackList() { } }
package com.ecyrd.jspwiki.providers; import java.io.IOException; import java.util.*; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.parser.MarkupParser; import com.ecyrd.jspwiki.render.RenderingManager; import com.ecyrd.jspwiki.util.ClassUtil; import com.opensymphony.oscache.base.Cache; import com.opensymphony.oscache.base.NeedsRefreshException; import com.opensymphony.oscache.base.events.*; /** * Provides a caching page provider. This class rests on top of a * real provider class and provides a cache to speed things up. Only * if the cache copy of the page text has expired, we fetch it from * the provider. * <p> * This class also detects if someone has modified the page * externally, not through JSPWiki routines, and throws the proper * RepositoryModifiedException. * <p> * Heavily based on ideas by Chris Brooking. * <p> * Since 2.1.52 uses the OSCache library from OpenSymphony. * * @author Janne Jalkanen * @since 1.6.4 * @see RepositoryModifiedException */ // FIXME: Synchronization is a bit inconsistent in places. // FIXME: A part of the stuff is now redundant, since we could easily use the text cache // for a lot of things. RefactorMe. public class CachingProvider implements WikiPageProvider, VersioningProvider { private static final Logger log = Logger.getLogger(CachingProvider.class); private WikiPageProvider m_provider; // FIXME: Find another way to the search engine to use instead of from WikiEngine? private WikiEngine m_engine; private Cache m_cache; private Cache m_negCache; // Cache for holding non-existing pages private Cache m_textCache; private Cache m_historyCache; private long m_cacheMisses = 0; private long m_cacheHits = 0; private long m_historyCacheMisses = 0; private long m_historyCacheHits = 0; private int m_expiryPeriod = 30; /** * This can be very long, as normally all modifications are noticed in an earlier * stage. */ private int m_pageContentExpiryPeriod = 24*60*60; // FIXME: This MUST be cached somehow. private boolean m_gotall = false; private CacheItemCollector m_allCollector = new CacheItemCollector(); /** * Defines, in seconds, the amount of time a text will live in the cache * at most before requiring a refresh. */ public static final String PROP_CACHECHECKINTERVAL = "jspwiki.cachingProvider.cacheCheckInterval"; public static final String PROP_CACHECAPACITY = "jspwiki.cachingProvider.capacity"; private static final int DEFAULT_CACHECAPACITY = 1000; // Good most wikis private static final String OSCACHE_ALGORITHM = "com.opensymphony.oscache.base.algorithm.LRUCache"; public void initialize( WikiEngine engine, Properties properties ) throws NoRequiredPropertyException, IOException { log.debug("Initing CachingProvider"); // engine is used for getting the search engine m_engine = engine; // Cache consistency checks m_expiryPeriod = TextUtil.getIntegerProperty( properties, PROP_CACHECHECKINTERVAL, m_expiryPeriod ); log.debug("Cache expiry period is "+m_expiryPeriod+" s"); // Text cache capacity int capacity = TextUtil.getIntegerProperty( properties, PROP_CACHECAPACITY, DEFAULT_CACHECAPACITY ); log.debug("Cache capacity "+capacity+" pages."); m_cache = new Cache( true, false, false ); // OSCache documentation sucks big time. The clazz-parameter is completely // undefined; I had to read the source code to figure out that you need // to declare what type of a listener you are adding by sending the type // of the interface. m_cache.addCacheEventListener( m_allCollector, CacheEntryEventListener.class ); // FIXME: There's an interesting issue here... It would probably be // possible to DOS a JSPWiki instance by bombarding it with names that // do not exist, as they would fill the negcache. Will need to // think about this some more... m_negCache = new Cache( true, false, false ); m_textCache = new Cache( true, false, false, false, OSCACHE_ALGORITHM, capacity ); m_historyCache = new Cache( true, false, false, false, OSCACHE_ALGORITHM, capacity ); // Find and initialize real provider. String classname = WikiEngine.getRequiredProperty( properties, PageManager.PROP_PAGEPROVIDER ); try { Class providerclass = ClassUtil.findClass( "com.ecyrd.jspwiki.providers", classname ); m_provider = (WikiPageProvider)providerclass.newInstance(); log.debug("Initializing real provider class "+m_provider); m_provider.initialize( engine, properties ); } catch( ClassNotFoundException e ) { log.error("Unable to locate provider class "+classname,e); throw new IllegalArgumentException("no provider class"); } catch( InstantiationException e ) { log.error("Unable to create provider class "+classname,e); throw new IllegalArgumentException("faulty provider class"); } catch( IllegalAccessException e ) { log.error("Illegal access to provider class "+classname,e); throw new IllegalArgumentException("illegal provider class"); } } private WikiPage getPageInfoFromCache( String name ) throws ProviderException, RepositoryModifiedException { boolean wasUpdated = false; // Sanity check; seems to occur sometimes if( name == null ) return null; try { WikiPage item = (WikiPage)m_cache.getFromCache( name, m_expiryPeriod ); wasUpdated = true; if( item != null ) return item; return null; } catch( NeedsRefreshException e ) { WikiPage cached = (WikiPage)e.getCacheContent(); // int version = (cached != null) ? cached.getVersion() : WikiPageProvider.LATEST_VERSION; WikiPage refreshed; // Just be careful that we don't accidentally leave the cache in a // hung state refreshed = m_provider.getPageInfo( name, WikiPageProvider.LATEST_VERSION ); if( refreshed == null && cached != null ) { // Page has been removed evilly by a goon from outer space log.debug("Page "+name+" has been removed externally."); m_cache.putInCache( name, null ); m_textCache.putInCache( name, null ); m_historyCache.putInCache( name, null ); // We cache a page miss m_negCache.putInCache( name, name ); wasUpdated = true; throw new RepositoryModifiedException( "Removed: "+name, name ); } else if( cached == null ) { // The page did not exist in the first place if( refreshed != null ) { // We must now add it m_cache.putInCache( name, refreshed ); // Requests for this page are now no longer denied m_negCache.putInCache( name, null ); wasUpdated = true; throw new RepositoryModifiedException( "Added: "+name, name ); } // Cache page miss m_negCache.putInCache( name, name ); } else if( cached.getVersion() != refreshed.getVersion() ) { // The newest version has been deleted, but older versions still remain log.debug("Page "+cached.getName()+" newest version deleted, reloading..."); m_cache.putInCache( name, refreshed ); // Requests for this page are now no longer denied m_negCache.putInCache( name, null ); m_textCache.flushEntry( name ); m_historyCache.flushEntry( name ); wasUpdated = true; return refreshed; } else if( Math.abs(refreshed.getLastModified().getTime()-cached.getLastModified().getTime()) > 1000L ) { // Yes, the page has been modified externally and nobody told us log.info("Page "+cached.getName()+" changed, reloading..."); m_cache.putInCache( name, refreshed ); // Requests for this page are now no longer denied m_negCache.putInCache( name, null ); m_textCache.flushEntry( name ); m_historyCache.flushEntry( name ); wasUpdated = true; throw new RepositoryModifiedException( "Modified: "+name, name ); } else { // Refresh the cache by putting the same object back m_cache.putInCache( name, cached ); // Requests for this page are now no longer denied m_negCache.putInCache( name, null ); wasUpdated = true; } return cached; } finally { if( !wasUpdated ) m_cache.cancelUpdate(name); } } public boolean pageExists( String pageName, int version ) { if( pageName == null ) return false; // First, check the negative cache if we've seen it before try { String isNonExistant = (String) m_negCache.getFromCache( pageName, m_expiryPeriod ); if( isNonExistant != null ) return false; // No such page } catch( NeedsRefreshException e ) { m_negCache.cancelUpdate(pageName); } WikiPage p = null; try { p = getPageInfoFromCache( pageName ); } catch( RepositoryModifiedException e ) { // The repository was modified, we need to check now if the page was removed or // added. // TODO: This information would be available in the exception, but we would // need to subclass. try { p = getPageInfoFromCache( pageName ); } catch( Exception ex ) { return false; } // This should not happen } catch( ProviderException e ) { log.info("Provider failed while trying to check if page exists: "+pageName); return false; } if( p != null ) { int latestVersion = p.getVersion(); if( version == latestVersion || version == LATEST_VERSION ) { return true; } if( m_provider instanceof VersioningProvider ) return ((VersioningProvider) m_provider).pageExists( pageName, version ); } try { return getPageInfo( pageName, version ) != null; } catch( ProviderException e ) {} return false; } public boolean pageExists( String pageName ) { if( pageName == null ) return false; // First, check the negative cache if we've seen it before try { String isNonExistant = (String) m_negCache.getFromCache( pageName, m_expiryPeriod ); if( isNonExistant != null ) return false; // No such page } catch( NeedsRefreshException e ) { m_negCache.cancelUpdate(pageName); } WikiPage p = null; try { p = getPageInfoFromCache( pageName ); } catch( RepositoryModifiedException e ) { // The repository was modified, we need to check now if the page was removed or // added. // TODO: This information would be available in the exception, but we would // need to subclass. try { p = getPageInfoFromCache( pageName ); } catch( Exception ex ) { return false; } // This should not happen } catch( ProviderException e ) { log.info("Provider failed while trying to check if page exists: "+pageName); return false; } // A null item means that the page either does not // exist, or has not yet been cached; a non-null // means that the page does exist. if( p != null ) { return true; } // If we have a list of all pages in memory, then any page // not in the cache must be non-existent. // FIXME: There's a problem here; if someone modifies the // repository by adding a page outside JSPWiki, // we won't notice it. if( m_gotall ) { return false; } // We could add the page to the cache here as well, // but in order to understand whether that is a // good thing or not we would need to analyze // the JSPWiki calling patterns extensively. Presumably // it would be a good thing if pageExists() is called // many times before the first getPageText() is called, // and the whole page is cached. return m_provider.pageExists( pageName ); } /** * @throws RepositoryModifiedException If the page has been externally modified. */ public String getPageText( String pageName, int version ) throws ProviderException, RepositoryModifiedException { String result = null; if( pageName == null ) return null; if( version == WikiPageProvider.LATEST_VERSION ) { result = getTextFromCache( pageName ); } else { WikiPage p = getPageInfoFromCache( pageName ); // Or is this the latest version fetched by version number? if( p != null && p.getVersion() == version ) { result = getTextFromCache( pageName ); } else { result = m_provider.getPageText( pageName, version ); } } return result; } /** * @throws RepositoryModifiedException If the page has been externally modified. */ private String getTextFromCache( String pageName ) throws ProviderException, RepositoryModifiedException { String text; boolean wasUpdated = false; if( pageName == null ) return null; WikiPage page = getPageInfoFromCache( pageName ); try { text = (String)m_textCache.getFromCache( pageName, m_pageContentExpiryPeriod ); wasUpdated = true; if( text == null ) { if( page != null ) { text = m_provider.getPageText( pageName, WikiPageProvider.LATEST_VERSION ); m_textCache.putInCache( pageName, text ); m_cacheMisses++; } else { return null; } } else { m_cacheHits++; } } catch( NeedsRefreshException e ) { if( pageExists(pageName) ) { text = m_provider.getPageText( pageName, WikiPageProvider.LATEST_VERSION ); m_textCache.putInCache( pageName, text ); wasUpdated = true; m_cacheMisses++; } else { m_textCache.putInCache( pageName, null ); wasUpdated = true; return null; // No page exists } } finally { if( !wasUpdated ) m_textCache.cancelUpdate(pageName); } return text; } public void putPageText( WikiPage page, String text ) throws ProviderException { synchronized(this) { m_provider.putPageText( page, text ); page.setLastModified( new Date() ); // Refresh caches properly m_cache.flushEntry( page.getName() ); m_textCache.flushEntry( page.getName() ); m_historyCache.flushEntry( page.getName() ); m_negCache.flushEntry( page.getName() ); // Refresh caches try { getPageInfoFromCache( page.getName() ); } catch(RepositoryModifiedException e) {} // Expected } } public Collection getAllPages() throws ProviderException { Collection all; if( m_gotall == false ) { all = m_provider.getAllPages(); // Make sure that all pages are in the cache. synchronized(this) { for( Iterator i = all.iterator(); i.hasNext(); ) { WikiPage p = (WikiPage) i.next(); m_cache.putInCache( p.getName(), p ); // Requests for this page are now no longer denied m_negCache.putInCache( p.getName(), null ); } m_gotall = true; } } else { all = m_allCollector.getAllItems(); } return all; } public Collection getAllChangedSince( Date date ) { return m_provider.getAllChangedSince( date ); } public int getPageCount() throws ProviderException { return m_provider.getPageCount(); } public Collection findPages( QueryItem[] query ) { // If the provider is a fast searcher, then // just pass this request through. return m_provider.findPages( query ); // FIXME: Does not implement fast searching } // FIXME: Kludge: make sure that the page is also parsed and it gets all the // necessary variables. private void refreshMetadata( WikiPage page ) { if( page != null && !page.hasMetadata() ) { RenderingManager mgr = m_engine.getRenderingManager(); try { String data = m_provider.getPageText(page.getName(), page.getVersion()); WikiContext ctx = new WikiContext( m_engine, page ); MarkupParser parser = mgr.getParser( ctx, data ); parser.parse(); } catch( Exception ex ) { log.debug("Failed to retrieve variables for wikipage "+page); } } } public WikiPage getPageInfo( String pageName, int version ) throws ProviderException, RepositoryModifiedException { WikiPage page = null; WikiPage cached = getPageInfoFromCache( pageName ); int latestcached = (cached != null) ? cached.getVersion() : Integer.MIN_VALUE; if( version == WikiPageProvider.LATEST_VERSION || version == latestcached ) { if( cached == null ) { WikiPage data = m_provider.getPageInfo( pageName, version ); if( data != null ) { m_cache.putInCache( pageName, data ); // Requests for this page are now no longer denied m_negCache.putInCache( pageName, null ); } page = data; } else { page = cached; } } else { // We do not cache old versions. page = m_provider.getPageInfo( pageName, version ); //refreshMetadata( page ); } refreshMetadata( page ); return page; } public List getVersionHistory( String pageName ) throws ProviderException { List history = null; boolean wasUpdated = false; if( pageName == null ) return null; try { history = (List)m_historyCache.getFromCache( pageName, m_expiryPeriod ); log.debug("History cache hit for page "+pageName); m_historyCacheHits++; wasUpdated = true; } catch( NeedsRefreshException e ) { history = m_provider.getVersionHistory( pageName ); m_historyCache.putInCache( pageName, history ); log.debug("History cache miss for page "+pageName); m_historyCacheMisses++; wasUpdated = true; } finally { if( !wasUpdated ) m_historyCache.cancelUpdate( pageName ); } return history; } public synchronized String getProviderInfo() { return("Real provider: "+m_provider.getClass().getName()+ ". Cache misses: "+m_cacheMisses+ ". Cache hits: "+m_cacheHits+ ". History cache hits: "+m_historyCacheHits+ ". History cache misses: "+m_historyCacheMisses+ ". Cache consistency checks: "+m_expiryPeriod+"s"); } public void deleteVersion( String pageName, int version ) throws ProviderException { // Luckily, this is such a rare operation it is okay // to synchronize against the whole thing. synchronized( this ) { WikiPage cached = getPageInfoFromCache( pageName ); int latestcached = (cached != null) ? cached.getVersion() : Integer.MIN_VALUE; // If we have this version cached, remove from cache. if( version == WikiPageProvider.LATEST_VERSION || version == latestcached ) { m_cache.flushEntry( pageName ); m_textCache.putInCache( pageName, null ); m_historyCache.putInCache( pageName, null ); } m_provider.deleteVersion( pageName, version ); } } public void deletePage( String pageName ) throws ProviderException { // See note in deleteVersion(). synchronized(this) { m_cache.putInCache( pageName, null ); m_textCache.putInCache( pageName, null ); m_historyCache.putInCache( pageName, null ); m_negCache.putInCache( pageName, pageName ); m_provider.deletePage( pageName ); } } public void movePage( String from, String to ) throws ProviderException { m_provider.movePage( from, to ); synchronized(this) { // Clear any cached version of the old page log.debug("Removing page "+from+" from cache"); m_cache.flushEntry( from ); // Clear the cache for the to page, if that page already exists //if ( m_cache.get( to ) != null ) log.debug("Removing page "+to+" from cache"); m_cache.flushEntry( to ); } } /** * Returns the actual used provider. * @since 2.0 */ public WikiPageProvider getRealProvider() { return m_provider; } /** * This is a simple class that keeps a list of all WikiPages that * we have in memory. Because the OSCache cannot give us a list * of all pages currently in cache, we'll have to check this * ourselves. * * @author jalkanen * * @since 2.4 */ private class CacheItemCollector implements CacheEntryEventListener { private Map m_allItems = new HashMap(); /** * Returns a clone of the set - you cannot manipulate this. * * @return */ public Set getAllItems() { Set ret = new TreeSet(); ret.addAll(m_allItems.values()); return ret; } public void cacheEntryAdded( CacheEntryEvent arg0 ) { cacheEntryUpdated( arg0 ); } public void cachePatternFlushed( CachePatternEvent ev ) { } public void cacheGroupFlushed( CacheGroupEvent ev ) { } public void cacheFlushed( CachewideEvent ev ) { } public void cacheEntryFlushed( CacheEntryEvent arg0 ) { cacheEntryRemoved( arg0 ); } public void cacheEntryRemoved( CacheEntryEvent arg0 ) { WikiPage item = (WikiPage) arg0.getEntry().getContent(); if( item != null ) { m_allItems.remove( item ); } } public void cacheEntryUpdated( CacheEntryEvent arg0 ) { WikiPage item = (WikiPage) arg0.getEntry().getContent(); if( item != null ) { // Item added or replaced. m_allItems.put( item.getName(), item ); } else { // Removed item // FIXME: If the page system is changed during this time, we'll just fail gracefully m_allItems.remove( arg0.getKey() ); } } } }
package com.gmail.harleenssahni.mbr; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.gmail.harleenssahni.mbr.receivers.MediaButtonReceiver; /** * Allows the user to choose which media receiver will handle a media button * press. Can be navigated via touch screen or media button keys. Provides voice * feedback. * * @author harleenssahni@gmail.com */ public class MediaButtonList extends ListActivity implements OnInitListener { private class SweepBroadcastReceiver extends BroadcastReceiver { String name; public SweepBroadcastReceiver(String name) { this.name = name; } @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "After running broadcast receiver " + name + "have resultcode: " + getResultCode() + " result Data: " + getResultData()); } } /** Our tag for logging purposes and identification purposes. */ private static final String TAG = "MediaButtonRouter.Selector"; /** * Key used to store and retrieve last selected receiver. */ private static final String SELECTION_KEY = "btButtonSelection"; /** * Number of seconds to wait before timing out and just cancelling. */ private static final long TIMEOUT_TIME = 7; /** * The media button event that {@link MediaButtonReceiver} captured, and * that we will be forwarding to a music player's {@code BroadcastReceiver} * on selection. */ private KeyEvent trappedKeyEvent; /** * The {@code BroadcastReceiver}'s registered in the system for * * {@link Intent.ACTION_MEDIA_BUTTON}. */ private List<ResolveInfo> receivers; /** The intent filter for registering our local {@code BroadcastReceiver}. */ private IntentFilter uiIntentFilter; /** The text to speech engine used to announce navigation to the user. */ private TextToSpeech textToSpeech; /** * The receiver currently selected by bluetooth next/prev navigation. We * track this ourselves because there isn't persisted selection w/ touch * screen interfaces. */ private int btButtonSelection; /** * Whether we've done the start up announcement to the user using the text * to speech. Tracked so we don't repeat ourselves on orientation change. */ private boolean announced; /** * The power manager used to wake the device with a wake lock so that we can * handle input. Allows us to have a regular activity life cycle when media * buttons are pressed when and the screen is off. */ private PowerManager powerManager; /** * Used to wake up screen so that we can navigate our UI and select an app * to handle media button presses when display is off. */ private WakeLock wakeLock; /** * Local broadcast receiver that allows us to handle media button events for * navigation inside the activity. */ private BroadcastReceiver uiMediaReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { KeyEvent navigationKeyEvent = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT); int keyCode = navigationKeyEvent.getKeyCode(); if (Utils.isMediaButton(keyCode)) { Log.i(TAG, "Media Button Selector UI is directly handling key: " + navigationKeyEvent); if (navigationKeyEvent.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_NEXT: moveSelection(1); break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: moveSelection(-1); break; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: select(); break; case KeyEvent.KEYCODE_MEDIA_STOP: // just cancel finish(); break; default: break; } } abortBroadcast(); } } } }; /** * ScheduledExecutorService used to time out and close activity if the user * doesn't make a selection within certain amount of time. Resets on user * interaction. */ private ScheduledExecutorService timeoutExecutor; /** * ScheduledFuture of timeout. */ private ScheduledFuture<?> timeoutScheduledFuture; private View cancelButton; private ImageView mediaImage; private TextView header; /** * {@inheritDoc} */ @Override public void onInit(int status) { // text to speech initialized // XXX This is where we announce to the user what we're handling. It's // not clear that this will always get called. I don't know how else to // query if the text to speech is started though. // Only annouce if we haven't before if (!announced && trappedKeyEvent != null) { String actionText = ""; switch (trappedKeyEvent.getKeyCode()) { case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: // This is just play even though the keycode is both play/pause, // the app shouldn't handle // pause if music is already playing, it should go to whoever is // playing the music. actionText = "Play"; break; case KeyEvent.KEYCODE_MEDIA_NEXT: actionText = "Next"; break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: actionText = "Previous"; break; case KeyEvent.KEYCODE_MEDIA_STOP: actionText = "Stop"; break; } String textToSpeak = null; if (btButtonSelection > 0 && btButtonSelection < receivers.size()) { textToSpeak = "Select app to use for " + actionText + ", currently " + getAppName(receivers.get(btButtonSelection)); } else { textToSpeak = "Select app to use for " + actionText; } textToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null); announced = true; } } /** * {@inheritDoc} */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "On Create Called"); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); setContentView(R.layout.media_button_list); uiIntentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); uiIntentFilter.setPriority(Integer.MAX_VALUE); // TODO Handle text engine not installed, etc. Documented on android // developer guide textToSpeech = new TextToSpeech(this, this); powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); // XXX Is mode private right? Will this result in the selection being // stored in different places for this // and MediaButtonListLocked // btButtonSelection = savedInstanceState != null ? // savedInstanceState.getInt(SELECTION_KEY, -1) : -1; btButtonSelection = getPreferences(MODE_PRIVATE).getInt(SELECTION_KEY, -1); Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); receivers = getPackageManager().queryBroadcastReceivers(mediaButtonIntent, PackageManager.GET_INTENT_FILTERS | PackageManager.GET_RESOLVED_FILTER); Boolean lastAnnounced = (Boolean) getLastNonConfigurationInstance(); if (lastAnnounced != null) { announced = lastAnnounced; } // Remove our app's receiver from the list so users can't select it. // NOTE: Our local receiver isn't registered at this point so we don't // have to remove it. if (receivers != null) { for (int i = 0; i < receivers.size(); i++) { if (MediaButtonReceiver.class.getName().equals(receivers.get(i).activityInfo.name)) { receivers.remove(i); break; } } } // TODO MAYBE sort receivers by MRU so user doesn't have to skip as many // apps, // right now apps are sorted by priority (not set by the user, set by // the app authors.. ) setListAdapter(new BaseAdapter() { @Override public int getCount() { return receivers.size(); } @Override public Object getItem(int position) { return receivers.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = vi.inflate(R.layout.media_receiver_view, null); } ResolveInfo resolveInfo = receivers.get(position); ImageView imageView = (ImageView) view.findViewById(R.id.receiverAppImage); imageView.setImageDrawable(resolveInfo.loadIcon(getPackageManager())); TextView textView = (TextView) view.findViewById(R.id.receiverAppName); textView.setText(getAppName(resolveInfo)); return view; } }); header = (TextView) findViewById(R.id.dialogHeader); cancelButton = findViewById(R.id.cancelButton); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); mediaImage = (ImageView) findViewById(R.id.mediaImage); Log.i(TAG, "Media button selector created."); } /** * {@inheritDoc} */ @Override protected void onDestroy() { super.onDestroy(); textToSpeech.shutdown(); Log.d(TAG, "Media button selector destroyed."); } /** * {@inheritDoc} */ @Override protected void onListItemClick(ListView l, View v, int position, long id) { btButtonSelection = position; forwardToMediaReceiver(position); } /** * {@inheritDoc} */ @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause"); Log.d(TAG, "unegistered UI receiver"); unregisterReceiver(uiMediaReceiver); if (wakeLock.isHeld()) { wakeLock.release(); } textToSpeech.stop(); timeoutExecutor.shutdownNow(); getPreferences(MODE_PRIVATE).edit().putInt(SELECTION_KEY, btButtonSelection).commit(); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "On Start called"); // TODO Originally thought most work should happen onResume and onPause. // I don't know if the onResume part is // right since you can't actually ever get back to this view, single // instance, and not shown in recents. Maybe it's possible if ANOTHER // dialog opens in front of ours? } /** * {@inheritDoc} */ @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume"); // TODO Clean this up, figure out which things need to be set on the // list view and which don't. if (getIntent().getExtras() != null && getIntent().getExtras().get(Intent.EXTRA_KEY_EVENT) != null) { trappedKeyEvent = (KeyEvent) getIntent().getExtras().get(Intent.EXTRA_KEY_EVENT); Log.i(TAG, "Media button selector handling event: " + trappedKeyEvent + " from intent:" + getIntent()); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); getListView().setClickable(true); getListView().setFocusable(true); getListView().setFocusableInTouchMode(true); switch (trappedKeyEvent.getKeyCode()) { case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: header.setText("Android Media Router: Play"); break; case KeyEvent.KEYCODE_MEDIA_NEXT: header.setText("Android Media Router: Next"); break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: header.setText("Android Media Router: Previous"); break; case KeyEvent.KEYCODE_MEDIA_STOP: header.setText("Android Media Router: Stop"); break; } } else { Log.i(TAG, "Media button selector launched without key event, started with intent: " + getIntent()); trappedKeyEvent = null; getListView().setClickable(false); getListView().setChoiceMode(ListView.CHOICE_MODE_NONE); getListView().setFocusable(false); getListView().setFocusableInTouchMode(false); } Log.d(TAG, "Registered UI receiver"); registerReceiver(uiMediaReceiver, uiIntentFilter); // power on device's screen so we can interact with it, otherwise on // pause gets called immediately. // alternative would be to change all of the selection logic to happen // in a service?? don't know if that process life cycle would fit well // -- look into // added On after release so screen stays on a little longer instead of // immediately to try and stop resume pause cycle that sometimes // happens. wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG); wakeLock.setReferenceCounted(false); // FIXME The wakelock is too late here. We end up doing multiple // resume/pause cycles (at least three) before the screen turns on and // our app is stable (not flickering). What to do? wakeLock.acquire(); timeoutExecutor = Executors.newSingleThreadScheduledExecutor(); resetTimeout(); } /** * {@inheritDoc} */ @Override public Object onRetainNonConfigurationInstance() { return announced; } private void resetTimeout() { if (timeoutScheduledFuture != null) { timeoutScheduledFuture.cancel(false); } // TODO Clean this up timeoutScheduledFuture = timeoutExecutor.schedule(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { onTimeout(); } }); } }, TIMEOUT_TIME, TimeUnit.SECONDS); } /** * {@inheritDoc} */ @Override public void onUserInteraction() { super.onUserInteraction(); // Reset timeout to finish if (!timeoutExecutor.isShutdown()) { resetTimeout(); } } // /** // * {@inheritDoc} // */ // @Override // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt(SELECTION_KEY, btButtonSelection); // Log.d(TAG, "Saving selection state, selected is " + btButtonSelection); /** * Forwards the {@code #trappedKeyEvent} to the receiver at specified * position. * * @param position * The index of the receiver to select. Must be in bounds. */ private void forwardToMediaReceiver(int position) { ResolveInfo resolveInfo = receivers.get(position); if (resolveInfo != null) { if (trappedKeyEvent != null) { ComponentName selectedReceiver = new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name); Utils.forwardKeyCodeToComponent(this, selectedReceiver, true, trappedKeyEvent.getKeyCode(), new SweepBroadcastReceiver(selectedReceiver.toString())); finish(); } } } /** * Returns the name of the application of the broadcast receiver specified * by {@code resolveInfo}. * * @param resolveInfo * The receiver. * @return The name of the application. */ private String getAppName(ResolveInfo resolveInfo) { return resolveInfo.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString(); } /** * Moves selection by the amount specified in the list. If we're already at * the last item and we're moving forward, wraps to the first item. If we're * already at the first item, and we're moving backwards, wraps to the last * item. * * @param amount * The amount to move, may be positive or negative. */ private void moveSelection(int amount) { resetTimeout(); btButtonSelection += amount; if (btButtonSelection >= receivers.size()) { // wrap btButtonSelection = 0; } else if (btButtonSelection < 0) { // wrap btButtonSelection = receivers.size() - 1; } // May not highlight, but will scroll to item getListView().setSelection(btButtonSelection); // todo scroll to item, highlight it textToSpeech.speak(getAppName(receivers.get(btButtonSelection)), TextToSpeech.QUEUE_FLUSH, null); } /** * Select the currently selected receiver. */ private void select() { // TODO if there is no selection, we should either forward to whoever // would have handled if we didn't exist, or to mru if (btButtonSelection == -1) { finish(); } else { forwardToMediaReceiver(btButtonSelection); } } /** * Takes appropriate action to notify user and dismiss activity on timeout. */ private void onTimeout() { Log.d(TAG, "Timed out waiting for user interaction, finishing activity"); final MediaPlayer timeoutPlayer = MediaPlayer.create(this, R.raw.dismiss); timeoutPlayer.start(); // not having an on error listener results in on completion listener // being called anyway timeoutPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { timeoutPlayer.release(); } }); finish(); } }
package com.ibm.nmon.data.definition; import java.util.Collection; import java.util.List; import com.ibm.nmon.data.DataSet; import com.ibm.nmon.data.DataType; import com.ibm.nmon.data.matcher.HostMatcher; import com.ibm.nmon.data.matcher.TypeMatcher; import com.ibm.nmon.data.matcher.FieldMatcher; import com.ibm.nmon.analysis.Statistic; /** * Base class for programmatically defining a set of data. A definition can match any number of * hosts (via {@link DataSet DataSets}), {@link DataType DataTypes}, or fields. This class also * supports renaming these values as well. Finally, a {@link Statistic}, which defaults to * <code>AVERAGE</code>, can be specified for clients that need aggregated data. */ public abstract class DataDefinition { private final Statistic stat; private final boolean useSecondaryYAxis; public static DataDefinition ALL_DATA = new DataDefinition() { public List<DataSet> getMatchingHosts(Collection<DataSet> toMatch) { return HostMatcher.ALL.getMatchingHosts(toMatch); }; public List<DataType> getMatchingTypes(DataSet data) { return TypeMatcher.ALL.getMatchingTypes(data); }; public List<String> getMatchingFields(DataType type) { return FieldMatcher.ALL.getMatchingFields(type); } }; protected DataDefinition() { this(null, false); } protected DataDefinition(Statistic stat, boolean useSecondaryYAxis) { if (stat == null) { stat = Statistic.AVERAGE; } this.stat = stat; this.useSecondaryYAxis = useSecondaryYAxis; } public Statistic getStatistic() { return stat; } public boolean usesSecondaryYAxis() { return useSecondaryYAxis; } /** * Does the definition match the given host? * * @return <code>true</code>; by default matches all hosts */ public boolean matchesHost(DataSet data) { return HostMatcher.ALL.matchesHost(data); } /** * Given a list of <code>DataSet</code>s, return a new list containing the ones that match this * definition. */ public abstract List<DataSet> getMatchingHosts(Collection<DataSet> toMatch); /** * Given a list of <code>DataType</code>s, return a new list containing the ones that match this * definition. */ public abstract List<DataType> getMatchingTypes(DataSet data); /** * Given a <code>DataType</code>, return a new list containing the fields that match this * definition. */ public abstract List<String> getMatchingFields(DataType type); /** * Get a new hostname for the given <code>DataSet</code>. * * @return {@link DataSet#getHostname()} by default */ public String renameHost(DataSet data) { return data.getHostname(); } /** * Get a new name for the given <code>DataType</code>. * * @return {@link DataType#toString()} by default */ public String renameType(DataType type) { return type.toString(); } /** * Get a new name for the given field. * * @return the same field name by default */ public String renameField(String field) { return field; } }
package com.lassedissing.gamenight.events; import com.jme3.math.Vector3f; import com.jme3.network.serializing.Serializable; import com.lassedissing.gamenight.eventmanagning.EventClosure; import com.lassedissing.gamenight.world.Entity; import java.util.ArrayList; import java.util.List; @Serializable public class FlagEvent extends Event { private int flagId; private int playerId; private boolean reset; private boolean isMove; private Vector3f newLocation = new Vector3f(); public FlagEvent(int playerId, int flagId) { this.playerId = playerId; this.flagId = flagId; } public FlagEvent(int flagId, boolean reset) { this.reset = reset; } public FlagEvent(int flagId, Vector3f newLocation) { this.newLocation.set(newLocation); } public int getPlayerId() { return this.playerId; } public int getFlagId() { return this.flagId; } public boolean isReset() { return reset; } public boolean isMove() { return isMove; } public Vector3f getLocation() { return newLocation; } /** * Serialization */ public FlagEvent() { } //ClosureHolder section private static List<EventClosure> closures = new ArrayList<>(); @Override public int getClosureLevel() { return 1; } @Override public List<EventClosure> getClosures(int level) { switch (level) { case 0: return super.getClosures(level); case 1: return closures; default: throw new UnsupportedOperationException("Level " + level + " is not supported by " + getEventName()); } } }
package com.mebigfatguy.fbcontrib.debug; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.ClassContext; public class OCSDebugger extends BytecodeScanningDetector { private static final String OCS_OUTPUT_FILE = "fb-contrib.ocs.output"; private static final String OCS_METHOD_DESC = "fb-contrib.ocs.method"; private static final String OUTPUT_FILE_NAME = System.getProperty(OCS_OUTPUT_FILE); private static final String METHOD_DESC = System.getProperty(OCS_METHOD_DESC); private OpcodeStack stack = new OpcodeStack(); private PrintWriter pw = null; public OCSDebugger(BugReporter bugReporter) { } public void visitClassContext(ClassContext classContext) { if ((OUTPUT_FILE_NAME != null) && (METHOD_DESC != null)) super.visitClassContext(classContext); } public void visitCode(Code obj) { Method m = getMethod(); String curMethodDesc = getClassContext().getJavaClass().getClassName() + "." + m.getName() + m.getSignature(); if (curMethodDesc.equals(METHOD_DESC)) { try { pw = new PrintWriter(new FileWriter(OUTPUT_FILE_NAME)); stack.resetForMethodEntry(this); super.visitCode(obj); } catch (IOException e) { } finally { pw.close(); pw = null; } } } public void sawOpcode(int seen) { stack.precomputation(this); stack.sawOpcode(this, seen); pw.println(String.format("After executing: %-16s at PC: %-5d Stack Size: %-3d", Constants.OPCODE_NAMES[getOpcode()], getPC(), stack.getStackDepth())); } }
package com.miracle.intermediate.visitor; import com.miracle.MiracleOption; import com.miracle.intermediate.Root; import com.miracle.intermediate.instruction.*; import com.miracle.intermediate.instruction.arithmetic.BinaryArithmetic; import com.miracle.intermediate.instruction.arithmetic.UnaryArithmetic; import com.miracle.intermediate.instruction.fork.BinaryBranch; import com.miracle.intermediate.instruction.fork.Jump; import com.miracle.intermediate.instruction.fork.Return; import com.miracle.intermediate.instruction.fork.UnaryBranch; import com.miracle.intermediate.number.*; import com.miracle.intermediate.number.Number; import com.miracle.intermediate.structure.BasicBlock; import com.miracle.intermediate.structure.Function; import com.miracle.intermediate.visitor.printer.IRPrinter; import org.apache.commons.io.FileUtils; import java.io.IOException; import java.util.*; import static com.miracle.MiracleOption.CallingConvention; import static com.miracle.intermediate.number.PhysicalRegister.*; public class X64Printer implements IRPrinter { private StringBuilder builder; private Set<BasicBlock> blockProcessed; private String builtinPath; private Function curFunction; public X64Printer(String builtinPath) { this.builtinPath = builtinPath; } @Override public String getOutput() throws IOException { builder.append(FileUtils.readFileToString( new java.io.File(builtinPath), "utf-8" )); return builder.toString(); } private List<String> divideStringIntoByte(String value) { List<String> list = new ArrayList<>(); value = value.substring(1, value.length() - 1); for (int i = 0, length = value.length(); i < length; i++) { if (i + 1 < value.length() && value.charAt(i) == '\\' && value.charAt(i + 1) == 'n') { list.add(String.valueOf(10)); i++; } else { list.add(String.valueOf((int) value.charAt(i))); } } return list; } @Override public void visit(Root ir) { blockProcessed = new HashSet<>(); builder = new StringBuilder(); builder.append("; Code generated by Kipsora").append('\n'); builder.append('\n').append("default rel").append('\n'); builder.append('\n').append("extern").append(' ').append("malloc"); builder.append('\n').append("extern").append(' ').append("scanf").append('\n'); builder.append('\n').append("global").append(' ').append("main").append('\n'); builder.append('\n').append("section .bss").append('\n'); ir.globalVariable.forEach((key, value) -> builder.append(key).append(':').append('\t') .append("resb").append(' ').append(value.size).append('\n') ); builder.append("int$buf").append(':').append('\t') .append("resw").append(' ').append('1').append('\n'); builder.append('\n').append("section .data").append('\n'); ir.globalString.forEach((key, value) -> { List<String> bytes = divideStringIntoByte(value.value); builder.append('\t').append("dq").append(' ').append(bytes.size()).append('\n'); builder.append(value.name).append(':').append('\t'); if (!bytes.isEmpty()) { builder.append("db").append(' ').append(String.join(", ", bytes)); } builder.append('\n'); }); builder.append("int$fmt").append(':').append('\t') .append("db").append(' ').append("25H").append(", ") .append("64H").append(", ").append("00H").append('\n'); builder.append("str$fmt").append(':').append('\t') .append("db").append(' ').append("25H").append(", ") .append("73H").append(", ").append("00H").append('\n'); builder.append("fln$fmt").append(':').append('\t') .append("db").append(' ').append("10").append('\n'); builder.append('\n').append("section .text").append('\n'); ir.globalFunction.forEach((key, value) -> { value.accept(this); builder.append('\n'); }); } @Override public void visit(BinaryArithmetic binaryArithmetic) { if (binaryArithmetic.operator.equals(BinaryArithmetic.Types.SHL) || binaryArithmetic.operator.equals(BinaryArithmetic.Types.SHR)) { builder.append('\t').append("mov").append(' ') .append(PhysicalRegister.getBy16BITName("RCX", binaryArithmetic.getSource().getNumberSize())) .append(", ").append(binaryArithmetic.getSource()).append('\n'); } else if (binaryArithmetic.operator.equals(BinaryArithmetic.Types.DIV)) { /* * Div Instruction: DIV RAX, src (src != RDX, RAX, imm) RAX /= src * - src cannot be immediate number -> processed in MLIRTransformer * - src cannot be RDX and RAX -> TODO: in Register Allocator * - tar must be RAX -> TODO: in Register Allocator * cdq * idiv src */ builder.append('\t').append("mov").append(' ') .append(PhysicalRegister.getBy16BITName("RAX", binaryArithmetic.getSource().getNumberSize())) .append(", ").append(binaryArithmetic.getTarget()).append('\n'); builder.append('\t').append("cdq").append('\n'); builder.append('\t').append("idiv").append(' ').append(binaryArithmetic.getSource()).append('\n'); builder.append('\t').append("mov") .append(' ').append(binaryArithmetic.getTarget()) .append(", ").append(getBy16BITName("RAX", binaryArithmetic.getTarget().size)).append('\n'); } else if (binaryArithmetic.operator.equals(BinaryArithmetic.Types.MOD)) { /* * Div Instruction: MOD RAX, src RAX /= src * - src cannot be immediate number -> processed in MLIRTransformer * - src cannot be RDX and RAX -> TODO: in Register Allocator * - tar must be RAX -> TODO: in Register Allocator * cdq * idiv src * mov RAX, RDX */ builder.append('\t').append("mov").append(' ') .append(PhysicalRegister.getBy16BITName("RAX", binaryArithmetic.getSource().getNumberSize())) .append(", ").append(binaryArithmetic.getTarget()).append('\n'); builder.append('\t').append("cdq").append('\n'); builder.append('\t').append("idiv").append(' ').append(binaryArithmetic.getSource()).append('\n'); builder.append('\t').append("mov") .append(' ').append(binaryArithmetic.getTarget()) .append(", ").append(getBy16BITName("RDX", binaryArithmetic.getTarget().size)).append('\n'); } else { /* * Other Arithmetic Instruction: OP tar, src (tar != src) tar OP= src * - tar and src cannot be both indirect registers -> TODO: in Register Allocator * EXCEPTION: * >>, <<: target must be physical registers -> TODO: in Register Allocator * *: source cannot be indirect registers -> TODO: in Register Allocator */ builder.append('\t').append(binaryArithmetic.operator) .append(' ').append(binaryArithmetic.getTarget()) .append(", ").append(binaryArithmetic.getSource()) .append('\n'); } } @Override public void visit(Move move) { /* * Move Instruction: * tar and src cannot be both indirect registers -> TODO: in Register Allocator */ if (move.getSource().toString().equals(move.getTarget().toString())) return; if (move.getSource().getNumberSize() > move.getTarget().getNumberSize()) { builder.append('\t').append("movsx").append(' ').append(move.getTarget()) .append(", ").append(move.getSource()).append('\n'); } else if (move.getSource().getNumberSize() > move.getTarget().getNumberSize()) { builder.append('\t').append("movzx").append(' ').append(move.getTarget()) .append(", ").append(move.getSource()).append('\n'); } else { builder.append('\t').append("mov").append(' ').append(move.getTarget()) .append(", ").append(move.getSource()).append('\n'); } } @Override public void visit(Function function) { curFunction = function; builder.append(function.identifier).append(':').append('\n'); function.getEntryBasicBlock().accept(this); curFunction = null; } private int get16Multiplier(int totalSize) { return (totalSize + 15) / 16 * 16; } @Override public void visit(BasicBlock block) { if (blockProcessed.contains(block)) return; blockProcessed.add(block); builder.append(block.name).append(':').append('\n'); if (block.isFunctionEntryBlock()) { if (curFunction.buffer.getSpillSize() > 0 || !curFunction.buffer.getCalleeSaveRegisters().isEmpty()) { builder.append('\t').append("push").append(' ').append(RBP.getELF64Name()).append('\n'); builder.append('\t').append("mov").append(' ').append(RBP).append(", ") .append(RSP).append('\n'); if (curFunction.buffer.getSpillSize() > 0) { builder.append('\t').append("sub").append(' ').append(RSP).append(", ") .append(get16Multiplier(block.blockFrom.buffer.getSpillSize())) .append('\n'); } curFunction.buffer.getCalleeSaveRegisters().forEach(element -> { builder.append('\t').append("push").append(' ') .append(element.getELF64Name()).append('\n'); }); for (int i = 0, size = curFunction.parameters.size(); i < size && i < MiracleOption.CallingConvention.size(); i++) { if (!(curFunction.parameters.get(i) instanceof PhysicalRegister) || !((PhysicalRegister) curFunction.parameters.get(i)).indexName.equals(MiracleOption.CallingConvention.get(i))) { builder.append('\t').append("mov").append(' ').append(curFunction.parameters.get(i)).append(", ") .append(PhysicalRegister.getBy16BITName( MiracleOption.CallingConvention.get(i), curFunction.parameters.get(i).size )).append('\n'); } } } } for (BasicBlock.Node it = block.getHead(); it != block.tail; it = it.getSucc()) { it.instruction.accept(this); } block.getSuccBasicBlock().forEach(element -> element.accept(this)); } @Override public void visit(Call call) { /* * CALL instruction: * returnRegister must be null or RAX -> TODO: in Register Allocator * The last 6 parameters must follow calling conventions -> TODO: in Register Allocator */ List<PhysicalRegister> registers = new LinkedList<>(call.callerSave); registers.forEach(element -> { if (element.isCallerSave) { builder.append('\t').append("push") .append(' ').append(element.getELF64Name()).append('\n'); } }); List<Number> parameters = call.parameters; int spillSize = 0; for (int i = CallingConvention.size(), size = parameters.size(); i < size; i++) { spillSize += parameters.get(i).getNumberSize(); } int fitSize = get16Multiplier(spillSize); if (fitSize != 0) { // if there are more than 6 args builder.append('\t').append("sub").append(' ').append(RSP) .append(", ").append(fitSize).append('\n'); spillSize = 0; for (int i = CallingConvention.size(), size = parameters.size(); i < size; i++) { spillSize += parameters.get(i).getNumberSize(); if (parameters.get(i) instanceof IndirectRegister) { builder.append('\t').append("mov").append(' ') .append(PhysicalRegister.getBy16BITName("RDI", parameters.get(i).getNumberSize())) .append(", ").append(parameters.get(i)).append('\n'); builder.append('\t').append("mov").append(' ') .append(new OffsetRegister( RSP, fitSize - spillSize, null, null, parameters.get(i).getNumberSize() )) .append(", ") .append(PhysicalRegister.getBy16BITName("RDI", parameters.get(i).getNumberSize())) .append('\n'); } else { builder.append('\t').append("mov").append(' ') .append(new OffsetRegister( RSP, fitSize - spillSize, null, null, parameters.get(i).getNumberSize() )) .append(", ").append(parameters.get(i)).append('\n'); } } } for (int i = 0; i < parameters.size() && i < MiracleOption.CallingConvention.size(); i++) { if (!(parameters.get(i) instanceof PhysicalRegister) || !((PhysicalRegister) parameters.get(i)).indexName.equals(MiracleOption.CallingConvention.get(i))) { builder.append('\t').append("push").append(' ').append(parameters.get(i)).append('\n'); } } for (int i = Math.min(parameters.size() - 1, MiracleOption.CallingConvention.size() - 1); i >= 0; i if (!(parameters.get(i) instanceof PhysicalRegister) || !((PhysicalRegister) parameters.get(i)).indexName.equals(MiracleOption.CallingConvention.get(i))) { builder.append('\t').append("pop").append(' ').append(PhysicalRegister.getBy16BITName(MiracleOption.CallingConvention.get(i), parameters.get(i).getNumberSize())).append('\n'); } } builder.append('\t').append("call").append(' ') .append(call.function.identifier).append('\n'); if (fitSize != 0) { builder.append('\t').append("add").append(' ').append(RSP) .append(", ").append(fitSize).append('\n'); } Collections.reverse(registers); registers.forEach(element -> { if (element.isCallerSave) { builder.append('\t').append("pop") .append(' ').append(element.getELF64Name()).append('\n'); } }); if (call.getTarget() != null) { builder.append('\t').append("mov").append(' ') .append(call.getTarget()).append(", ") .append(PhysicalRegister.getBy16BITName( "RAX", call.getTarget().size )).append('\n'); } } @Override public void visit(UnaryArithmetic prefixArithmetic) { /* * UnaryArithmetic Instruction: * NO LIMITS */ builder.append('\t').append(prefixArithmetic.operator).append(' ') .append(prefixArithmetic.getTarget()).append('\n'); } @Override public void visit(UnaryBranch unaryBranch) { /* * UnaryBranch Instruction: * expression cannot be immediate number -> processed in MLIRTransformer */ builder.append('\t').append("cmp").append(' ').append(unaryBranch.getExpression()) .append(", ").append(0).append('\n'); builder.append('\t').append("jnz").append(' ') .append(unaryBranch.getBranchTrue().name).append('\n'); } @Override public void visit(Return irReturn) { /* * Return Instruction: * - value must be null -> processed in LLIRTransformer */ List<PhysicalRegister> registers = new LinkedList<>(curFunction.buffer.getCalleeSaveRegisters()); Collections.reverse(registers); registers.forEach(element -> { builder.append('\t').append("pop").append(' ').append(element.getELF64Name()).append('\n'); }); if (curFunction.buffer.getSpillSize() > 0 || !curFunction.buffer.getCalleeSaveRegisters().isEmpty()) { builder.append('\t').append("leave").append('\n'); } builder.append('\t').append("ret").append('\n'); } @Override public void visit(Jump jump) { builder.append('\t').append("jmp").append(' ') .append(jump.block.name).append('\n'); } @Override public void visit(Compare compare) { /* * Compare Instruction: * - srcA, srcB cannot be both immediate number -> processed in MLIRTransformer * - srcA, srcB cannot be both indirect registers -> TODO: in Register Allocator */ builder.append('\t').append("cmp").append(' ').append(compare.getSourceA()) .append(", ").append(compare.getSourceB()).append('\n'); builder.append('\t').append(compare.getOperator()).append(' ') .append(compare.getTarget()).append('\n'); } @Override public void visit(HeapAllocate allocate) { /* * HeapAllocate Instruction: * - size must be one -> processed in MLIRTransformer */ allocate.callerSave.forEach(element -> builder.append('\t').append("push").append(' ') .append(element).append('\n') ); builder.append('\t').append("mov").append(' ').append("rdi").append(", ") .append(allocate.getNumber()).append('\n'); builder.append('\t').append("call").append(' ').append("malloc").append('\n'); allocate.callerSave.forEach(element -> builder.append('\t').append("pop").append(' ') .append(element).append('\n') ); builder.append('\t').append("mov").append(' ').append(allocate.getTarget()) .append(", ").append(PhysicalRegister.getBy16BITName("RAX", allocate.getTarget().size)) .append("\n"); } @Override public void visit(BinaryBranch binaryBranch) { /* * BinaryBranch expression: * - expA and expB cannot be both immediate number -> processed in MLIRTransformer * - expA and expB cannot be both indirect registers -> TODO: in Register Allocator */ builder.append('\t').append("cmp") .append(' ').append(binaryBranch.getExpressionA()) .append(", ").append(binaryBranch.getExpressionB()) .append('\n'); builder.append('\t').append(binaryBranch.getOperator()) .append(' ').append(binaryBranch.getBranchTrue().name).append('\n'); } @Override public void visit(PhiInstruction phiInstruction) { throw new RuntimeException("unprocessed phis"); } }
package com.ram.kainterview; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JTextField; import org.graphstream.graph.Graph; import org.graphstream.ui.view.Viewer; import org.graphstream.ui.view.ViewerListener; import org.graphstream.ui.view.ViewerPipe; import com.ram.kainterview.user.User; /** * Controller of the infection model */ public class InfectionControllerImpl implements InfectionController { /** * Map of all id's to users in the user base */ private Map<String,User> users; /** * Manages GraphStream's ViewerPipe pump requests */ private boolean loop; /** * Constructs a controller with the given user base */ public InfectionControllerImpl(List<User> users) { this.users = new HashMap<>(); for (User user : users) this.users.put(user.id(), user); loop = true; } @Override public void init(GraphView view, Graph graph, Viewer viewer) { for (Entry<String,User> entry : users.entrySet()) { User user = entry.getValue(); // build ids of adjacent nodes List<String> toIds = new LinkedList<String>(); List<String> fromIds = new LinkedList<String>(); for (User coach : user.coaches()) toIds.add(coach.id()); for (User student : user.students()) fromIds.add(student.id()); view.addNode(user.id(),user.version(), toIds, fromIds); } ViewerPipe fromViewer = viewer.newViewerPipe(); fromViewer.addViewerListener(new ViewerListener() { @Override public void buttonPushed(String id) { // unused as only a release event indicates a complete click // TODO highlight outline of selected node } @Override public void buttonReleased(String id) { users.get(id).totalInfect(users.get(id).version()+1); for (Entry<String,User> entry : users.entrySet()) view.updateNode(entry.getKey(), entry.getValue().version()); } @Override public void viewClosed(String id) { loop = false; } }); // connect the graph to the viewer fromViewer.addSink(graph); fromViewer.removeElementSink(graph); // for issue in library // run on separate thread to prevent UI thread blocking new Thread(() -> { while (loop) { // request the pipe to check if the viewer thread sent events try { fromViewer.blockingPump(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } @Override public void registerInfectField(JTextField textField) { // TODO } @Override public void registerInfectButton(JButton button) { button.addActionListener((event) -> { // TODO (toggle for different infection types) }); } @Override public void registerExecuteButton(JButton button) { button.addActionListener((event) -> { // TODO }); } @Override public void registerHelpButton(JButton button) { button.addActionListener((event) -> { // TODO }); } }
package com.syncleus.dann.associativemap; import java.io.Serializable; import java.util.List; public class Hyperpoint implements Serializable { private double[] coordinates; public Hyperpoint(int dimensions) { if(dimensions <= 0) throw new IllegalArgumentException("dimensions can not be less than or equal to zero"); this.coordinates = new double[dimensions]; } public Hyperpoint(double[] coordinates) { if(coordinates == null) throw new NullPointerException("coordinates can not be null!"); if(coordinates.length <= 0) throw new IllegalArgumentException("coordinates must have atleast one member, 0 dimensions isnt valid!"); this.coordinates = (double[]) coordinates.clone(); } public Hyperpoint(List<Double> coordinates) { if(coordinates == null) throw new NullPointerException("coordinates can not be null!"); if(coordinates.size() <= 0) throw new IllegalArgumentException("coordinates must have atleast one member, 0 dimensions isnt valid!"); this.coordinates = new double[coordinates.size()]; int coordinatesIndex = 0; for(Double coordinate : coordinates) { this.coordinates[coordinatesIndex++] = coordinate.doubleValue(); } } public Hyperpoint(Hyperpoint copy) { this.coordinates = (double[]) copy.coordinates.clone(); } public int getDimensions() { return this.coordinates.length; } public void setCoordinate(double coordinate, int dimension) { if(dimension <= 0) throw new IllegalArgumentException("dimensions can not be less than or equal to zero"); if(dimension >= this.coordinates.length) throw new IllegalArgumentException("dimensions is larger than the dimensionality of this point"); this.coordinates[dimension-1] = coordinate; } public double getCoordinate(int dimension) { if(dimension <= 0) throw new IllegalArgumentException("dimensions can not be less than or equal to zero"); if(dimension > this.coordinates.length) throw new IllegalArgumentException("dimensions is larger than the dimensionality of this point"); return this.coordinates[dimension-1]; } public void setDistance(double distance) { double[] newCoords = (double[]) this.coordinates.clone(); for(int coordinateIndex = 0; coordinateIndex < this.getDimensions(); coordinateIndex++) { double sphericalProducts = distance; for(int angleDimension = 1; angleDimension - 1 < (coordinateIndex + 1);angleDimension++) { if( angleDimension < (coordinateIndex + 1)) sphericalProducts *= Math.sin(this.getAngularComponent(angleDimension)); else { if((coordinateIndex + 1) == this.getDimensions()) sphericalProducts *= Math.sin(this.getAngularComponent(angleDimension)); else sphericalProducts *= Math.cos(this.getAngularComponent(angleDimension)); } } newCoords[coordinateIndex] = sphericalProducts; } this.coordinates = newCoords; } public void setAngularComponent(double angle, int dimension) { if(dimension <= 0) throw new IllegalArgumentException("dimensions can not be less than or equal to zero"); if((dimension-2) >= this.coordinates.length) throw new IllegalArgumentException("dimensions is larger than the dimensionality (minus 1) of this point"); double[] newCoords = (double[]) this.coordinates.clone(); for(int coordinateIndex = dimension-1; coordinateIndex < this.getDimensions(); coordinateIndex++) { double sphericalProducts = this.getDistance(); for(int angleDimension = 1; angleDimension - 1 < (coordinateIndex + 1);angleDimension++) { if( angleDimension < (coordinateIndex + 1)) sphericalProducts *= Math.sin(this.getAngularComponent(angleDimension)); else { if((coordinateIndex + 1) == this.getDimensions()) sphericalProducts *= Math.sin(this.getAngularComponent(angleDimension)); else sphericalProducts *= Math.cos(this.getAngularComponent(angleDimension)); } } newCoords[coordinateIndex] = sphericalProducts; } this.coordinates = newCoords; } public double getDistance() { double squaredSum = 0.0; for(double coordinate : this.coordinates) squaredSum += Math.pow(coordinate,2); return Math.sqrt(squaredSum); } public double getAngularComponent(int dimension) { if(dimension <= 0) throw new IllegalArgumentException("dimensions can not be less than or equal to zero"); if((dimension-2) >= this.coordinates.length) throw new IllegalArgumentException("dimensions is larger than the dimensionality (minus 1) of this point"); double squaredSum = 0.0; for(int coordinateIndex = this.coordinates.length-1; coordinateIndex >= (dimension); coordinateIndex squaredSum += Math.pow(this.coordinates[coordinateIndex], 2.0); return Math.atan2(Math.sqrt(squaredSum), this.coordinates[dimension-1]); } public Hyperpoint calculateRelativeTo(Hyperpoint absolutePoint) { if(absolutePoint == null) throw new NullPointerException("absolutePoint can not be null!"); if(absolutePoint.getDimensions() != this.getDimensions()) throw new IllegalArgumentException("absolutePoint must have the same dimensions as this point"); double[] relativeCoords = new double[this.coordinates.length]; for(int coordIndex = 0; coordIndex < this.coordinates.length; coordIndex++) { relativeCoords[coordIndex] = this.coordinates[coordIndex] - absolutePoint.getCoordinate(coordIndex+1); } return new Hyperpoint(relativeCoords); } public Hyperpoint add(Hyperpoint pointToAdd) { if(pointToAdd == null) throw new NullPointerException("pointToAdd can not be null!"); if(pointToAdd.getDimensions() != this.getDimensions()) throw new IllegalArgumentException("pointToAdd must have the same dimensions as this point"); double[] relativeCoords = new double[this.coordinates.length]; for(int coordIndex = 0; coordIndex < this.coordinates.length; coordIndex++) { relativeCoords[coordIndex] = this.coordinates[coordIndex] + pointToAdd.getCoordinate(coordIndex+1); } return new Hyperpoint(relativeCoords); } }