answer
stringlengths
17
10.2M
package com.thindeck.dynamo; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; /** * Utility class which provides convenient methods for annotations check etc. * @author Paul Polishchuk (ppol@ua.fm) * @version $Id$ * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class ClasspathRule implements TestRule { /** * Package prefix. **/ private final transient String prefix; /** * Constructor. * @param pfx Prefix. */ public ClasspathRule(final String pfx) { this.prefix = pfx; } /** * Provides all classes in prefix. * @return Classes */ public Iterable<Class<?>> allTypes() { return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners( new SubTypesScanner(false), new ResourcesScanner() ) .setUrls( ClasspathHelper.forPackage(this.prefix) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix(this.prefix) ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); // @checkstyle BooleanExpressionComplexityCheck (6 lines) return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && !name.endsWith("RepoRule") && (input.getEnclosingClass() == null || name.endsWith("Smart")); } } ); } @Override public Statement apply(final Statement statement, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { statement.evaluate(); } }; } /** * Provides all public methods from classes in prefix. * @return Methods */ public Iterable<Method> allPublicMethods() { return Iterables.concat( Iterables.transform( this.allTypes(), new Function<Class<?>, Iterable<Method>>() { @Override public Iterable<Method> apply(final Class<?> input) { return Iterables.filter( Arrays.asList(input.getDeclaredMethods()), new Predicate<Method>() { @Override public boolean apply(final Method method) { return Modifier.isPublic( method.getModifiers() ); } } ); } } ) ); } }
package net.imagej.ops.conditions; import static org.junit.Assert.assertSame; import net.imagej.ops.AbstractOpTest; import org.junit.Test; public class AndTest extends AbstractOpTest { @Test public void testAnd() { final Condition<?> c1 = ops.op(FunctionGreaterCondition.class, Double.class, 3.0); final Condition<?> c2 = ops.op(FunctionLesserCondition.class, Double.class, 6.0); final Boolean result = (Boolean) ops.run(AndCondition.class, 5.0, c1, c2); assertSame(result, true); final Boolean result2 = (Boolean) ops.run(AndCondition.class, 2.0, c1, c2); assertSame(result2, false); final Boolean result3 = (Boolean) ops.run(AndCondition.class, 7.0, c1, c2); assertSame(result3, false); final Boolean result4 = (Boolean) ops.run(AndCondition.class, Double.NaN, c1, c2); assertSame(result4, false); } }
package org.animotron.bridge; import org.animotron.ATest; import org.animotron.exception.AnimoException; import org.animotron.graph.serializer.AnimoSerializer; import org.animotron.statement.operator.THE; import org.junit.Test; import org.neo4j.graphdb.Relationship; import java.io.IOException; import static org.junit.Assert.assertNotNull; /** * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class FSBridgeTest extends ATest { private static final String PATH = "src/main/animo/mime-type/application-animo.animo"; private void check(String the) throws IOException { Relationship r = THE._.get(the); assertNotNull(r); AnimoSerializer.serialize(r, System.out); System.out.println(); } @Test public void loadAndSerialize() throws IOException, AnimoException { System.out.println("Test repository loader ..."); FSBridge.load(PATH); System.out.println("loaded ..."); check("application-animo"); System.out.println("done."); } }
package org.komamitsu.fluency; import org.junit.Test; import org.komamitsu.fluency.buffer.Buffer; import org.komamitsu.fluency.buffer.MessageBuffer; import org.komamitsu.fluency.buffer.PackedForwardBuffer; import org.komamitsu.fluency.flusher.AsyncFlusher; import org.komamitsu.fluency.flusher.Flusher; import org.komamitsu.fluency.flusher.SyncFlusher; import org.komamitsu.fluency.sender.Sender; import org.komamitsu.fluency.sender.TCPSender; import org.msgpack.value.MapValue; import org.msgpack.value.Value; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static org.junit.Assert.*; public class FluencyTest { private static final Logger LOG = LoggerFactory.getLogger(FluencyTest.class); @Test public void testDefaultFluency() throws IOException { Fluency fluency = null; fluency = Fluency.defaultFluency(); fluency = Fluency.defaultFluency(12345); fluency = Fluency.defaultFluency("333.333.333.333", 12345); fluency = Fluency.defaultFluency(Arrays.asList(new InetSocketAddress(43210))); Fluency.Config config = new Fluency.Config(); config.setFlushIntervalMillis(200).setMaxBufferSize(64 * 1024 * 1024).setSenderMaxRetryCount(99); fluency = Fluency.defaultFluency(config); fluency = Fluency.defaultFluency(12345, config); fluency = Fluency.defaultFluency("333.333.333.333", 12345, config); fluency = Fluency.defaultFluency(Arrays.asList(new InetSocketAddress(43210)), config); } interface FluencyFactory { Fluency generate(int fluentdPort) throws IOException; } @Test public void testFluencyEachCombination() throws Exception { testFluencyUsingPackedForwardBufferAndAsyncFlusher(); testFluencyUsingMessageAndAsyncFlusher(); testFluencyUsingPackedForwardBufferAndSyncFlusher(); testFluencyUsingMessageAndSyncFlusher(); testFluencyUsingMessageAndSyncFlusherWithAckResponse(); testFluencyUsingMessageAndAsyncFlusherWithAckResponse(); testFluencyUsingPackedForwardAndSyncFlusherWithAckResponse(); testFluencyUsingPackedForwardAndAsyncFlusherWithAckResponse(); } public void testFluencyUsingPackedForwardBufferAndAsyncFlusher() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new PackedForwardBuffer.Config(); Flusher.Config flusherConfig = new AsyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyUsingMessageAndAsyncFlusher() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new MessageBuffer.Config(); Flusher.Config flusherConfig = new AsyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyUsingPackedForwardBufferAndSyncFlusher() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new PackedForwardBuffer.Config(); Flusher.Config flusherConfig = new SyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyUsingMessageAndSyncFlusher() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new MessageBuffer.Config(); Flusher.Config flusherConfig = new SyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyUsingMessageAndSyncFlusherWithAckResponse() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new MessageBuffer.Config().setAckResponseMode(true); Flusher.Config flusherConfig = new SyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyUsingMessageAndAsyncFlusherWithAckResponse() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new MessageBuffer.Config().setAckResponseMode(true); Flusher.Config flusherConfig = new AsyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyUsingPackedForwardAndSyncFlusherWithAckResponse() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new PackedForwardBuffer.Config().setAckResponseMode(true); Flusher.Config flusherConfig = new SyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyUsingPackedForwardAndAsyncFlusherWithAckResponse() throws Exception { testFluencyBase(new FluencyFactory() { @Override public Fluency generate(int fluentdPort) throws IOException { Sender sender = new TCPSender(fluentdPort); Buffer.Config bufferConfig = new PackedForwardBuffer.Config().setAckResponseMode(true); Flusher.Config flusherConfig = new AsyncFlusher.Config(); return new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); } }); } public void testFluencyBase(FluencyFactory fluencyFactory) throws Exception { MockFluentdServer fluentd = new MockFluentdServer(); fluentd.start(); TimeUnit.MILLISECONDS.sleep(500); final Fluency fluency = fluencyFactory.generate(fluentd.getLocalPort()); final int maxNameLen = 200; final HashMap<Integer, String> nameLenTable = new HashMap<Integer, String>(maxNameLen); for (int i = 1; i <= maxNameLen; i++) { StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < i; j++) { stringBuilder.append('x'); } nameLenTable.put(i, stringBuilder.toString()); } final AtomicLong ageEventsSum = new AtomicLong(); final AtomicLong nameEventsLength = new AtomicLong(); final AtomicLong tag0EventsCounter = new AtomicLong(); final AtomicLong tag1EventsCounter = new AtomicLong(); final AtomicLong tag2EventsCounter = new AtomicLong(); final AtomicLong tag3EventsCounter = new AtomicLong(); try { final Random random = new Random(); int concurrency = 10; final int reqNum = 6000; long start = System.currentTimeMillis(); final CountDownLatch latch = new CountDownLatch(concurrency); ExecutorService es = Executors.newCachedThreadPool(); for (int i = 0; i < concurrency; i++) { es.execute(new Runnable() { @Override public void run() { for (int i = 0; i < reqNum; i++) { int tagNum = i % 4; final String tag = String.format("foodb%d.bartbl%d", tagNum, tagNum); switch (tagNum) { case 0: tag0EventsCounter.incrementAndGet(); break; case 1: tag1EventsCounter.incrementAndGet(); break; case 2: tag2EventsCounter.incrementAndGet(); break; case 3: tag3EventsCounter.incrementAndGet(); break; default: throw new RuntimeException("Never reach here"); } int rand = random.nextInt(maxNameLen); final Map<String, Object> hashMap = new HashMap<String, Object>(); String name = nameLenTable.get(rand + 1); nameEventsLength.addAndGet(name.length()); hashMap.put("name", name); rand = random.nextInt(100); int age = rand; ageEventsSum.addAndGet(age); hashMap.put("age", age); hashMap.put("comment", "hello, world"); hashMap.put("rate", 1.23); try { fluency.emit(tag, hashMap); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Failed", e); } } latch.countDown(); } }); } assertTrue(latch.await(30, TimeUnit.SECONDS)); fluency.flush(); TimeUnit.MILLISECONDS.sleep(5000); fluentd.stop(); TimeUnit.MILLISECONDS.sleep(5000); assertEquals(1, fluentd.connectCounter.get()); assertEquals(1, fluentd.closeCounter.get()); assertEquals((long)concurrency * reqNum, fluentd.ageEventsCounter.get()); assertEquals(ageEventsSum.get(), fluentd.ageEventsSum.get()); assertEquals((long)concurrency * reqNum, fluentd.nameEventsCounter.get()); assertEquals(nameEventsLength.get(), fluentd.nameEventsLength.get()); assertEquals(tag0EventsCounter.get(), fluentd.tag0EventsCounter.get()); assertEquals(tag1EventsCounter.get(), fluentd.tag1EventsCounter.get()); assertEquals(tag2EventsCounter.get(), fluentd.tag2EventsCounter.get()); assertEquals(tag3EventsCounter.get(), fluentd.tag3EventsCounter.get()); System.out.println(System.currentTimeMillis() - start); } finally { fluency.close(); fluentd.stop(); } } private static class MockFluentdServer extends AbstractFluentdServer { private AtomicLong connectCounter = new AtomicLong(); private AtomicLong ageEventsCounter = new AtomicLong(); private AtomicLong ageEventsSum = new AtomicLong(); private AtomicLong nameEventsCounter = new AtomicLong(); private AtomicLong nameEventsLength = new AtomicLong(); private AtomicLong tag0EventsCounter = new AtomicLong(); private AtomicLong tag1EventsCounter = new AtomicLong(); private AtomicLong tag2EventsCounter = new AtomicLong(); private AtomicLong tag3EventsCounter = new AtomicLong(); private AtomicLong closeCounter = new AtomicLong(); private final long startTimestamp; public MockFluentdServer() throws IOException { startTimestamp = System.currentTimeMillis() / 1000; } @Override protected EventHandler getFluentdEventHandler() { return new EventHandler() { @Override public void onConnect(SocketChannel accpetSocketChannel) { connectCounter.incrementAndGet(); } @Override public void onReceive(String tag, long timestampMillis, MapValue data) { if (tag.equals("foodb0.bartbl0")) { tag0EventsCounter.incrementAndGet(); } else if (tag.equals("foodb1.bartbl1")) { tag1EventsCounter.incrementAndGet(); } else if (tag.equals("foodb2.bartbl2")) { tag2EventsCounter.incrementAndGet(); } else if (tag.equals("foodb3.bartbl3")) { tag3EventsCounter.incrementAndGet(); } else { throw new IllegalArgumentException("Unexpected tag: tag=" + tag); } assertTrue(startTimestamp <= timestampMillis && timestampMillis < startTimestamp + 60 * 1000); assertEquals(4, data.size()); for (Map.Entry<Value, Value> kv : data.entrySet()) { String key = kv.getKey().asStringValue().toString(); Value val = kv.getValue(); if (key.equals("comment")) { assertEquals("hello, world", val.toString()); } else if (key.equals("rate")) { // Treating the value as String to avoid a failure of calling asFloatValue()... assertEquals("1.23", val.toString()); } else if (key.equals("name")) { nameEventsCounter.incrementAndGet(); nameEventsLength.addAndGet(val.asRawValue().asString().length()); } else if (key.equals("age")) { ageEventsCounter.incrementAndGet(); ageEventsSum.addAndGet(val.asIntegerValue().asInt()); } } } @Override public void onClose(SocketChannel accpetSocketChannel) { closeCounter.incrementAndGet(); } }; } } private static class EmitTask implements Runnable { private final Fluency fluency; private final String tag; private Map<String, Object> data; private final int count; private final CountDownLatch latch; private EmitTask(Fluency fluency, String tag, Map<String, Object> data, int count, CountDownLatch latch) { this.fluency = fluency; this.tag = tag; this.data = data; this.count = count; this.latch = latch; } @Override public void run() { for (int i = 0; i < count; i++) { try { fluency.emit(tag, data); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Failed", e); } } latch.countDown(); } } // @Test public void testWithRealFluentd() throws IOException, InterruptedException { int concurrency = 4; int reqNum = 1000000; // Fluency fluency = Fluency.defaultFluency(); TCPSender sender = new TCPSender(); Buffer.Config bufferConfig = new PackedForwardBuffer.Config().setMaxBufferSize(256 * 1024 * 1024); Flusher.Config flusherConfig = new AsyncFlusher.Config().setFlushIntervalMillis(200); Fluency fluency = new Fluency.Builder(sender).setBufferConfig(bufferConfig).setFlusherConfig(flusherConfig).build(); HashMap<String, Object> data = new HashMap<String, Object>(); data.put("name", "komamitsu"); data.put("age", 42); data.put("comment", "hello, world"); CountDownLatch latch = new CountDownLatch(concurrency); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < concurrency; i++) { executorService.execute(new EmitTask(fluency, "foodb.bartbl", data, reqNum, latch)); } assertTrue(latch.await(60, TimeUnit.SECONDS)); fluency.close(); } // @Test public void testWithRealMultipleFluentd() throws IOException, InterruptedException { int concurrency = 4; int reqNum = 1000000; // Fluency fluency = Fluency.defaultFluency(); Fluency fluency = Fluency.defaultFluency(Arrays.asList(new InetSocketAddress(24224), new InetSocketAddress(24225))); HashMap<String, Object> data = new HashMap<String, Object>(); data.put("name", "komamitsu"); data.put("age", 42); data.put("comment", "hello, world"); CountDownLatch latch = new CountDownLatch(concurrency); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < concurrency; i++) { executorService.execute(new EmitTask(fluency, "foodb.bartbl", data, reqNum, latch)); } assertTrue(latch.await(20, TimeUnit.SECONDS)); fluency.close(); } }
package org.lantern.udtrelay; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.Future; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.handler.codec.http.HttpRequest; import org.junit.Test; import org.lantern.LanternUtils; import org.littleshoot.proxy.DefaultHttpProxyServer; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.ProxyCacheManager; import org.littleshoot.proxy.ProxyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.barchart.udt.net.NetSocketUDT; public class UdtRelayTest { private final Logger log = LoggerFactory.getLogger(getClass()); @Test public void test() throws Exception { // The idea here is to start an HTTP proxy server locally that the UDT // relay relays to -- i.e. just like the real world setup. final boolean udt = true; // Note that an internet connection is required to run this test. final int proxyPort = LanternUtils.randomPort(); final int relayPort = LanternUtils.randomPort(); startProxyServer(proxyPort); final InetSocketAddress localRelayAddress = new InetSocketAddress("127.0.0.1", relayPort); final UdtRelayProxy relay = new UdtRelayProxy(localRelayAddress.getPort(), "127.0.0.1", proxyPort); startRelay(relay, localRelayAddress.getPort(), udt); // We do this a few times to make sure there are no issues with // subsequent runs. for (int i = 0; i < 3; i++) { //hitRelay(proxyPort); if (udt) { hitRelayUdt(relayPort); } else { hitRelayRaw(relayPort); } } } private static final String REQUEST = "GET http: "Host: www.google.com\r\n"+ "Proxy-Connection: Keep-Alive\r\n"+ "User-Agent: Apache-HttpClient/4.2.2 (java 1.5)\r\n" + "\r\n"; private static final String RESPONSE = "HTTP/1.1 200 OK\r\n" + "Server: Gnutella\r\n"+ "Content-type: application/binary\r\n"+ "Content-Length: 0\r\n" + "\r\n"; private void startProxyServer(final int port) throws Exception { // We configure the proxy server to always return a cache hit with // the same generic response. final Thread t = new Thread(new Runnable() { @Override public void run() { final HttpProxyServer server = new DefaultHttpProxyServer(port, new ProxyCacheManager() { @Override public boolean returnCacheHit(final HttpRequest request, final Channel channel) { System.err.println("GOT REQUEST:\n"+request); //channel.write(ChannelBuffers.wrappedBuffer(RESPONSE.getBytes())); //ProxyUtils.closeOnFlush(channel); //return true; return false; } @Override public Future<String> cache(final HttpRequest originalRequest, final org.jboss.netty.handler.codec.http.HttpResponse httpResponse, final Object response, ChannelBuffer encoded) { return null; } }); System.out.println("About to start..."); server.start(); } }, "Relay-to-Proxy-Test-Thread"); t.setDaemon(true); t.start(); if (!LanternUtils.waitForServer(port, 6000)) { fail("Could not start local test proxy server!!"); } } private void hitRelayUdt(final int relayPort) throws Exception { final Socket sock = new NetSocketUDT(); sock.connect(new InetSocketAddress("127.0.0.1", relayPort)); sock.getOutputStream().write(REQUEST.getBytes()); final InputStream is = sock.getInputStream(); sock.setSoTimeout(4000); /* final BufferedReader br = new BufferedReader(new InputStreamReader(is)); final StringBuilder sb = new StringBuilder(); String cur = br.readLine(); sb.append(cur); int count = 0; while(StringUtils.isNotBlank(cur) && count < 6) { System.err.println("LINE:\n"+cur); cur = br.readLine(); sb.append(cur); count++; } assertTrue("Unexpected response "+sb.toString(), sb.toString().startsWith("HTTP/1.1 200 OK")); final StringBuilder sb = new StringBuilder(); int count = 0; while (count < 500) { sb.append((char)is.read()); count++; } System.err.println("READ:\n"+sb.toString()); */ IOUtils.copy(is, new FileOutputStream(new File("test-windows-x86-jre.tar.gz"))); /* final BufferedReader br = new BufferedReader(new InputStreamReader(IOUtils.copy(sock.getInputStream(), new FileOutputStream(new File("test-windows-x86-jre.tar.gz")));)); final StringBuilder sb = new StringBuilder(); String cur = br.readLine(); sb.append(cur); while(StringUtils.isNotBlank(cur)) { //System.err.println(cur); cur = br.readLine(); sb.append(cur); } //assertTrue("Unexpected response "+sb.toString(), sb.toString().startsWith("HTTP 200 OK")); assertTrue("Unexpected response "+sb.toString(), sb.toString().startsWith("HTTP/1.1 200 OK")); //System.out.println(""); sock.close(); */ } private void hitRelayRaw(final int relayPort) throws Exception { final Socket sock = new Socket(); sock.connect(new InetSocketAddress("127.0.0.1", relayPort)); sock.getOutputStream().write(REQUEST.getBytes()); //IOUtils.copy(sock.getInputStream(), new FileOutputStream(new File("test-windows-x86-jre.tar.gz"))); final BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream())); final StringBuilder sb = new StringBuilder(); String cur = br.readLine(); sb.append(cur); while(StringUtils.isNotBlank(cur)) { //System.err.println(cur); cur = br.readLine(); sb.append(cur); } assertTrue("Unexpected response "+sb.toString(), sb.toString().startsWith("HTTP 200 OK")); //System.out.println(""); sock.close(); } private void hitRelay(final int relayPort) throws Exception { // We create new clients each time here to ensure that we're always // using a new client-side port. final DefaultHttpClient httpClient = new DefaultHttpClient(); final HttpHost proxy = new HttpHost("127.0.0.1", relayPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(2,true)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 50000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120000); final HttpGet get = new HttpGet("http://lantern.s3.amazonaws.com/windows-x86-1.7.0_03.tar.gz"); final HttpResponse response = httpClient.execute(get); final HttpEntity entity = response.getEntity(); final InputStream is = entity.getContent(); IOUtils.copy(is, new FileOutputStream(new File("test-windows-x86-jre.tar.gz"))); //final String body = // IOUtils.toString(entity.getContent()).toLowerCase(); EntityUtils.consume(entity); //assertTrue(body.trim().endsWith("</script></body></html>")); get.reset(); } private void startRelay(final UdtRelayProxy relay, final int localRelayPort, final boolean udt) throws Exception { final Thread t = new Thread(new Runnable() { @Override public void run() { try { if (udt) { relay.run(); } else { relay.runTcp(); } } catch (Exception e) { throw new RuntimeException("Error running server", e); } } }, "Relay-Test-Thread"); t.setDaemon(true); t.start(); if (udt) { // Just sleep if it's UDT... Thread.sleep(800); } else if (!LanternUtils.waitForServer(localRelayPort, 6000)) { fail("Could not start relay server!!"); } } }
package org.minimalj.util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class CloneHelperTest { @Test public void should_copy_string_attribute() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); a.a = "Hallo"; CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertEquals(a.a, clone.a); } @Test public void should_copy_enum_attribute() throws Exception { CloneHelperTestE e = new CloneHelperTestE(); e.f.add(CloneHelperTestF.B); CloneHelperTestE clone = CloneHelper.clone(e); Assert.assertTrue(clone.f.size() == 1); Assert.assertTrue(clone.f.iterator().next() == CloneHelperTestF.B); } @Test public void should_copy_transient_attribute() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); a.t = "Transient"; CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertEquals(a.t, clone.t); } @Test public void should_copy_inline_attribute() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); a.b_inline.b = "b"; CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertEquals(a.b_inline.b, clone.b_inline.b); } @Test public void should_copy_list() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); CloneHelperTestB b = new CloneHelperTestB(); b.b = "Du"; a.b.add(b); CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertEquals(a.b.size(), clone.b.size()); } @Test public void should_generate_new_instances_for_list_items() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); CloneHelperTestB b = new CloneHelperTestB(); b.b = "Du"; a.b.add(b); CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertNotSame(a.b.get(0), clone.b.get(0)); } @Test public void should_copy_attributes_of_list_items() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); CloneHelperTestB b = new CloneHelperTestB(); b.b = "Du"; a.b.add(b); CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertEquals(a.b.get(0).b, clone.b.get(0).b); } @Test public void should_copy_list_with_lists() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); CloneHelperTestC c = new CloneHelperTestC(); c.c = "Test"; c.d = new CloneHelperTestD(); c.d.d = 23; a.c = new ArrayList<CloneHelperTestC>(); a.c.add(c); CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertEquals(a.c.get(0).d.d, clone.c.get(0).d.d); } @Test public void should_leave_alone_null_lists() throws Exception { CloneHelperTestA a = new CloneHelperTestA(); CloneHelperTestA clone = CloneHelper.clone(a); Assert.assertEquals(null, clone.empty); } public static class CloneHelperTestA { public String a; public final List<CloneHelperTestB> b = new ArrayList<CloneHelperTestB>(); public List<CloneHelperTestC> c; public List<CloneHelperTestC> empty; public transient String t; public final CloneHelperTestB b_inline = new CloneHelperTestB(); } public static class CloneHelperTestB { public String b; } public static class CloneHelperTestC { public String c; public CloneHelperTestD d; } public static class CloneHelperTestD { public Integer d; } public static class CloneHelperTestE { public final Set<CloneHelperTestF> f = new HashSet<>(); } public static enum CloneHelperTestF { A, B, C; } }
package org.nwapw.abacus.tests; import org.junit.Assert; import org.junit.Test; import org.nwapw.abacus.lexing.Lexer; import org.nwapw.abacus.lexing.pattern.Match; import java.util.List; public class LexerTests { @Test public void testBasicSuccess(){ Lexer<Integer> lexer = new Lexer<>(); lexer.register("abc", 0); lexer.register("def", 1); List<Match<Integer>> matchedIntegers = lexer.lexAll("abcdefabc", 0, Integer::compare); Assert.assertEquals(matchedIntegers.get(0).getType(), Integer.valueOf(0)); Assert.assertEquals(matchedIntegers.get(1).getType(), Integer.valueOf(1)); Assert.assertEquals(matchedIntegers.get(2).getType(), Integer.valueOf(0)); } @Test public void testBasicFailure(){ Lexer<Integer> lexer = new Lexer<>(); lexer.register("abc", 0); lexer.register("def", 1); Assert.assertNull(lexer.lexAll("abcdefabcz", 0, Integer::compare)); } }
package org.yaml.snakeyaml; import java.util.List; import java.util.Map; import junit.framework.TestCase; public class Chapter2_1Test extends TestCase { @SuppressWarnings("unchecked") public void testExample_2_1() { YamlDocument document = new YamlDocument("example2_1.yaml"); List<String> list = (List<String>) document.getNativeData(); assertEquals(3, list.size()); assertEquals("Mark McGwire", list.get(0)); assertEquals("Sammy Sosa", list.get(1)); assertEquals("Ken Griffey", list.get(2)); assertTrue(document.getPresentation().contains(document.getSource())); assertEquals("Must generate the same document.", document.getSource(), document .getPresentation()); } @SuppressWarnings("unchecked") public void testExample_2_2() { YamlDocument document = new YamlDocument("example2_2.yaml"); Map<String, Object> map = (Map<String, Object>) document.getNativeData(); assertEquals(3, map.size()); assertEquals("Expect 65 to be a Long", Long.class, map.get("hr").getClass()); assertEquals(new Long(65), map.get("hr")); assertEquals(new Float(0.278), new Float("0.278")); assertEquals("Expect 0.278 to be a Float", Double.class, map.get("avg").getClass()); assertEquals(new Double(0.278), map.get("avg")); assertEquals("Expect 147 to be an Long", Long.class, map.get("rbi").getClass()); assertEquals(new Long(147), map.get("rbi")); } @SuppressWarnings("unchecked") public void testExample_2_3() { YamlDocument document = new YamlDocument("example2_3.yaml"); Map<String, List<String>> map = (Map<String, List<String>>) document.getNativeData(); assertEquals(2, map.size()); List<String> list1 = map.get("american"); assertEquals(3, list1.size()); assertEquals("Boston Red Sox", list1.get(0)); assertEquals("Detroit Tigers", list1.get(1)); assertEquals("New York Yankees", list1.get(2)); List<String> list2 = map.get("national"); assertEquals(3, list2.size()); assertEquals("New York Mets", list2.get(0)); assertEquals("Chicago Cubs", list2.get(1)); assertEquals("Atlanta Braves", list2.get(2)); } @SuppressWarnings("unchecked") public void testExample_2_4() { YamlDocument document = new YamlDocument("example2_4.yaml"); List<Map<String, Object>> list = (List<Map<String, Object>>) document.getNativeData(); assertEquals(2, list.size()); Map<String, Object> map1 = list.get(0); assertEquals(3, map1.size()); assertEquals("Mark McGwire", map1.get("name")); } @SuppressWarnings("unchecked") public void testExample_2_5() { YamlDocument document = new YamlDocument("example2_5.yaml"); List<List<Object>> list = (List<List<Object>>) document.getNativeData(); assertEquals(3, list.size()); List<Object> list1 = list.get(0); assertEquals(3, list1.size()); assertEquals("name", list1.get(0)); assertEquals("hr", list1.get(1)); assertEquals("avg", list1.get(2)); assertEquals(3, list.get(1).size()); assertEquals(3, list.get(2).size()); } @SuppressWarnings("unchecked") public void testExample_2_6() { YamlDocument document = new YamlDocument("example2_6.yaml"); Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) document .getNativeData(); assertEquals(2, map.size()); Map<String, Object> map1 = map.get("Mark McGwire"); assertEquals(2, map1.size()); Map<String, Object> map2 = map.get("Sammy Sosa"); assertEquals(2, map2.size()); } }
//@@author A0147984L package seedu.address.model.task; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.text.ParseException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.commons.exceptions.IllegalValueException; public class DateTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void isValidDate() { // invalid date assertFalse(TaskDate.isValidDate(" ")); // space only assertFalse(TaskDate.isValidDate("*")); // non-alphanumeric assertFalse(TaskDate.isValidDate("month")); // contains alphabets assertFalse(TaskDate.isValidDate("0/1")); // day less than 1 assertFalse(TaskDate.isValidDate("1/0")); // month less than 1 assertFalse(TaskDate.isValidDate("1/13")); // month more than 12 assertFalse(TaskDate.isValidDate("32/1")); // day exceeds limit assertFalse(TaskDate.isValidDate("31/4")); // day exceeds limit assertFalse(TaskDate.isValidDate("20/11/1995")); // invalid year assertFalse(TaskDate.isValidDate("29/2/2021")); // invalid year assertFalse(TaskDate.isValidDate("29/2/2021")); // invalid year assertFalse(TaskDate.isValidDate("20/12/2017/1111")); // more than 3 parts assertFalse(TaskDate.isValidDate("mond")); // invalid name in a week // valid date assertTrue(TaskDate.isValidDate("")); // empty assertTrue(TaskDate.isValidDate("1/1")); // both day and month are 1 digit assertTrue(TaskDate.isValidDate("01/1")); // day is 2 digits assertTrue(TaskDate.isValidDate("01/01")); // month is 2 digits beginning with 0 assertTrue(TaskDate.isValidDate("1/12")); // month is 2 digits beginning with 1 assertTrue(TaskDate.isValidDate("31/1")); // day is 31 for January assertTrue(TaskDate.isValidDate("30/11")); // day is 30 for November assertTrue(TaskDate.isValidDate("29/2")); // day is 29 for February assertTrue(TaskDate.isValidDate("30/11/2017")); // with valid year assertTrue(TaskDate.isValidDate("28/2/2019")); // with valid year assertTrue(TaskDate.isValidDate("29/2/2020")); // with valid year assertTrue(TaskDate.isValidDate("Monday")); // day in a week assertTrue(TaskDate.isValidDate("mon")); // day in a week in short assertTrue(TaskDate.isValidDate("ToDay")); // today } @Test public void testOnFeb29() throws IllegalValueException { assertTrue(TaskDate.isValidDate("29/2/2020")); TaskDate tester1 = new TaskDate("29/2/2020"); // Feb 29 will pass isValidDate test if no year is given assertTrue(TaskDate.isValidDate("29/2")); thrown.expect(IllegalValueException.class); // but it should throw exception at construction, because next year is 2018 TaskDate tester2 = new TaskDate("29/2"); } @SuppressWarnings("deprecation") @Test public void testOnValidYear() throws IllegalValueException, ParseException { assertTrue(TaskDate.isValidDate("20/3")); // with valid year without year; TaskDate tester1 = new TaskDate("20/3"); assertEquals(tester1.date.getYear() + 1900, 2018); assertEquals(tester1.getValue(), "20/3/2018"); assertTrue(TaskDate.isValidDate("20/09/2017")); // with valid year after; TaskDate tester2 = new TaskDate("20/09/2017"); assertEquals(tester2.date.getYear() + 1900, 2017); assertTrue(TaskDate.isValidDate("20/09/2017")); TaskDate testerNull = new TaskDate(""); // with space; assertEquals(testerNull.date, TaskDate.FORMATTER.parse(TaskDate.INF_DATE)); } @Test public void compareTo() throws IllegalValueException { TaskDate testerNull = new TaskDate(""); TaskDate tester1 = new TaskDate("20/3/2018"); TaskDate tester2 = new TaskDate("20/3/2019"); TaskDate tester3 = new TaskDate("20/3"); TaskDate tester4 = new TaskDate("20/3/2020"); assertEquals(testerNull.compareTo(tester1), TaskDate.INF); assertEquals(testerNull.compareTo(testerNull), 0); assertEquals(tester1.compareTo(testerNull), -TaskDate.INF); assertEquals(tester2.compareTo(tester1), 365); assertEquals(tester1.compareTo(tester3), 0); assertEquals(tester1.compareTo(tester2), -365); assertEquals(tester1.compareTo(tester4), -731); // handle leap year } @Test public void isPastDue() throws IllegalValueException { TaskDate tester1 = new TaskDate("25/3/2017"); TaskDate tester2 = new TaskDate("20/3/2019"); assertTrue(tester1.isPastDue()); assertFalse(tester2.isPastDue()); } }
package seedu.ezdo.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.ezdo.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.ezdo.commons.core.EventsCenter; import seedu.ezdo.commons.events.model.EzDoChangedEvent; import seedu.ezdo.commons.events.ui.JumpToListRequestEvent; import seedu.ezdo.commons.events.ui.ShowHelpRequestEvent; import seedu.ezdo.logic.commands.AddCommand; import seedu.ezdo.logic.commands.ClearCommand; import seedu.ezdo.logic.commands.Command; import seedu.ezdo.logic.commands.CommandResult; import seedu.ezdo.logic.commands.DeleteCommand; import seedu.ezdo.logic.commands.ExitCommand; import seedu.ezdo.logic.commands.FindCommand; import seedu.ezdo.logic.commands.HelpCommand; import seedu.ezdo.logic.commands.ListCommand; import seedu.ezdo.logic.commands.SelectCommand; import seedu.ezdo.logic.commands.exceptions.CommandException; import seedu.ezdo.model.EzDo; import seedu.ezdo.model.Model; import seedu.ezdo.model.ModelManager; import seedu.ezdo.model.ReadOnlyEzDo; import seedu.ezdo.model.tag.Tag; import seedu.ezdo.model.tag.UniqueTagList; import seedu.ezdo.model.todo.DueDate; import seedu.ezdo.model.todo.Email; import seedu.ezdo.model.todo.Name; import seedu.ezdo.model.todo.Priority; import seedu.ezdo.model.todo.ReadOnlyTask; import seedu.ezdo.model.todo.StartDate; import seedu.ezdo.model.todo.Task; import seedu.ezdo.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyEzDo latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(EzDoChangedEvent abce) { latestSavedAddressBook = new EzDo(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new EzDo(model.getEzDo()); // last saved assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and that the result message is correct. * Also confirms that both the 'address book' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyEzDo expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that the result message is correct. * Both the 'address book' and the 'last shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { EzDo expectedAddressBook = new EzDo(model.getEzDo()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that the result message is correct * and that a CommandException is thrown if expected * and also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyEzDo expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } //Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getEzDo()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new EzDo(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new EzDo(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new EzDo(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandFailure("add wrong args wrong args", expectedMessage); assertCommandFailure("add Valid Name 12345 e/valid@email.butNoPriorityPrefix s/valid,address", expectedMessage); assertCommandFailure("add Valid Name p/1 valid@email.butNoPrefix s/valid, address", expectedMessage); assertCommandFailure("add Valid Name p/1 e/valid@email.butNoAddressPrefix valid, address", expectedMessage); } @Test public void execute_add_invalidPersonData() { assertCommandFailure("add []\\[;] p/3 e/valid@e.mail s/valid, address", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("add Valid Name p/not_numbers e/valid@e.mail s/valid, address", Priority.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add Valid Name p/2 e/notAnEmail s/valid, address", Email.MESSAGE_EMAIL_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 e/valid@e.mail s/valid, address t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); EzDo expectedAB = new EzDo(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // person already in internal address book // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllPersons() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); EzDo expectedAB = helper.generateEzDo(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list * based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord , expectedMessage); //index missing assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list * based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> personList = helper.generateTaskList(2); // set AB state to 2 persons model.resetData(new EzDo()); for (Task p : personList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threePersons = helper.generateTaskList(3); EzDo expectedAB = helper.generateEzDo(threePersons); helper.addToModel(model, threePersons); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threePersons.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threePersons = helper.generateTaskList(3); EzDo expectedAB = helper.generateEzDo(threePersons); expectedAB.removeTask(threePersons.get(1)); helper.addToModel(model, threePersons); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threePersons.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { private Task adam() throws Exception { Name name = new Name("Adam Brown"); Priority privatePriority = new Priority("1"); Email email = new Email("adam@gmail.com"); StartDate privateStartDate = new StartDate("111, alpha street"); DueDate privateDueDate = new DueDate("111, alpha street"); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, privatePriority, email, privateStartDate, privateDueDate, tags); } /** * Generates a valid task using the given seed. * Running this function with the same parameter values guarantees the returned task will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the task data field values */ private Task generateTask(int seed) throws Exception { return new Task( new Name("Person " + seed), new Priority("1"), new Email(seed + "@email"), new StartDate("House of " + seed), new DueDate("House of " + seed), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the task given */ private String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" e/").append(p.getEmail()); cmd.append(" p/").append(p.getPriority()); cmd.append(" s/").append(p.getStartDate()); UniqueTagList tags = p.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an EzDo with auto-generated tasks. */ private EzDo generateEzDo(int numGenerated) throws Exception { EzDo ezDo = new EzDo(); addToEzDo(ezDo, numGenerated); return ezDo; } /** * Generates an EzDo based on the list of Tasks given. */ private EzDo generateEzDo(List<Task> tasks) throws Exception { EzDo ezDo = new EzDo(); addToEzDo(ezDo, tasks); return ezDo; } /** * Adds auto-generated Task objects to the given EzDo * @param ezDo The EzDo to which the Tasks will be added */ private void addToEzDo(EzDo ezDo, int numGenerated) throws Exception { addToEzDo(ezDo, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given EzDo */ private void addToEzDo(EzDo ezDo, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { ezDo.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Tasks will be added */ private void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ private void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { model.addTask(p); } } /** * Generates a list of Tasks based on the flags. */ private List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } private List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ private Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new Priority("1"), new Email("1@email"), new StartDate("House of 1"), new DueDate("House of 1"), new UniqueTagList(new Tag("tag")) ); } } }
package test.blog.distrib; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import org.junit.Test; import blog.distrib.Categorical; /** * @author cgioia * @since Jun 17, 2014 */ public class TestCategorical implements TestDistributions { private final double ERROR = 10e-5; /** Categorical. "Albert" => 0.5, "Bob" => 0.2, "Craig" => 0.3. */ public void testCategorical1(Categorical cat) { assertEquals(0.0, cat.getProb("Andy"), ERROR); assertEquals(0.5, cat.getProb("Albert"), ERROR); assertEquals(0.2, cat.getProb("Bob"), ERROR); assertEquals(0.3, cat.getProb("Craig"), ERROR); assertEquals(0.0, cat.getProb(null), ERROR); assertEquals(Double.NEGATIVE_INFINITY, cat.getLogProb("Andy"), ERROR); assertEquals(Math.log(0.5), cat.getLogProb("Albert"), ERROR); assertEquals(Math.log(0.2), cat.getLogProb("Bob"), ERROR); assertEquals(Math.log(0.3), cat.getLogProb("Craig"), ERROR); assertEquals(Double.NEGATIVE_INFINITY, cat.getLogProb(null), ERROR); } @Test public void testProbabilityViaConstructor() { // not needed. will be removed } @Test public void testProbabilityViaSetParams() { Categorical cat = new Categorical(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("Bob", 0.2); map.put("Craig", 0.3); map.put("Albert", 0.5); cat.setParams(new Object[] { map }); testCategorical1(cat); } @Test(expected = IllegalArgumentException.class) public void testInsufficientArguments() { Categorical cat = new Categorical(); cat.setParams(new Object[] { null }); cat.sampleVal(); } @Test(expected = IllegalArgumentException.class) public void testIncorrectArguments() { Categorical cat = new Categorical(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("Bob", 0.2); map.put("Craig", -0.01); cat.setParams(new Object[] { map }); cat.sampleVal(); } @Test(expected = IllegalArgumentException.class) public void testProbabilitySumTooSmall() { Categorical cat = new Categorical(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("Albert", 0.0); map.put("Bob", 0.0); cat.setParams(new Object[] { map }); cat.sampleVal(); } @Test public void testNormalization() { Categorical cat = new Categorical(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("Bob", 6.0); map.put("Craig", 9.0); map.put("Albert", 15.0); cat.setParams(new Object[] { map }); testCategorical1(cat); } @Test public void testDoubleSet() { Categorical cat = new Categorical(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("Albert", 0.5); map.put("Bob", 0.2); map.put("Craig", 0.3); cat.setParams(new Object[] { null }); cat.setParams(new Object[] { map }); testCategorical1(cat); } @Test public void testSetParamsIntegerArguments() { Categorical cat = new Categorical(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("Albert", 15); map.put("Bob", 6); map.put("Craig", 9); cat.setParams(new Object[] { map }); testCategorical1(cat); } @Test public void testGetProbIntegerArguments() { // not needed } @Test public void testGetFiniteSupport() { Categorical cat = new Categorical(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("Bob", 0.2); map.put("Craig", 0.3); map.put("Albert", 0.5); map.put("Andy", 0.0); cat.setParams(new Object[] { map }); Object[] list = cat.getFiniteSupport(); HashSet<Object> values = new HashSet<Object>(Arrays.asList(list)); assertEquals(3, values.size()); assertTrue(values.contains("Bob")); assertTrue(values.contains("Craig")); assertTrue(values.contains("Albert")); } }
package test.com.qiniu.storage; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Response; import com.qiniu.storage.BucketManager; import com.qiniu.storage.Configuration; import com.qiniu.storage.model.*; import com.qiniu.util.StringUtils; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; import test.com.qiniu.TestConfig; import java.text.SimpleDateFormat; import java.util.*; @SuppressWarnings("ConstantConditions") public class BucketTest extends TestCase { private BucketManager bucketManager; private BucketManager bucketManagerNa0; private BucketManager dummyBucketManager; ArrayList<Integer> batchStatusCode = new ArrayList(){{ this.add(200); this.add(298); }}; @Override protected void setUp() throws Exception { //default config Configuration cfg = new Configuration(); cfg.useHttpsDomains = false; // cfg.useHttpsDomains = true; this.bucketManager = new BucketManager(TestConfig.testAuth, cfg); //na0 config Configuration cfgNa0 = new Configuration(Zone.zoneNa0()); this.bucketManagerNa0 = new BucketManager(TestConfig.testAuth, cfgNa0); //dummy config this.dummyBucketManager = new BucketManager(TestConfig.dummyAuth, new Configuration()); } @Test public void testBuckets() { try { String[] buckets = bucketManager.buckets(); assertTrue(StringUtils.inStringArray(TestConfig.testBucket_z0, buckets)); assertTrue(StringUtils.inStringArray(TestConfig.testBucket_na0, buckets)); } catch (QiniuException e) { fail(e.response.toString()); } try { dummyBucketManager.buckets(); fail(); } catch (QiniuException e) { assertEquals(401, e.code()); } } @Test public void testDomains() { try { String[] domains = bucketManager.domainList(TestConfig.testBucket_z0); assertNotNull(domains); } catch (QiniuException e) { assertEquals(401, e.code()); } } @Test public void testList() { try { String[] buckets = new String[]{TestConfig.testBucket_z0, TestConfig.testBucket_na0}; for (String bucket : buckets) { FileListing l = bucketManager.listFiles(bucket, null, null, 2, null); assertNotNull(l.items[0]); assertNotNull(l.marker); } } catch (QiniuException e) { fail(e.response.toString()); } } @Test public void testListUseDelimiter() { try { Map<String, String> bucketKeyMap = new HashMap<String, String>(); //bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); bucketManager.copy(bucket, key, bucket, "test/" + key, true); bucketManager.copy(bucket, key, bucket, "test/1/" + key, true); bucketManager.copy(bucket, key, bucket, "test/2/" + key, true); bucketManager.copy(bucket, key, bucket, "test/3/" + key, true); FileListing l = bucketManager.listFiles(bucket, "test/", null, 10, "/"); assertEquals(1, l.items.length); assertEquals(3, l.commonPrefixes.length); } } catch (QiniuException e) { fail(e.response.toString()); } } @Test public void testListIterator() { String[] buckets = new String[]{TestConfig.testBucket_z0, TestConfig.testBucket_na0}; for (String bucket : buckets) { BucketManager.FileListIterator it = bucketManager.createFileListIterator(bucket, "", 20, null); assertTrue(it.hasNext()); FileInfo[] items0 = it.next(); assertNotNull(items0[0]); while (it.hasNext()) { FileInfo[] items = it.next(); if (items.length > 1) { assertNotNull(items[0]); } } } } @Test public void testListIteratorWithDefaultLimit() { String[] buckets = new String[]{TestConfig.testBucket_z0, TestConfig.testBucket_na0}; for (String bucket : buckets) { BucketManager.FileListIterator it = bucketManager.createFileListIterator(bucket, ""); assertTrue(it.hasNext()); FileInfo[] items0 = it.next(); assertNotNull(items0[0]); while (it.hasNext()) { FileInfo[] items = it.next(); if (items.length > 1) { assertNotNull(items[0]); } } } } @Test public void testStat() { //test exists Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); try { FileInfo info = bucketManager.stat(bucket, key); assertNotNull(info.hash); assertNotNull(info.mimeType); } catch (QiniuException e) { fail(bucket + ":" + key + "==> " + e.response.toString()); } } //test bucket not exits or file not exists Map<String[], Integer> entryCodeMap = new HashMap<String[], Integer>(); entryCodeMap.put(new String[]{TestConfig.testBucket_z0, TestConfig.dummyKey}, TestConfig.ERROR_CODE_KEY_NOT_EXIST); entryCodeMap.put(new String[]{TestConfig.dummyBucket, TestConfig.testKey_z0}, TestConfig.ERROR_CODE_BUCKET_NOT_EXIST); entryCodeMap.put(new String[]{TestConfig.dummyBucket, TestConfig.dummyKey}, TestConfig.ERROR_CODE_BUCKET_NOT_EXIST); for (Map.Entry<String[], Integer> entry : entryCodeMap.entrySet()) { String bucket = entry.getKey()[0]; String key = entry.getKey()[1]; int code = entry.getValue(); try { bucketManager.stat(bucket, key); fail(); } catch (QiniuException e) { assertEquals(code, e.code()); } } } @Test public void testDelete() { Map<String[], Integer> entryCodeMap = new HashMap<String[], Integer>(); entryCodeMap.put(new String[]{TestConfig.testBucket_z0, TestConfig.dummyKey}, TestConfig.ERROR_CODE_KEY_NOT_EXIST); entryCodeMap.put(new String[]{TestConfig.testBucket_z0, null}, TestConfig.ERROR_CODE_BUCKET_NOT_EXIST); entryCodeMap.put(new String[]{TestConfig.dummyBucket, null}, TestConfig.ERROR_CODE_BUCKET_NOT_EXIST); entryCodeMap.put(new String[]{TestConfig.dummyBucket, TestConfig.dummyKey}, TestConfig.ERROR_CODE_BUCKET_NOT_EXIST); for (Map.Entry<String[], Integer> entry : entryCodeMap.entrySet()) { String bucket = entry.getKey()[0]; String key = entry.getKey()[1]; int code = entry.getValue(); try { bucketManager.delete(bucket, key); fail(bucket + ":" + key + "==> " + "delete failed"); } catch (QiniuException e) { assertEquals(code, e.code()); } } } @Test public void testRename() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String renameFromKey = "renameFrom" + Math.random(); try { bucketManager.copy(bucket, key, bucket, renameFromKey); String renameToKey = "renameTo" + key; bucketManager.rename(bucket, renameFromKey, renameToKey); bucketManager.delete(bucket, renameToKey); } catch (QiniuException e) { fail(bucket + ":" + key + "==> " + e.response.toString()); } } } @Test public void testCopy() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String copyToKey = "copyTo" + Math.random(); try { bucketManager.copy(bucket, key, bucket, copyToKey); bucketManager.delete(bucket, copyToKey); } catch (QiniuException e) { fail(bucket + ":" + key + "==> " + e.response.toString()); } } } @Test public void testChangeMime() { List<String[]> cases = new ArrayList<String[]>(); cases.add(new String[]{TestConfig.testBucket_z0, TestConfig.testKey_z0, "image/png"}); cases.add(new String[]{TestConfig.testBucket_na0, TestConfig.testKey_na0, "image/png"}); for (String[] icase : cases) { String bucket = icase[0]; String key = icase[1]; String mime = icase[2]; try { bucketManager.changeMime(bucket, key, mime); } catch (QiniuException e) { fail(bucket + ":" + key + "==> " + e.response.toString()); } } } @Test public void testChangeHeaders() { List<String[]> cases = new ArrayList<String[]>(); cases.add(new String[]{TestConfig.testBucket_z0, TestConfig.testKey_z0}); cases.add(new String[]{TestConfig.testBucket_na0, TestConfig.testKey_na0}); for (String[] icase : cases) { String bucket = icase[0]; String key = icase[1]; try { Map<String, String> headers = new HashMap<>(); Date d = new Date(); SimpleDateFormat dateFm = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.ENGLISH); System.out.println(dateFm.format(d)); headers.put("Content-Type", "image/png"); headers.put("Last-Modified", dateFm.format(d)); bucketManager.changeHeaders(bucket, key, headers); } catch (QiniuException e) { fail(bucket + ":" + key + "==> " + e.response.toString()); } } } @Test public void testPrefetch() { String[] buckets = new String[]{TestConfig.testBucket_z0, TestConfig.testBucket_na0}; for (String bucket : buckets) { try { bucketManager.setImage(bucket, "https://developer.qiniu.com/"); bucketManager.prefetch(bucket, "kodo/sdk/1239/java"); bucketManager.unsetImage(bucket); } catch (QiniuException e) { fail(bucket + "==>" + e.response.toString()); } } } @Test public void testFetch() { String[] buckets = new String[]{TestConfig.testBucket_z0, TestConfig.testBucket_na0}; for (String bucket : buckets) { try { String resUrl = "http://devtools.qiniu.com/qiniu.png"; String resKey = "qiniu.png"; String resHash = "FpHyF0kkil3sp-SaXXX8TBJY3jDh"; FetchRet fRet = bucketManager.fetch(resUrl, bucket, resKey); assertEquals(resHash, fRet.hash); //no key specified, use hash as file key fRet = bucketManager.fetch(resUrl, bucket); assertEquals(resHash, fRet.hash); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testFetchNa0() { try { String resUrl = "http://devtools.qiniu.com/qiniu.png"; String resKey = "qiniu.png"; String resHash = "FpHyF0kkil3sp-SaXXX8TBJY3jDh"; FetchRet fRet = bucketManagerNa0.fetch(resUrl, TestConfig.testBucket_na0, resKey); assertEquals(resHash, fRet.hash); //no key specified, use hash as file key fRet = bucketManagerNa0.fetch(resUrl, TestConfig.testBucket_na0); assertEquals(resHash, fRet.hash); } catch (QiniuException e) { fail(e.response.toString()); } } @Test public void testBatchCopy() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String copyToKey = "copyTo" + Math.random(); BucketManager.BatchOperations ops = new BucketManager.BatchOperations(). addCopyOp(bucket, key, bucket, copyToKey); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); Assert.assertTrue("200 or 298", batchStatusCode.contains(bs[0].code)); } catch (QiniuException e) { fail(e.response.toString()); } ops = new BucketManager.BatchOperations().addDeleteOp(bucket, copyToKey); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); Assert.assertTrue("200 or 298", batchStatusCode.contains(bs[0].code)); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testBatchMove() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String moveFromKey = "moveFrom" + Math.random(); try { bucketManager.copy(bucket, key, bucket, moveFromKey); } catch (QiniuException e) { fail(e.response.toString()); } String moveToKey = key + "to"; BucketManager.BatchOperations ops = new BucketManager.BatchOperations() .addMoveOp(bucket, moveFromKey, bucket, moveToKey); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); Assert.assertTrue("200 or 298", batchStatusCode.contains(bs[0].code)); } catch (QiniuException e) { fail(e.response.toString()); } try { bucketManager.delete(bucket, moveToKey); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testBatchRename() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String renameFromKey = "renameFrom" + Math.random(); try { bucketManager.copy(bucket, key, bucket, renameFromKey); } catch (QiniuException e) { fail(e.response.toString()); } String renameToKey = "renameTo" + key; BucketManager.BatchOperations ops = new BucketManager.BatchOperations() .addRenameOp(bucket, renameFromKey, renameToKey); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); Assert.assertTrue("200 or 298", batchStatusCode.contains(bs[0].code)); } catch (QiniuException e) { fail(e.response.toString()); } try { bucketManager.delete(bucket, renameToKey); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testBatchStat() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String[] keyArray = new String[100]; for (int i = 0; i < keyArray.length; i++) { keyArray[i] = key; } BucketManager.BatchOperations ops = new BucketManager.BatchOperations() .addStatOps(bucket, keyArray); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); Assert.assertTrue("200 or 298", batchStatusCode.contains(bs[0].code)); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testBatchChangeType() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String okey = entry.getValue(); String key = "batchChangeType" + Math.random(); String key2 = "batchChangeType" + Math.random(); String[] keyArray = new String[100]; keyArray[0] = key; keyArray[1] = key2; BucketManager.BatchOperations opsCopy = new BucketManager.BatchOperations(). addCopyOp(bucket, okey, bucket, key).addCopyOp(bucket, okey, bucket, key2); try { bucketManager.batch(opsCopy); } catch (QiniuException e) { fail("batch copy failed: " + e.response.toString()); } BucketManager.BatchOperations ops = new BucketManager.BatchOperations() .addChangeTypeOps(bucket, StorageType.INFREQUENCY, keyArray); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); Assert.assertTrue("200 or 298", batchStatusCode.contains(bs[0].code)); } catch (QiniuException e) { fail(e.response.toString()); } finally { try { bucketManager.delete(bucket, key); bucketManager.delete(bucket, key2); } catch (QiniuException e) { e.printStackTrace(); } } } } @Test public void testBatchCopyChgmDelete() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); //make 100 copies String[] keyArray = new String[100]; for (int i = 0; i < keyArray.length; i++) { keyArray[i] = String.format("%s-copy-%d", key, i); } BucketManager.BatchOperations ops = new BucketManager.BatchOperations(); for (int i = 0; i < keyArray.length; i++) { ops.addCopyOp(bucket, key, bucket, keyArray[i]); } try { Response response = bucketManager.batch(ops); Assert.assertTrue("200 or 298", batchStatusCode.contains(response.statusCode)); //clear ops ops.clearOps(); //batch chane mimetype for (int i = 0; i < keyArray.length; i++) { ops.addChgmOp(bucket, keyArray[i], "image/png"); } response = bucketManager.batch(ops); Assert.assertTrue("200 or 298", batchStatusCode.contains(response.statusCode)); //clear ops for (int i = 0; i < keyArray.length; i++) { ops.addDeleteOp(bucket, keyArray[i]); } response = bucketManager.batch(ops); Assert.assertTrue("200 or 298", batchStatusCode.contains(response.statusCode)); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testBatch() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String[] array = {key}; String copyFromKey = "copyFrom" + Math.random(); String moveFromKey = "moveFrom" + Math.random(); String moveToKey = "moveTo" + Math.random(); String moveFromKey2 = "moveFrom" + Math.random(); String moveToKey2 = "moveTo" + Math.random(); try { bucketManager.copy(bucket, key, bucket, moveFromKey); bucketManager.copy(bucket, key, bucket, moveFromKey2); } catch (QiniuException e) { fail(e.response.toString()); } BucketManager.BatchOperations ops = new BucketManager.BatchOperations() .addCopyOp(bucket, key, bucket, copyFromKey) .addMoveOp(bucket, moveFromKey, bucket, moveToKey) .addRenameOp(bucket, moveFromKey2, moveToKey2) .addStatOps(bucket, array) .addStatOps(bucket, array[0]); try { Response r = bucketManager.batch(ops); BatchStatus[] bs = r.jsonToObject(BatchStatus[].class); for (BatchStatus b : bs) { Assert.assertTrue("200 or 298", batchStatusCode.contains(b.code)); } } catch (QiniuException e) { fail(e.response.toString()); } BucketManager.BatchOperations opsDel = new BucketManager.BatchOperations() .addDeleteOp(bucket, copyFromKey, moveFromKey, moveToKey, moveFromKey2, moveToKey2); try { bucketManager.batch(opsDel); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testSetAndUnsetImage() { String[] buckets = new String[]{TestConfig.testBucket_z0, TestConfig.testBucket_na0}; for (String bucket : buckets) { String srcSiteUrl = "http://developer.qiniu.com/"; String host = "developer.qiniu.com"; try { Response setResp = bucketManager.setImage(bucket, srcSiteUrl); assertEquals(200, setResp.statusCode); setResp = bucketManager.setImage(bucket, srcSiteUrl, host); assertEquals(200, setResp.statusCode); Response unsetResp = bucketManager.unsetImage(bucket); assertEquals(200, unsetResp.statusCode); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testDeleteAfterDays() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String keyForDelete = "keyForDelete" + Math.random(); try { bucketManager.copy(bucket, key, bucket, keyForDelete); Response response = bucketManager.deleteAfterDays(bucket, key, 10); Assert.assertEquals(200, response.statusCode); } catch (QiniuException e) { fail(e.response.toString()); } } } @Test public void testChangeFileType() { Map<String, String> bucketKeyMap = new HashMap<String, String>(); bucketKeyMap.put(TestConfig.testBucket_z0, TestConfig.testKey_z0); bucketKeyMap.put(TestConfig.testBucket_na0, TestConfig.testKey_na0); for (Map.Entry<String, String> entry : bucketKeyMap.entrySet()) { String bucket = entry.getKey(); String key = entry.getValue(); String keyToChangeType = "keyToChangeType" + Math.random(); try { bucketManager.copy(bucket, key, bucket, keyToChangeType); Response response = bucketManager.changeType(bucket, keyToChangeType, StorageType.INFREQUENCY); Assert.assertEquals(200, response.statusCode); //stat FileInfo fileInfo = bucketManager.stat(bucket, keyToChangeType); Assert.assertEquals(StorageType.INFREQUENCY.ordinal(), fileInfo.type); //delete the temp file bucketManager.delete(bucket, keyToChangeType); } catch (QiniuException e) { fail(bucket + ":" + key + " > " + keyToChangeType + " >> " + StorageType.INFREQUENCY + " ==> " + e.response.toString()); } } } @Test public void testAcl() throws QiniuException { bucketManager.setBucketAcl("javasdk", AclType.PRIVATE); BucketInfo info = bucketManager.getBucketInfo("javasdk"); Assert.assertEquals(1, info.getPrivate()); bucketManager.setBucketAcl("javasdk", AclType.PUBLIC); info = bucketManager.getBucketInfo("javasdk"); Assert.assertEquals(0, info.getPrivate()); try { bucketManager.setBucketAcl("javsfsdfsfsdfsdfsdfasdk1", AclType.PRIVATE); // Assert.fail(" javasdk2 "); // kodo 200 } catch (QiniuException e) { e.printStackTrace(); throw e; } } @Test public void testBucketInfo() throws QiniuException { BucketInfo info = bucketManager.getBucketInfo("javasdk"); System.out.println(info.getRegion()); System.out.println(info.getZone()); System.out.println(info.getPrivate()); try { BucketInfo info2 = bucketManager.getBucketInfo("javasdk2"); Assert.fail(" javasdk2 "); } catch (QiniuException e) { if (e.response != null) { System.out.println(e.response.getInfo()); throw e; } } } @Test public void testIndexPage() throws QiniuException { bucketManager.setIndexPage("javasdk", IndexPageType.HAS); BucketInfo info = bucketManager.getBucketInfo("javasdk"); Assert.assertEquals(0, info.getNoIndexPage()); bucketManager.setIndexPage("javasdk", IndexPageType.NO); info = bucketManager.getBucketInfo("javasdk"); Assert.assertEquals(1, info.getNoIndexPage()); try { bucketManager.setIndexPage("javasdk2", IndexPageType.HAS); // Assert.fail(" javasdk2 "); // kodo 200 } catch (QiniuException e) { e.printStackTrace(); throw e; } } }
package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Date; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests {@link org.apache.commons.lang.ArrayUtils}. * * @author Stephen Colebourne * @author Moritz Petersen * @author Nikolay Metchev * @author Matthew Hawthorne * @author Tim O'Brien * @author <a href="mailto:equinus100@hotmail.com">Ashwin S</a> * @author Fredrik Westermarck * @author Gary Gregory * @version $Id: ArrayUtilsTest.java,v 1.21 2004/01/19 22:55:05 ggregory Exp $ */ public class ArrayUtilsTest extends TestCase { public ArrayUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(ArrayUtilsTest.class); suite.setName("ArrayUtils Tests"); return suite; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testConstructor() { assertNotNull(new ArrayUtils()); Constructor[] cons = ArrayUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(ArrayUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(ArrayUtils.class.getModifiers())); } public void testToString() { assertEquals("{}", ArrayUtils.toString(null)); assertEquals("{}", ArrayUtils.toString(new Object[0])); assertEquals("{}", ArrayUtils.toString(new String[0])); assertEquals("{<null>}", ArrayUtils.toString(new String[] {null})); assertEquals("{pink,blue}", ArrayUtils.toString(new String[] {"pink","blue"})); assertEquals("<empty>", ArrayUtils.toString(null, "<empty>")); assertEquals("{}", ArrayUtils.toString(new Object[0], "<empty>")); assertEquals("{}", ArrayUtils.toString(new String[0], "<empty>")); assertEquals("{<null>}", ArrayUtils.toString(new String[] {null}, "<empty>")); assertEquals("{pink,blue}", ArrayUtils.toString(new String[] {"pink","blue"}, "<empty>")); } public void testHashCode() { long[][] array1 = new long[][] {{2,5}, {4,5}}; long[][] array2 = new long[][] {{2,5}, {4,6}}; assertEquals(true, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array1)); assertEquals(false, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array2)); Object[] array3 = new Object[] {new String(new char[] {'A', 'B'})}; Object[] array4 = new Object[] {"AB"}; assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array3)); assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array4)); } public void testIsEquals() { long[][] array1 = new long[][] {{2,5}, {4,5}}; long[][] array2 = new long[][] {{2,5}, {4,6}}; assertEquals(true, ArrayUtils.isEquals(array1, array1)); assertEquals(false, ArrayUtils.isEquals(array1, array2)); Object[] array3 = new Object[] {new String(new char[] {'A', 'B'})}; Object[] array4 = new Object[] {"AB"}; assertEquals(true, ArrayUtils.isEquals(array3, array3)); assertEquals(true, ArrayUtils.isEquals(array3, array4)); assertEquals(true, ArrayUtils.isEquals(null, null)); assertEquals(false, ArrayUtils.isEquals(null, array4)); } public void testToMap() { Map map = ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"hello", "world"}}); assertEquals("bar", map.get("foo")); assertEquals("world", map.get("hello")); assertEquals(null, ArrayUtils.toMap(null)); try { ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"short"}}); fail("exception expected"); } catch (IllegalArgumentException ex) {} try { ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, "illegal type"}); fail("exception expected"); } catch (IllegalArgumentException ex) {} try { ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, null}); fail("exception expected"); } catch (IllegalArgumentException ex) {} map = ArrayUtils.toMap(new Object[] {new Map.Entry() { public Object getKey() { return "foo"; } public Object getValue() { return "bar"; } public Object setValue(Object value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { throw new UnsupportedOperationException(); } public int hashCode() { throw new UnsupportedOperationException(); } }}); assertEquals("bar", map.get("foo")); } public void testClone() { assertEquals(null, ArrayUtils.clone((Object[]) null)); Object[] original1 = new Object[0]; Object[] cloned1 = ArrayUtils.clone(original1); assertTrue(Arrays.equals(original1, cloned1)); assertTrue(original1 != cloned1); StringBuffer buf = new StringBuffer("pick"); original1 = new Object[] {buf, "a", new String[] {"stick"}}; cloned1 = ArrayUtils.clone(original1); assertTrue(Arrays.equals(original1, cloned1)); assertTrue(original1 != cloned1); assertSame(original1[0], cloned1[0]); assertSame(original1[1], cloned1[1]); assertSame(original1[2], cloned1[2]); } public void testCloneBoolean() { assertEquals(null, ArrayUtils.clone((boolean[]) null)); boolean[] original = new boolean[] {true, false}; boolean[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneLong() { assertEquals(null, ArrayUtils.clone((long[]) null)); long[] original = new long[] {0L, 1L}; long[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneInt() { assertEquals(null, ArrayUtils.clone((int[]) null)); int[] original = new int[] {5, 8}; int[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneShort() { assertEquals(null, ArrayUtils.clone((short[]) null)); short[] original = new short[] {1, 4}; short[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneChar() { assertEquals(null, ArrayUtils.clone((char[]) null)); char[] original = new char[] {'a', '4'}; char[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneByte() { assertEquals(null, ArrayUtils.clone((byte[]) null)); byte[] original = new byte[] {1, 6}; byte[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneDouble() { assertEquals(null, ArrayUtils.clone((double[]) null)); double[] original = new double[] {2.4d, 5.7d}; double[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneFloat() { assertEquals(null, ArrayUtils.clone((float[]) null)); float[] original = new float[] {2.6f, 6.4f}; float[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testSubarrayObject() { Object[] nullArray = null; Object[] objectArray = { "a", "b", "c", "d", "e", "f"}; assertEquals("0 start, mid end", "abcd", StringUtils.join(ArrayUtils.subarray(objectArray, 0, 4))); assertEquals("0 start, length end", "abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 0, objectArray.length))); assertEquals("mid start, mid end", "bcd", StringUtils.join(ArrayUtils.subarray(objectArray, 1, 4))); assertEquals("mid start, length end", "bcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 1, objectArray.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", "", StringUtils.join(ArrayUtils.subarray(ArrayUtils.EMPTY_OBJECT_ARRAY, 1, 2))); assertEquals("start > end", "", StringUtils.join(ArrayUtils.subarray(objectArray, 4, 2))); assertEquals("start == end", "", StringUtils.join(ArrayUtils.subarray(objectArray, 3, 3))); assertEquals("start undershoot, normal end", "abcd", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 4))); assertEquals("start overshoot, any end", "", StringUtils.join(ArrayUtils.subarray(objectArray, 33, 4))); assertEquals("normal start, end overshoot", "cdef", StringUtils.join(ArrayUtils.subarray(objectArray, 2, 33))); assertEquals("start undershoot, end overshoot", "abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 12))); // array type tests Date[] dateArray = { new java.sql.Date(new Date().getTime()), new Date(), new Date(), new Date(), new Date() }; assertSame("Object type", Object.class, ArrayUtils.subarray(objectArray, 2, 4).getClass().getComponentType()); assertSame("java.util.Date type", java.util.Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType()); assertNotSame("java.sql.Date type", java.sql.Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType()); try { Object dummy = (java.sql.Date[])ArrayUtils.subarray(dateArray, 1,3); fail("Invalid downcast"); } catch (ClassCastException e) {} } public void testSubarrayLong() { long[] nullArray = null; long[] array = { 999910, 999911, 999912, 999913, 999914, 999915 }; long[] leftSubarray = { 999910, 999911, 999912, 999913 }; long[] midSubarray = { 999911, 999912, 999913, 999914 }; long[] rightSubarray = { 999912, 999913, 999914, 999915 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("long type", long.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayInt() { int[] nullArray = null; int[] array = { 10, 11, 12, 13, 14, 15 }; int[] leftSubarray = { 10, 11, 12, 13 }; int[] midSubarray = { 11, 12, 13, 14 }; int[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("int type", int.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayShort() { short[] nullArray = null; short[] array = { 10, 11, 12, 13, 14, 15 }; short[] leftSubarray = { 10, 11, 12, 13 }; short[] midSubarray = { 11, 12, 13, 14 }; short[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("short type", short.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrChar() { char[] nullArray = null; char[] array = { 'a', 'b', 'c', 'd', 'e', 'f' }; char[] leftSubarray = { 'a', 'b', 'c', 'd', }; char[] midSubarray = { 'b', 'c', 'd', 'e', }; char[] rightSubarray = { 'c', 'd', 'e', 'f', }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("char type", char.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayByte() { byte[] nullArray = null; byte[] array = { 10, 11, 12, 13, 14, 15 }; byte[] leftSubarray = { 10, 11, 12, 13 }; byte[] midSubarray = { 11, 12, 13, 14 }; byte[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("byte type", byte.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayDouble() { double[] nullArray = null; double[] array = { 10.123, 11.234, 12.345, 13.456, 14.567, 15.678 }; double[] leftSubarray = { 10.123, 11.234, 12.345, 13.456, }; double[] midSubarray = { 11.234, 12.345, 13.456, 14.567, }; double[] rightSubarray = { 12.345, 13.456, 14.567, 15.678 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("double type", double.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayFloat() { float[] nullArray = null; float[] array = { 10, 11, 12, 13, 14, 15 }; float[] leftSubarray = { 10, 11, 12, 13 }; float[] midSubarray = { 11, 12, 13, 14 }; float[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("float type", float.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayBoolean() { boolean[] nullArray = null; boolean[] array = { true, true, false, true, false, true }; boolean[] leftSubarray = { true, true, false, true }; boolean[] midSubarray = { true, false, true, false }; boolean[] rightSubarray = { false, true, false, true }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("boolean type", boolean.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSameLength() { Object[] nullArray = null; Object[] emptyArray = new Object[0]; Object[] oneArray = new Object[] {"pick"}; Object[] twoArray = new Object[] {"pick", "stick"}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthBoolean() { boolean[] nullArray = null; boolean[] emptyArray = new boolean[0]; boolean[] oneArray = new boolean[] {true}; boolean[] twoArray = new boolean[] {true, false}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthLong() { long[] nullArray = null; long[] emptyArray = new long[0]; long[] oneArray = new long[] {0L}; long[] twoArray = new long[] {0L, 76L}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthInt() { int[] nullArray = null; int[] emptyArray = new int[0]; int[] oneArray = new int[] {4}; int[] twoArray = new int[] {5, 7}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthShort() { short[] nullArray = null; short[] emptyArray = new short[0]; short[] oneArray = new short[] {4}; short[] twoArray = new short[] {6, 8}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthChar() { char[] nullArray = null; char[] emptyArray = new char[0]; char[] oneArray = new char[] {'f'}; char[] twoArray = new char[] {'d', 't'}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthByte() { byte[] nullArray = null; byte[] emptyArray = new byte[0]; byte[] oneArray = new byte[] {3}; byte[] twoArray = new byte[] {4, 6}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthDouble() { double[] nullArray = null; double[] emptyArray = new double[0]; double[] oneArray = new double[] {1.3d}; double[] twoArray = new double[] {4.5d, 6.3d}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthFloat() { float[] nullArray = null; float[] emptyArray = new float[0]; float[] oneArray = new float[] {2.5f}; float[] twoArray = new float[] {6.4f, 5.8f}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameType() { try { ArrayUtils.isSameType(null, null); fail(); } catch (IllegalArgumentException ex) {} try { ArrayUtils.isSameType(null, new Object[0]); fail(); } catch (IllegalArgumentException ex) {} try { ArrayUtils.isSameType(new Object[0], null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, ArrayUtils.isSameType(new Object[0], new Object[0])); assertEquals(false, ArrayUtils.isSameType(new String[0], new Object[0])); assertEquals(true, ArrayUtils.isSameType(new String[0][0], new String[0][0])); assertEquals(false, ArrayUtils.isSameType(new String[0], new String[0][0])); assertEquals(false, ArrayUtils.isSameType(new String[0][0], new String[0])); } public void testReverse() { StringBuffer str1 = new StringBuffer("pick"); String str2 = "a"; String[] str3 = new String[] {"stick"}; String str4 = "up"; Object[] array = new Object[] {str1, str2, str3}; ArrayUtils.reverse(array); assertEquals(array[0], str3); assertEquals(array[1], str2); assertEquals(array[2], str1); array = new Object[] {str1, str2, str3, str4}; ArrayUtils.reverse(array); assertEquals(array[0], str4); assertEquals(array[1], str3); assertEquals(array[2], str2); assertEquals(array[3], str1); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseLong() { long[] array = new long[] {1L, 2L, 3L}; ArrayUtils.reverse(array); assertEquals(array[0], 3L); assertEquals(array[1], 2L); assertEquals(array[2], 1L); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseInt() { int[] array = new int[] {1, 2, 3}; ArrayUtils.reverse(array); assertEquals(array[0], 3); assertEquals(array[1], 2); assertEquals(array[2], 1); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseShort() { short[] array = new short[] {1, 2, 3}; ArrayUtils.reverse(array); assertEquals(array[0], 3); assertEquals(array[1], 2); assertEquals(array[2], 1); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseChar() { char[] array = new char[] {'a', 'f', 'C'}; ArrayUtils.reverse(array); assertEquals(array[0], 'C'); assertEquals(array[1], 'f'); assertEquals(array[2], 'a'); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseByte() { byte[] array = new byte[] {2, 3, 4}; ArrayUtils.reverse(array); assertEquals(array[0], 4); assertEquals(array[1], 3); assertEquals(array[2], 2); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseDouble() { double[] array = new double[] {0.3d, 0.4d, 0.5d}; ArrayUtils.reverse(array); assertEquals(array[0], 0.5d, 0.0d); assertEquals(array[1], 0.4d, 0.0d); assertEquals(array[2], 0.3d, 0.0d); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseFloat() { float[] array = new float[] {0.3f, 0.4f, 0.5f}; ArrayUtils.reverse(array); assertEquals(array[0], 0.5f, 0.0f); assertEquals(array[1], 0.4f, 0.0f); assertEquals(array[2], 0.3f, 0.0f); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseBoolean() { boolean[] array = new boolean[] {false, false, true}; ArrayUtils.reverse(array); assertEquals(array[0], true); assertEquals(array[1], false); assertEquals(array[2], false); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testIndexOf() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.indexOf(null, null)); assertEquals(-1, ArrayUtils.indexOf(null, "0")); assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0")); assertEquals(0, ArrayUtils.indexOf(array, "0")); assertEquals(1, ArrayUtils.indexOf(array, "1")); assertEquals(2, ArrayUtils.indexOf(array, "2")); assertEquals(3, ArrayUtils.indexOf(array, "3")); assertEquals(4, ArrayUtils.indexOf(array, null)); assertEquals(-1, ArrayUtils.indexOf(array, "notInArray")); } public void testIndexOfWithStartIndex() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.indexOf(null, null, 2)); assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0", 0)); assertEquals(-1, ArrayUtils.indexOf(null, "0", 2)); assertEquals(5, ArrayUtils.indexOf(array, "0", 2)); assertEquals(-1, ArrayUtils.indexOf(array, "1", 2)); assertEquals(2, ArrayUtils.indexOf(array, "2", 2)); assertEquals(3, ArrayUtils.indexOf(array, "3", 2)); assertEquals(4, ArrayUtils.indexOf(array, null, 2)); assertEquals(-1, ArrayUtils.indexOf(array, "notInArray", 2)); assertEquals(4, ArrayUtils.indexOf(array, null, -1)); assertEquals(-1, ArrayUtils.indexOf(array, null, 8)); assertEquals(-1, ArrayUtils.indexOf(array, "0", 8)); } public void testLastIndexOf() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.lastIndexOf(null, null)); assertEquals(-1, ArrayUtils.lastIndexOf(null, "0")); assertEquals(5, ArrayUtils.lastIndexOf(array, "0")); assertEquals(1, ArrayUtils.lastIndexOf(array, "1")); assertEquals(2, ArrayUtils.lastIndexOf(array, "2")); assertEquals(3, ArrayUtils.lastIndexOf(array, "3")); assertEquals(4, ArrayUtils.lastIndexOf(array, null)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray")); } public void testLastIndexOfWithStartIndex() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.lastIndexOf(null, null, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(null, "0", 2)); assertEquals(0, ArrayUtils.lastIndexOf(array, "0", 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, "1", 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, "2", 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", -1)); assertEquals(4, ArrayUtils.lastIndexOf(array, null, 5)); assertEquals(-1, ArrayUtils.lastIndexOf(array, null, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray", 5)); assertEquals(-1, ArrayUtils.lastIndexOf(array, null, -1)); assertEquals(5, ArrayUtils.lastIndexOf(array, "0", 88)); } public void testContains() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(false, ArrayUtils.contains(null, null)); assertEquals(false, ArrayUtils.contains(null, "1")); assertEquals(true, ArrayUtils.contains(array, "0")); assertEquals(true, ArrayUtils.contains(array, "1")); assertEquals(true, ArrayUtils.contains(array, "2")); assertEquals(true, ArrayUtils.contains(array, "3")); assertEquals(true, ArrayUtils.contains(array, null)); assertEquals(false, ArrayUtils.contains(array, "notInArray")); } public void testIndexOfLong() { long[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, 0)); assertEquals(1, ArrayUtils.indexOf(array, 1)); assertEquals(2, ArrayUtils.indexOf(array, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3)); assertEquals(-1, ArrayUtils.indexOf(array, 99)); } public void testIndexOfLongWithStartIndex() { long[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); } public void testLastIndexOfLong() { long[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); } public void testLastIndexOfLongWithStartIndex() { long[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99, 4)); assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); } public void testContainsLong() { long[] array = null; assertEquals(false, ArrayUtils.contains(array, 1)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, 0)); assertEquals(true, ArrayUtils.contains(array, 1)); assertEquals(true, ArrayUtils.contains(array, 2)); assertEquals(true, ArrayUtils.contains(array, 3)); assertEquals(false, ArrayUtils.contains(array, 99)); } public void testIndexOfInt() { int[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, 0)); assertEquals(1, ArrayUtils.indexOf(array, 1)); assertEquals(2, ArrayUtils.indexOf(array, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3)); assertEquals(-1, ArrayUtils.indexOf(array, 99)); } public void testIndexOfIntWithStartIndex() { int[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); } public void testLastIndexOfInt() { int[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); } public void testLastIndexOfIntWithStartIndex() { int[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); } public void testContainsInt() { int[] array = null; assertEquals(false, ArrayUtils.contains(array, 1)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, 0)); assertEquals(true, ArrayUtils.contains(array, 1)); assertEquals(true, ArrayUtils.contains(array, 2)); assertEquals(true, ArrayUtils.contains(array, 3)); assertEquals(false, ArrayUtils.contains(array, 99)); } public void testIndexOfShort() { short[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (short) 0)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (short) 0)); assertEquals(1, ArrayUtils.indexOf(array, (short) 1)); assertEquals(2, ArrayUtils.indexOf(array, (short) 2)); assertEquals(3, ArrayUtils.indexOf(array, (short) 3)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 99)); } public void testIndexOfShortWithStartIndex() { short[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 2)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (short) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (short) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (short) 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, (short) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 6)); } public void testLastIndexOfShort() { short[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (short) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); } public void testLastIndexOfShortWithStartIndex() { short[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0, 2)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (short) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0, 88)); } public void testContainsShort() { short[] array = null; assertEquals(false, ArrayUtils.contains(array, (short) 1)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (short) 0)); assertEquals(true, ArrayUtils.contains(array, (short) 1)); assertEquals(true, ArrayUtils.contains(array, (short) 2)); assertEquals(true, ArrayUtils.contains(array, (short) 3)); assertEquals(false, ArrayUtils.contains(array, (short) 99)); } public void testIndexOfByte() { byte[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (byte) 0)); assertEquals(1, ArrayUtils.indexOf(array, (byte) 1)); assertEquals(2, ArrayUtils.indexOf(array, (byte) 2)); assertEquals(3, ArrayUtils.indexOf(array, (byte) 3)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99)); } public void testIndexOfByteWithStartIndex() { byte[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 2)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (byte) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (byte) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 6)); } public void testLastIndexOfByte() { byte[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (byte) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); } public void testLastIndexOfByteWithStartIndex() { byte[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0, 88)); } public void testContainsByte() { byte[] array = null; assertEquals(false, ArrayUtils.contains(array, (byte) 1)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (byte) 0)); assertEquals(true, ArrayUtils.contains(array, (byte) 1)); assertEquals(true, ArrayUtils.contains(array, (byte) 2)); assertEquals(true, ArrayUtils.contains(array, (byte) 3)); assertEquals(false, ArrayUtils.contains(array, (byte) 99)); } public void testIndexOfDouble() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (double) 0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2)); assertEquals(3, ArrayUtils.indexOf(array, (double) 3)); assertEquals(3, ArrayUtils.indexOf(array, (double) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 99)); } public void testIndexOfDoubleTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (double) 0, (double) 0.3)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2.2, (double) 0.35)); assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, (double) 2.0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, (double) 0.0001)); } public void testIndexOfDoubleWithStartIndex() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (double) 3, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 6)); } public void testIndexOfDoubleWithStartIndexTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 99, (double) 0.3)); assertEquals(0, ArrayUtils.indexOf(array, (double) 0, 0, (double) 0.3)); assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 3, (double) 0.3)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2.2, 0, (double) 0.35)); assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, 0, (double) 2.0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, 0, (double) 0.0001)); assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, -1, (double) 2.0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, -300, (double) 0.0001)); } public void testLastIndexOfDouble() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); } public void testLastIndexOfDoubleTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0.3)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2.2, (double) 0.35)); assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 4.15, (double) 2.0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1.00001324, (double) 0.0001)); } public void testLastIndexOfDoubleWithStartIndex() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 88)); } public void testLastIndexOfDoubleWithStartIndexTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 99, (double) 0.3)); assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 3, (double) 0.3)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2.2, 3, (double) 0.35)); assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 4.15, array.length, (double) 2.0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1.00001324, array.length, (double) 0.0001)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 4.15, -200, (double) 2.0)); } public void testContainsDouble() { double[] array = null; assertEquals(false, ArrayUtils.contains(array, (double) 1)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (double) 0)); assertEquals(true, ArrayUtils.contains(array, (double) 1)); assertEquals(true, ArrayUtils.contains(array, (double) 2)); assertEquals(true, ArrayUtils.contains(array, (double) 3)); assertEquals(false, ArrayUtils.contains(array, (double) 99)); } public void testContainsDoubleTolerance() { double[] array = null; assertEquals(false, ArrayUtils.contains(array, (double) 1, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(false, ArrayUtils.contains(array, (double) 4.0, (double) 0.33)); assertEquals(false, ArrayUtils.contains(array, (double) 2.5, (double) 0.49)); assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.50)); assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.51)); } public void testIndexOfFloat() { float[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); array = new float[0]; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (float) 0)); assertEquals(1, ArrayUtils.indexOf(array, (float) 1)); assertEquals(2, ArrayUtils.indexOf(array, (float) 2)); assertEquals(3, ArrayUtils.indexOf(array, (float) 3)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 99)); } public void testIndexOfFloatWithStartIndex() { float[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); array = new float[0]; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (float) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (float) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (float) 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, (float) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 6)); } public void testLastIndexOfFloat() { float[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); array = new float[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (float) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); } public void testLastIndexOfFloatWithStartIndex() { float[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); array = new float[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (float) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0, 88)); } public void testContainsFloat() { float[] array = null; assertEquals(false, ArrayUtils.contains(array, (float) 1)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (float) 0)); assertEquals(true, ArrayUtils.contains(array, (float) 1)); assertEquals(true, ArrayUtils.contains(array, (float) 2)); assertEquals(true, ArrayUtils.contains(array, (float) 3)); assertEquals(false, ArrayUtils.contains(array, (float) 99)); } public void testIndexOfBoolean() { boolean[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, true)); array = new boolean[0]; assertEquals(-1, ArrayUtils.indexOf(array, true)); array = new boolean[] { true, false, true }; assertEquals(0, ArrayUtils.indexOf(array, true)); assertEquals(1, ArrayUtils.indexOf(array, false)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.indexOf(array, false)); } public void testIndexOfBooleanWithStartIndex() { boolean[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); array = new boolean[0]; assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); array = new boolean[] { true, false, true }; assertEquals(2, ArrayUtils.indexOf(array, true, 1)); assertEquals(-1, ArrayUtils.indexOf(array, false, 2)); assertEquals(1, ArrayUtils.indexOf(array, false, 0)); assertEquals(1, ArrayUtils.indexOf(array, false, -1)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.indexOf(array, false, 0)); assertEquals(-1, ArrayUtils.indexOf(array, false, -1)); } public void testLastIndexOfBoolean() { boolean[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); array = new boolean[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); array = new boolean[] { true, false, true }; assertEquals(2, ArrayUtils.lastIndexOf(array, true)); assertEquals(1, ArrayUtils.lastIndexOf(array, false)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.lastIndexOf(array, false)); } public void testLastIndexOfBooleanWithStartIndex() { boolean[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); array = new boolean[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); array = new boolean[] { true, false, true }; assertEquals(2, ArrayUtils.lastIndexOf(array, true, 2)); assertEquals(0, ArrayUtils.lastIndexOf(array, true, 1)); assertEquals(1, ArrayUtils.lastIndexOf(array, false, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.lastIndexOf(array, false, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); } public void testContainsBoolean() { boolean[] array = null; assertEquals(false, ArrayUtils.contains(array, true)); array = new boolean[] { true, false, true }; assertEquals(true, ArrayUtils.contains(array, true)); assertEquals(true, ArrayUtils.contains(array, false)); array = new boolean[] { true, true }; assertEquals(true, ArrayUtils.contains(array, true)); assertEquals(false, ArrayUtils.contains(array, false)); } // testToPrimitive/Object for boolean public void testToPrimitive_boolean() { final Boolean[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0])); assertTrue(Arrays.equals( new boolean[] {true, false, true}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE})) ); try { ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_boolean_boolean() { assertEquals(null, ArrayUtils.toPrimitive(null, false)); assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0], false)); assertTrue(Arrays.equals( new boolean[] {true, false, true}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, false)) ); assertTrue(Arrays.equals( new boolean[] {true, false, false}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null, Boolean.FALSE}, false)) ); assertTrue(Arrays.equals( new boolean[] {true, true, false}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null, Boolean.FALSE}, true)) ); } public void testToObject_boolean() { final boolean[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.toObject(new boolean[0])); assertTrue(Arrays.equals( new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, ArrayUtils.toObject(new boolean[] {true, false, true})) ); } // testToPrimitive/Object for byte public void testToPrimitive_byte() { final Byte[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.toPrimitive(new Byte[0])); assertTrue(Arrays.equals( new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999}, ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), new Byte(Byte.MAX_VALUE), new Byte((byte)9999999)})) ); try { ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_byte_byte() { final Byte[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b, Byte.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.toPrimitive(new Byte[0], (byte)1)); assertTrue(Arrays.equals( new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999}, ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), new Byte(Byte.MAX_VALUE), new Byte((byte)9999999)}, Byte.MIN_VALUE)) ); assertTrue(Arrays.equals( new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999}, ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), null, new Byte((byte)9999999)}, Byte.MAX_VALUE)) ); } public void testToObject_byte() { final byte[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.toObject(new byte[0])); assertTrue(Arrays.equals( new Byte[] {new Byte(Byte.MIN_VALUE), new Byte(Byte.MAX_VALUE), new Byte((byte)9999999)}, ArrayUtils.toObject(new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999})) ); } // testToPrimitive/Object for short public void testToPrimitive_short() { final Short[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0])); assertTrue(Arrays.equals( new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999}, ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), new Short(Short.MAX_VALUE), new Short((short)9999999)})) ); try { ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_short_short() { final Short[] s = null; assertEquals(null, ArrayUtils.toPrimitive(s, Short.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0], Short.MIN_VALUE)); assertTrue(Arrays.equals( new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999}, ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), new Short(Short.MAX_VALUE), new Short((short)9999999)}, Short.MIN_VALUE)) ); assertTrue(Arrays.equals( new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999}, ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), null, new Short((short)9999999)}, Short.MAX_VALUE)) ); } public void testToObject_short() { final short[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.toObject(new short[0])); assertTrue(Arrays.equals( new Short[] {new Short(Short.MIN_VALUE), new Short(Short.MAX_VALUE), new Short((short)9999999)}, ArrayUtils.toObject(new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999})) ); } // testToPrimitive/Object for int public void testToPrimitive_int() { final Integer[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.toPrimitive(new Integer[0])); assertTrue(Arrays.equals( new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), new Integer(Integer.MAX_VALUE), new Integer(9999999)})) ); try { ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_int_int() { final Long[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Integer.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.toPrimitive(new Integer[0], 1)); assertTrue(Arrays.equals( new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), new Integer(Integer.MAX_VALUE), new Integer(9999999)},1))); assertTrue(Arrays.equals( new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), null, new Integer(9999999)}, Integer.MAX_VALUE)) ); } public void testToPrimitive_intNull() { Integer[] iArray = null; assertEquals(null, ArrayUtils.toPrimitive(iArray, Integer.MIN_VALUE)); } public void testToObject_int() { final int[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.toObject(new int[0])); assertTrue( Arrays.equals( new Integer[] { new Integer(Integer.MIN_VALUE), new Integer(Integer.MAX_VALUE), new Integer(9999999)}, ArrayUtils.toObject( new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999 }))); } // testToPrimitive/Object for long public void testToPrimitive_long() { final Long[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.toPrimitive(new Long[0])); assertTrue(Arrays.equals( new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), new Long(Long.MAX_VALUE), new Long(9999999)})) ); try { ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_long_long() { final Long[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Long.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.toPrimitive(new Long[0], 1)); assertTrue(Arrays.equals( new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), new Long(Long.MAX_VALUE), new Long(9999999)},1))); assertTrue(Arrays.equals( new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), null, new Long(9999999)}, Long.MAX_VALUE)) ); } public void testToObject_long() { final long[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.toObject(new long[0])); assertTrue( Arrays.equals( new Long[] { new Long(Long.MIN_VALUE), new Long(Long.MAX_VALUE), new Long(9999999)}, ArrayUtils.toObject( new long[] { Long.MIN_VALUE, Long.MAX_VALUE, 9999999 }))); } // testToPrimitive/Object for float public void testToPrimitive_float() { final Float[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.toPrimitive(new Float[0])); assertTrue(Arrays.equals( new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), new Float(Float.MAX_VALUE), new Float(9999999)})) ); try { ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_float_float() { final Float[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Float.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.toPrimitive(new Float[0], 1)); assertTrue(Arrays.equals( new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), new Float(Float.MAX_VALUE), new Float(9999999)},1))); assertTrue(Arrays.equals( new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), null, new Float(9999999)}, Float.MAX_VALUE)) ); } public void testToObject_float() { final float[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.toObject(new float[0])); assertTrue( Arrays.equals( new Float[] { new Float(Float.MIN_VALUE), new Float(Float.MAX_VALUE), new Float(9999999)}, ArrayUtils.toObject( new float[] { Float.MIN_VALUE, Float.MAX_VALUE, 9999999 }))); } // testToPrimitive/Object for double public void testToPrimitive_double() { final Double[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.toPrimitive(new Double[0])); assertTrue(Arrays.equals( new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[] {new Double(Double.MIN_VALUE), new Double(Double.MAX_VALUE), new Double(9999999)})) ); try { ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_double_double() { final Double[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Double.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.toPrimitive(new Double[0], 1)); assertTrue(Arrays.equals( new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[] {new Double(Double.MIN_VALUE), new Double(Double.MAX_VALUE), new Double(9999999)},1))); assertTrue(Arrays.equals( new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[] {new Double(Double.MIN_VALUE), null, new Double(9999999)}, Double.MAX_VALUE)) ); } public void testToObject_double() { final double[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.toObject(new double[0])); assertTrue( Arrays.equals( new Double[] { new Double(Double.MIN_VALUE), new Double(Double.MAX_VALUE), new Double(9999999)}, ArrayUtils.toObject( new double[] { Double.MIN_VALUE, Double.MAX_VALUE, 9999999 }))); } /** * Test for {@link ArrayUtils#isEmpty(java.lang.Object[])}. */ public void testIsEmptyObject() { Object[] emptyArray = new Object[] {}; Object[] notEmptyArray = new Object[] { new String("Value") }; assertEquals(true, ArrayUtils.isEmpty((Object[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyArray)); } /** * Tests for {@link ArrayUtils#isEmpty(long[])}, * {@link ArrayUtils#isEmpty(int[])}, * {@link ArrayUtils#isEmpty(short[])}, * {@link ArrayUtils#isEmpty(char[])}, * {@link ArrayUtils#isEmpty(byte[])}, * {@link ArrayUtils#isEmpty(double[])}, * {@link ArrayUtils#isEmpty(float[])} and * {@link ArrayUtils#isEmpty(boolean[])}. */ public void testIsEmptyPrimitives() { long[] emptyLongArray = new long[] {}; long[] notEmptyLongArray = new long[] { 1L }; assertEquals(true, ArrayUtils.isEmpty((long[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyLongArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyLongArray)); int[] emptyIntArray = new int[] {}; int[] notEmptyIntArray = new int[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((int[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyIntArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyIntArray)); short[] emptyShortArray = new short[] {}; short[] notEmptyShortArray = new short[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((short[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyShortArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyShortArray)); char[] emptyCharArray = new char[] {}; char[] notEmptyCharArray = new char[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((char[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyCharArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyCharArray)); byte[] emptyByteArray = new byte[] {}; byte[] notEmptyByteArray = new byte[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((byte[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyByteArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyByteArray)); double[] emptyDoubleArray = new double[] {}; double[] notEmptyDoubleArray = new double[] { 1.0 }; assertEquals(true, ArrayUtils.isEmpty((double[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyDoubleArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyDoubleArray)); float[] emptyFloatArray = new float[] {}; float[] notEmptyFloatArray = new float[] { 1.0F }; assertEquals(true, ArrayUtils.isEmpty((float[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyFloatArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyFloatArray)); boolean[] emptyBooleanArray = new boolean[] {}; boolean[] notEmptyBooleanArray = new boolean[] { true }; assertEquals(true, ArrayUtils.isEmpty((boolean[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyBooleanArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyBooleanArray)); } }
package org.chai.kevin.dsr; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.chai.kevin.LanguageService; import org.chai.kevin.Period; import org.chai.kevin.data.DataService; import org.chai.kevin.data.Enum; import org.chai.kevin.data.EnumOption; import org.chai.kevin.location.DataLocation; import org.chai.kevin.location.DataLocationType; import org.chai.kevin.location.Location; import org.chai.kevin.location.LocationLevel; import org.chai.kevin.reports.ReportProgram; import org.chai.kevin.reports.ReportService; import org.chai.kevin.reports.ReportValue; import org.chai.kevin.util.Utils; import org.chai.kevin.value.DataValue; import org.chai.kevin.value.ValueService; import org.springframework.cache.annotation.Cacheable; import org.springframework.transaction.annotation.Transactional; public class DsrService { private static final Log log = LogFactory.getLog(DsrService.class); private ReportService reportService; private ValueService valueService; private DataService dataService; private LanguageService languageService; private Set<String> skipLevels; @Cacheable("dsrCache") @Transactional(readOnly = true) public DsrTable getDsrTable(Location location, ReportProgram program, Period period, Set<DataLocationType> types, DsrTargetCategory category) { if (log.isDebugEnabled()) log.debug("getDsrTable(period="+period+",location="+location+",program="+program+",types="+types+",category="+category+")"); List<DataLocation> dataLocations = location.collectDataLocations(null, types); List<DsrTarget> targets = reportService.getReportTargets(DsrTarget.class, program); Map<DataLocation, Map<DsrTarget, ReportValue>> valueMap = new HashMap<DataLocation, Map<DsrTarget, ReportValue>>(); List<DsrTargetCategory> targetCategories = new ArrayList<DsrTargetCategory>(); if(dataLocations.isEmpty() || targets.isEmpty()) return new DsrTable(valueMap, targets, targetCategories); List<DsrTarget> categoryTargets = new ArrayList<DsrTarget>(); if(category != null){ for(DsrTarget target : targets){ if(category.equals(target.getCategory())) categoryTargets.add(target); } if(!categoryTargets.isEmpty()) targets = categoryTargets; } for (DataLocation dataLocation : dataLocations) { Map<DsrTarget, ReportValue> targetMap = new HashMap<DsrTarget, ReportValue>(); for (DsrTarget target : targets) { targetMap.put(target, getDsrValue(target, dataLocation, period)); } valueMap.put(dataLocation, targetMap); } targetCategories = getTargetCategories(program); DsrTable dsrTable = new DsrTable(valueMap, targets, targetCategories); if (log.isDebugEnabled()) log.debug("getDsrTable(...)="+dsrTable); return dsrTable; } private ReportValue getDsrValue(DsrTarget target, DataLocation dataLocation, Period period){ String value = null; Set<String> targetUuids = Utils.split(target.getTypeCodeString()); if (targetUuids.contains(dataLocation.getType().getCode())) { DataValue dataValue = valueService.getDataElementValue(target.getDataElement(), dataLocation, period); if (dataValue != null && !dataValue.getValue().isNull()) { // TODO put this in templates ? switch (target.getDataElement().getType().getType()) { case BOOL: if (dataValue.getValue().getBooleanValue()) value = "&#10003;"; else value = "&#10007;"; break; case STRING: value = dataValue.getValue().getStringValue(); break; case NUMBER: value = getFormat(target, dataValue.getValue().getNumberValue().doubleValue()); break; case ENUM: String code = target.getDataElement().getType().getEnumCode(); Enum enume = dataService.findEnumByCode(code); if (enume != null) { EnumOption option = enume.getOptionForValue(dataValue.getValue().getEnumValue()); if (option != null) value = languageService.getText(option.getNames()); else value = dataValue.getValue().getEnumValue(); } else value = "N/A"; break; default: value = "N/A"; break; } } else value = "N/A"; } else value="N/A"; return new ReportValue(value); } public List<DsrTargetCategory> getTargetCategories(ReportProgram program){ Set<DsrTargetCategory> categories = new HashSet<DsrTargetCategory>(); List<DsrTarget> targets = reportService.getReportTargets(DsrTarget.class, program); for(DsrTarget target : targets) if(target.getCategory() != null) categories.add(target.getCategory()); List<DsrTargetCategory> sortedCategories = new ArrayList<DsrTargetCategory>(categories); Collections.sort(sortedCategories); return sortedCategories; } private static String getFormat(DsrTarget target, Double value) { String format = target.getFormat(); if (format == null) format = " DecimalFormat frmt = new DecimalFormat(format); return frmt.format(value).toString(); } public void setReportService(ReportService reportService) { this.reportService = reportService; } public void setValueService(ValueService valueService) { this.valueService = valueService; } public void setDataService(DataService dataService) { this.dataService = dataService; } public void setLanguageService(LanguageService languageService) { this.languageService = languageService; } public void setSkipLevels(Set<String> skipLevels) { this.skipLevels = skipLevels; } public Set<LocationLevel> getSkipLocationLevels(){ return reportService.getSkipLocationLevels(skipLevels); } }
package verification.platu.logicAnalysis; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import javax.swing.JOptionPane; import lpn.parser.Abstraction; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.LpnDecomposition.LpnProcess; import main.Gui; import verification.platu.MDD.MDT; import verification.platu.MDD.Mdd; import verification.platu.MDD.mddNode; import verification.platu.common.IndexObjMap; import verification.platu.lpn.LPNTranRelation; import verification.platu.lpn.LpnTranList; import verification.platu.main.Options; import verification.platu.partialOrders.DependentSet; import verification.platu.partialOrders.DependentSetComparator; import verification.platu.partialOrders.StaticSets; import verification.platu.project.PrjState; import verification.platu.stategraph.State; import verification.platu.stategraph.StateGraph; import verification.timed_state_exploration.zoneProject.EventSet; import verification.timed_state_exploration.zoneProject.StateSet; import verification.timed_state_exploration.zoneProject.TimedPrjState; import verification.timed_state_exploration.zoneProject.Zone; public class Analysis { private LinkedList<Transition> traceCex; protected Mdd mddMgr = null; private HashMap<Transition, HashSet<Transition>> cachedNecessarySets = new HashMap<Transition, HashSet<Transition>>(); private String PORdebugFileName; private FileWriter PORdebugFileStream; private BufferedWriter PORdebugBufferedWriter; /* * visitedTrans is used in computeNecessary for a disabled transition of interest, to keep track of all transitions visited during trace-back. */ private HashSet<Transition> visitedTrans; HashMap<Transition, StaticSets> staticDependency = new HashMap<Transition, StaticSets>(); public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) { traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); if (method.equals("dfs")) { //if (Options.getPOR().equals("off")) { //this.search_dfs(lpnList, initStateArray); //this.search_dfs_mdd_1(lpnList, initStateArray); //this.search_dfs_mdd_2(lpnList, initStateArray); //else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); } else if (method.equals("bfs")==true) this.search_bfs(lpnList, initStateArray); else if (method == "dfs_noDisabling") //this.search_dfs_noDisabling(lpnList, initStateArray); this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * This constructor performs dfs. * @param lpnList */ public Analysis(StateGraph[] lpnList){ traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); if (Options.getDebugMode()) { PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg"; try { PORdebugFileStream = new FileWriter(PORdebugFileName); } catch (IOException e) { e.printStackTrace(); } PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } // if (method.equals("dfs")) { // if (Options.getPOR().equals("off")) { // //this.search_dfs(lpnList, initStateArray); // this.search_dfsNative(lpnList, initStateArray); // //this.search_dfs_mdd_1(lpnList, initStateArray); // //this.search_dfs_mdd_2(lpnList, initStateArray); // else // //behavior analysis // boolean BA = true; // if(BA==true) // CompositionalAnalysis.searchCompositional(lpnList); // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); // else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "lpn"); // else if (method.equals("bfs")==true) // this.search_bfs(lpnList, initStateArray); // else if (method == "dfs_noDisabling") // //this.search_dfs_noDisabling(lpnList, initStateArray); // this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * Recursively find all reachable project states. */ int iterations = 0; int stack_depth = 0; int max_stack_depth = 0; public void search_recursive(final StateGraph[] lpnList, final State[] curPrjState, final ArrayList<LinkedList<Transition>> enabledList, HashSet<PrjState> stateTrace) { int lpnCnt = lpnList.length; HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); stack_depth++; if (stack_depth > max_stack_depth) max_stack_depth = stack_depth; iterations++; if (iterations % 50000 == 0) System.out.println("iterations: " + iterations + ", # of prjStates found: " + prjStateSet.size() + ", max_stack_depth: " + max_stack_depth); for (int index = 0; index < lpnCnt; index++) { LinkedList<Transition> curEnabledSet = enabledList.get(index); if (curEnabledSet == null) continue; for (Transition firedTran : curEnabledSet) { // while(curEnabledSet.size() != 0) { // LPNTran firedTran = curEnabledSet.removeFirst(); // TODO: (check) Not sure if lpnList[index] is correct State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran); // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. PrjState nextPrjState = new PrjState(nextStateArray); if (stateTrace.contains(nextPrjState) == true) ;// System.out.println("found a cycle"); if (prjStateSet.add(nextPrjState) == false) { continue; } // Get the list of enabled transition sets, and call // findsg_recursive. ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>(); for (int i = 0; i < lpnCnt; i++) { if (curPrjState[i] != nextStateArray[i]) { StateGraph Lpn_tmp = lpnList[i]; nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran, // enabledList.get(i), // false)); } else { nextEnabledList.add(i, enabledList.get(i)); } } stateTrace.add(nextPrjState); search_recursive(lpnList, nextStateArray, nextEnabledList, stateTrace); stateTrace.remove(nextPrjState); } } } /** * An iterative implement of findsg_recursive(). * * @param sgList * @param start * @param curLocalStateArray * @param enabledArray */ public StateGraph[] search_dfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function search_dfs"); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; //Stack<State[]> stateStack = new Stack<State[]>(); HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); //HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // Set of PrjStates that have been seen before. Set class documentation // for how it behaves. Timing Change. StateSet prjStateSet = new StateSet(); PrjState initPrjState; // Create the appropriate type for the PrjState depending on whether timing is // being used or not. Timing Change. if(!Options.getTimingAnalysisFlag()){ // If not doing timing. initPrjState = new PrjState(initStateArray); } else{ // If timing is enabled. initPrjState = new TimedPrjState(initStateArray); // Set the initial values of the inequality variables. //((TimedPrjState) initPrjState).updateInequalityVariables(); } prjStateSet.add(initPrjState); prjStateSet.set_initState(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) { // System.out.println("%%%%%%% stateStackTop %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) { // printDstLpnList(sgList); } boolean init = true; LpnTranList initEnabled; if(!Options.getTimingAnalysisFlag()){ // Timing Change. initEnabled = sgList[0].getEnabled(initStateArray[0], init); } else { // When timing is enabled, it is the project state that will determine // what is enabled since it contains the zone. This indicates the zeroth zone // contained in the project and the zeroth LPN to get the transitions from. initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0); } lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); init = false; if (Options.getDebugMode()) { // System.out.println("call getEnabled on initStateArray at 0: "); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet(initEnabled, ""); } boolean memExceedsLimit = false; main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { // System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) { if (curUsedMem > Options.getMemUpperBound()) { System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******"); System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******"); memExceedsLimit = true; } } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); if (failureTranIsEnabled(curEnabled)) { return null; } if (Options.getDebugMode()) { // printStateArray(curStateArray); // System.out.println("+++++++ curEnabled trans ++++++++"); // printTransLinkedList(curEnabled); } // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); if (Options.getDebugMode()) { // System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // System.out.println(" // printLpnTranStack(lpnTranStack); } curIndexStack.pop(); curIndex++; while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); if(!Options.getTimingAnalysisFlag()){ // Timing Change //curEnabled = (sgList[curIndex].getEnabled(curStateArray[curIndex], init)).clone(); curEnabled = sgList[curIndex].getEnabled(curStateArray[curIndex], init); } else{ // Get the enabled transitions from the zone that are associated with // the current LPN. curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex); } if (curEnabled.size() > 0) { if (Options.getDebugMode()) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransLinkedList(curEnabled); } lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); if (Options.getDebugMode()) { //printIntegerStack("curIndexStack after push 1", curIndexStack); } break; } curIndex++; } } if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curEnabled.removeLast(); if (Options.getDebugMode()) { // System.out.println(" // System.out.println("Fired transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getLabel() + ")"); // System.out.println(" } State[] nextStateArray; PrjState nextPrjState; // Moved this definition up. Timing Change. // The next state depends on whether timing is in use or not. // Timing Change. if(!Options.getTimingAnalysisFlag()){ // Get the next states from the fire method and define the next project state. nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); nextPrjState = new PrjState(nextStateArray); } else{ // Get the next timed state and extract the next un-timed states. nextPrjState = sgList[curIndex].fire(sgList, stateStackTop, (EventSet) firedTran); nextStateArray = nextPrjState.toStateArray(); } tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns]; for (int i = 0; i < numLpns; i++) { StateGraph sg = sgList[i]; LinkedList<Transition> enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sg.getEnabled(curStateArray[i], init); } else{ // Get the enabled transitions from the Zone for the appropriate // LPN. //enabledList = ((TimedPrjState) stateStackTop).getEnabled(i); enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i); } curEnabledArray[i] = enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sg.getEnabled(nextStateArray[i], init); } else{ //enabledList = ((TimedPrjState) nextPrjState).getEnabled(i); enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i); } nextEnabledArray[i] = enabledList; if (Options.getReportDisablingError()) { Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } if(!Options.getTimingAnalysisFlag()){ if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } } else{ if (Analysis.deadLock(sgList, nextStateArray) == true){ System.out.println("*** Verification failed: deadlock."); failure = true; JOptionPane.showMessageDialog(Gui.frame, "The system deadlocked.", "Error", JOptionPane.ERROR_MESSAGE); break main_while_loop; } } //PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change. Boolean existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState); if (existingState == false) { prjStateSet.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState.equals(stateStackTop)) { prjState.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(prjState.getNextStateMap()); } } } } stateStackTop = nextPrjState; if (Options.getDebugMode()) { // System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextEnabledArray[0], ""); } lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); if (Options.getDebugMode()) { // printLpnTranStack(lpnTranStack); } curIndexStack.push(0); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); } for (PrjState prjState : prjStateSet) { if (prjState.equals(nextPrjState)) { nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone()); } } if (Options.getDebugMode()) { // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { // printNextStateMap(prjState.getNextStateMap()); } } } } } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt //+ ", # of prjStates found: " + totalStateCnt + ", " + prjStateSet.stateString() + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if(Options.getTimingAnalysisFlag() && !failure){ JOptionPane.showMessageDialog(Gui.frame, "Verification was successful.", "Success", JOptionPane.INFORMATION_MESSAGE); } if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { System.out.println("outputSGPath = " + Options.getPrjSgPath()); drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true); } return sgList; } private boolean failureCheck(LinkedList<Transition> curEnabled) { boolean failureTranIsEnabled = false; for (Transition tran : curEnabled) { if (tran.isFail()) { JOptionPane.showMessageDialog(Gui.frame, "Failure transition " + tran.getLabel() + " is enabled.", "Error", JOptionPane.ERROR_MESSAGE); failureTranIsEnabled = true; break; } } return failureTranIsEnabled; } private boolean failureTranIsEnabled(LinkedList<Transition> curAmpleTrans) { boolean failureTranIsEnabled = false; for (Transition tran : curAmpleTrans) { if (tran.isFail()) { if(Zone.get_writeLogFile() != null){ try { Zone.get_writeLogFile().write(tran.getLabel()); Zone.get_writeLogFile().newLine(); } catch (IOException e) { e.printStackTrace(); } } JOptionPane.showMessageDialog(Gui.frame, "Failure transition " + tran.getLabel() + " is enabled.", "Error", JOptionPane.ERROR_MESSAGE); failureTranIsEnabled = true; break; } } return failureTranIsEnabled; } private void drawGlobalStateGraph(StateGraph[] sgList, HashSet<PrjState> prjStateSet, boolean fullSG) { try { String fileName = null; if (fullSG) { fileName = Options.getPrjSgPath() + "full_sg.dot"; } else { fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_" + Options.getCycleClosingMthd().toLowerCase() + "_" + Options.getCycleClosingAmpleMethd().toLowerCase() + "_sg.dot"; } BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (PrjState curGlobalState : prjStateSet) { // Build composite current global state. String curVarNames = ""; String curVarValues = ""; String curMarkings = ""; String curEnabledTrans = ""; String curGlobalStateIndex = ""; HashMap<String, Integer> vars = new HashMap<String, Integer>(); for (State curLocalState : curGlobalState.toStateArray()) { LhpnFile curLpn = curLocalState.getLpn(); for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) { //System.out.println(curLpn.getVarIndexMap().getKey(i) + " = " + curLocalState.getVector()[i]); vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVector()[i]); } curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState); if (!boolArrayToString("enabled trans", curLocalState).equals("")) curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState); curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); curVarValues = curVarValues + vValue + ", "; curVarNames = curVarNames + vName + ", "; } if (!curVarNames.isEmpty() && !curVarValues.isEmpty()) { curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(",")); curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(",")); } curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length()); curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length()); curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length()); out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n"); out.write(curGlobalStateIndex + "[shape=\"ellipse\",label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n"); // // Build composite next global states. HashMap<Transition, PrjState> nextStateMap = curGlobalState.getNextStateMap(); for (Transition outTran : nextStateMap.keySet()) { PrjState nextGlobalState = nextStateMap.get(outTran); String nextVarNames = ""; String nextVarValues = ""; String nextMarkings = ""; String nextEnabledTrans = ""; String nextGlobalStateIndex = ""; for (State nextLocalState : nextGlobalState.toStateArray()) { LhpnFile nextLpn = nextLocalState.getLpn(); for(int i = 0; i < nextLpn.getVarIndexMap().size(); i++) { vars.put(nextLpn.getVarIndexMap().getKey(i), nextLocalState.getVector()[i]); } nextMarkings = nextMarkings + "," + intArrayToString("markings", nextLocalState); if (!boolArrayToString("enabled trans", nextLocalState).equals("")) nextEnabledTrans = nextEnabledTrans + "," + boolArrayToString("enabled trans", nextLocalState); nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); nextVarValues = nextVarValues + vValue + ", "; nextVarNames = nextVarNames + vName + ", "; } if (!nextVarNames.isEmpty() && !nextVarValues.isEmpty()) { nextVarNames = nextVarNames.substring(0, nextVarNames.lastIndexOf(",")); nextVarValues = nextVarValues.substring(0, nextVarValues.lastIndexOf(",")); } nextMarkings = nextMarkings.substring(nextMarkings.indexOf(",")+1, nextMarkings.length()); nextEnabledTrans = nextEnabledTrans.substring(nextEnabledTrans.indexOf(",")+1, nextEnabledTrans.length()); nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length()); out.write("Inits[shape=plaintext, label=\"<" + nextVarNames + ">\"]\n"); out.write(nextGlobalStateIndex + "[shape=\"ellipse\",label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\"]\n"); String outTranName = outTran.getLabel(); if (outTran.isFail() && !outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n"); else if (!outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n"); else if (outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n"); else out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n"); } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void drawDependencyGraphs(LhpnFile[] lpnList) { String fileName = Options.getPrjSgPath() + "dependencyGraph.dot"; BufferedWriter out; try { out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (Transition curTran : staticDependency.keySet()) { String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel(); out.write(curTranStr + "[shape=\"box\"];"); out.newLine(); } for (Transition curTran : staticDependency.keySet()) { StaticSets curStaticSets = staticDependency.get(curTran); String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel(); for (Transition curTranInDisable : curStaticSets.getOtherTransDisableCurTranSet()) { String curTranInDisableStr = curTranInDisable.getLpn().getLabel() + "_" + curTranInDisable.getLabel(); out.write(curTranInDisableStr + "->" + curTranStr + "[color=\"chocolate\"];"); out.newLine(); } // for (Transition curTranInDisable : curStaticSets.getCurTranDisableOtherTransSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"chocolate\"];"); // out.newLine(); // for (Transition curTranInDisable : curStaticSets.getDisableSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"blue\"];"); // out.newLine(); HashSet<Transition> enableByBringingToken = new HashSet<Transition>(); for (Place p : curTran.getPreset()) { for (Transition presetTran : p.getPreset()) { enableByBringingToken.add(presetTran); } } for (Transition curTranInCanEnable : enableByBringingToken) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"mediumaquamarine\"];"); out.newLine(); } for (HashSet<Transition> canEnableOneConjunctSet : curStaticSets.getOtherTransSetCurTranEnablingTrue()) { for (Transition curTranInCanEnable : canEnableOneConjunctSet) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"deepskyblue\"];"); out.newLine(); } } } out.write("}"); out.close(); } catch (IOException e) { e.printStackTrace(); } } private String intArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("markings")) { for (int i=0; i< curState.getMarking().length; i++) { if (curState.getMarking()[i] == 1) { arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ","; } // String tranName = curState.getLpn().getAllTransitions()[i].getName(); // if (curState.getTranVector()[i]) // System.out.println(tranName + " " + "Enabled"); // else // System.out.println(tranName + " " + "Not Enabled"); } arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } else if (type.equals("vars")) { for (int i=0; i< curState.getVector().length; i++) { arrayStr = arrayStr + curState.getVector()[i] + ","; } if (arrayStr.contains(",")) arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private String boolArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("enabled trans")) { for (int i=0; i< curState.getTranVector().length; i++) { if (curState.getTranVector()[i]) { arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getLabel() + ","; } } if (arrayStr != "") arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private void printStateArray(State[] stateArray) { for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +") -> "); System.out.print("markings: " + intArrayToString("markings", stateArray[i]) + " / "); System.out.print("enabled trans: " + boolArrayToString("enabled trans", stateArray[i]) + " / "); System.out.print("var values: " + intArrayToString("vars", stateArray[i]) + " / "); System.out.print("\n"); } } private void printTransLinkedList(LinkedList<Transition> curPop) { for (int i=0; i< curPop.size(); i++) { System.out.print(curPop.get(i).getLabel() + " "); } System.out.println(""); } private void printIntegerStack(String stackName, Stack<Integer> curIndexStack) { System.out.println("+++++++++" + stackName + "+++++++++"); for (int i=0; i < curIndexStack.size(); i++) { System.out.println(stackName + "[" + i + "]" + curIndexStack.get(i)); } System.out.println(" } private void printDstLpnList(StateGraph[] lpnList) { System.out.println("++++++ dstLpnList ++++++"); for (int i=0; i<lpnList.length; i++) { LhpnFile curLPN = lpnList[i].getLpn(); System.out.println("LPN: " + curLPN.getLabel()); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j< allTrans.length; j++) { System.out.print(allTrans[j].getLabel() + ": "); for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) { System.out.print(allTrans[j].getDstLpnList().get(k).getLabel() + ","); } System.out.print("\n"); } System.out.println(" } System.out.println("++++++++++++++++++++"); } private void constructDstLpnList(StateGraph[] sgList) { for (int i=0; i<sgList.length; i++) { LhpnFile curLPN = sgList[i].getLpn(); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j<allTrans.length; j++) { Transition curTran = allTrans[j]; for (int k=0; k<sgList.length; k++) { curTran.setDstLpnList(sgList[k].getLpn()); } } } } /** * This method performs first-depth search on an array of LPNs and applies partial order reduction technique with trace-back on LPNs. * @param sgList * @param initStateArray * @param cycleClosingMthdIndex * @return */ @SuppressWarnings("unchecked") public StateGraph[] searchPOR_taceback(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function searchPOR_traceback"); System.out.println("---> " + Options.getPOR()); System.out.println("---> " + Options.getCycleClosingMthd()); System.out.println("---> " + Options.getCycleClosingAmpleMethd()); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; LhpnFile[] lpnList = new LhpnFile[numLpns]; for (int i=0; i<numLpns; i++) { lpnList[i] = sgList[i].getLpn(); } HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); prjStateSet.add(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) { // System.out.println("%%%%%%% stateStackTop %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) { // printDstLpnList(sgList); createPORDebugFile(); } // Find static pieces for POR. HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length); //HashMap<Transition, StaticSets> staticSetsMap = new HashMap<Transition, StaticSets>(); HashMap<Transition, Integer> allProcessTransInOneLpn = new HashMap<Transition, Integer>(); HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses = new HashMap<Transition, LpnProcess>(); for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { allTransitions.put(lpnIndex, lpnList[lpnIndex].getAllTransitions()); Abstraction abs = new Abstraction(lpnList[lpnIndex]); abs.decomposeLpnIntoProcesses(); allProcessTransInOneLpn = (HashMap<Transition, Integer>)abs.getTransWithProcIDs(); HashMap<Integer, LpnProcess> processMapForOneLpn = new HashMap<Integer, LpnProcess>(); for (Transition curTran: allProcessTransInOneLpn.keySet()) { Integer procId = allProcessTransInOneLpn.get(curTran); if (!processMapForOneLpn.containsKey(procId)) { LpnProcess newProcess = new LpnProcess(procId); newProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (newProcess.getStateMachineFlag() && ((curTran.getPreset().length > 1) || (curTran.getPostset().length > 1))) { newProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { newProcess.addPlaceToProcess(p); } } processMapForOneLpn.put(procId, newProcess); allTransitionsToLpnProcesses.put(curTran, newProcess); } else { LpnProcess curProcess = processMapForOneLpn.get(procId); curProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (curProcess.getStateMachineFlag() && (curTran.getPreset().length > 1 || curTran.getPostset().length > 1)) { curProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { curProcess.addPlaceToProcess(p); } } allTransitionsToLpnProcesses.put(curTran, curProcess); } } } HashMap<Transition, Integer> tranFiringFreq = null; if (Options.getUseDependentQueue()) tranFiringFreq = new HashMap<Transition, Integer>(allTransitions.keySet().size()); // Need to build conjuncts for each transition's enabling condition first before dealing with dependency and enable sets. for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { for (Transition curTran: allTransitions.get(lpnIndex)) { if (curTran.getEnablingTree() != null) curTran.buildConjunctsOfEnabling(curTran.getEnablingTree()); } } for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("=======LPN = " + lpnList[lpnIndex].getLabel() + "======="); } for (Transition curTran: allTransitions.get(lpnIndex)) { StaticSets curStatic = new StaticSets(curTran, allTransitionsToLpnProcesses); curStatic.buildOtherTransSetCurTranEnablingTrue(); curStatic.buildCurTranDisableOtherTransSet(); if (Options.getPORdeadlockPreserve()) curStatic.buildOtherTransDisableCurTranSet(); else curStatic.buildModifyAssignSet(); staticDependency.put(curTran, curStatic); if (Options.getUseDependentQueue()) tranFiringFreq.put(curTran, 0); } } if (Options.getDebugMode()) { writeStaticSetsMapToPORDebugFile(lpnList); } boolean init = true; //LpnTranList initAmpleTrans = new LpnTranList(); LpnTranList initAmpleTrans = getAmple(initStateArray, null, init, tranFiringFreq, sgList, lpnList, stateStack, stateStackTop); lpnTranStack.push(initAmpleTrans); init = false; if (Options.getDebugMode()) { // System.out.println("+++++++ Push trans onto lpnTranStack @ 1++++++++"); // printTransitionSet(initAmpleTrans, ""); drawDependencyGraphs(lpnList); } // HashSet<Transition> initAmple = new HashSet<Transition>(); // for (Transition t: initAmpleTrans) { // initAmple.add(t); updateLocalAmpleTbl(initAmpleTrans, sgList, initStateArray); boolean memExceedsLimit = false; main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) { if (curUsedMem > Options.getMemUpperBound()) { System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******"); System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******"); memExceedsLimit = true; } } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); if (failureTranIsEnabled(curAmpleTrans)) { return null; } if (curAmpleTrans.size() == 0) { lpnTranStack.pop(); prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // System.out.println(" // printLpnTranStack(lpnTranStack); //// System.out.println(" //// printStateStack(stateStack); // System.out.println(" // printPrjStateSet(prjStateSet); // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curAmpleTrans.removeLast(); //Transition firedTran = curAmpleTrans.removelast(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(" writeStringWithEndOfLineToPORDebugFile("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getLabel() + ")"); writeStringWithEndOfLineToPORDebugFile(" } if (Options.getUseDependentQueue()) { Integer freq = tranFiringFreq.get(firedTran) + 1; tranFiringFreq.put(firedTran, freq); if (Options.getDebugMode()) { // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, sgList); } } State[] nextStateArray = sgList[firedTran.getLpn().getLpnIndex()].fire(sgList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. if (Options.getReportDisablingError()) { for (int i=0; i<numLpns; i++) { Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } LpnTranList nextAmpleTrans = new LpnTranList(); nextAmpleTrans = getAmple(curStateArray, nextStateArray, init, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop); // check for possible deadlock if (nextAmpleTrans.size() == 0) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } PrjState nextPrjState = new PrjState(nextStateArray); Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); if (existingState == false) { if (Options.getDebugMode()) { // System.out.println("%%%%%%% existingSate == false %%%%%%%%"); } if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState.equals(stateStackTop)) { prjState.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(prjState.getNextStateMap()); } } } } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack @ 2++++++++"); // printTransitionSet((LpnTranList) nextAmpleTrans, ""); } lpnTranStack.push((LinkedList<Transition>) nextAmpleTrans.clone()); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); } for (PrjState prjState : prjStateSet) { if (prjState.equals(nextPrjState)) { nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone()); } } if (Options.getDebugMode()) { // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { // printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { // printNextStateMap(prjState.getNextStateMap()); } } } } if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) { // Cycle closing check if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) { if (Options.getDebugMode()) { // System.out.println("%%%%%%% Cycle Closing %%%%%%%%"); } HashSet<Transition> nextAmpleSet = new HashSet<Transition>(); HashSet<Transition> curAmpleSet = new HashSet<Transition>(); for (Transition t : nextAmpleTrans) nextAmpleSet.add(t); for (Transition t: curAmpleTrans) curAmpleSet.add(t); curAmpleSet.add(firedTran); HashSet<Transition> newNextAmple = new HashSet<Transition>(); newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticDependency, tranFiringFreq, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack); if (newNextAmple != null && !newNextAmple.isEmpty()) { //LpnTranList newNextAmpleTrans = getLpnTranList(newNextAmple, sgList); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getDebugMode()) { // System.out.println("nextPrjState: "); // printStateArray(nextPrjState.toStateArray()); // System.out.println("nextStateMap for nextPrjState: "); // printNextStateMap(nextPrjState.getNextStateMap()); } stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("nextStateMap for stateStackTop: "); // printNextStateMap(nextPrjState.getNextStateMap()); } lpnTranStack.push((LinkedList<Transition>) newNextAmple.clone()); if (Options.getDebugMode()) { // System.out.println("+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++"); // printTransitionSet((LpnTranList) newNextAmpleTrans, ""); // printLpnTranStack(lpnTranStack); } } } } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); } } if (Options.getDebugMode()) { try { PORdebugBufferedWriter.close(); PORdebugFileStream.close(); } catch (IOException e) { e.printStackTrace(); } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStateCnt + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { drawGlobalStateGraph(sgList, prjStateSet, false); } return sgList; } private void createPORDebugFile() { try { PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg"; PORdebugFileStream = new FileWriter(PORdebugFileName, true); PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing the debugging file for partial order reduction."); } } private void writeStringWithEndOfLineToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writeStringToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); //PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt, double peakTotalMem, double peakUsedMem) { try { String fileName = null; if (isPOR) { fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; } else fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log"; BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n"); out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t" + peakUsedMem + "\n"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void printLpnTranStack(Stack<LinkedList<Transition>> lpnTranStack) { for (int i=0; i<lpnTranStack.size(); i++) { LinkedList<Transition> tranList = lpnTranStack.get(i); for (int j=0; j<tranList.size(); j++) { System.out.println(tranList.get(j).getLabel()); } System.out.println(" } } private void printNextStateMap(HashMap<Transition, PrjState> nextStateMap) { for (Transition t: nextStateMap.keySet()) { System.out.print(t.getLabel() + " -> "); State[] stateArray = nextStateMap.get(t).getStateArray(); for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + ", "); } System.out.print("\n"); } } // private HashSet<Transition> getTransition(LpnTranList ampleTrans) { // HashSet<Transition> ample = new HashSet<Transition>(); // for (Transition tran : ampleTrans) { // ample.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // return ample; private LpnTranList convertToLpnTranList(HashSet<Transition> newNextAmple) { LpnTranList newNextAmpleTrans = new LpnTranList(); for (Transition lpnTran : newNextAmple) { newNextAmpleTrans.add(lpnTran); } return newNextAmpleTrans; } private HashSet<Transition> computeCycleClosingTrans(State[] curStateArray, State[] nextStateArray, HashMap<Transition, StaticSets> staticSetsMap, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> prjStateSet, PrjState nextPrjState, HashSet<Transition> nextAmple, HashSet<Transition> curAmple, HashSet<PrjState> stateStack) { for (State s : nextStateArray) if (s == null) throw new NullPointerException(); String cycleClosingMthd = Options.getCycleClosingMthd(); HashSet<Transition> newNextAmple = new HashSet<Transition>(); HashSet<Transition> nextEnabled = new HashSet<Transition>(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { Transition tran = curLpn.getAllTransitions()[i]; if (nextStateArray[lpnIndex].getTranVector()[i]) nextEnabled.add(tran); if (curStateArray[lpnIndex].getTranVector()[i]) curEnabled.add(tran); } } // Cycle closing on global state graph if (Options.getDebugMode()) { //System.out.println("~~~~~~~ existing global state ~~~~~~~~"); } if (cycleClosingMthd.equals("strong")) { newNextAmple.addAll(setSubstraction(curEnabled, nextAmple)); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } else if (cycleClosingMthd.equals("behavioral")) { if (Options.getDebugMode()) { } HashSet<Transition> curReduced = setSubstraction(curEnabled, curAmple); HashSet<Transition> oldNextAmple = new HashSet<Transition>(); DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // TODO: Is oldNextAmple correctly obtained below? if (Options.getDebugMode()) { // printStateArray(nextStateArray); } for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) { if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) { LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]); if (Options.getDebugMode()) { // printTransitionSet(oldLocalNextAmpleTrans, "oldLocalNextAmpleTrans"); } for (Transition oldLocalTran : oldLocalNextAmpleTrans) oldNextAmple.add(oldLocalTran); } } HashSet<Transition> ignored = setSubstraction(curReduced, oldNextAmple); boolean isCycleClosingAmpleComputation = true; for (Transition seed : ignored) { HashSet<Transition> dependent = new HashSet<Transition>(); dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); } // TODO: Is this still necessary? // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if ((newNextAmple.size() == 0 || dependent.size() < newNextAmple.size()) && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); DependentSet dependentSet = new DependentSet(dependent, seed,isDummyTran(seed.getLabel())); dependentSetQueue.add(dependentSet); } cachedNecessarySets.clear(); if (!dependentSetQueue.isEmpty()) { // System.out.println("depdentSetQueue is NOT empty."); // newNextAmple = dependentSetQueue.poll().getDependent(); // TODO: Will newNextAmpleTmp - oldNextAmple be safe? HashSet<Transition> newNextAmpleTmp = dependentSetQueue.poll().getDependent(); newNextAmple = setSubstraction(newNextAmpleTmp, oldNextAmple); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } if (Options.getDebugMode()) { // printIntegerSet(newNextAmple, sgList, "newNextAmple"); } } else if (cycleClosingMthd.equals("state_search")) { // TODO: complete cycle closing check for state search. } return newNextAmple; } private void updateLocalAmpleTbl(LpnTranList nextAmpleTrans, StateGraph[] sgList, State[] nextStateArray) { // Ample set at each state is stored in the enabledSetTbl in each state graph. for (Transition lpnTran : nextAmpleTrans) { State nextState = nextStateArray[lpnTran.getLpn().getLpnIndex()]; LpnTranList a = sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().get(nextState); if (a != null) { if (!a.contains(lpnTran)) a.add(lpnTran); } else { LpnTranList newLpnTranList = new LpnTranList(); newLpnTranList.add(lpnTran); sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().put(nextStateArray[lpnTran.getLpn().getLpnIndex()], newLpnTranList); if (Options.getDebugMode()) { // System.out.println("@ updateLocalAmpleTbl: "); // System.out.println("Add S" + nextStateArray[lpnTran.getLpnIndex()].getIndex() + " to the enabledSetTbl of " // + sgList[lpnTran.getLpnIndex()].getLpn().getLabel() + "."); } } } if (Options.getDebugMode()) { // printEnabledSetTbl(sgList); } } private void printPrjStateSet(HashSet<PrjState> prjStateSet) { for (PrjState curGlobal : prjStateSet) { State[] curStateArray = curGlobal.toStateArray(); printStateArray(curStateArray); System.out.println(" } } // /** // * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back. // * @param sgList // * @param initStateArray // * @param cycleClosingMthdIndex // * @return // */ // public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) { // if (cycleClosingMthdIndex == 1) // else if (cycleClosingMthdIndex == 2) // else if (cycleClosingMthdIndex == 4) // double peakUsedMem = 0; // double peakTotalMem = 0; // boolean failure = false; // int tranFiringCnt = 0; // int totalStates = 1; // int numLpns = sgList.length; // HashSet<PrjState> stateStack = new HashSet<PrjState>(); // Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); // Stack<Integer> curIndexStack = new Stack<Integer>(); // HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // PrjState initPrjState = new PrjState(initStateArray); // prjStateSet.add(initPrjState); // PrjState stateStackTop = initPrjState; // System.out.println("%%%%%%% Add states to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.add(stateStackTop); // // Prepare static pieces for POR // HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>(); // Transition[] allTransitions = sgList[0].getLpn().getAllTransitions(); // HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>(); // HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length); // for (Transition curTran: allTransitions) { // StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions); // curStatic.buildDisableSet(); // curStatic.buildEnableSet(); // curStatic.buildModifyAssignSet(); // tmpMap.put(curTran.getIndex(), curStatic); // tranFiringFreq.put(curTran.getIndex(), 0); // staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap); // printStaticSetMap(staticSetsMap); // System.out.println("call getAmple on initStateArray at 0: "); // boolean init = true; // AmpleSet initAmple = new AmpleSet(); // initAmple = sgList[0].getAmple(initStateArray[0], staticSetsMap, init, tranFiringFreq); // HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl(); // lpnTranStack.push(initAmple.getAmpleSet()); // curIndexStack.push(0); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) initAmple.getAmpleSet(), ""); // main_while_loop: while (failure == false && stateStack.size() != 0) { // System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); // long curTotalMem = Runtime.getRuntime().totalMemory(); // long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); // if (curTotalMem > peakTotalMem) // peakTotalMem = curTotalMem; // if (curUsedMem > peakUsedMem) // peakUsedMem = curUsedMem; // if (stateStack.size() > max_stack_depth) // max_stack_depth = stateStack.size(); // iterations++; // if (iterations % 100000 == 0) { // System.out.println("---> #iteration " + iterations // + "> # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStates // + ", stack_depth: " + stateStack.size() // + " used memory: " + (float) curUsedMem / 1000000 // + " free memory: " // + (float) Runtime.getRuntime().freeMemory() / 1000000); // State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); // int curIndex = curIndexStack.peek(); //// System.out.println("curIndex = " + curIndex); // //AmpleSet curAmple = new AmpleSet(); // //LinkedList<Transition> curAmpleTrans = curAmple.getAmpleSet(); // LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); //// printStateArray(curStateArray); //// System.out.println("+++++++ curAmple trans ++++++++"); //// printTransLinkedList(curAmpleTrans); // // If all enabled transitions of the current LPN are considered, // // then consider the next LPN // // by increasing the curIndex. // // Otherwise, if all enabled transitions of all LPNs are considered, // // then pop the stacks. // if (curAmpleTrans.size() == 0) { // lpnTranStack.pop(); //// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // curIndexStack.pop(); //// System.out.println("+++++++ Pop index off curIndexStack ++++++++"); // curIndex++; //// System.out.println("curIndex = " + curIndex); // while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); // LpnTranList tmpAmpleTrans = (LpnTranList) (sgList[curIndex].getAmple(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getAmpleSet(); // curAmpleTrans = tmpAmpleTrans.clone(); // //printTransitionSet(curEnabled, "curEnabled set"); // if (curAmpleTrans.size() > 0) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransLinkedList(curAmpleTrans); // lpnTranStack.push(curAmpleTrans); // curIndexStack.push(curIndex); // printIntegerStack("curIndexStack after push 1", curIndexStack); // break; // curIndex++; // if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.remove(stateStackTop); // stateStackTop = stateStackTop.getFather(); // continue; // Transition firedTran = curAmpleTrans.removeLast(); // System.out.println(" // System.out.println("Fired transition: " + firedTran.getName()); // System.out.println(" // Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1; // tranFiringFreq.put(firedTran.getIndex(), freq); // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, allTransitions); // State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); // tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. // @SuppressWarnings("unchecked") // LinkedList<Transition>[] curAmpleArray = new LinkedList[numLpns]; // @SuppressWarnings("unchecked") // LinkedList<Transition>[] nextAmpleArray = new LinkedList[numLpns]; // boolean updatedAmpleDueToCycleRule = false; // for (int i = 0; i < numLpns; i++) { // StateGraph sg_tmp = sgList[i]; // System.out.println("call getAmple on curStateArray at 2: i = " + i); // AmpleSet ampleList = new AmpleSet(); // if (init) { // ampleList = initAmple; // sg_tmp.setEnabledSetTbl(initEnabledSetTbl); // init = false; // else // ampleList = sg_tmp.getAmple(curStateArray[i], staticSetsMap, init, tranFiringFreq); // curAmpleArray[i] = ampleList.getAmpleSet(); // System.out.println("call getAmpleRefinedCycleRule on nextStateArray at 3: i = " + i); // ampleList = sg_tmp.getAmpleRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq); // nextAmpleArray[i] = ampleList.getAmpleSet(); // if (!updatedAmpleDueToCycleRule && ampleList.getAmpleChanged()) { // updatedAmpleDueToCycleRule = true; // for (LinkedList<Transition> tranList : curAmpleArray) { // printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : curAmpleArray) { //// printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : nextAmpleArray) { //// printTransLinkedList(tranList); // Transition disabledTran = firedTran.disablingError( // curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); // if (disabledTran != null) { // System.err.println("Disabling Error: " // + disabledTran.getFullLabel() + " is disabled by " // + firedTran.getFullLabel()); // failure = true; // break main_while_loop; // if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) { // failure = true; // break main_while_loop; // PrjState nextPrjState = new PrjState(nextStateArray); // Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); // if (existingState == true && updatedAmpleDueToCycleRule) { // // cycle closing // System.out.println("%%%%%%% existingSate == true %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // if (existingState == false) { // System.out.println("%%%%%%% existingSate == false %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // totalStates++; // // end of main_while_loop // double totalStateCnt = prjStateSet.size(); // System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStateCnt // + ", max_stack_depth: " + max_stack_depth // + ", peak total memory: " + peakTotalMem / 1000000 + " MB" // + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); // // This currently works for a single LPN. // return sgList; // return null; private void writeStaticSetsMapToPORDebugFile( LhpnFile[] lpnList) { try { PORdebugBufferedWriter.write(" PORdebugBufferedWriter.newLine(); for (Transition lpnTranPair : staticDependency.keySet()) { StaticSets statSets = staticDependency.get(lpnTranPair); writeLpnTranPairToPORDebugFile(statSets.getTran(), statSets.getDisableSet(), "disableSet"); for (HashSet<Transition> setOneConjunctTrue : statSets.getOtherTransSetCurTranEnablingTrue()) { writeLpnTranPairToPORDebugFile(statSets.getTran(), setOneConjunctTrue, "enableBySetingEnablingTrue for one conjunct"); } } } catch (IOException e) { e.printStackTrace(); } } // private Transition[] assignStickyTransitions(LhpnFile lpn) { // // allProcessTrans is a hashmap from a transition to its process color (integer). // HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>(); // // create an Abstraction object to call the divideProcesses method. // Abstraction abs = new Abstraction(lpn); // abs.decomposeLpnIntoProcesses(); // allProcessTrans.putAll( // (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone()); // HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>(); // for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) { // Transition curTran = tranIter.next(); // Integer procId = allProcessTrans.get(curTran); // if (!processMap.containsKey(procId)) { // LpnProcess newProcess = new LpnProcess(procId); // newProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // newProcess.addPlaceToProcess(p); // processMap.put(procId, newProcess); // else { // LpnProcess curProcess = processMap.get(procId); // curProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // curProcess.addPlaceToProcess(p); // for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) { // LpnProcess curProc = processMap.get(processMapIter.next()); // curProc.assignStickyTransitions(); // curProc.printProcWithStickyTrans(); // return lpn.getAllTransitions(); // private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran, // HashSet<Transition> curDisable, String setName) { // System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); // if (curDisable.isEmpty()) { // System.out.println("empty"); // else { // for (Transition lpnTranPair: curDisable) { // System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() // + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); // System.out.print("\n"); private void writeLpnTranPairToPORDebugFile(Transition curTran, HashSet<Transition> TransitionSet, String setName) { try { //PORdebugBufferedWriter.write(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); PORdebugBufferedWriter.write(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getLabel() + ") is: "); if (TransitionSet.isEmpty()) { PORdebugBufferedWriter.write("empty"); PORdebugBufferedWriter.newLine(); } else { for (Transition lpnTranPair: TransitionSet) PORdebugBufferedWriter.append("(" + lpnTranPair.getLpn().getLabel() + ", " + lpnTranPair.getLabel() + ")," + " "); PORdebugBufferedWriter.newLine(); } PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void printTransitionSet(LpnTranList transitionSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + " is: "); if (transitionSet.isEmpty()) { System.out.println("empty"); } else { for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { Transition tranInDisable = curTranIter.next(); System.out.print(tranInDisable.getLabel() + " "); } System.out.print("\n"); } } // private void printTransitionSet(LinkedList<Transition> transitionSet, String setName) { // System.out.print(setName + " is: "); // if (transitionSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { // Transition tranInDisable = curTranIter.next(); // System.out.print(tranInDisable.getIndex() + " "); // System.out.print("\n"); /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. The enabledSetTbl (for each StateGraph obj) stores the AMPLE set for each state of each LPN. * @param stateArray * @param stateStack * @param enable * @param disableByStealingToken * @param disable * @param init * @param sgList * @return */ public LpnTranList getAmple(State[] curStateArray, State[] nextStateArray, boolean init, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, LhpnFile[] lpnList, HashSet<PrjState> stateStack, PrjState stateStackTop) { State[] stateArray = null; if (nextStateArray == null) stateArray = curStateArray; else stateArray = nextStateArray; for (State s : stateArray) if (s == null) throw new NullPointerException(); LpnTranList ample = new LpnTranList(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) { State state = stateArray[lpnIndex]; if (init) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { if (sgList[lpnIndex].isEnabled(curLpn.getAllTransitions()[i], state)){ curEnabled.add(curLpn.getAllTransitions()[i]); } } } else { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { if (stateArray[lpnIndex].getTranVector()[i]) { curEnabled.add(curLpn.getAllTransitions()[i]); } } } } if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("******* Partial Order Reduction *******"); writeIntegerSetToPORDebugFile(curEnabled, "Enabled set"); writeStringWithEndOfLineToPORDebugFile("******* Begin POR *******"); } if (curEnabled.isEmpty()) { return ample; } HashSet<Transition> ready = partialOrderReduction(stateArray, curEnabled, tranFiringFreq, sgList); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("******* End POR *******"); writeIntegerSetToPORDebugFile(ready, "Ample set"); writeStringWithEndOfLineToPORDebugFile("********************"); } if (tranFiringFreq != null) { LinkedList<Transition> readyList = new LinkedList<Transition>(); for (Transition inReady : ready) { readyList.add(inReady); } mergeSort(readyList, tranFiringFreq); for (Transition inReady : readyList) { ample.addFirst(inReady); } } else { for (Transition tran : ready) { ample.add(tran); } } return ample; } private LinkedList<Transition> mergeSort(LinkedList<Transition> array, HashMap<Transition, Integer> tranFiringFreq) { if (array.size() == 1) return array; int middle = array.size() / 2; LinkedList<Transition> left = new LinkedList<Transition>(); LinkedList<Transition> right = new LinkedList<Transition>(); for (int i=0; i<middle; i++) { left.add(i, array.get(i)); } for (int i=middle; i<array.size();i++) { right.add(i-middle, array.get(i)); } left = mergeSort(left, tranFiringFreq); right = mergeSort(right, tranFiringFreq); return merge(left, right, tranFiringFreq); } private LinkedList<Transition> merge(LinkedList<Transition> left, LinkedList<Transition> right, HashMap<Transition, Integer> tranFiringFreq) { LinkedList<Transition> result = new LinkedList<Transition>(); while (left.size() > 0 || right.size() > 0) { if (left.size() > 0 && right.size() > 0) { if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) { result.addLast(left.poll()); } else { result.addLast(right.poll()); } } else if (left.size()>0) { result.addLast(left.poll()); } else if (right.size()>0) { result.addLast(right.poll()); } } return result; } /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. * @param nextState * @param stateStackTop * @param enable * @param disableByStealingToken * @param disable * @param init * @param cycleClosingMthdIndex * @param lpnIndex * @param isNextState * @return */ public LpnTranList getAmpleRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<Transition,StaticSets> staticSetsMap, boolean init, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> stateStack, PrjState stateStackTop) { // AmpleSet nextAmple = new AmpleSet(); // if (nextState == null) { // throw new NullPointerException(); // if(ampleSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) { // System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~"); // printTransitionSet((LpnTranList)ampleSetTbl.get(nextState), "Old ample at this state: "); // // Cycle closing check // LpnTranList nextAmpleTransOld = (LpnTranList) nextAmple.getAmpleSet(); // nextAmpleTransOld = ampleSetTbl.get(nextState); // LpnTranList curAmpleTrans = ampleSetTbl.get(curState); // LpnTranList curReduced = new LpnTranList(); // LpnTranList curEnabled = curState.getEnabledTransitions(); // for (int i=0; i<curEnabled.size(); i++) { // if (!curAmpleTrans.contains(curEnabled.get(i))) { // curReduced.add(curEnabled.get(i)); // if (!nextAmpleTransOld.containsAll(curReduced)) { // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // printTransitionSet(curEnabled, "curEnabled:"); // printTransitionSet(curAmpleTrans, "curAmpleTrans:"); // printTransitionSet(curReduced, "curReduced:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:"); // printTransitionSet(nextAmpleTransOld, "nextAmpleTransOld:"); // nextAmple.setAmpleChanged(); // HashSet<Transition> curEnabledIndicies = new HashSet<Transition>(); // for (int i=0; i<curEnabled.size(); i++) { // curEnabledIndicies.add(curEnabled.get(i).getIndex()); // // transToAdd = curReduced - nextAmpleOld // LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextAmpleTransOld); // HashSet<Integer> transToAddIndices = new HashSet<Integer>(); // for (int i=0; i<overlyReducedTrans.size(); i++) { // transToAddIndices.add(overlyReducedTrans.get(i).getIndex()); // HashSet<Integer> nextAmpleNewIndices = (HashSet<Integer>) curEnabledIndicies.clone(); // for (Integer tranToAdd : transToAddIndices) { // HashSet<Transition> dependent = new HashSet<Transition>(); // //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd]; // dependent = computeDependent(curState,tranToAdd,dependent,curEnabledIndicies,staticMap); // // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]); // boolean dependentOnlyHasDummyTrans = true; // for (Integer curTranIndex : dependent) { // Transition curTran = this.lpn.getAllTransitions()[curTranIndex]; // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName()); // if (dependent.size() < nextAmpleNewIndices.size() && !dependentOnlyHasDummyTrans) // nextAmpleNewIndices = (HashSet<Integer>) dependent.clone(); // if (nextAmpleNewIndices.size() == 1) // break; // LpnTranList nextAmpleNew = new LpnTranList(); // for (Integer nextAmpleNewIndex : nextAmpleNewIndices) { // nextAmpleNew.add(this.getLpn().getTransition(nextAmpleNewIndex)); // LpnTranList transToAdd = getSetSubtraction(nextAmpleNew, nextAmpleTransOld); // boolean allTransToAddFired = false; // if (cycleClosingMthdIndex == 2) { // // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. // if (transToAdd != null) { // LpnTranList transToAddCopy = transToAdd.copy(); // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // allTransToAddFired = allTransToAddFired(transToAddCopy, // allTransToAddFired, stateVisited, stateStackTop, lpnIndex); // // Update the old ample of the next state // if (!allTransToAddFired || cycleClosingMthdIndex == 1) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(transToAdd); // ampleSetTbl.get(nextState).addAll(transToAdd); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // if (cycleClosingMthdIndex == 4) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(overlyReducedTrans); // ampleSetTbl.get(nextState).addAll(overlyReducedTrans); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // // enabledSetTble stores the ample set at curState. // // The fully enabled set at each state is stored in the tranVector in each state. // return (AmpleSet) nextAmple; // for (State s : nextStateArray) // if (s == null) // throw new NullPointerException(); // cachedNecessarySets.clear(); // String cycleClosingMthd = Options.getCycleClosingMthd(); // AmpleSet nextAmple = new AmpleSet(); // HashSet<Transition> nextEnabled = new HashSet<Transition>(); //// boolean allEnabledAreSticky = false; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State nextState = nextStateArray[lpnIndex]; // if (init) { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // //allEnabledAreSticky = true; // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (sgList[lpnIndex].isEnabled(tran,nextState)){ // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // else { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (nextStateArray[lpnIndex].getTranVector()[i]) { // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // LhpnFile[] lpnList = new LhpnFile[sgList.length]; // for (int i=0; i<sgList.length; i++) // lpnList[i] = sgList[i].getLpn(); // HashMap<Transition, LpnTranList> transToAddMap = new HashMap<Transition, LpnTranList>(); // Integer cycleClosingLpnIndex = -1; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State curState = curStateArray[lpnIndex]; // State nextState = nextStateArray[lpnIndex]; // if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true // && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty() // && stateOnStack(lpnIndex, nextState, stateStack) // && nextState.getIndex() != curState.getIndex()) { // cycleClosingLpnIndex = lpnIndex; // System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~"); // printAmpleSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old ample at this state: "); // LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState); // LpnTranList curLocalAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState); // LpnTranList reducedLocalTrans = new LpnTranList(); // LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions(); // System.out.println("The firedTran is a cycle closing transition."); // if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) { // // firedTran is a cycle closing transition. // for (int i=0; i<curLocalEnabledTrans.size(); i++) { // if (!curLocalAmpleTrans.contains(curLocalEnabledTrans.get(i))) { // reducedLocalTrans.add(curLocalEnabledTrans.get(i)); // if (!oldLocalNextAmpleTrans.containsAll(reducedLocalTrans)) { // printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:"); // printTransitionSet(curLocalAmpleTrans, "curAmpleTrans:"); // printTransitionSet(reducedLocalTrans, "reducedLocalTrans:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:"); // printTransitionSet(oldLocalNextAmpleTrans, "nextAmpleTransOld:"); // // nextAmple.setAmpleChanged(); // // ignoredTrans should not be empty here. // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // if (cycleClosingMthd.toLowerCase().equals("behavioral")) { // for (Transition seed : ignored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); //// if (nextAmpleNewIndices.size() == 1) //// break; // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else if (cycleClosingMthd.toLowerCase().equals("state_search")) { // // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new ample of nextState. // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // LpnTranList trulyIgnoredTrans = ignoredTrans.copy(); // trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]); // if (!trulyIgnoredTrans.isEmpty()) { // HashSet<Transition> trulyIgnored = new HashSet<Transition>(); // for (Transition tran : trulyIgnoredTrans) { // trulyIgnored.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : trulyIgnored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else { // All ignored transitions were fired before. It is safe to close the current cycle. // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // // oldNextAmpleTrans.containsAll(curReducedTrans) == true (safe to close the current cycle) // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else if (cycleClosingMthd.toLowerCase().equals("strong")) { // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> allNewNextAmple = new HashSet<Transition>(); // for (Transition seed : ignored) { // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // allNewNextAmple.addAll(newNextAmple); // // The strong cycle condition requires all seeds in ignored to be included in the allNewNextAmple, as well as dependent set for each seed. // // So each seed should have the same new ample set. // for (Transition seed : ignored) { // DependentSet dependentSet = new DependentSet(allNewNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // firedTran is not a cycle closing transition. Compute next ample. //// if (nextEnabled.size() == 1) //// return nextEnabled; // System.out.println("The firedTran is NOT a cycle closing transition."); // HashSet<Transition> ready = null; // for (Transition seed : nextEnabled) { // System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")"); // HashSet<Transition> dependent = new HashSet<Transition>(); // Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()]; // boolean enabledIsDummy = false; //// if (enabledTransition.isSticky()) { //// dependent = (HashSet<Transition>) nextEnabled.clone(); //// else { //// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList); // dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // if (isDummyTran(enabledTransition.getName())) // enabledIsDummy = true; // for (Transition inDependent : dependent) { // if(inDependent.getLpnIndex() == cycleClosingLpnIndex) { // // check cycle closing condition // break; // DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy); // dependentSetQueue.add(dependentSet); // ready = dependentSetQueue.poll().getDependent(); //// // Update the old ample of the next state //// boolean allTransToAddFired = false; //// if (cycleClosingMthdIndex == 2) { //// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. //// if (transToAdd != null) { //// LpnTranList transToAddCopy = transToAdd.copy(); //// HashSet<Integer> stateVisited = new HashSet<Integer>(); //// stateVisited.add(nextState.getIndex()); //// allTransToAddFired = allTransToAddFired(transToAddCopy, //// allTransToAddFired, stateVisited, stateStackTop, lpnIndex); //// // Update the old ample of the next state //// if (!allTransToAddFired || cycleClosingMthdIndex == 1) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(transToAdd); //// ampleSetTbl.get(nextState).addAll(transToAdd); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// if (cycleClosingMthdIndex == 4) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(ignoredTrans); //// ampleSetTbl.get(nextState).addAll(ignoredTrans); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// // enabledSetTble stores the ample set at curState. //// // The fully enabled set at each state is stored in the tranVector in each state. //// return (AmpleSet) nextAmple; return null; } private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans, HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) { State state = stateStackEntry.get(lpnIndex); System.out.println("state = " + state.getIndex()); State predecessor = stateStackEntry.getFather().get(lpnIndex); if (predecessor != null) System.out.println("predecessor = " + predecessor.getIndex()); if (predecessor == null || stateVisited.contains(predecessor.getIndex())) { return ignoredTrans; } else stateVisited.add(predecessor.getIndex()); LpnTranList predecessorOldAmple = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor); for (Transition oldAmpleTran : predecessorOldAmple) { State tmpState = sg.getNextStateMap().get(predecessor).get(oldAmpleTran); if (tmpState.getIndex() == state.getIndex()) { ignoredTrans.remove(oldAmpleTran); break; } } if (ignoredTrans.size()==0) { return ignoredTrans; } else { ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg); } return ignoredTrans; } // for (Transition oldAmpleTran : oldAmple) { // State successor = nextStateMap.get(nextState).get(oldAmpleTran); // if (stateVisited.contains(successor.getIndex())) { // break; // else // stateVisited.add(successor.getIndex()); // LpnTranList successorOldAmple = enabledSetTbl.get(successor); // // Either successor or sucessorOldAmple should not be null for a nonterminal state graph. // HashSet<Transition> transToAddFired = new HashSet<Transition>(); // for (Transition tran : transToAddCopy) { // if (successorOldAmple.contains(tran)) // transToAddFired.add(tran); // transToAddCopy.removeAll(transToAddFired); // if (transToAddCopy.size() == 0) { // allTransFired = true; // break; // else { // allTransFired = allTransToAddFired(successorOldAmple, nextState, successor, // transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex); // return allTransFired; /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) { boolean firingOrder = false; long peakUsedMem = 0; long peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length; HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>(); @SuppressWarnings("unchecked") IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize]; //HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize]; Stack<LpnState[]> stateStack = new Stack<LpnState[]>(); Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>(); //get initial enable transition set LpnTranList initEnabled = new LpnTranList(); LpnTranList initFireFirst = new LpnTranList(); LpnState[] initLpnStateArray = new LpnState[arraySize]; for (int i = 0; i < arraySize; i++) { lpnStateCache[i] = new IndexObjMap<LpnState>(); LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]); HashSet<Transition> enabledSet = new HashSet<Transition>(); if(!enabledTrans.isEmpty()) { for(Transition tran : enabledTrans) { enabledSet.add(tran); initEnabled.add(tran); } } LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet); lpnStateCache[i].add(curLpnState); initLpnStateArray[i] = curLpnState; } LpnTranList[] initEnabledSet = new LpnTranList[2]; initEnabledSet[0] = initFireFirst; initEnabledSet[1] = initEnabled; lpnTranStack.push(initEnabledSet); stateStack.push(initLpnStateArray); globalStateTbl.add(new PrjLpnState(initLpnStateArray)); main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; //if(iterations>2)break; if (iterations % 100000 == 0) System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", current_stack_depth: " + stateStack.size() + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); LpnTranList[] curEnabled = lpnTranStack.peek(); LpnState[] curLpnStateArray = stateStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if(curEnabled[0].size()==0 && curEnabled[1].size()==0){ lpnTranStack.pop(); stateStack.pop(); continue; } Transition firedTran = null; if(curEnabled[0].size() != 0) firedTran = curEnabled[0].removeFirst(); else firedTran = curEnabled[1].removeFirst(); traceCex.addLast(firedTran); State[] curStateArray = new State[arraySize]; for( int i = 0; i < arraySize; i++) curStateArray[i] = curLpnStateArray[i].getState(); StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled(); LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]); HashSet<Transition> nextEnabledSet = new HashSet<Transition>(); for(Transition tran : nextEnabledList) { nextEnabledSet.add(tran); } extendedNextEnabledArray[i] = nextEnabledSet; //non_disabling for(Transition curTran : curEnabledSet) { if(curTran == firedTran) continue; if(nextEnabledSet.contains(curTran) == false) { int[] nextMarking = nextStateArray[i].getMarking(); // Not sure if the code below is correct. int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getLabel()); boolean included = true; if (preset != null && preset.length > 0) { for (int pp : preset) { boolean temp = false; for (int mi = 0; mi < nextMarking.length; mi++) { if (nextMarking[mi] == pp) { temp = true; break; } } if (temp == false) { included = false; break; } } } if(preset==null || preset.length==0 || included==true) { extendedNextEnabledArray[i].add(curTran); } } } } boolean deadlock=true; for(int i = 0; i < arraySize; i++) { if(extendedNextEnabledArray[i].size() != 0){ deadlock = false; break; } } if(deadlock==true) { failure = true; break main_while_loop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. LpnState[] nextLpnStateArray = new LpnState[arraySize]; for(int i = 0; i < arraySize; i++) { HashSet<Transition> lpnEnabledSet = new HashSet<Transition>(); for(Transition tran : extendedNextEnabledArray[i]) { lpnEnabledSet.add(tran); } LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet); LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp)); nextLpnStateArray[i] = tmpCached; } boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray)); if(newState == false) { traceCex.removeLast(); continue; } stateStack.push(nextLpnStateArray); LpnTranList[] nextEnabledSet = new LpnTranList[2]; LpnTranList fireFirstTrans = new LpnTranList(); LpnTranList otherTrans = new LpnTranList(); for(int i = 0; i < arraySize; i++) { for(Transition tran : nextLpnStateArray[i].getEnabled()) { if(firingOrder == true) if(curLpnStateArray[i].getEnabled().contains(tran)) otherTrans.add(tran); else fireFirstTrans.add(tran); else fireFirstTrans.add(tran); } } nextEnabledSet[0] = fireFirstTrans; nextEnabledSet[1] = otherTrans; lpnTranStack.push(nextEnabledSet); }// END while (stateStack.empty() == false) // graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt, // prjStateSet.size())); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth); /* * by looking at stateStack, generate the trace showing the counter-example. */ if (failure == true) { System.out.println(" System.out.println("the deadlock trace:"); //update traceCex from stateStack // LpnState[] cur = null; // LpnState[] next = null; for(Transition tran : traceCex) System.out.println(tran.getFullLabel()); } System.out.println("Modules' local states: "); for (int i = 0; i < arraySize; i++) { System.out.println("module " + lpnList[i].getLpn().getLabel() + ": " + lpnList[i].reachSize()); } return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * When a state is considered during DFS, only one enabled transition is * selected to fire in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_1"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 500; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean compressed = false; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int arraySize = lpnList.length; int newStateCnt = 0; Stack<State[]> stateStack = new Stack<State[]>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); mddNode reachAll = null; mddNode reach = mddMgr.newNode(); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true); mddMgr.add(reach, localIdxArray, compressed); stateStack.push(initStateArray); LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]); lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); int numMddCompression = 0; main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack depth: " + stateStack.size() + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); numMddCompression++; if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); if(memUpBound < 1500) memUpBound *= numMddCompression; } } State[] curStateArray = stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); curIndexStack.pop(); curIndex++; while (curIndex < arraySize) { LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex])); if (enabledCached.size() > 0) { curEnabled = enabledCached.clone(); lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); break; } else curIndex++; } } if (curIndex == arraySize) { stateStack.pop(); continue; } Transition firedTran = curEnabled.removeLast(); State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. * if not, add it into reachable set, and push it onto stack. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; if (existingState == false) { mddMgr.add(reach, localIdxArray, compressed); newStateCnt++; stateStack.push(nextStateArray); lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); curIndexStack.push(0); totalStates++; } } double totalStateCnt = mddMgr.numberOfStates(reach); System.out.println("---> run statistics: \n" + "# LPN transition firings: " + tranFiringCnt + "\n" + "# of prjStates found: " + totalStateCnt + "\n" + "max_stack_depth: " + max_stack_depth + "\n" + "peak MDD nodes: " + peakMddNodeCnt + "\n" + "peak used memory: " + peakUsedMem / 1000000 + " MB\n" + "peak total memory: " + peakTotalMem / 1000000 + " MB\n"); return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * It is similar to findsg_dfs_mdd_1 except that when a state is considered * during DFS, all enabled transition are fired, and all its successor * states are found in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_2"); int tranFiringCnt = 0; int totalStates = 0; int arraySize = lpnList.length; long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean failure = false; MDT state2Explore = new MDT(arraySize); state2Explore.push(initStateArray); totalStates++; long peakState2Explore = 0; Stack<Integer> searchDepth = new Stack<Integer>(); searchDepth.push(1); boolean compressed = false; mddNode reachAll = null; mddNode reach = mddMgr.newNode(); main_while_loop: while (failure == false && state2Explore.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; iterations++; if (iterations % 100000 == 0) { int mddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt; int state2ExploreSize = state2Explore.size(); peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", # states to explore: " + state2ExploreSize + ", # MDT nodes: " + state2Explore.nodeCnt() + ", total MDD nodes: " + mddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } } State[] curStateArray = state2Explore.pop(); State[] nextStateArray = null; int states2ExploreCurLevel = searchDepth.pop(); if(states2ExploreCurLevel > 1) searchDepth.push(states2ExploreCurLevel-1); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false); mddMgr.add(reach, localIdxArray, compressed); int nextStates2Explore = 0; for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; State curState = curStateArray[index]; LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState); LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone(); while (curEnabled.size() > 0) { Transition firedTran = curEnabled.removeLast(); // TODO: (check) Not sure if curLpn.fire is correct. nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; if (curStateArray[i] == nextStateArray[i]) continue; LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.err.println("Verification failed: deadlock."); failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; else if(state2Explore.contains(nextStateArray)==true) existingState = true; if (existingState == false) { totalStates++; //mddMgr.add(reach, localIdxArray, compressed); state2Explore.push(nextStateArray); nextStates2Explore++; } } } if(nextStates2Explore > 0) searchDepth.push(nextStates2Explore); } System.out.println(" + "---> run statistics: \n" + " # Depth of search (Length of Cex): " + searchDepth.size() + "\n" + " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n" + " # of prjStates found: " + (double)totalStates / 1000000 + " M\n" + " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n" + " peak MDD nodes: " + peakMddNodeCnt + "\n" + " peak used memory: " + peakUsedMem / 1000000 + " MB\n" + " peak total memory: " + peakTotalMem /1000000 + " MB\n" + "_____________________________________"); return null; } public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. int arraySize = sgList.length; for (int i = 0; i < arraySize; i++) sgList[i].addState(initStateArray[i]); mddNode reachSet = null; mddNode reach = mddMgr.newNode(); MDT frontier = new MDT(arraySize); MDT image = new MDT(arraySize); frontier.push(initStateArray); State[] curStateArray = null; int tranFiringCnt = 0; int totalStates = 0; int imageSize = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachSet == null) reachSet = reach; else { mddNode newReachSet = mddMgr.union(reachSet, reach); if (newReachSet != reachSet) { mddMgr.remove(reachSet); reachSet = newReachSet; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } while(frontier.empty() == false) { boolean deadlock = true; // Stack<State[]> curStateArrayList = frontier.pop(); // while(curStateArrayList.empty() == false) { // curStateArray = curStateArrayList.pop(); { curStateArray = frontier.pop(); int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false); mddMgr.add(reach, localIdxArray, false); totalStates++; for (int i = 0; i < arraySize; i++) { LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]); if (curEnabled.size() > 0) deadlock = false; for (Transition firedTran : curEnabled) { // TODO: (check) Not sure if sgList[i].fire is correct. State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran); tranFiringCnt++; /* * Check if any transitions can be disabled by fireTran. */ LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled); if (disabledTran != null) { System.err.println("*** Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false); if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) { if(image.contains(nextStateArray)==false) { image.push(nextStateArray); imageSize++; } } } } } /* * If curStateArray deadlocks (no enabled transitions), terminate. */ if (deadlock == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } } if(image.empty()==true) break; System.out.println("---> size of image: " + imageSize); frontier = image; image = new MDT(arraySize); imageSize = 0; } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n" + "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MDD nodes: " + peakMddNodeCnt); return null; } /** * BFS findsg using iterative approach. THe states found are stored in MDD. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; int arraySize = lpnList.length; for (int i = 0; i < arraySize; i++) lpnList[i].addState(initStateArray[i]); // mddNode reachSet = mddMgr.newNode(); // mddMgr.add(reachSet, curLocalStateArray); mddNode reachSet = null; mddNode exploredSet = null; LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]); for (int i = 0; i < arraySize; i++) nextSetArray[i] = new LinkedList<State>(); mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null); mddNode curMdd = initMdd; reachSet = curMdd; mddNode nextMdd = null; int[] curStateArray = null; int tranFiringCnt = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; curStateArray = mddMgr.next(curMdd, curStateArray); if (curStateArray == null) { // Break the loop if no new next states are found. // System.out.println("nextSet size " + nextSet.size()); if (nextMdd == null) break bfsWhileLoop; if (exploredSet == null) exploredSet = curMdd; else { mddNode newExplored = mddMgr.union(exploredSet, curMdd); if (newExplored != exploredSet) mddMgr.remove(exploredSet); exploredSet = newExplored; } mddMgr.remove(curMdd); curMdd = nextMdd; nextMdd = null; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of union calls: " + mddNode.numCalls + ", # of union cache nodes: " + mddNode.cacheNodes + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet) + ", CurSet.Size = " + mddMgr.numberOfStates(curMdd)); continue; } if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true) continue; // If curStateArray deadlocks (no enabled transitions), terminate. if (Analysis.deadLock(lpnList, curStateArray) == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } // Do firings of non-local LPN transitions. for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]); if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true) continue; for (Transition firedTran : curLocalEnabled) { if (firedTran.isLocal() == true) continue; // TODO: (check) Not sure if curLpn.fire is correct. State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; @SuppressWarnings("unused") ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1); for (int i = 0; i < arraySize; i++) { if (curStateArray[i] == nextStateArray[i].getIndex()) continue; StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex()); Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + ": is disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { verifyError = true; break bfsWhileLoop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the // next // enabled transition. int[] nextIdxArray = Analysis.getIdxArray(nextStateArray); if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true) continue; mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet); mddNode newReachSet = mddMgr.union(reachSet, newNextMdd); if (newReachSet != reachSet) mddMgr.remove(reachSet); reachSet = newReachSet; if (nextMdd == null) nextMdd = newNextMdd; else { mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd); if (tmpNextMdd != nextMdd) mddMgr.remove(nextMdd); nextMdd = tmpNextMdd; mddMgr.remove(newNextMdd); } } } } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + "\n" + "---> # of prjStates found: " + (mddMgr.numberOfStates(reachSet)) + "\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt()); return null; } /** * partial order reduction (Original version of Hao's POR with behavioral analysis) * This method is not used anywhere. See search_dfs_por_behavioral for POR with behavioral analysis. * * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> Calling search_dfs with partial order reduction"); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; boolean useMdd = true; mddNode reach = mddMgr.newNode(); //init por verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); //System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel()); // TODO: (??) Not sure if the state graph sg below is correct. StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return null; } /** * partial order reduction with behavioral analysis. (Adapted from search_dfs_por.) * * @param sgList * @param curLocalStateArray * @param enabledArray */ public StateGraph[] searchPOR_behavioral(final StateGraph[] sgList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> calling function searchPOR_behavioral"); System.out.println("---> " + Options.getPOR()); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; // TODO: Is useMdd default for POR + behavioral analysis? //boolean useMdd = true; boolean useMdd = false; mddNode reach = mddMgr.newNode(); //init por verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(sgList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(sgList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = sgList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { sgList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = sgList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); StateGraph sg = null; for (int i=0; i<sgList.length; i++) { if (sgList[i].getLpn().equals(firedTran.getLpn())) { sg = sgList[i]; } } State[] nextStateArray = sg.fire(sgList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { sgList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = sgList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + sgList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + sgList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return sgList; } // /** // * Check if this project deadlocks in the current state 'stateArray'. // * @param sgList // * @param stateArray // * @param staticSetsMap // * @param enableSet // * @param disableByStealingToken // * @param disableSet // * @param init // * @return // */ // // Called by search search_dfsPOR // public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<Transition,StaticSets> staticSetsMap, // boolean init, HashMap<Transition, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) { // boolean deadlock = true; // System.out.println("@ deadlock:"); //// for (int i = 0; i < stateArray.length; i++) { //// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); //// if (tmp.size() > 0) { //// deadlock = false; //// break; // LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); // if (tmp.size() > 0) { // deadlock = false; // System.out.println("@ end of deadlock"); // return deadlock; public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) { boolean deadlock = true; for (int i = 0; i < stateArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) { boolean deadlock = true; for (int i = 0; i < stateIdxArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } // /* // * Scan enabledArray, identify all sticky transitions other the firedTran, and return them. // * // * Arguments remain constant. // */ // public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) { // int arraySize = enabledArray.length; // LpnTranList[] stickyTranArray = new LpnTranList[arraySize]; // for (int i = 0; i < arraySize; i++) { // stickyTranArray[i] = new LpnTranList(); // for (Transition tran : enabledArray[i]) { // if (tran != firedTran) // stickyTranArray[i].add(tran); // if(stickyTranArray[i].size()==0) // stickyTranArray[i] = null; // return stickyTranArray; /** * Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to * nextStickyTransArray. * * Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions * from curStickyTransArray. * * Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState. */ public static LpnTranList[] checkStickyTrans( LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray, LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) { int arraySize = curStickyTransArray.length; LpnTranList[] stickyTransArray = new LpnTranList[arraySize]; boolean[] hasStickyTrans = new boolean[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> tmp = new HashSet<Transition>(); if(nextStickyTransArray[i] != null) for(Transition tran : nextStickyTransArray[i]) tmp.add(tran); stickyTransArray[i] = new LpnTranList(); hasStickyTrans[i] = false; for (Transition tran : curStickyTransArray[i]) { if (tran.isPersistent() == true && tmp.contains(tran)==false) { int[] nextMarking = nextState.getMarking(); int[] preset = LPN.getPresetIndex(tran.getLabel());//tran.getPreSet(); boolean included = false; if (preset != null && preset.length > 0) { for (int pp : preset) { for (int mi = 0; i < nextMarking.length; i++) { if (nextMarking[mi] == pp) { included = true; break; } } if (included == false) break; } } if(preset==null || preset.length==0 || included==true) { stickyTransArray[i].add(tran); hasStickyTrans[i] = true; } } } if(stickyTransArray[i].size()==0) stickyTransArray[i] = null; } return stickyTransArray; } /* * Return an array of indices for the given stateArray. */ private static int[] getIdxArray(State[] stateArray) { int[] idxArray = new int[stateArray.length]; for(int i = 0; i < stateArray.length; i++) { idxArray[i] = stateArray[i].getIndex(); } return idxArray; } private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) { int arraySize = sgList.length; int[] localIdxArray = new int[arraySize]; for(int i = 0; i < arraySize; i++) { if(reverse == false) localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex(); else localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex(); //System.out.print(localIdxArray[i] + " "); } //System.out.println(); return localIdxArray; } private void printEnabledSetTbl(StateGraph[] sgList) { for (int i=0; i<sgList.length; i++) { System.out.println("******* enabledSetTbl for " + sgList[i].getLpn().getLabel() + " **********"); for (State s : sgList[i].getEnabledSetTbl().keySet()) { System.out.print("S" + s.getIndex() + " -> "); printTransitionSet(sgList[i].getEnabledSetTbl().get(s), ""); } } } private HashSet<Transition> partialOrderReduction(State[] curStateArray, HashSet<Transition> curEnabled, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; if (Options.getUseDependentQueue()) { DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()){ writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); } HashSet<Transition> dependent = new HashSet<Transition>(); boolean enabledIsDummy = false; boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); } // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) if(isDummyTran(enabledTran.getLabel())) enabledIsDummy = true; DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); dependentSetQueue.add(dependentSet); } //cachedNecessarySets.clear(); ready = dependentSetQueue.poll().getDependent(); //return ready; } else { for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()){ writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); } HashSet<Transition> dependent = new HashSet<Transition>(); boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); } if (ready.isEmpty() || dependent.size() < ready.size()) ready = dependent; if (ready.size() == 1) { cachedNecessarySets.clear(); return ready; } } } cachedNecessarySets.clear(); return ready; } // private HashSet<Transition> partialOrderReduction(State[] curStateArray, // HashSet<Transition> curEnabled, HashMap<Transition, StaticSets> staticMap, // HashMap<Transition,Integer> tranFiringFreqMap, StateGraph[] sgList, LhpnFile[] lpnList) { // if (curEnabled.size() == 1) // return curEnabled; // HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; // if (Options.getUseDependentQueue()) { // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean enabledIsDummy = false; // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) // if(isDummyTran(enabledTran.getName())) // enabledIsDummy = true; // DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); // dependentSetQueue.add(dependentSet); // //cachedNecessarySets.clear(); // ready = dependentSetQueue.poll().getDependent(); // //return ready; // else { // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // if (ready.isEmpty() || dependent.size() < ready.size()) // ready = dependent;//(HashSet<Transition>) dependent.clone(); // if (ready.size() == 1) { // cachedNecessarySets.clear(); // return ready; // cachedNecessarySets.clear(); // return ready; private boolean isDummyTran(String tranName) { if (tranName.contains("_dummy")) return true; else return false; } private HashSet<Transition> computeDependent(State[] curStateArray, Transition seedTran, HashSet<Transition> dependent, HashSet<Transition> curEnabled, boolean isCycleClosingAmpleComputation) { // disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran. HashSet<Transition> disableSet = staticDependency.get(seedTran).getDisableSet(); HashSet<Transition> otherTransDisableEnabledTran = staticDependency.get(seedTran).getOtherTransDisableCurTranSet(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ beginning of computeDependent, consider transition " + getNamesOfLPNandTrans(seedTran)); writeIntegerSetToPORDebugFile(disableSet, "Disable set for " + getNamesOfLPNandTrans(seedTran)); } dependent.add(seedTran); // for (Transition lpnTranPair : canModifyAssign) { // if (curEnabled.contains(lpnTranPair)) // dependent.add(lpnTranPair); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ computeDependent at 0, dependent set for " + getNamesOfLPNandTrans(seedTran)); } // dependent is equal to enabled. Terminate. if (dependent.size() == curEnabled.size()) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Check 0: Size of dependent is equal to enabled. Return dependent."); } return dependent; } for (Transition tranInDisableSet : disableSet) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Consider transition in the disable set of " + getNamesOfLPNandTrans(seedTran) + ": " + getNamesOfLPNandTrans(tranInDisableSet)); } if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet) && (!tranInDisableSet.isPersistent() || otherTransDisableEnabledTran.contains(tranInDisableSet))) { dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,isCycleClosingAmpleComputation)); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "@ computeDependent at 1 for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (!curEnabled.contains(tranInDisableSet)) { if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back || (Options.getCycleClosingAmpleMethd().toLowerCase().equals("cctboff") && isCycleClosingAmpleComputation)) { dependent.addAll(curEnabled); break; } HashSet<Transition> necessary = null; if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } if (cachedNecessarySets.containsKey(tranInDisableSet)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@ computeDependent: Found transition " + getNamesOfLPNandTrans(tranInDisableSet) + "in the cached necessary sets."); } necessary = cachedNecessarySets.get(tranInDisableSet); } else { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("==== Compute necessary using DFS ===="); } if (visitedTrans == null) visitedTrans = new HashSet<Transition>(); else visitedTrans.clear(); necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled);//, tranInDisableSet.getFullLabel()); } if (necessary != null && !necessary.isEmpty()) { cachedNecessarySets.put(tranInDisableSet, necessary); if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(necessary, "@ computeDependent, necessary set for transition " + getNamesOfLPNandTrans(tranInDisableSet)); } for (Transition tranNecessary : necessary) { if (!dependent.contains(tranNecessary)) { if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent,"Check if the newly found necessary transition is in the dependent set of " + getNamesOfLPNandTrans(seedTran)); writeStringWithEndOfLineToPORDebugFile("It does not contain this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + ". Compute its dependent set."); } dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,isCycleClosingAmpleComputation)); } else { if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent, "Check if the newly found necessary transition is in the dependent set. Dependent set for " + getNamesOfLPNandTrans(seedTran)); writeStringWithEndOfLineToPORDebugFile("It already contains this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + "."); } } } } else { if (Options.getDebugMode()) { if (necessary == null) { writeStringWithEndOfLineToPORDebugFile("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is null."); } else { writeStringWithEndOfLineToPORDebugFile("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is empty."); } } //dependent.addAll(curEnabled); return curEnabled; } if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent,"@ computeDependent at 2, dependent set for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (dependent.contains(tranInDisableSet)) { if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(dependent,"@ computeDependent at 3 for transition " + getNamesOfLPNandTrans(seedTran)); writeStringWithEndOfLineToPORDebugFile("Transition " + getNamesOfLPNandTrans(tranInDisableSet) + " is already in the dependent set of " + getNamesOfLPNandTrans(seedTran) + "."); } } } return dependent; } private String getNamesOfLPNandTrans(Transition tran) { return tran.getLpn().getLabel() + "(" + tran.getLabel() + ")"; } private HashSet<Transition> computeNecessary(State[] curStateArray, Transition tran, HashSet<Transition> dependent, HashSet<Transition> curEnabled) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + getNamesOfLPNandTrans(tran)); } if (cachedNecessarySets.containsKey(tran)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@ computeNecessary: Found transition " + getNamesOfLPNandTrans(tran) + "'s necessary set in the cached necessary sets. Return the cached necessary set."); } return cachedNecessarySets.get(tran); } // Search for transition(s) that can help to bring the marking(s). HashSet<Transition> nMarking = null; //Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()); //int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName()); for (int i=0; i < tran.getPreset().length; i++) { int placeIndex = tran.getLpn().getPresetIndex(tran.getLabel())[i]; if (curStateArray[tran.getLpn().getLpnIndex()].getMarking()[placeIndex]==0) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(" } HashSet<Transition> nMarkingTemp = new HashSet<Transition>(); String placeName = tran.getLpn().getPlaceList()[placeIndex]; Transition[] presetTrans = tran.getLpn().getPlace(placeName).getPreset(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Consider preset place of " + getNamesOfLPNandTrans(tran) + ": " + placeName); } for (int j=0; j < presetTrans.length; j++) { Transition presetTran = presetTrans[j]; if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Preset of place " + placeName + " has transition(s): "); for (int k=0; k<presetTrans.length; k++) { writeStringToPORDebugFile(getNamesOfLPNandTrans(presetTrans[k]) + ", "); } writeStringWithEndOfLineToPORDebugFile(""); writeStringWithEndOfLineToPORDebugFile("@ nMarking: Consider transition of " + getNamesOfLPNandTrans(presetTran)); } if (curEnabled.contains(presetTran)) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: curEnabled contains transition " + getNamesOfLPNandTrans(presetTran) + "). Add to nMarkingTmp."); } nMarkingTemp.add(presetTran); } else { if (visitedTrans.contains(presetTran)) {//seedTranInDisableSet.getVisitedTrans().contains(presetTran)) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Transition " + getNamesOfLPNandTrans(presetTran) + " was visted before"); } if (cachedNecessarySets.containsKey(presetTran)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@nMarking: Found transition " + getNamesOfLPNandTrans(presetTran) + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nMarkingTemp = cachedNecessarySets.get(presetTran); } continue; } else visitedTrans.add(presetTran); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("~~~~~~~~~ transVisited ~~~~~~~~~"); for (Transition visitedTran :visitedTrans) { writeStringWithEndOfLineToPORDebugFile(getNamesOfLPNandTrans(visitedTran)); } writeStringWithEndOfLineToPORDebugFile("@ nMarking, before call computeNecessary: consider transition: " + getNamesOfLPNandTrans(presetTran)); writeStringWithEndOfLineToPORDebugFile("@ nMarking: transition " + getNamesOfLPNandTrans(presetTran) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabled); if (tmp != null) { nMarkingTemp.addAll(tmp); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(presetTran) + " is not null."); writeIntegerSetToPORDebugFile(nMarkingTemp, getNamesOfLPNandTrans(presetTran) + "'s nMarkingTemp"); } } else if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: necessary set for transition " + getNamesOfLPNandTrans(presetTran) + " is null."); } } } if (!nMarkingTemp.isEmpty()) //if (nMarking == null || nMarkingTemp.size() < nMarking.size()) if (nMarking == null || setSubstraction(nMarkingTemp, dependent).size() < setSubstraction(nMarking, dependent).size()) nMarking = nMarkingTemp; } else if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nMarking: Place " + tran.getLpn().getLabel() + "(" + tran.getLpn().getPlaceList()[placeIndex] + ") is marked."); } } if (nMarking != null && nMarking.size() ==1 && setSubstraction(nMarking, dependent).size() == 0) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Return nMarking as necessary set."); writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } // Search for transition(s) that can help to enable the current transition. HashSet<Transition> nEnable = null; int[] varValueVector = curStateArray[tran.getLpn().getLpnIndex()].getVector(); //HashSet<Transition> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue(); ArrayList<HashSet<Transition>> canEnable = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(" writeIntegerSetToPORDebugFile(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); } if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && !canEnable.isEmpty()) { for(int index=0; index < tran.getConjunctsOfEnabling().size(); index++) { ExprTree conjunctExprTree = tran.getConjunctsOfEnabling().get(index); HashSet<Transition> nEnableForOneConjunct = null; if (Options.getDebugMode()) { writeIntegerSetToPORDebugFile(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); writeStringWithEndOfLineToPORDebugFile("@ nEnable: Consider conjunct for transition " + getNamesOfLPNandTrans(tran) + ": " + conjunctExprTree.toString()); } if (conjunctExprTree.evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0) { HashSet<Transition> canEnableOneConjunctSet = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue().get(index); nEnableForOneConjunct = new HashSet<Transition>(); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to FALSE."); writeIntegerSetToPORDebugFile(canEnableOneConjunctSet, "@ nEnable: Transitions that can enable this conjunct are"); } for (Transition tranCanEnable : canEnableOneConjunctSet) { if (curEnabled.contains(tranCanEnable)) { nEnableForOneConjunct.add(tranCanEnable); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: curEnabled contains transition " + getNamesOfLPNandTrans(tranCanEnable) + ". Add to nEnableOfOneConjunct."); } } else { if (visitedTrans.contains(tranCanEnable)) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " was visted before."); } if (cachedNecessarySets.containsKey(tranCanEnable)) { if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); writeStringWithEndOfLineToPORDebugFile("@ nEnable: Found transition " + getNamesOfLPNandTrans(tranCanEnable) + "'s necessary set in the cached necessary sets. Add it to nEnableOfOneConjunct."); } nEnableForOneConjunct.addAll(cachedNecessarySets.get(tranCanEnable)); } continue; } else visitedTrans.add(tranCanEnable); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabled); if (tmp != null) { nEnableForOneConjunct.addAll(tmp); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(tranCanEnable) + ": "); writeIntegerSetToPORDebugFile(tmp, ""); writeIntegerSetToPORDebugFile(nEnableForOneConjunct, getNamesOfLPNandTrans(tranCanEnable) + "'s nEnableOfOneConjunct"); } } else if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: necessary set for transition " + getNamesOfLPNandTrans(tranCanEnable) + " is null."); } } } if (!nEnableForOneConjunct.isEmpty()) { if (nEnable == null || setSubstraction(nEnableForOneConjunct, dependent).size() < setSubstraction(nEnable, dependent).size()) { //&& !nEnableForOneConjunct.isEmpty())) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" is replaced by nEnableForOneConjunct."); writeIntegerSetToPORDebugFile(nEnable, "nEnable"); writeIntegerSetToPORDebugFile(nEnableForOneConjunct, "nEnableForOneConjunct"); } nEnable = nEnableForOneConjunct; } else { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" remains unchanged."); writeIntegerSetToPORDebugFile(nEnable, "nEnable"); } } } } else { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to TRUE. No need to trace back on it."); } } } } else { if (Options.getDebugMode()) { if (tran.getEnablingTree() == null) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + " has no enabling condition."); } else if (tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) !=0.0) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is true."); } else if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && canEnable.isEmpty()) { writeStringWithEndOfLineToPORDebugFile("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is false, but no other transitions that can help to enable it were found ."); } writeIntegerSetToPORDebugFile(nMarking, "=== nMarking for transition " + getNamesOfLPNandTrans(tran)); writeIntegerSetToPORDebugFile(nEnable, "=== nEnable for transition " + getNamesOfLPNandTrans(tran)); } } if (nMarking != null && nEnable == null) { if (!nMarking.isEmpty()) cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } else if (nMarking == null && nEnable != null) { if (!nEnable.isEmpty()) cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nEnable; } else if (nMarking == null && nEnable == null) { return null; } else { if (!nMarking.isEmpty() && !nEnable.isEmpty()) { if (setSubstraction(nMarking, dependent).size() < setSubstraction(nEnable, dependent).size()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } else { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nEnable; } } else if (nMarking.isEmpty() && !nEnable.isEmpty()) { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nEnable; } else if (!nMarking.isEmpty() && nEnable.isEmpty()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { writeCachedNecessarySetsToPORDebugFile(); } return nMarking; } else { return null; } } } // private HashSet<Transition> computeNecessaryUsingDependencyGraphs(State[] curStateArray, // Transition tran, HashSet<Transition> curEnabled, // HashMap<Transition, StaticSets> staticMap, // LhpnFile[] lpnList, Transition seedTran) { // if (Options.getDebugMode()) { //// System.out.println("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // // Use breadth-first search to find the shorted path from the seed transition to an enabled transition. // LinkedList<Transition> exploredTransQueue = new LinkedList<Transition>(); // HashSet<Transition> allExploredTrans = new HashSet<Transition>(); // exploredTransQueue.add(tran); // //boolean foundEnabledTran = false; // HashSet<Transition> canEnable = new HashSet<Transition>(); // while(!exploredTransQueue.isEmpty()){ // Transition curTran = exploredTransQueue.poll(); // allExploredTrans.add(curTran); // if (cachedNecessarySets.containsKey(curTran)) { // if (Options.getDebugMode()) { // writeStringWithEndOfLineToPORDebugFile("Found transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" // + "'s necessary set in the cached necessary sets. Terminate BFS."); // return cachedNecessarySets.get(curTran); // canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // // Decide if canSetEnablingTrue set can help to enable curTran. // Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); // int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector(); // if (curTransition.getEnablingTree() != null // && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) { // canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue()); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to set the enabling of transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // writeIntegerSetToPORDebugFile(staticMap.get(curTran).getEnableBySettingEnablingTrue(), lpnList, "Neighbors that can help to set the enabling transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // for (Transition neighborTran : canEnable) { // if (curEnabled.contains(neighborTran)) { // if (!neighborTran.equals(seedTran)) { // HashSet<Transition> necessarySet = new HashSet<Transition>(); // necessarySet.add(neighborTran); // // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed? // cachedNecessarySets.put(tran, necessarySet); // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // return necessarySet; // else if (neighborTran.equals(seedTran) && canEnable.size()==1) { // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // return null; //// if (exploredTransQueue.isEmpty()) { //// System.out.println("exploredTransQueue is empty. Return null necessary set."); //// writeStringWithNewLineToPORDebugFile("exploredTransQueue is empty. Return null necessary set."); //// return null; // if (!allExploredTrans.contains(neighborTran)) { // allExploredTrans.add(neighborTran); // exploredTransQueue.add(neighborTran); // canEnable.clear(); // return null; private void writeCachedNecessarySetsToPORDebugFile() { writeStringWithEndOfLineToPORDebugFile("================ cached necessary sets ================="); for (Transition key : cachedNecessarySets.keySet()) { writeStringToPORDebugFile(key.getLpn().getLabel() + "(" + key.getLabel() + ") => "); for (Transition necessary : cachedNecessarySets.get(key)) { writeStringToPORDebugFile(necessary.getLpn().getLabel() + "(" + necessary.getLabel() + ") "); } writeStringWithEndOfLineToPORDebugFile(""); } } private HashSet<Transition> setSubstraction( HashSet<Transition> left, HashSet<Transition> right) { HashSet<Transition> sub = new HashSet<Transition>(); for (Transition lpnTranPair : left) { if (!right.contains(lpnTranPair)) sub.add(lpnTranPair); } return sub; } public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); if(stateArray[lpnIndex].equals(curState)) {// (stateArray[lpnIndex] == curState) { isStateOnStack = true; break; } } return isStateOnStack; } private void writeIntegerSetToPORDebugFile(HashSet<Transition> Trans, String setName) { if (!setName.isEmpty()) writeStringToPORDebugFile(setName + ": "); if (Trans == null) { writeStringWithEndOfLineToPORDebugFile("null"); } else if (Trans.isEmpty()) { writeStringWithEndOfLineToPORDebugFile("empty"); } else { for (Transition lpnTranPair : Trans) { writeStringToPORDebugFile(lpnTranPair.getLpn().getLabel() + "(" + lpnTranPair.getLabel() + "),"); } writeStringWithEndOfLineToPORDebugFile(""); } } // private void writeIntegerSetToPORDebugFile(HashSet<Transition> trans, String setName) { // if (!setName.isEmpty()) // writeStringToPORDebugFile(setName + ": "); // if (trans == null) { // writeStringWithEndOfLineToPORDebugFile("null"); // else if (trans.isEmpty()) { // writeStringWithEndOfLineToPORDebugFile("empty"); // else { // for (Transition lpnTranPair : trans) { // writeStringToPORDebugFile(lpnTranPair.getLpn().getLabel() + "(" // + lpnTranPair.getName() + "),"); // writeStringWithEndOfLineToPORDebugFile(""); private void writeIntegerSetToPORDebugFile(ArrayList<HashSet<Transition>> transSet, String setName) { if (!setName.isEmpty()) writeStringToPORDebugFile(setName + ": "); if (transSet == null) { writeStringWithEndOfLineToPORDebugFile("null"); } else if (transSet.isEmpty()) { writeStringWithEndOfLineToPORDebugFile("empty"); } else { for (HashSet<Transition> lpnTranPairSet : transSet) { for (Transition lpnTranPair : lpnTranPairSet) writeStringToPORDebugFile(lpnTranPair.getLpn().getLabel() + "(" + lpnTranPair.getLabel() + "),"); } writeStringWithEndOfLineToPORDebugFile(""); } } }
package verification.platu.logicAnalysis; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import javax.swing.JOptionPane; import lpn.parser.Abstraction; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.LpnDecomposition.LpnProcess; import main.Gui; import verification.platu.MDD.MDT; import verification.platu.MDD.Mdd; import verification.platu.MDD.mddNode; import verification.platu.common.IndexObjMap; import verification.platu.lpn.LPNTranRelation; import verification.platu.lpn.LpnTranList; import verification.platu.main.Options; import verification.platu.markovianAnalysis.ProbGlobalState; import verification.platu.markovianAnalysis.ProbGlobalStateSet; import verification.platu.markovianAnalysis.ProbLocalStateGraph; import verification.platu.partialOrders.DependentSet; import verification.platu.partialOrders.DependentSetComparator; import verification.platu.partialOrders.StaticSets; import verification.platu.por1.AmpleSet; import verification.platu.project.PrjState; import verification.platu.stategraph.State; import verification.platu.stategraph.StateGraph; import verification.timed_state_exploration.zoneProject.EventSet; import verification.timed_state_exploration.zoneProject.TimedPrjState; import verification.timed_state_exploration.zoneProject.TimedStateSet; import verification.timed_state_exploration.zoneProject.Zone; public class Analysis { private LinkedList<Transition> traceCex; protected Mdd mddMgr = null; private HashMap<Transition, HashSet<Transition>> cachedNecessarySets = new HashMap<Transition, HashSet<Transition>>(); /* * visitedTrans is used in computeNecessary for a disabled transition of interest, to keep track of all transitions visited during trace-back. */ private HashSet<Transition> visitedTrans; HashMap<Transition, StaticSets> staticDependency = new HashMap<Transition, StaticSets>(); public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) { traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); if (method.equals("dfs")) { //if (Options.getPOR().equals("off")) { //this.search_dfs(lpnList, initStateArray); //this.search_dfs_mdd_1(lpnList, initStateArray); //this.search_dfs_mdd_2(lpnList, initStateArray); //else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); } else if (method.equals("bfs")==true) this.search_bfs(lpnList, initStateArray); else if (method == "dfs_noDisabling") //this.search_dfs_noDisabling(lpnList, initStateArray); this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * This constructor performs dfs. * @param lpnList */ public Analysis(StateGraph[] lpnList){ traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); // if (method.equals("dfs")) { // if (Options.getPOR().equals("off")) { // //this.search_dfs(lpnList, initStateArray); // this.search_dfsNative(lpnList, initStateArray); // //this.search_dfs_mdd_1(lpnList, initStateArray); // //this.search_dfs_mdd_2(lpnList, initStateArray); // else // //behavior analysis // boolean BA = true; // if(BA==true) // CompositionalAnalysis.searchCompositional(lpnList); // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); // else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "lpn"); // else if (method.equals("bfs")==true) // this.search_bfs(lpnList, initStateArray); // else if (method == "dfs_noDisabling") // //this.search_dfs_noDisabling(lpnList, initStateArray); // this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * Recursively find all reachable project states. */ int iterations = 0; int stack_depth = 0; int max_stack_depth = 0; public void search_recursive(final StateGraph[] lpnList, final State[] curPrjState, final ArrayList<LinkedList<Transition>> enabledList, HashSet<PrjState> stateTrace) { int lpnCnt = lpnList.length; HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); stack_depth++; if (stack_depth > max_stack_depth) max_stack_depth = stack_depth; iterations++; if (iterations % 50000 == 0) System.out.println("iterations: " + iterations + ", # of prjStates found: " + prjStateSet.size() + ", max_stack_depth: " + max_stack_depth); for (int index = 0; index < lpnCnt; index++) { LinkedList<Transition> curEnabledSet = enabledList.get(index); if (curEnabledSet == null) continue; for (Transition firedTran : curEnabledSet) { // while(curEnabledSet.size() != 0) { // LPNTran firedTran = curEnabledSet.removeFirst(); // TODO: (check) Not sure if lpnList[index] is correct State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran); // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. PrjState nextPrjState = new PrjState(nextStateArray); if (stateTrace.contains(nextPrjState) == true) ;// System.out.println("found a cycle"); if (prjStateSet.add(nextPrjState) == false) { continue; } // Get the list of enabled transition sets, and call // findsg_recursive. ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>(); for (int i = 0; i < lpnCnt; i++) { if (curPrjState[i] != nextStateArray[i]) { StateGraph Lpn_tmp = lpnList[i]; nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran, // enabledList.get(i), // false)); } else { nextEnabledList.add(i, enabledList.get(i)); } } stateTrace.add(nextPrjState); search_recursive(lpnList, nextStateArray, nextEnabledList, stateTrace); stateTrace.remove(nextPrjState); } } } /** * An iterative implement of findsg_recursive(). * * @param sgList * @param start * @param curLocalStateArray * @param enabledArray */ @SuppressWarnings("unchecked") public StateSetInterface search_dfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println(" System.out.println("---> calling function search_dfs"); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; //Stack<State[]> stateStack = new Stack<State[]>(); HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); //HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // Set of PrjStates that have been seen before. Set class documentation // for how it behaves. Timing Change. // HashMap<PrjState, PrjState> prjStateSet = generateStateSet(); StateSetInterface prjStateSet = generateStateSet(); PrjState initPrjState; // Create the appropriate type for the PrjState depending on whether timing is // being used or not. Timing Change. if(!Options.getTimingAnalysisFlag()){ // If not doing timing. if (!Options.getMarkovianModelFlag()) initPrjState = new PrjState(initStateArray); else initPrjState = new ProbGlobalState(initStateArray); } else{ // If timing is enabled. initPrjState = new TimedPrjState(initStateArray); // Set the initial values of the inequality variables. //((TimedPrjState) initPrjState).updateInequalityVariables(); } prjStateSet.add(initPrjState); //prjStateSet.put(initPrjState, initPrjState); if(Options.getMarkovianModelFlag()) ((ProbGlobalStateSet) prjStateSet).setInitState(initPrjState); PrjState stateStackTop; stateStackTop = initPrjState; if (Options.getDebugMode()) printStateArray(stateStackTop.toStateArray(), "~~~~ stateStackTop ~~~~"); stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) printDstLpnList(sgList); LpnTranList initEnabled; if(!Options.getTimingAnalysisFlag()){ // Timing Change. initEnabled = sgList[0].getEnabledFromTranVector(initStateArray[0]); // The init } else { // When timing is enabled, it is the project state that will determine // what is enabled since it contains the zone. This indicates the zeroth zone // contained in the project and the zeroth LPN to get the transitions from. initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0); } lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); if (Options.getDebugMode()) { System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); printTransList(initEnabled, "initEnabled"); } main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); if (failureTranIsEnabled(curEnabled)) { return null; } if (Options.getDebugMode()) { printStateArray(curStateArray, " printTransList(curEnabled, "+++++++ curEnabled trans ++++++++"); } // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); if (Options.getDebugMode()) { System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); printTranStack(lpnTranStack, "***** lpnTranStack *****"); } curIndexStack.pop(); curIndex++; while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); if(!Options.getTimingAnalysisFlag()){ // Timing Change curEnabled = sgList[curIndex].getEnabledFromTranVector(curStateArray[curIndex]).clone(); } else{ // Get the enabled transitions from the zone that are associated with // the current LPN. curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex); } if (curEnabled.size() > 0) { if (Options.getDebugMode()) { printTransList(curEnabled, "+++++++ Push trans onto lpnTranStack ++++++++"); } lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); break; } curIndex++; } } if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "~~~~ Remove stateStackTop from stateStack ~~~~"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curEnabled.removeLast(); if (Options.getDebugMode()) { System.out.println(" System.out.println("Fired transition: " + firedTran.getFullLabel()); System.out.println(" } State[] nextStateArray; PrjState nextPrjState; // Moved this definition up. Timing Change. // The next state depends on whether timing is in use or not. // Timing Change. if(!Options.getTimingAnalysisFlag()){ nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); if (!Options.getMarkovianModelFlag()) nextPrjState = new PrjState(nextStateArray); else nextPrjState = new ProbGlobalState(nextStateArray); } else{ // Get the next timed state and extract the next un-timed states. nextPrjState = sgList[curIndex].fire(sgList, stateStackTop, (EventSet) firedTran); nextStateArray = nextPrjState.toStateArray(); } tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns]; LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns]; for (int i = 0; i < numLpns; i++) { LinkedList<Transition> enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sgList[i].getEnabledFromTranVector(curStateArray[i]); } else{ // Get the enabled transitions from the Zone for the appropriate // LPN. //enabledList = ((TimedPrjState) stateStackTop).getEnabled(i); enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i); } curEnabledArray[i] = enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sgList[i].getEnabledFromTranVector(nextStateArray[i]); } else{ //enabledList = ((TimedPrjState) nextPrjState).getEnabled(i); enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i); } nextEnabledArray[i] = enabledList; // TODO: (temp) Stochastic model does not need disabling error? if (Options.getReportDisablingError() && !Options.getMarkovianModelFlag()) { Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } if(!Options.getTimingAnalysisFlag()){ if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } } else{ if (Analysis.deadLock(sgList, nextStateArray) == true){ System.out.println("*** Verification failed: deadlock."); failure = true; JOptionPane.showMessageDialog(Gui.frame, "The system deadlocked.", "Error", JOptionPane.ERROR_MESSAGE); break main_while_loop; } } //PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change. Boolean existingState; existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState); //existingState = prjStateSet.keySet().contains(nextPrjState); //|| stateStack.contains(nextPrjState); if (existingState == false) { prjStateSet.add(nextPrjState); //prjStateSet.put(nextPrjState,nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getMarkovianModelFlag()) { if (Options.getBuildGlobalStateGraph()) { // Add <firedTran, nextPrjState> to stateStackTop's nextGlobalStateMap. ((ProbGlobalState) stateStackTop).addNextGlobalState(firedTran, nextPrjState); } } else { if (Options.getDebugMode()) { // printStateArray(curStateArray); // printStateArray(nextStateArray); // System.out.println("stateStackTop: "); // printStateArray(stateStackTop.toStateArray()); // System.out.println("firedTran = " + firedTran.getName()); // printNextStateMap(stateStackTop.getNextStateMap()); } } stateStackTop = nextPrjState; stateStack.add(stateStackTop); lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); curIndexStack.push(0); totalStates++; if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "~~~~~~~ Add global state to stateStack ~~~~~~~"); System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); printTransList(nextEnabledArray[0], ""); printTranStack(lpnTranStack, "******** lpnTranStack ***********"); } } else { // existingState == true if (Options.getMarkovianModelFlag()) { if (Options.getBuildGlobalStateGraph()) { // Add <firedTran, nextPrjState> to stateStackTop's nextGlobalStateMap. ((ProbGlobalState) stateStackTop).addNextGlobalState(firedTran, nextPrjState); } } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { printStateArray(curStateArray, "******* curStateArray *******"); printStateArray(nextStateArray, "******* nextStateArray *******"); printStateArray(stateStackTop.toStateArray(), "stateStackTop: "); System.out.println("firedTran = " + firedTran.getFullLabel()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextGlobalStateMap(stateStackTop.getNextStateMap()); } } } } } double totalStateCnt =0; totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStateCnt + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if(Options.getTimingAnalysisFlag() && !failure){ JOptionPane.showMessageDialog(Gui.frame, "Verification was successful.", "Success", JOptionPane.INFORMATION_MESSAGE); System.out.println(prjStateSet.toString()); } if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { System.out.println("outputSGPath = " + Options.getPrjSgPath()); // TODO: Andrew: I don't think you need the toHashSet() now. //drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true); drawGlobalStateGraph(sgList, initPrjState, prjStateSet, true); } // try{ // File stateFile = new File(Options.getPrjSgPath() + Options.getLogName() + ".txt"); // FileWriter fileWritter = new FileWriter(stateFile,true); // BufferedWriter bufferWritter = new BufferedWriter(fileWritter); // // TODO: Need to merge variable vectors from different local states. // ArrayList<Integer> vector; // String curPrjStInfo = ""; // for (PrjState prjSt : prjStateSet) { // // marking // curPrjStInfo += "marking: "; // for (State localSt : prjSt.toStateArray()) // curPrjStInfo += intArrayToString("markings", localSt) + "\n"; // // variable vector // curPrjStInfo += "var values: "; // for (State localSt : prjSt.toStateArray()) { // localSt.getLpn().getAllVarsWithValuesAsInt(localSt.getVariableVector()); // //curPrjStInfo += intArrayToString("vars", localSt)+ "\n"; // // tranVector // curPrjStInfo += "tran vector: "; // for (State localSt : prjSt.toStateArray()) // curPrjStInfo += boolArrayToString("enabled trans", localSt)+ "\n"; // bufferWritter.write(curPrjStInfo); // //bufferWritter.flush(); // bufferWritter.close(); // System.out.println("Done writing state file."); // }catch(IOException e){ // e.printStackTrace(); //return sgList; return prjStateSet; } // private boolean failureCheck(LinkedList<Transition> curEnabled) { // boolean failureTranIsEnabled = false; // for (Transition tran : curEnabled) { // if (tran.isFail()) { // JOptionPane.showMessageDialog(Gui.frame, // "Failure transition " + tran.getLabel() + " is enabled.", "Error", // JOptionPane.ERROR_MESSAGE); // failureTranIsEnabled = true; // break; // return failureTranIsEnabled; // /** // * Generates the appropriate version of a HashSet<PrjState> for storing // * the "already seen" set of project states. // * @return // * Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet // * depending on the type. // */ // private HashSet<PrjState> generateStateSet(){ // boolean timed = Options.getTimingAnalysisFlag(); // boolean subsets = Zone.getSubsetFlag(); // boolean supersets = Zone.getSupersetFlag(); // if(Options.getMarkovianModelFlag()){ // return new ProbGlobalStateSet(); // else if(timed && (subsets || supersets)){ // return new TimedStateSet(); // return new HashSet<PrjState>(); /** * Generates the appropriate version of a HashSet<PrjState> for storing * the "already seen" set of project states. * @return * Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet * depending on the type. */ private StateSetInterface generateStateSet(){ boolean timed = Options.getTimingAnalysisFlag(); boolean subsets = Zone.getSubsetFlag(); boolean supersets = Zone.getSupersetFlag(); if(Options.getMarkovianModelFlag()){ return new ProbGlobalStateSet(); } else if(timed && (subsets || supersets)){ return new TimedStateSet(); } return new HashSetWrapper(); } private boolean failureTranIsEnabled(LinkedList<Transition> curAmpleTrans) { boolean failureTranIsEnabled = false; for (Transition tran : curAmpleTrans) { if (tran.isFail()) { if(Zone.get_writeLogFile() != null){ try { Zone.get_writeLogFile().write(tran.getLabel()); Zone.get_writeLogFile().newLine(); } catch (IOException e) { e.printStackTrace(); } } JOptionPane.showMessageDialog(Gui.frame, "Failure transition " + tran.getLabel() + " is enabled.", "Error", JOptionPane.ERROR_MESSAGE); failureTranIsEnabled = true; break; } } return failureTranIsEnabled; } public void drawGlobalStateGraph(StateGraph[] sgList, PrjState initGlobalState, StateSetInterface prjStateSet, boolean fullSG) { try { String fileName = null; if (fullSG) { fileName = Options.getPrjSgPath() + "full_sg.dot"; } else { fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_" + Options.getCycleClosingMthd().toLowerCase() + "_" + Options.getCycleClosingAmpleMethd().toLowerCase() + "_sg.dot"; } BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); NumberFormat num = NumberFormat.getNumberInstance();//NumberFormat.getInstance(); num.setMaximumFractionDigits(6); num.setGroupingUsed(false); out.write("digraph G {\n"); for (PrjState curGlobalState : prjStateSet) { // Build composite current global state. String curVarNames = ""; String curVarValues = ""; String curMarkings = ""; String curEnabledTrans = ""; String curGlobalStateIndex = ""; String curGlobalStateProb = null; HashMap<String, Integer> vars = new HashMap<String, Integer>(); for (State curLocalState : curGlobalState.toStateArray()) { curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex(); curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length()); LhpnFile curLpn = curLocalState.getLpn(); for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) { vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVariableVector()[i]); } curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState); if (!boolArrayToString("enabled trans", curLocalState).equals("")) curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); curVarValues = curVarValues + vValue + ", "; curVarNames = curVarNames + vName + ", "; } if (!curVarNames.isEmpty() && !curVarValues.isEmpty()) { curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(",")); curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(",")); } curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length()); curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length()); if (Options.getMarkovianModelFlag()) { // State probability after steady state analysis. curGlobalStateProb = num.format(((ProbGlobalState) curGlobalState).getCurrentProb()); } if (curGlobalState.equals(initGlobalState)) { out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n"); if (!Options.getMarkovianModelFlag()) out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\", style=filled]\n"); else out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\", style=filled]\n"); } else { if (!Options.getMarkovianModelFlag()) out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n"); else out.write(curGlobalStateIndex + "[shape=ellipse,label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\"]\n"); } //curGlobalState // Build composite next global states. for (Transition outTran : curGlobalState.getOutgoingTrans()) { PrjState nextGlobalState = curGlobalState.getNextPrjState(outTran, (HashMap<PrjState, PrjState>) prjStateSet); String nextVarNames = ""; String nextVarValues = ""; String nextMarkings = ""; String nextEnabledTrans = ""; String nextGlobalStateIndex = ""; String nextGlobalStateProb = null; for (State nextLocalState : nextGlobalState.toStateArray()) { LhpnFile nextLpn = nextLocalState.getLpn(); for(int i = 0; i < nextLpn.getVarIndexMap().size(); i++) { vars.put(nextLpn.getVarIndexMap().getKey(i), nextLocalState.getVariableVector()[i]); } nextMarkings = nextMarkings + "," + intArrayToString("markings", nextLocalState); if (!boolArrayToString("enabled trans", nextLocalState).equals("")) nextEnabledTrans = nextEnabledTrans + "," + boolArrayToString("enabled trans", nextLocalState); nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); nextVarValues = nextVarValues + vValue + ", "; nextVarNames = nextVarNames + vName + ", "; } if (!nextVarNames.isEmpty() && !nextVarValues.isEmpty()) { nextVarNames = nextVarNames.substring(0, nextVarNames.lastIndexOf(",")); nextVarValues = nextVarValues.substring(0, nextVarValues.lastIndexOf(",")); } nextMarkings = nextMarkings.substring(nextMarkings.indexOf(",")+1, nextMarkings.length()); nextEnabledTrans = nextEnabledTrans.substring(nextEnabledTrans.indexOf(",")+1, nextEnabledTrans.length()); nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length()); if (Options.getMarkovianModelFlag()) { // State probability after steady state analysis. nextGlobalStateProb = num.format(((ProbGlobalState) nextGlobalState).getCurrentProb()); out.write(nextGlobalStateIndex + "[shape=ellipse,label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\\nProb = " + nextGlobalStateProb + "\"]\n"); } else out.write(nextGlobalStateIndex + "[shape=ellipse,label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\"]\n"); String outTranName = outTran.getLabel(); if (!Options.getMarkovianModelFlag()) { if (outTran.isFail() && !outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n"); else if (!outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n"); else if (outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n"); else out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n"); } else { State localState = curGlobalState.toStateArray()[outTran.getLpn().getLpnIndex()]; String outTranRate = num.format(((ProbLocalStateGraph) localState.getStateGraph()).getTranRate(localState, outTran)); if (outTran.isFail() && !outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=red]\n"); else if (!outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=blue]\n"); else if (outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=purple]\n"); else out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\\n" + outTranRate + "\"]\n"); } } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void drawDependencyGraphs(LhpnFile[] lpnList) { String fileName = Options.getPrjSgPath() + "dependencyGraph.dot"; BufferedWriter out; try { out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (Transition curTran : staticDependency.keySet()) { String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel(); out.write(curTranStr + "[shape=\"box\"];"); out.newLine(); } for (Transition curTran : staticDependency.keySet()) { StaticSets curStaticSets = staticDependency.get(curTran); String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel(); for (Transition curTranInDisable : curStaticSets.getOtherTransDisableCurTranSet()) { String curTranInDisableStr = curTranInDisable.getLpn().getLabel() + "_" + curTranInDisable.getLabel(); out.write(curTranInDisableStr + "->" + curTranStr + "[color=\"chocolate\"];"); out.newLine(); } // for (Transition curTranInDisable : curStaticSets.getCurTranDisableOtherTransSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"chocolate\"];"); // out.newLine(); // for (Transition curTranInDisable : curStaticSets.getDisableSet()) { // String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel() // + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName(); // out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"blue\"];"); // out.newLine(); HashSet<Transition> enableByBringingToken = new HashSet<Transition>(); for (Place p : curTran.getPreset()) { for (Transition presetTran : p.getPreset()) { enableByBringingToken.add(presetTran); } } for (Transition curTranInCanEnable : enableByBringingToken) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"mediumaquamarine\"];"); out.newLine(); } for (HashSet<Transition> canEnableOneConjunctSet : curStaticSets.getOtherTransSetCurTranEnablingTrue()) { for (Transition curTranInCanEnable : canEnableOneConjunctSet) { String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel(); out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"deepskyblue\"];"); out.newLine(); } } } out.write("}"); out.close(); } catch (IOException e) { e.printStackTrace(); } } private String intArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("markings")) { for (int i=0; i< curState.getMarking().length; i++) { if (curState.getMarking()[i] == 1) { arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ","; } // String tranName = curState.getLpn().getAllTransitions()[i].getName(); // if (curState.getTranVector()[i]) // System.out.println(tranName + " " + "Enabled"); // else // System.out.println(tranName + " " + "Not Enabled"); } arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } else if (type.equals("vars")) { for (int i=0; i< curState.getVariableVector().length; i++) { arrayStr = arrayStr + curState.getVariableVector()[i] + ","; } if (arrayStr.contains(",")) arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private String boolArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("enabled trans")) { for (int i=0; i< curState.getTranVector().length; i++) { if (curState.getTranVector()[i]) { //arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getFullLabel() + ", "; arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getLabel() + ", "; } } if (arrayStr != "") arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private void printStateArray(State[] stateArray, String title) { if (title != null) System.out.println(title); for (int i=0; i<stateArray.length; i++) { System.out.println("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +"): "); System.out.println("\tmarkings: " + intArrayToString("markings", stateArray[i])); System.out.println("\tvar values: " + intArrayToString("vars", stateArray[i])); System.out.println("\tenabled trans: " + boolArrayToString("enabled trans", stateArray[i])); } System.out.println(" } private void printTransList(LinkedList<Transition> tranList, String title) { if (title != null) System.out.println("+++++++" + title + "+++++++"); for (int i=0; i< tranList.size(); i++) System.out.println(tranList.get(i).getFullLabel() + ", "); System.out.println("+++++++++++++"); } // private void writeIntegerStackToDebugFile(Stack<Integer> curIndexStack, String title) { // if (title != null) // System.out.println(title); // for (int i=0; i < curIndexStack.size(); i++) { // System.out.println(title + "[" + i + "]" + curIndexStack.get(i)); private void printDstLpnList(StateGraph[] lpnList) { System.out.println("++++++ dstLpnList ++++++"); for (int i=0; i<lpnList.length; i++) { LhpnFile curLPN = lpnList[i].getLpn(); System.out.println("LPN: " + curLPN.getLabel()); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j< allTrans.length; j++) { System.out.println(allTrans[j].getLabel() + ": "); for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) { System.out.println(allTrans[j].getDstLpnList().get(k).getLabel() + ","); } System.out.print("\n"); } System.out.println(" } System.out.println("++++++++++++++++++++"); } private void constructDstLpnList(StateGraph[] sgList) { for (int i=0; i<sgList.length; i++) { LhpnFile curLPN = sgList[i].getLpn(); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j<allTrans.length; j++) { Transition curTran = allTrans[j]; for (int k=0; k<sgList.length; k++) { curTran.setDstLpnList(sgList[k].getLpn()); } } } } /** * This method performs first-depth search on an array of LPNs and applies partial order reduction technique with trace-back on LPNs. * @param sgList * @param initStateArray * @param cycleClosingMthdIndex * @return */ @SuppressWarnings("unchecked") public StateGraph[] searchPOR_taceback(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function searchPOR_traceback"); System.out.println("---> " + Options.getPOR()); System.out.println("---> " + Options.getCycleClosingMthd()); System.out.println("---> " + Options.getCycleClosingAmpleMethd()); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; LhpnFile[] lpnList = new LhpnFile[numLpns]; for (int i=0; i<numLpns; i++) { lpnList[i] = sgList[i].getLpn(); } HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); prjStateSet.add(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) printStateArray(stateStackTop.toStateArray(), "%%%%%%% stateStackTop %%%%%%%%"); stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) printDstLpnList(sgList); // Find static pieces for POR. HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length); //HashMap<Transition, StaticSets> staticSetsMap = new HashMap<Transition, StaticSets>(); HashMap<Transition, Integer> allProcessTransInOneLpn = new HashMap<Transition, Integer>(); HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses = new HashMap<Transition, LpnProcess>(); for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { allTransitions.put(lpnIndex, lpnList[lpnIndex].getAllTransitions()); Abstraction abs = new Abstraction(lpnList[lpnIndex]); abs.decomposeLpnIntoProcesses(); allProcessTransInOneLpn = (HashMap<Transition, Integer>)abs.getTransWithProcIDs(); HashMap<Integer, LpnProcess> processMapForOneLpn = new HashMap<Integer, LpnProcess>(); for (Transition curTran: allProcessTransInOneLpn.keySet()) { Integer procId = allProcessTransInOneLpn.get(curTran); if (!processMapForOneLpn.containsKey(procId)) { LpnProcess newProcess = new LpnProcess(procId); newProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (newProcess.getStateMachineFlag() && ((curTran.getPreset().length > 1) || (curTran.getPostset().length > 1))) { newProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { newProcess.addPlaceToProcess(p); } } processMapForOneLpn.put(procId, newProcess); allTransitionsToLpnProcesses.put(curTran, newProcess); } else { LpnProcess curProcess = processMapForOneLpn.get(procId); curProcess.addTranToProcess(curTran); if (curTran.getPreset() != null) { if (curProcess.getStateMachineFlag() && (curTran.getPreset().length > 1 || curTran.getPostset().length > 1)) { curProcess.setStateMachineFlag(false); } Place[] preset = curTran.getPreset(); for (Place p : preset) { curProcess.addPlaceToProcess(p); } } allTransitionsToLpnProcesses.put(curTran, curProcess); } } } HashMap<Transition, Integer> tranFiringFreq = null; if (Options.getUseDependentQueue()) tranFiringFreq = new HashMap<Transition, Integer>(allTransitions.keySet().size()); // Need to build conjuncts for each transition's enabling condition first before dealing with dependency and enable sets. for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { for (Transition curTran: allTransitions.get(lpnIndex)) { if (curTran.getEnablingTree() != null) curTran.buildConjunctsOfEnabling(curTran.getEnablingTree()); } } for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { if (Options.getDebugMode()) { System.out.println("=======LPN = " + lpnList[lpnIndex].getLabel() + "======="); } for (Transition curTran: allTransitions.get(lpnIndex)) { StaticSets curStatic = new StaticSets(curTran, allTransitionsToLpnProcesses); curStatic.buildOtherTransSetCurTranEnablingTrue(); curStatic.buildCurTranDisableOtherTransSet(); if (Options.getPORdeadlockPreserve()) curStatic.buildOtherTransDisableCurTranSet(); else curStatic.buildModifyAssignSet(); staticDependency.put(curTran, curStatic); if (Options.getUseDependentQueue()) tranFiringFreq.put(curTran, 0); } } if (Options.getDebugMode()) { printStaticSetsMap(lpnList); } //boolean init = true; //LpnTranList initAmpleTrans = new LpnTranList(); LpnTranList initAmpleTrans = getAmple(initStateArray, null, tranFiringFreq, sgList, lpnList, stateStack, stateStackTop); lpnTranStack.push(initAmpleTrans); //init = false; if (Options.getDebugMode()) { printTransList(initAmpleTrans, "+++++++ Push trans onto lpnTranStack @ 1++++++++"); drawDependencyGraphs(lpnList); } // HashSet<Transition> initAmple = new HashSet<Transition>(); // for (Transition t: initAmpleTrans) { // initAmple.add(t); updateLocalAmpleTbl(initAmpleTrans, sgList, initStateArray); main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); if (failureTranIsEnabled(curAmpleTrans)) { return null; } if (curAmpleTrans.size() == 0) { lpnTranStack.pop(); prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); printTranStack(lpnTranStack, " System.out.println(" printPrjStateSet(prjStateSet); System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curAmpleTrans.removeLast(); //Transition firedTran = curAmpleTrans.removelast(); if (Options.getDebugMode()) { System.out.println(" System.out.println("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getLabel() + ")"); System.out.println(" } if (Options.getUseDependentQueue()) { Integer freq = tranFiringFreq.get(firedTran) + 1; tranFiringFreq.put(firedTran, freq); // if (Options.getDebugMode()) { // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, sgList); } State[] nextStateArray = sgList[firedTran.getLpn().getLpnIndex()].fire(sgList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. if (Options.getReportDisablingError()) { for (int i=0; i<numLpns; i++) { Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } LpnTranList nextAmpleTrans = new LpnTranList(); nextAmpleTrans = getAmple(curStateArray, nextStateArray, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop); // check for possible deadlock if (nextAmpleTrans.size() == 0) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } PrjState nextPrjState = new PrjState(nextStateArray); Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); if (existingState == false) { if (Options.getDebugMode()) { System.out.println("%%%%%%% existingSate == false %%%%%%%%"); printStateArray(curStateArray, "******* curStateArray *******"); printStateArray(nextStateArray, "******* nextStateArray *******"); printStateArray(stateStackTop.toStateArray(), "stateStackTop"); System.out.println("firedTran = " + firedTran.getFullLabel()); // printNextGlobalStateMap(stateStackTop.getNextStateMap()); System.out.println(" } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add global state to stateStack %%%%%%%%"); printTransList(nextAmpleTrans, "+++++++ Push trans onto lpnTranStack @ 2++++++++"); } lpnTranStack.push((LinkedList<Transition>) nextAmpleTrans.clone()); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { printStateArray(curStateArray, "******* curStateArray *******"); printStateArray(nextStateArray, "******* nextStateArray *******"); System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray(), "stateStackTop: "); System.out.println("firedTran = " + firedTran.getFullLabel()); // System.out.println("nextStateMap for stateStackTop before firedTran being added: "); // printNextGlobalStateMap(stateStackTop.getNextStateMap()); System.out.println(" } } if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) { // Cycle closing check if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) { if (Options.getDebugMode()) { System.out.println("%%%%%%% Cycle Closing %%%%%%%%"); } HashSet<Transition> nextAmpleSet = new HashSet<Transition>(); HashSet<Transition> curAmpleSet = new HashSet<Transition>(); for (Transition t : nextAmpleTrans) nextAmpleSet.add(t); for (Transition t: curAmpleTrans) curAmpleSet.add(t); curAmpleSet.add(firedTran); HashSet<Transition> newNextAmple = new HashSet<Transition>(); newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticDependency, tranFiringFreq, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack); if (newNextAmple != null && !newNextAmple.isEmpty()) { //LpnTranList newNextAmpleTrans = getLpnTranList(newNextAmple, sgList); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getDebugMode()) { printStateArray(nextPrjState.toStateArray(), "nextPrjState"); // System.out.println( "nextStateMap for nextPrjState"); // printNextGlobalStateMap(nextPrjState.getNextStateMap()); } stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add state to stateStack %%%%%%%%"); System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray(), "stateStackTop"); // System.out.println("nextStateMap for stateStackTop: "); // printNextGlobalStateMap(nextPrjState.getNextStateMap()); } lpnTranStack.push((LinkedList<Transition>) newNextAmple.clone()); if (Options.getDebugMode()) { printTransList((LinkedList<Transition>) newNextAmple.clone(), "+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++"); printTranStack(lpnTranStack, "******* lpnTranStack ***************"); } } } } updateLocalAmpleTbl(nextAmpleTrans, sgList, nextStateArray); } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStateCnt + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { //drawGlobalStateGraph(sgList, prjStateSet, false); } return sgList; } private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt, double peakTotalMem, double peakUsedMem) { try { String fileName = null; if (isPOR) { fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; } else fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log"; BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n"); out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t" + peakUsedMem + "\n"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void printTranStack(Stack<LinkedList<Transition>> lpnTranStack, String title) { if (title != null) System.out.println(title); for (int i=0; i<lpnTranStack.size(); i++) { LinkedList<Transition> tranList = lpnTranStack.get(i); for (int j=0; j<tranList.size(); j++) { System.out.println(tranList.get(j).getFullLabel()); } System.out.println(" } } private void printNextGlobalStateMap(HashMap<Transition, PrjState> nextStateMap) { for (Transition t: nextStateMap.keySet()) { System.out.println(t.getFullLabel() + " -> "); State[] stateArray = nextStateMap.get(t).getStateArray(); for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +")" +", "); } System.out.println(""); } } private LpnTranList convertToLpnTranList(HashSet<Transition> newNextAmple) { LpnTranList newNextAmpleTrans = new LpnTranList(); for (Transition lpnTran : newNextAmple) { newNextAmpleTrans.add(lpnTran); } return newNextAmpleTrans; } private HashSet<Transition> computeCycleClosingTrans(State[] curStateArray, State[] nextStateArray, HashMap<Transition, StaticSets> staticSetsMap, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> prjStateSet, PrjState nextPrjState, HashSet<Transition> nextAmple, HashSet<Transition> curAmple, HashSet<PrjState> stateStack) { for (State s : nextStateArray) if (s == null) throw new NullPointerException(); String cycleClosingMthd = Options.getCycleClosingMthd(); HashSet<Transition> newNextAmple = new HashSet<Transition>(); HashSet<Transition> nextEnabled = new HashSet<Transition>(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { Transition tran = curLpn.getAllTransitions()[i]; if (nextStateArray[lpnIndex].getTranVector()[i]) nextEnabled.add(tran); if (curStateArray[lpnIndex].getTranVector()[i]) curEnabled.add(tran); } } // Cycle closing on global state graph if (Options.getDebugMode()) { //System.out.println("~~~~~~~ existing global state ~~~~~~~~"); } if (cycleClosingMthd.equals("strong")) { newNextAmple.addAll(setSubstraction(curEnabled, nextAmple)); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } else if (cycleClosingMthd.equals("behavioral")) { if (Options.getDebugMode()) { } HashSet<Transition> curReduced = setSubstraction(curEnabled, curAmple); HashSet<Transition> oldNextAmple = new HashSet<Transition>(); DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // TODO: Is oldNextAmple correctly obtained below? if (Options.getDebugMode()) printStateArray(nextStateArray,"******* nextStateArray *******"); for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) { if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) { LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]); if (Options.getDebugMode()) { // printTransitionSet(oldLocalNextAmpleTrans, "oldLocalNextAmpleTrans"); } for (Transition oldLocalTran : oldLocalNextAmpleTrans) oldNextAmple.add(oldLocalTran); } } HashSet<Transition> ignored = setSubstraction(curReduced, oldNextAmple); boolean isCycleClosingAmpleComputation = true; for (Transition seed : ignored) { HashSet<Transition> dependent = new HashSet<Transition>(); dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); } // TODO: Is this still necessary? // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if ((newNextAmple.size() == 0 || dependent.size() < newNextAmple.size()) && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); DependentSet dependentSet = new DependentSet(dependent, seed,isDummyTran(seed.getLabel())); dependentSetQueue.add(dependentSet); } cachedNecessarySets.clear(); if (!dependentSetQueue.isEmpty()) { // System.out.println("depdentSetQueue is NOT empty."); // newNextAmple = dependentSetQueue.poll().getDependent(); // TODO: Will newNextAmpleTmp - oldNextAmple be safe? HashSet<Transition> newNextAmpleTmp = dependentSetQueue.poll().getDependent(); newNextAmple = setSubstraction(newNextAmpleTmp, oldNextAmple); updateLocalAmpleTbl(convertToLpnTranList(newNextAmple), sgList, nextStateArray); } if (Options.getDebugMode()) { // printIntegerSet(newNextAmple, sgList, "newNextAmple"); } } else if (cycleClosingMthd.equals("state_search")) { // TODO: complete cycle closing check for state search. } return newNextAmple; } private void updateLocalAmpleTbl(LpnTranList nextAmpleTrans, StateGraph[] sgList, State[] nextStateArray) { // Ample set at each state is stored in the enabledSetTbl in each state graph. for (Transition lpnTran : nextAmpleTrans) { State nextState = nextStateArray[lpnTran.getLpn().getLpnIndex()]; LpnTranList a = sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().get(nextState); if (a != null) { if (!a.contains(lpnTran)) a.add(lpnTran); } else { LpnTranList newLpnTranList = new LpnTranList(); newLpnTranList.add(lpnTran); sgList[lpnTran.getLpn().getLpnIndex()].getEnabledSetTbl().put(nextStateArray[lpnTran.getLpn().getLpnIndex()], newLpnTranList); if (Options.getDebugMode()) { // System.out.println("@ updateLocalAmpleTbl: "); // System.out.println("Add S" + nextStateArray[lpnTran.getLpnIndex()].getIndex() + " to the enabledSetTbl of " // + sgList[lpnTran.getLpnIndex()].getLpn().getLabel() + "."); } } } if (Options.getDebugMode()) { // printEnabledSetTbl(sgList); } } private void printPrjStateSet(HashSet<PrjState> prjStateSet) { for (PrjState curGlobal : prjStateSet) { State[] curStateArray = curGlobal.toStateArray(); printStateArray(curStateArray, null); System.out.println(" } } // /** // * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back. // * @param sgList // * @param initStateArray // * @param cycleClosingMthdIndex // * @return // */ // public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) { // if (cycleClosingMthdIndex == 1) // else if (cycleClosingMthdIndex == 2) // else if (cycleClosingMthdIndex == 4) // double peakUsedMem = 0; // double peakTotalMem = 0; // boolean failure = false; // int tranFiringCnt = 0; // int totalStates = 1; // int numLpns = sgList.length; // HashSet<PrjState> stateStack = new HashSet<PrjState>(); // Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); // Stack<Integer> curIndexStack = new Stack<Integer>(); // HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // PrjState initPrjState = new PrjState(initStateArray); // prjStateSet.add(initPrjState); // PrjState stateStackTop = initPrjState; // System.out.println("%%%%%%% Add states to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.add(stateStackTop); // // Prepare static pieces for POR // HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>(); // Transition[] allTransitions = sgList[0].getLpn().getAllTransitions(); // HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>(); // HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length); // for (Transition curTran: allTransitions) { // StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions); // curStatic.buildDisableSet(); // curStatic.buildEnableSet(); // curStatic.buildModifyAssignSet(); // tmpMap.put(curTran.getIndex(), curStatic); // tranFiringFreq.put(curTran.getIndex(), 0); // staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap); // printStaticSetMap(staticSetsMap); // System.out.println("call getAmple on initStateArray at 0: "); // boolean init = true; // AmpleSet initAmple = new AmpleSet(); // initAmple = sgList[0].getAmple(initStateArray[0], staticSetsMap, init, tranFiringFreq); // HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl(); // lpnTranStack.push(initAmple.getAmpleSet()); // curIndexStack.push(0); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) initAmple.getAmpleSet(), ""); // main_while_loop: while (failure == false && stateStack.size() != 0) { // System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); // long curTotalMem = Runtime.getRuntime().totalMemory(); // long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); // if (curTotalMem > peakTotalMem) // peakTotalMem = curTotalMem; // if (curUsedMem > peakUsedMem) // peakUsedMem = curUsedMem; // if (stateStack.size() > max_stack_depth) // max_stack_depth = stateStack.size(); // iterations++; // if (iterations % 100000 == 0) { // System.out.println("---> #iteration " + iterations // + "> # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStates // + ", stack_depth: " + stateStack.size() // + " used memory: " + (float) curUsedMem / 1000000 // + " free memory: " // + (float) Runtime.getRuntime().freeMemory() / 1000000); // State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); // int curIndex = curIndexStack.peek(); //// System.out.println("curIndex = " + curIndex); // //AmpleSet curAmple = new AmpleSet(); // //LinkedList<Transition> curAmpleTrans = curAmple.getAmpleSet(); // LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); //// printStateArray(curStateArray); //// System.out.println("+++++++ curAmple trans ++++++++"); //// printTransLinkedList(curAmpleTrans); // // If all enabled transitions of the current LPN are considered, // // then consider the next LPN // // by increasing the curIndex. // // Otherwise, if all enabled transitions of all LPNs are considered, // // then pop the stacks. // if (curAmpleTrans.size() == 0) { // lpnTranStack.pop(); //// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // curIndexStack.pop(); //// System.out.println("+++++++ Pop index off curIndexStack ++++++++"); // curIndex++; //// System.out.println("curIndex = " + curIndex); // while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); // LpnTranList tmpAmpleTrans = (LpnTranList) (sgList[curIndex].getAmple(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getAmpleSet(); // curAmpleTrans = tmpAmpleTrans.clone(); // //printTransitionSet(curEnabled, "curEnabled set"); // if (curAmpleTrans.size() > 0) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransLinkedList(curAmpleTrans); // lpnTranStack.push(curAmpleTrans); // curIndexStack.push(curIndex); // printIntegerStack("curIndexStack after push 1", curIndexStack); // break; // curIndex++; // if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.remove(stateStackTop); // stateStackTop = stateStackTop.getFather(); // continue; // Transition firedTran = curAmpleTrans.removeLast(); // System.out.println(" // System.out.println("Fired transition: " + firedTran.getName()); // System.out.println(" // Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1; // tranFiringFreq.put(firedTran.getIndex(), freq); // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, allTransitions); // State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); // tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. // @SuppressWarnings("unchecked") // LinkedList<Transition>[] curAmpleArray = new LinkedList[numLpns]; // @SuppressWarnings("unchecked") // LinkedList<Transition>[] nextAmpleArray = new LinkedList[numLpns]; // boolean updatedAmpleDueToCycleRule = false; // for (int i = 0; i < numLpns; i++) { // StateGraph sg_tmp = sgList[i]; // System.out.println("call getAmple on curStateArray at 2: i = " + i); // AmpleSet ampleList = new AmpleSet(); // if (init) { // ampleList = initAmple; // sg_tmp.setEnabledSetTbl(initEnabledSetTbl); // init = false; // else // ampleList = sg_tmp.getAmple(curStateArray[i], staticSetsMap, init, tranFiringFreq); // curAmpleArray[i] = ampleList.getAmpleSet(); // System.out.println("call getAmpleRefinedCycleRule on nextStateArray at 3: i = " + i); // ampleList = sg_tmp.getAmpleRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq); // nextAmpleArray[i] = ampleList.getAmpleSet(); // if (!updatedAmpleDueToCycleRule && ampleList.getAmpleChanged()) { // updatedAmpleDueToCycleRule = true; // for (LinkedList<Transition> tranList : curAmpleArray) { // printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : curAmpleArray) { //// printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : nextAmpleArray) { //// printTransLinkedList(tranList); // Transition disabledTran = firedTran.disablingError( // curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); // if (disabledTran != null) { // System.err.println("Disabling Error: " // + disabledTran.getFullLabel() + " is disabled by " // + firedTran.getFullLabel()); // failure = true; // break main_while_loop; // if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) { // failure = true; // break main_while_loop; // PrjState nextPrjState = new PrjState(nextStateArray); // Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); // if (existingState == true && updatedAmpleDueToCycleRule) { // // cycle closing // System.out.println("%%%%%%% existingSate == true %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // if (existingState == false) { // System.out.println("%%%%%%% existingSate == false %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // totalStates++; // // end of main_while_loop // double totalStateCnt = prjStateSet.size(); // System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStateCnt // + ", max_stack_depth: " + max_stack_depth // + ", peak total memory: " + peakTotalMem / 1000000 + " MB" // + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); // // This currently works for a single LPN. // return sgList; // return null; private void printStaticSetsMap( LhpnFile[] lpnList) { System.out.println(" for (Transition lpnTranPair : staticDependency.keySet()) { StaticSets statSets = staticDependency.get(lpnTranPair); printLpnTranPair(statSets.getTran(), statSets.getDisableSet(), "disableSet"); for (HashSet<Transition> setOneConjunctTrue : statSets.getOtherTransSetCurTranEnablingTrue()) { printLpnTranPair(statSets.getTran(), setOneConjunctTrue, "enableBySetingEnablingTrue for one conjunct"); } } } // private Transition[] assignStickyTransitions(LhpnFile lpn) { // // allProcessTrans is a hashmap from a transition to its process color (integer). // HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>(); // // create an Abstraction object to call the divideProcesses method. // Abstraction abs = new Abstraction(lpn); // abs.decomposeLpnIntoProcesses(); // allProcessTrans.putAll( // (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone()); // HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>(); // for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) { // Transition curTran = tranIter.next(); // Integer procId = allProcessTrans.get(curTran); // if (!processMap.containsKey(procId)) { // LpnProcess newProcess = new LpnProcess(procId); // newProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // newProcess.addPlaceToProcess(p); // processMap.put(procId, newProcess); // else { // LpnProcess curProcess = processMap.get(procId); // curProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // curProcess.addPlaceToProcess(p); // for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) { // LpnProcess curProc = processMap.get(processMapIter.next()); // curProc.assignStickyTransitions(); // curProc.printProcWithStickyTrans(); // return lpn.getAllTransitions(); // private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran, // HashSet<Transition> curDisable, String setName) { // System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); // if (curDisable.isEmpty()) { // System.out.println("empty"); // else { // for (Transition lpnTranPair: curDisable) { // System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() // + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); // System.out.print("\n"); private void printLpnTranPair(Transition curTran, HashSet<Transition> TransitionSet, String setName) { System.out.println(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getLabel() + ") is: "); if (TransitionSet.isEmpty()) { System.out.println("empty"); } else { for (Transition lpnTranPair: TransitionSet) System.out.print("(" + lpnTranPair.getLpn().getLabel() + ", " + lpnTranPair.getLabel() + ")," + " "); System.out.println(); } } /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. The enabledSetTbl (for each StateGraph obj) stores the AMPLE set for each state of each LPN. * @param stateArray * @param stateStack * @param enable * @param disableByStealingToken * @param disable * @param sgList * @return */ private LpnTranList getAmple(State[] curStateArray, State[] nextStateArray, HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, LhpnFile[] lpnList, HashSet<PrjState> stateStack, PrjState stateStackTop) { State[] stateArray = null; if (nextStateArray == null) stateArray = curStateArray; else stateArray = nextStateArray; for (State s : stateArray) if (s == null) throw new NullPointerException(); LpnTranList ample = new LpnTranList(); HashSet<Transition> curEnabled = new HashSet<Transition>(); for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { if (stateArray[lpnIndex].getTranVector()[i]) { curEnabled.add(curLpn.getAllTransitions()[i]); } } } if (Options.getDebugMode()) { System.out.println("******* Partial Order Reduction *******"); printIntegerSet(curEnabled, "Enabled set"); System.out.println("******* Begin POR *******"); } if (curEnabled.isEmpty()) { return ample; } HashSet<Transition> ready = partialOrderReduction(stateArray, curEnabled, tranFiringFreq, sgList); if (Options.getDebugMode()) { System.out.println("******* End POR *******"); printIntegerSet(ready, "Ample set"); System.out.println("********************"); } if (tranFiringFreq != null) { LinkedList<Transition> readyList = new LinkedList<Transition>(); for (Transition inReady : ready) { readyList.add(inReady); } mergeSort(readyList, tranFiringFreq); for (Transition inReady : readyList) { ample.addFirst(inReady); } } else { for (Transition tran : ready) { ample.add(tran); } } return ample; } private LinkedList<Transition> mergeSort(LinkedList<Transition> array, HashMap<Transition, Integer> tranFiringFreq) { if (array.size() == 1) return array; int middle = array.size() / 2; LinkedList<Transition> left = new LinkedList<Transition>(); LinkedList<Transition> right = new LinkedList<Transition>(); for (int i=0; i<middle; i++) { left.add(i, array.get(i)); } for (int i=middle; i<array.size();i++) { right.add(i-middle, array.get(i)); } left = mergeSort(left, tranFiringFreq); right = mergeSort(right, tranFiringFreq); return merge(left, right, tranFiringFreq); } private LinkedList<Transition> merge(LinkedList<Transition> left, LinkedList<Transition> right, HashMap<Transition, Integer> tranFiringFreq) { LinkedList<Transition> result = new LinkedList<Transition>(); while (left.size() > 0 || right.size() > 0) { if (left.size() > 0 && right.size() > 0) { if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) { result.addLast(left.poll()); } else { result.addLast(right.poll()); } } else if (left.size()>0) { result.addLast(left.poll()); } else if (right.size()>0) { result.addLast(right.poll()); } } return result; } /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. * @param nextState * @param stateStackTop * @param enable * @param disableByStealingToken * @param disable * @param init * @param cycleClosingMthdIndex * @param lpnIndex * @param isNextState * @return */ private LpnTranList getAmpleRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<Transition,StaticSets> staticSetsMap, boolean init, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> stateStack, PrjState stateStackTop) { // AmpleSet nextAmple = new AmpleSet(); // if (nextState == null) { // throw new NullPointerException(); // if(ampleSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) { // System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~"); // printTransitionSet((LpnTranList)ampleSetTbl.get(nextState), "Old ample at this state: "); // // Cycle closing check // LpnTranList nextAmpleTransOld = (LpnTranList) nextAmple.getAmpleSet(); // nextAmpleTransOld = ampleSetTbl.get(nextState); // LpnTranList curAmpleTrans = ampleSetTbl.get(curState); // LpnTranList curReduced = new LpnTranList(); // LpnTranList curEnabled = curState.getEnabledTransitions(); // for (int i=0; i<curEnabled.size(); i++) { // if (!curAmpleTrans.contains(curEnabled.get(i))) { // curReduced.add(curEnabled.get(i)); // if (!nextAmpleTransOld.containsAll(curReduced)) { // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // printTransitionSet(curEnabled, "curEnabled:"); // printTransitionSet(curAmpleTrans, "curAmpleTrans:"); // printTransitionSet(curReduced, "curReduced:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:"); // printTransitionSet(nextAmpleTransOld, "nextAmpleTransOld:"); // nextAmple.setAmpleChanged(); // HashSet<Transition> curEnabledIndicies = new HashSet<Transition>(); // for (int i=0; i<curEnabled.size(); i++) { // curEnabledIndicies.add(curEnabled.get(i).getIndex()); // // transToAdd = curReduced - nextAmpleOld // LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextAmpleTransOld); // HashSet<Integer> transToAddIndices = new HashSet<Integer>(); // for (int i=0; i<overlyReducedTrans.size(); i++) { // transToAddIndices.add(overlyReducedTrans.get(i).getIndex()); // HashSet<Integer> nextAmpleNewIndices = (HashSet<Integer>) curEnabledIndicies.clone(); // for (Integer tranToAdd : transToAddIndices) { // HashSet<Transition> dependent = new HashSet<Transition>(); // //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd]; // dependent = computeDependent(curState,tranToAdd,dependent,curEnabledIndicies,staticMap); // // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]); // boolean dependentOnlyHasDummyTrans = true; // for (Integer curTranIndex : dependent) { // Transition curTran = this.lpn.getAllTransitions()[curTranIndex]; // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName()); // if (dependent.size() < nextAmpleNewIndices.size() && !dependentOnlyHasDummyTrans) // nextAmpleNewIndices = (HashSet<Integer>) dependent.clone(); // if (nextAmpleNewIndices.size() == 1) // break; // LpnTranList nextAmpleNew = new LpnTranList(); // for (Integer nextAmpleNewIndex : nextAmpleNewIndices) { // nextAmpleNew.add(this.getLpn().getTransition(nextAmpleNewIndex)); // LpnTranList transToAdd = getSetSubtraction(nextAmpleNew, nextAmpleTransOld); // boolean allTransToAddFired = false; // if (cycleClosingMthdIndex == 2) { // // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. // if (transToAdd != null) { // LpnTranList transToAddCopy = transToAdd.copy(); // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // allTransToAddFired = allTransToAddFired(transToAddCopy, // allTransToAddFired, stateVisited, stateStackTop, lpnIndex); // // Update the old ample of the next state // if (!allTransToAddFired || cycleClosingMthdIndex == 1) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(transToAdd); // ampleSetTbl.get(nextState).addAll(transToAdd); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // if (cycleClosingMthdIndex == 4) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(overlyReducedTrans); // ampleSetTbl.get(nextState).addAll(overlyReducedTrans); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // // enabledSetTble stores the ample set at curState. // // The fully enabled set at each state is stored in the tranVector in each state. // return (AmpleSet) nextAmple; // for (State s : nextStateArray) // if (s == null) // throw new NullPointerException(); // cachedNecessarySets.clear(); // String cycleClosingMthd = Options.getCycleClosingMthd(); // AmpleSet nextAmple = new AmpleSet(); // HashSet<Transition> nextEnabled = new HashSet<Transition>(); //// boolean allEnabledAreSticky = false; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State nextState = nextStateArray[lpnIndex]; // if (init) { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // //allEnabledAreSticky = true; // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (sgList[lpnIndex].isEnabled(tran,nextState)){ // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // else { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (nextStateArray[lpnIndex].getTranVector()[i]) { // nextEnabled.add(new Transition(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // LhpnFile[] lpnList = new LhpnFile[sgList.length]; // for (int i=0; i<sgList.length; i++) // lpnList[i] = sgList[i].getLpn(); // HashMap<Transition, LpnTranList> transToAddMap = new HashMap<Transition, LpnTranList>(); // Integer cycleClosingLpnIndex = -1; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State curState = curStateArray[lpnIndex]; // State nextState = nextStateArray[lpnIndex]; // if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true // && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty() // && stateOnStack(lpnIndex, nextState, stateStack) // && nextState.getIndex() != curState.getIndex()) { // cycleClosingLpnIndex = lpnIndex; // System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~"); // printAmpleSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old ample at this state: "); // LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState); // LpnTranList curLocalAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState); // LpnTranList reducedLocalTrans = new LpnTranList(); // LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions(); // System.out.println("The firedTran is a cycle closing transition."); // if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) { // // firedTran is a cycle closing transition. // for (int i=0; i<curLocalEnabledTrans.size(); i++) { // if (!curLocalAmpleTrans.contains(curLocalEnabledTrans.get(i))) { // reducedLocalTrans.add(curLocalEnabledTrans.get(i)); // if (!oldLocalNextAmpleTrans.containsAll(reducedLocalTrans)) { // printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:"); // printTransitionSet(curLocalAmpleTrans, "curAmpleTrans:"); // printTransitionSet(reducedLocalTrans, "reducedLocalTrans:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:"); // printTransitionSet(oldLocalNextAmpleTrans, "nextAmpleTransOld:"); // // nextAmple.setAmpleChanged(); // // ignoredTrans should not be empty here. // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // if (cycleClosingMthd.toLowerCase().equals("behavioral")) { // for (Transition seed : ignored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); //// if (nextAmpleNewIndices.size() == 1) //// break; // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else if (cycleClosingMthd.toLowerCase().equals("state_search")) { // // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new ample of nextState. // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // LpnTranList trulyIgnoredTrans = ignoredTrans.copy(); // trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]); // if (!trulyIgnoredTrans.isEmpty()) { // HashSet<Transition> trulyIgnored = new HashSet<Transition>(); // for (Transition tran : trulyIgnoredTrans) { // trulyIgnored.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : trulyIgnored) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (Transition tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else { // All ignored transitions were fired before. It is safe to close the current cycle. // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // // oldNextAmpleTrans.containsAll(curReducedTrans) == true (safe to close the current cycle) // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> oldLocalNextAmple = new HashSet<Transition>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (Transition seed : oldLocalNextAmple) { // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else if (cycleClosingMthd.toLowerCase().equals("strong")) { // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<Transition> ignored = new HashSet<Transition>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<Transition> allNewNextAmple = new HashSet<Transition>(); // for (Transition seed : ignored) { // HashSet<Transition> newNextAmple = (HashSet<Transition>) nextEnabled.clone(); // HashSet<Transition> dependent = new HashSet<Transition>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (Transition dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<Transition>) dependent.clone(); // allNewNextAmple.addAll(newNextAmple); // // The strong cycle condition requires all seeds in ignored to be included in the allNewNextAmple, as well as dependent set for each seed. // // So each seed should have the same new ample set. // for (Transition seed : ignored) { // DependentSet dependentSet = new DependentSet(allNewNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // firedTran is not a cycle closing transition. Compute next ample. //// if (nextEnabled.size() == 1) //// return nextEnabled; // System.out.println("The firedTran is NOT a cycle closing transition."); // HashSet<Transition> ready = null; // for (Transition seed : nextEnabled) { // System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")"); // HashSet<Transition> dependent = new HashSet<Transition>(); // Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()]; // boolean enabledIsDummy = false; //// if (enabledTransition.isSticky()) { //// dependent = (HashSet<Transition>) nextEnabled.clone(); //// else { //// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList); // dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // if (isDummyTran(enabledTransition.getName())) // enabledIsDummy = true; // for (Transition inDependent : dependent) { // if(inDependent.getLpnIndex() == cycleClosingLpnIndex) { // // check cycle closing condition // break; // DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy); // dependentSetQueue.add(dependentSet); // ready = dependentSetQueue.poll().getDependent(); //// // Update the old ample of the next state //// boolean allTransToAddFired = false; //// if (cycleClosingMthdIndex == 2) { //// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. //// if (transToAdd != null) { //// LpnTranList transToAddCopy = transToAdd.copy(); //// HashSet<Integer> stateVisited = new HashSet<Integer>(); //// stateVisited.add(nextState.getIndex()); //// allTransToAddFired = allTransToAddFired(transToAddCopy, //// allTransToAddFired, stateVisited, stateStackTop, lpnIndex); //// // Update the old ample of the next state //// if (!allTransToAddFired || cycleClosingMthdIndex == 1) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(transToAdd); //// ampleSetTbl.get(nextState).addAll(transToAdd); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// if (cycleClosingMthdIndex == 4) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(ignoredTrans); //// ampleSetTbl.get(nextState).addAll(ignoredTrans); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// // enabledSetTble stores the ample set at curState. //// // The fully enabled set at each state is stored in the tranVector in each state. //// return (AmpleSet) nextAmple; return null; } private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans, HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) { State state = stateStackEntry.get(lpnIndex); System.out.println("state = " + state.getIndex()); State predecessor = stateStackEntry.getFather().get(lpnIndex); if (predecessor != null) System.out.println("predecessor = " + predecessor.getIndex()); if (predecessor == null || stateVisited.contains(predecessor.getIndex())) { return ignoredTrans; } else stateVisited.add(predecessor.getIndex()); LpnTranList predecessorOldAmple = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor); for (Transition oldAmpleTran : predecessorOldAmple) { State tmpState = sg.getNextStateMap().get(predecessor).get(oldAmpleTran); if (tmpState.getIndex() == state.getIndex()) { ignoredTrans.remove(oldAmpleTran); break; } } if (ignoredTrans.size()==0) { return ignoredTrans; } else { ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg); } return ignoredTrans; } // for (Transition oldAmpleTran : oldAmple) { // State successor = nextStateMap.get(nextState).get(oldAmpleTran); // if (stateVisited.contains(successor.getIndex())) { // break; // else // stateVisited.add(successor.getIndex()); // LpnTranList successorOldAmple = enabledSetTbl.get(successor); // // Either successor or sucessorOldAmple should not be null for a nonterminal state graph. // HashSet<Transition> transToAddFired = new HashSet<Transition>(); // for (Transition tran : transToAddCopy) { // if (successorOldAmple.contains(tran)) // transToAddFired.add(tran); // transToAddCopy.removeAll(transToAddFired); // if (transToAddCopy.size() == 0) { // allTransFired = true; // break; // else { // allTransFired = allTransToAddFired(successorOldAmple, nextState, successor, // transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex); // return allTransFired; /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) { boolean firingOrder = false; long peakUsedMem = 0; long peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length; HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>(); @SuppressWarnings("unchecked") IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize]; //HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize]; Stack<LpnState[]> stateStack = new Stack<LpnState[]>(); Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>(); //get initial enable transition set LpnTranList initEnabled = new LpnTranList(); LpnTranList initFireFirst = new LpnTranList(); LpnState[] initLpnStateArray = new LpnState[arraySize]; for (int i = 0; i < arraySize; i++) { lpnStateCache[i] = new IndexObjMap<LpnState>(); LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]); HashSet<Transition> enabledSet = new HashSet<Transition>(); if(!enabledTrans.isEmpty()) { for(Transition tran : enabledTrans) { enabledSet.add(tran); initEnabled.add(tran); } } LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet); lpnStateCache[i].add(curLpnState); initLpnStateArray[i] = curLpnState; } LpnTranList[] initEnabledSet = new LpnTranList[2]; initEnabledSet[0] = initFireFirst; initEnabledSet[1] = initEnabled; lpnTranStack.push(initEnabledSet); stateStack.push(initLpnStateArray); globalStateTbl.add(new PrjLpnState(initLpnStateArray)); main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; //if(iterations>2)break; if (iterations % 100000 == 0) System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", current_stack_depth: " + stateStack.size() + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); LpnTranList[] curEnabled = lpnTranStack.peek(); LpnState[] curLpnStateArray = stateStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if(curEnabled[0].size()==0 && curEnabled[1].size()==0){ lpnTranStack.pop(); stateStack.pop(); continue; } Transition firedTran = null; if(curEnabled[0].size() != 0) firedTran = curEnabled[0].removeFirst(); else firedTran = curEnabled[1].removeFirst(); traceCex.addLast(firedTran); State[] curStateArray = new State[arraySize]; for( int i = 0; i < arraySize; i++) curStateArray[i] = curLpnStateArray[i].getState(); StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled(); LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]); HashSet<Transition> nextEnabledSet = new HashSet<Transition>(); for(Transition tran : nextEnabledList) { nextEnabledSet.add(tran); } extendedNextEnabledArray[i] = nextEnabledSet; //non_disabling for(Transition curTran : curEnabledSet) { if(curTran == firedTran) continue; if(nextEnabledSet.contains(curTran) == false) { int[] nextMarking = nextStateArray[i].getMarking(); // Not sure if the code below is correct. int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getLabel()); boolean included = true; if (preset != null && preset.length > 0) { for (int pp : preset) { boolean temp = false; for (int mi = 0; mi < nextMarking.length; mi++) { if (nextMarking[mi] == pp) { temp = true; break; } } if (temp == false) { included = false; break; } } } if(preset==null || preset.length==0 || included==true) { extendedNextEnabledArray[i].add(curTran); } } } } boolean deadlock=true; for(int i = 0; i < arraySize; i++) { if(extendedNextEnabledArray[i].size() != 0){ deadlock = false; break; } } if(deadlock==true) { failure = true; break main_while_loop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. LpnState[] nextLpnStateArray = new LpnState[arraySize]; for(int i = 0; i < arraySize; i++) { HashSet<Transition> lpnEnabledSet = new HashSet<Transition>(); for(Transition tran : extendedNextEnabledArray[i]) { lpnEnabledSet.add(tran); } LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet); LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp)); nextLpnStateArray[i] = tmpCached; } boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray)); if(newState == false) { traceCex.removeLast(); continue; } stateStack.push(nextLpnStateArray); LpnTranList[] nextEnabledSet = new LpnTranList[2]; LpnTranList fireFirstTrans = new LpnTranList(); LpnTranList otherTrans = new LpnTranList(); for(int i = 0; i < arraySize; i++) { for(Transition tran : nextLpnStateArray[i].getEnabled()) { if(firingOrder == true) if(curLpnStateArray[i].getEnabled().contains(tran)) otherTrans.add(tran); else fireFirstTrans.add(tran); else fireFirstTrans.add(tran); } } nextEnabledSet[0] = fireFirstTrans; nextEnabledSet[1] = otherTrans; lpnTranStack.push(nextEnabledSet); }// END while (stateStack.empty() == false) // graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt, // prjStateSet.size())); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth); /* * by looking at stateStack, generate the trace showing the counter-example. */ if (failure == true) { System.out.println(" System.out.println("the deadlock trace:"); //update traceCex from stateStack // LpnState[] cur = null; // LpnState[] next = null; for(Transition tran : traceCex) System.out.println(tran.getFullLabel()); } System.out.println("Modules' local states: "); for (int i = 0; i < arraySize; i++) { System.out.println("module " + lpnList[i].getLpn().getLabel() + ": " + lpnList[i].reachSize()); } return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * When a state is considered during DFS, only one enabled transition is * selected to fire in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_1"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 500; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean compressed = false; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int arraySize = lpnList.length; int newStateCnt = 0; Stack<State[]> stateStack = new Stack<State[]>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); mddNode reachAll = null; mddNode reach = mddMgr.newNode(); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true); mddMgr.add(reach, localIdxArray, compressed); stateStack.push(initStateArray); LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]); lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); int numMddCompression = 0; main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack depth: " + stateStack.size() + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); numMddCompression++; if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); if(memUpBound < 1500) memUpBound *= numMddCompression; } } State[] curStateArray = stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); curIndexStack.pop(); curIndex++; while (curIndex < arraySize) { LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex])); if (enabledCached.size() > 0) { curEnabled = enabledCached.clone(); lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); break; } else curIndex++; } } if (curIndex == arraySize) { stateStack.pop(); continue; } Transition firedTran = curEnabled.removeLast(); State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. * if not, add it into reachable set, and push it onto stack. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; if (existingState == false) { mddMgr.add(reach, localIdxArray, compressed); newStateCnt++; stateStack.push(nextStateArray); lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); curIndexStack.push(0); totalStates++; } } double totalStateCnt = mddMgr.numberOfStates(reach); System.out.println("---> run statistics: \n" + "# LPN transition firings: " + tranFiringCnt + "\n" + "# of prjStates found: " + totalStateCnt + "\n" + "max_stack_depth: " + max_stack_depth + "\n" + "peak MDD nodes: " + peakMddNodeCnt + "\n" + "peak used memory: " + peakUsedMem / 1000000 + " MB\n" + "peak total memory: " + peakTotalMem / 1000000 + " MB\n"); return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * It is similar to findsg_dfs_mdd_1 except that when a state is considered * during DFS, all enabled transition are fired, and all its successor * states are found in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_2"); int tranFiringCnt = 0; int totalStates = 0; int arraySize = lpnList.length; long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean failure = false; MDT state2Explore = new MDT(arraySize); state2Explore.push(initStateArray); totalStates++; long peakState2Explore = 0; Stack<Integer> searchDepth = new Stack<Integer>(); searchDepth.push(1); boolean compressed = false; mddNode reachAll = null; mddNode reach = mddMgr.newNode(); main_while_loop: while (failure == false && state2Explore.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; iterations++; if (iterations % 100000 == 0) { int mddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt; int state2ExploreSize = state2Explore.size(); peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", # states to explore: " + state2ExploreSize + ", # MDT nodes: " + state2Explore.nodeCnt() + ", total MDD nodes: " + mddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } } State[] curStateArray = state2Explore.pop(); State[] nextStateArray = null; int states2ExploreCurLevel = searchDepth.pop(); if(states2ExploreCurLevel > 1) searchDepth.push(states2ExploreCurLevel-1); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false); mddMgr.add(reach, localIdxArray, compressed); int nextStates2Explore = 0; for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; State curState = curStateArray[index]; LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState); LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone(); while (curEnabled.size() > 0) { Transition firedTran = curEnabled.removeLast(); // TODO: (check) Not sure if curLpn.fire is correct. nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; if (curStateArray[i] == nextStateArray[i]) continue; LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.err.println("Verification failed: deadlock."); failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; else if(state2Explore.contains(nextStateArray)==true) existingState = true; if (existingState == false) { totalStates++; //mddMgr.add(reach, localIdxArray, compressed); state2Explore.push(nextStateArray); nextStates2Explore++; } } } if(nextStates2Explore > 0) searchDepth.push(nextStates2Explore); } System.out.println(" + "---> run statistics: \n" + " # Depth of search (Length of Cex): " + searchDepth.size() + "\n" + " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n" + " # of prjStates found: " + (double)totalStates / 1000000 + " M\n" + " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n" + " peak MDD nodes: " + peakMddNodeCnt + "\n" + " peak used memory: " + peakUsedMem / 1000000 + " MB\n" + " peak total memory: " + peakTotalMem /1000000 + " MB\n" + "_____________________________________"); return null; } public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. int arraySize = sgList.length; for (int i = 0; i < arraySize; i++) sgList[i].addState(initStateArray[i]); mddNode reachSet = null; mddNode reach = mddMgr.newNode(); MDT frontier = new MDT(arraySize); MDT image = new MDT(arraySize); frontier.push(initStateArray); State[] curStateArray = null; int tranFiringCnt = 0; int totalStates = 0; int imageSize = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachSet == null) reachSet = reach; else { mddNode newReachSet = mddMgr.union(reachSet, reach); if (newReachSet != reachSet) { mddMgr.remove(reachSet); reachSet = newReachSet; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } while(frontier.empty() == false) { boolean deadlock = true; // Stack<State[]> curStateArrayList = frontier.pop(); // while(curStateArrayList.empty() == false) { // curStateArray = curStateArrayList.pop(); { curStateArray = frontier.pop(); int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false); mddMgr.add(reach, localIdxArray, false); totalStates++; for (int i = 0; i < arraySize; i++) { LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]); if (curEnabled.size() > 0) deadlock = false; for (Transition firedTran : curEnabled) { // TODO: (check) Not sure if sgList[i].fire is correct. State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran); tranFiringCnt++; /* * Check if any transitions can be disabled by fireTran. */ LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled); if (disabledTran != null) { System.err.println("*** Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false); if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) { if(image.contains(nextStateArray)==false) { image.push(nextStateArray); imageSize++; } } } } } /* * If curStateArray deadlocks (no enabled transitions), terminate. */ if (deadlock == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } } if(image.empty()==true) break; System.out.println("---> size of image: " + imageSize); frontier = image; image = new MDT(arraySize); imageSize = 0; } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n" + "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MDD nodes: " + peakMddNodeCnt); return null; } /** * BFS findsg using iterative approach. THe states found are stored in MDD. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; int arraySize = lpnList.length; for (int i = 0; i < arraySize; i++) lpnList[i].addState(initStateArray[i]); // mddNode reachSet = mddMgr.newNode(); // mddMgr.add(reachSet, curLocalStateArray); mddNode reachSet = null; mddNode exploredSet = null; LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]); for (int i = 0; i < arraySize; i++) nextSetArray[i] = new LinkedList<State>(); mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null); mddNode curMdd = initMdd; reachSet = curMdd; mddNode nextMdd = null; int[] curStateArray = null; int tranFiringCnt = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; curStateArray = mddMgr.next(curMdd, curStateArray); if (curStateArray == null) { // Break the loop if no new next states are found. // System.out.println("nextSet size " + nextSet.size()); if (nextMdd == null) break bfsWhileLoop; if (exploredSet == null) exploredSet = curMdd; else { mddNode newExplored = mddMgr.union(exploredSet, curMdd); if (newExplored != exploredSet) mddMgr.remove(exploredSet); exploredSet = newExplored; } mddMgr.remove(curMdd); curMdd = nextMdd; nextMdd = null; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of union calls: " + mddNode.numCalls + ", # of union cache nodes: " + mddNode.cacheNodes + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet) + ", CurSet.Size = " + mddMgr.numberOfStates(curMdd)); continue; } if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true) continue; // If curStateArray deadlocks (no enabled transitions), terminate. if (Analysis.deadLock(lpnList, curStateArray) == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } // Do firings of non-local LPN transitions. for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]); if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true) continue; for (Transition firedTran : curLocalEnabled) { if (firedTran.isLocal() == true) continue; // TODO: (check) Not sure if curLpn.fire is correct. State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; @SuppressWarnings("unused") ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1); for (int i = 0; i < arraySize; i++) { if (curStateArray[i] == nextStateArray[i].getIndex()) continue; StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex()); Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + ": is disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { verifyError = true; break bfsWhileLoop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the // next // enabled transition. int[] nextIdxArray = Analysis.getIdxArray(nextStateArray); if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true) continue; mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet); mddNode newReachSet = mddMgr.union(reachSet, newNextMdd); if (newReachSet != reachSet) mddMgr.remove(reachSet); reachSet = newReachSet; if (nextMdd == null) nextMdd = newNextMdd; else { mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd); if (tmpNextMdd != nextMdd) mddMgr.remove(nextMdd); nextMdd = tmpNextMdd; mddMgr.remove(newNextMdd); } } } } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + "\n" + "---> # of prjStates found: " + (mddMgr.numberOfStates(reachSet)) + "\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt()); return null; } /** * partial order reduction (Original version of Hao's POR with behavioral analysis) * This method is not used anywhere. See searchPOR_behavioral for POR with behavioral analysis. * * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> Calling search_dfs with partial order reduction"); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; boolean useMdd = true; mddNode reach = mddMgr.newNode(); //init por verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); //System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel()); // TODO: (??) Not sure if the state graph sg below is correct. StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return null; } /** * partial order reduction with behavioral analysis. (Adapted from search_dfs_por.) * * @param sgList * @param curLocalStateArray * @param enabledArray */ public StateGraph[] searchPOR_behavioral(final StateGraph[] sgList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> calling function searchPOR_behavioral"); System.out.println("---> " + Options.getPOR()); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; //boolean useMdd = true; boolean useMdd = false; mddNode reach = mddMgr.newNode(); //init por AmpleSet ampleClass = new AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(sgList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(sgList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = sgList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { sgList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = sgList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); StateGraph sg = null; for (int i=0; i<sgList.length; i++) { if (sgList[i].getLpn().equals(firedTran.getLpn())) { sg = sgList[i]; } } State[] nextStateArray = sg.fire(sgList, curStateArray, firedTran); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { sgList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = sgList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + sgList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + sgList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return sgList; } // /** // * Check if this project deadlocks in the current state 'stateArray'. // * @param sgList // * @param stateArray // * @param staticSetsMap // * @param enableSet // * @param disableByStealingToken // * @param disableSet // * @param init // * @return // */ // // Called by search search_dfsPOR // public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<Transition,StaticSets> staticSetsMap, // boolean init, HashMap<Transition, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) { // boolean deadlock = true; // System.out.println("@ deadlock:"); //// for (int i = 0; i < stateArray.length; i++) { //// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); //// if (tmp.size() > 0) { //// deadlock = false; //// break; // LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); // if (tmp.size() > 0) { // deadlock = false; // System.out.println("@ end of deadlock"); // return deadlock; public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) { boolean deadlock = true; for (int i = 0; i < stateArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) { boolean deadlock = true; for (int i = 0; i < stateIdxArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } // /* // * Scan enabledArray, identify all sticky transitions other the firedTran, and return them. // * // * Arguments remain constant. // */ // public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) { // int arraySize = enabledArray.length; // LpnTranList[] stickyTranArray = new LpnTranList[arraySize]; // for (int i = 0; i < arraySize; i++) { // stickyTranArray[i] = new LpnTranList(); // for (Transition tran : enabledArray[i]) { // if (tran != firedTran) // stickyTranArray[i].add(tran); // if(stickyTranArray[i].size()==0) // stickyTranArray[i] = null; // return stickyTranArray; /** * Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to * nextStickyTransArray. * * Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions * from curStickyTransArray. * * Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState. */ public static LpnTranList[] checkStickyTrans( LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray, LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) { int arraySize = curStickyTransArray.length; LpnTranList[] stickyTransArray = new LpnTranList[arraySize]; boolean[] hasStickyTrans = new boolean[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> tmp = new HashSet<Transition>(); if(nextStickyTransArray[i] != null) for(Transition tran : nextStickyTransArray[i]) tmp.add(tran); stickyTransArray[i] = new LpnTranList(); hasStickyTrans[i] = false; for (Transition tran : curStickyTransArray[i]) { if (tran.isPersistent() == true && tmp.contains(tran)==false) { int[] nextMarking = nextState.getMarking(); int[] preset = LPN.getPresetIndex(tran.getLabel());//tran.getPreSet(); boolean included = false; if (preset != null && preset.length > 0) { for (int pp : preset) { for (int mi = 0; i < nextMarking.length; i++) { if (nextMarking[mi] == pp) { included = true; break; } } if (included == false) break; } } if(preset==null || preset.length==0 || included==true) { stickyTransArray[i].add(tran); hasStickyTrans[i] = true; } } } if(stickyTransArray[i].size()==0) stickyTransArray[i] = null; } return stickyTransArray; } /* * Return an array of indices for the given stateArray. */ private static int[] getIdxArray(State[] stateArray) { int[] idxArray = new int[stateArray.length]; for(int i = 0; i < stateArray.length; i++) { idxArray[i] = stateArray[i].getIndex(); } return idxArray; } private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) { int arraySize = sgList.length; int[] localIdxArray = new int[arraySize]; for(int i = 0; i < arraySize; i++) { if(reverse == false) localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex(); else localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex(); //System.out.print(localIdxArray[i] + " "); } //System.out.println(); return localIdxArray; } // private void printEnabledSetTbl(StateGraph[] sgList) { // for (int i=0; i<sgList.length; i++) { // for (State s : sgList[i].getEnabledSetTbl().keySet()) { // System.out.print("S" + s.getIndex() + " -> "); // printTransList(sgList[i].getEnabledSetTbl().get(s), ""); private HashSet<Transition> partialOrderReduction(State[] curStateArray, HashSet<Transition> curEnabled, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; if (Options.getUseDependentQueue()) { DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()) System.out.println("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); HashSet<Transition> dependent = new HashSet<Transition>(); boolean enabledIsDummy = false; boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) if(isDummyTran(enabledTran.getLabel())) enabledIsDummy = true; DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); dependentSetQueue.add(dependentSet); } //cachedNecessarySets.clear(); ready = dependentSetQueue.poll().getDependent(); //return ready; } else { for (Transition enabledTran : curEnabled) { if (Options.getDebugMode()) System.out.print("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); HashSet<Transition> dependent = new HashSet<Transition>(); boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingAmpleComputation); if (Options.getDebugMode()) { printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " + getNamesOfLPNandTrans(enabledTran)); } if (ready.isEmpty() || dependent.size() < ready.size()) ready = dependent; if (ready.size() == 1) { cachedNecessarySets.clear(); return ready; } } } cachedNecessarySets.clear(); return ready; } // private HashSet<Transition> partialOrderReduction(State[] curStateArray, // HashSet<Transition> curEnabled, HashMap<Transition, StaticSets> staticMap, // HashMap<Transition,Integer> tranFiringFreqMap, StateGraph[] sgList, LhpnFile[] lpnList) { // if (curEnabled.size() == 1) // return curEnabled; // HashSet<Transition> ready = new HashSet<Transition>(); // for (Transition enabledTran : curEnabled) { // if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) { // ready.add(enabledTran); // return ready; // if (Options.getUseDependentQueue()) { // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean enabledIsDummy = false; // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) // if(isDummyTran(enabledTran.getName())) // enabledIsDummy = true; // DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); // dependentSetQueue.add(dependentSet); // //cachedNecessarySets.clear(); // ready = dependentSetQueue.poll().getDependent(); // //return ready; // else { // for (Transition enabledTran : curEnabled) { // if (Options.getDebugMode()){ // writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran)); // HashSet<Transition> dependent = new HashSet<Transition>(); // boolean isCycleClosingAmpleComputation = false; // dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingAmpleComputation); // if (Options.getDebugMode()) { // writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition " // + getNamesOfLPNandTrans(enabledTran)); // if (ready.isEmpty() || dependent.size() < ready.size()) // ready = dependent;//(HashSet<Transition>) dependent.clone(); // if (ready.size() == 1) { // cachedNecessarySets.clear(); // return ready; // cachedNecessarySets.clear(); // return ready; private boolean isDummyTran(String tranName) { if (tranName.contains("_dummy")) return true; else return false; } private HashSet<Transition> computeDependent(State[] curStateArray, Transition seedTran, HashSet<Transition> dependent, HashSet<Transition> curEnabled, boolean isCycleClosingAmpleComputation) { // disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran. HashSet<Transition> disableSet = staticDependency.get(seedTran).getDisableSet(); HashSet<Transition> otherTransDisableEnabledTran = staticDependency.get(seedTran).getOtherTransDisableCurTranSet(); if (Options.getDebugMode()) { System.out.println("@ beginning of computeDependent, consider transition " + getNamesOfLPNandTrans(seedTran)); printIntegerSet(disableSet, "Disable set for " + getNamesOfLPNandTrans(seedTran)); } dependent.add(seedTran); // for (Transition lpnTranPair : canModifyAssign) { // if (curEnabled.contains(lpnTranPair)) // dependent.add(lpnTranPair); if (Options.getDebugMode()) printIntegerSet(dependent, "@ computeDependent at 0, dependent set for " + getNamesOfLPNandTrans(seedTran)); // dependent is equal to enabled. Terminate. if (dependent.size() == curEnabled.size()) { if (Options.getDebugMode()) { System.out.println("Check 0: Size of dependent is equal to enabled. Return dependent."); } return dependent; } for (Transition tranInDisableSet : disableSet) { if (Options.getDebugMode()) System.out.println("Consider transition in the disable set of " + getNamesOfLPNandTrans(seedTran) + ": " + getNamesOfLPNandTrans(tranInDisableSet)); if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet) && (!tranInDisableSet.isPersistent() || otherTransDisableEnabledTran.contains(tranInDisableSet))) { dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,isCycleClosingAmpleComputation)); if (Options.getDebugMode()) { printIntegerSet(dependent, "@ computeDependent at 1 for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (!curEnabled.contains(tranInDisableSet)) { if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back || (Options.getCycleClosingAmpleMethd().toLowerCase().equals("cctboff") && isCycleClosingAmpleComputation)) { dependent.addAll(curEnabled); break; } HashSet<Transition> necessary = null; if (Options.getDebugMode()) { printCachedNecessarySets(); } if (cachedNecessarySets.containsKey(tranInDisableSet)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@ computeDependent: Found transition " + getNamesOfLPNandTrans(tranInDisableSet) + "in the cached necessary sets."); } necessary = cachedNecessarySets.get(tranInDisableSet); } else { if (Options.getDebugMode()) System.out.println("==== Compute necessary using DFS ===="); if (visitedTrans == null) visitedTrans = new HashSet<Transition>(); else visitedTrans.clear(); necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled);//, tranInDisableSet.getFullLabel()); } if (necessary != null && !necessary.isEmpty()) { cachedNecessarySets.put(tranInDisableSet, necessary); if (Options.getDebugMode()) printIntegerSet(necessary, "@ computeDependent, necessary set for transition " + getNamesOfLPNandTrans(tranInDisableSet)); for (Transition tranNecessary : necessary) { if (!dependent.contains(tranNecessary)) { if (Options.getDebugMode()) { printIntegerSet(dependent,"Check if the newly found necessary transition is in the dependent set of " + getNamesOfLPNandTrans(seedTran)); System.out.println("It does not contain this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + ". Compute its dependent set."); } dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,isCycleClosingAmpleComputation)); } else { if (Options.getDebugMode()) { printIntegerSet(dependent, "Check if the newly found necessary transition is in the dependent set. Dependent set for " + getNamesOfLPNandTrans(seedTran)); System.out.println("It already contains this transition found by computeNecessary: " + getNamesOfLPNandTrans(tranNecessary) + "."); } } } } else { if (Options.getDebugMode()) { if (necessary == null) System.out.println("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is null."); else System.out.println("necessary set for transition " + getNamesOfLPNandTrans(seedTran) + " is empty."); } //dependent.addAll(curEnabled); return curEnabled; } if (Options.getDebugMode()) { printIntegerSet(dependent,"@ computeDependent at 2, dependent set for transition " + getNamesOfLPNandTrans(seedTran)); } } else if (dependent.contains(tranInDisableSet)) { if (Options.getDebugMode()) { printIntegerSet(dependent,"@ computeDependent at 3 for transition " + getNamesOfLPNandTrans(seedTran)); System.out.println("Transition " + getNamesOfLPNandTrans(tranInDisableSet) + " is already in the dependent set of " + getNamesOfLPNandTrans(seedTran) + "."); } } } return dependent; } private String getNamesOfLPNandTrans(Transition tran) { return tran.getLpn().getLabel() + "(" + tran.getLabel() + ")"; } private HashSet<Transition> computeNecessary(State[] curStateArray, Transition tran, HashSet<Transition> dependent, HashSet<Transition> curEnabled) { if (Options.getDebugMode()) { System.out.println("@ computeNecessary, consider transition: " + getNamesOfLPNandTrans(tran)); } if (cachedNecessarySets.containsKey(tran)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@ computeNecessary: Found transition " + getNamesOfLPNandTrans(tran) + "'s necessary set in the cached necessary sets. Return the cached necessary set."); } return cachedNecessarySets.get(tran); } // Search for transition(s) that can help to bring the marking(s). HashSet<Transition> nMarking = null; //Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()); //int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName()); for (int i=0; i < tran.getPreset().length; i++) { int placeIndex = tran.getLpn().getPresetIndex(tran.getLabel())[i]; if (curStateArray[tran.getLpn().getLpnIndex()].getMarking()[placeIndex]==0) { if (Options.getDebugMode()) { System.out.println(" } HashSet<Transition> nMarkingTemp = new HashSet<Transition>(); String placeName = tran.getLpn().getPlaceList()[placeIndex]; Transition[] presetTrans = tran.getLpn().getPlace(placeName).getPreset(); if (Options.getDebugMode()) { System.out.println("@ nMarking: Consider preset place of " + getNamesOfLPNandTrans(tran) + ": " + placeName); } for (int j=0; j < presetTrans.length; j++) { Transition presetTran = presetTrans[j]; if (Options.getDebugMode()) { System.out.println("@ nMarking: Preset of place " + placeName + " has transition(s): "); for (int k=0; k<presetTrans.length; k++) { System.out.print(getNamesOfLPNandTrans(presetTrans[k]) + ", "); } System.out.println(""); System.out.println("@ nMarking: Consider transition of " + getNamesOfLPNandTrans(presetTran)); } if (curEnabled.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + getNamesOfLPNandTrans(presetTran) + "). Add to nMarkingTmp."); } nMarkingTemp.add(presetTran); } else { if (visitedTrans.contains(presetTran)) {//seedTranInDisableSet.getVisitedTrans().contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: Transition " + getNamesOfLPNandTrans(presetTran) + " was visted before"); } if (cachedNecessarySets.containsKey(presetTran)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@nMarking: Found transition " + getNamesOfLPNandTrans(presetTran) + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nMarkingTemp = cachedNecessarySets.get(presetTran); } continue; } else visitedTrans.add(presetTran); if (Options.getDebugMode()) { System.out.println("~~~~~~~~~ transVisited ~~~~~~~~~"); for (Transition visitedTran :visitedTrans) { System.out.println(getNamesOfLPNandTrans(visitedTran)); } System.out.println("@ nMarking, before call computeNecessary: consider transition: " + getNamesOfLPNandTrans(presetTran)); System.out.println("@ nMarking: transition " + getNamesOfLPNandTrans(presetTran) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabled); if (tmp != null) { nMarkingTemp.addAll(tmp); if (Options.getDebugMode()) { System.out.println("@ nMarking: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(presetTran) + " is not null."); printIntegerSet(nMarkingTemp, getNamesOfLPNandTrans(presetTran) + "'s nMarkingTemp"); } } else if (Options.getDebugMode()) { System.out.println("@ nMarking: necessary set for transition " + getNamesOfLPNandTrans(presetTran) + " is null."); } } } if (!nMarkingTemp.isEmpty()) //if (nMarking == null || nMarkingTemp.size() < nMarking.size()) if (nMarking == null || setSubstraction(nMarkingTemp, dependent).size() < setSubstraction(nMarking, dependent).size()) nMarking = nMarkingTemp; } else if (Options.getDebugMode()) { System.out.println("@ nMarking: Place " + tran.getLpn().getLabel() + "(" + tran.getLpn().getPlaceList()[placeIndex] + ") is marked."); } } if (nMarking != null && nMarking.size() ==1 && setSubstraction(nMarking, dependent).size() == 0) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { System.out.println("Return nMarking as necessary set."); printCachedNecessarySets(); } return nMarking; } // Search for transition(s) that can help to enable the current transition. HashSet<Transition> nEnable = null; int[] varValueVector = curStateArray[tran.getLpn().getLpnIndex()].getVariableVector(); //HashSet<Transition> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue(); ArrayList<HashSet<Transition>> canEnable = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue(); if (Options.getDebugMode()) { System.out.println(" printIntegerSet(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); } if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && !canEnable.isEmpty()) { for(int index=0; index < tran.getConjunctsOfEnabling().size(); index++) { ExprTree conjunctExprTree = tran.getConjunctsOfEnabling().get(index); HashSet<Transition> nEnableForOneConjunct = null; if (Options.getDebugMode()) { printIntegerSet(canEnable, "@ nEnable: " + getNamesOfLPNandTrans(tran) + " can be enabled by"); System.out.println("@ nEnable: Consider conjunct for transition " + getNamesOfLPNandTrans(tran) + ": " + conjunctExprTree.toString()); } if (conjunctExprTree.evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0) { HashSet<Transition> canEnableOneConjunctSet = staticDependency.get(tran).getOtherTransSetCurTranEnablingTrue().get(index); nEnableForOneConjunct = new HashSet<Transition>(); if (Options.getDebugMode()) { System.out.println("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to FALSE."); printIntegerSet(canEnableOneConjunctSet, "@ nEnable: Transitions that can enable this conjunct are"); } for (Transition tranCanEnable : canEnableOneConjunctSet) { if (curEnabled.contains(tranCanEnable)) { nEnableForOneConjunct.add(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: curEnabled contains transition " + getNamesOfLPNandTrans(tranCanEnable) + ". Add to nEnableOfOneConjunct."); } } else { if (visitedTrans.contains(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " was visted before."); } if (cachedNecessarySets.containsKey(tranCanEnable)) { if (Options.getDebugMode()) { printCachedNecessarySets(); System.out.println("@ nEnable: Found transition " + getNamesOfLPNandTrans(tranCanEnable) + "'s necessary set in the cached necessary sets. Add it to nEnableOfOneConjunct."); } nEnableForOneConjunct.addAll(cachedNecessarySets.get(tranCanEnable)); } continue; } else visitedTrans.add(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: Transition " + getNamesOfLPNandTrans(tranCanEnable) + " is not enabled. Compute its necessary set."); } HashSet<Transition> tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabled); if (tmp != null) { nEnableForOneConjunct.addAll(tmp); if (Options.getDebugMode()) { System.out.println("@ nEnable: tmp returned from computeNecessary for " + getNamesOfLPNandTrans(tranCanEnable) + ": "); printIntegerSet(tmp, ""); printIntegerSet(nEnableForOneConjunct, getNamesOfLPNandTrans(tranCanEnable) + "'s nEnableOfOneConjunct"); } } else if (Options.getDebugMode()) { System.out.println("@ nEnable: necessary set for transition " + getNamesOfLPNandTrans(tranCanEnable) + " is null."); } } } if (!nEnableForOneConjunct.isEmpty()) { if (nEnable == null || setSubstraction(nEnableForOneConjunct, dependent).size() < setSubstraction(nEnable, dependent).size()) { //&& !nEnableForOneConjunct.isEmpty())) { if (Options.getDebugMode()) { System.out.println("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" is replaced by nEnableForOneConjunct."); printIntegerSet(nEnable, "nEnable"); printIntegerSet(nEnableForOneConjunct, "nEnableForOneConjunct"); } nEnable = nEnableForOneConjunct; } else { if (Options.getDebugMode()) { System.out.println("@ nEnable: nEnable for transition " + getNamesOfLPNandTrans(tran) +" remains unchanged."); printIntegerSet(nEnable, "nEnable"); } } } } else { if (Options.getDebugMode()) { System.out.println("@ nEnable: Conjunct for transition " + getNamesOfLPNandTrans(tran) + " " + conjunctExprTree.toString() + " is evaluated to TRUE. No need to trace back on it."); } } } } else { if (Options.getDebugMode()) { if (tran.getEnablingTree() == null) { System.out.println("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + " has no enabling condition."); } else if (tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) !=0.0) { System.out.println("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is true."); } else if (tran.getEnablingTree() != null && tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0 && canEnable.isEmpty()) { System.out.println("@ nEnable: transition " + getNamesOfLPNandTrans(tran) + "'s enabling condition is false, but no other transitions that can help to enable it were found ."); } printIntegerSet(nMarking, "=== nMarking for transition " + getNamesOfLPNandTrans(tran)); printIntegerSet(nEnable, "=== nEnable for transition " + getNamesOfLPNandTrans(tran)); } } if (nMarking != null && nEnable == null) { if (!nMarking.isEmpty()) cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nMarking; } else if (nMarking == null && nEnable != null) { if (!nEnable.isEmpty()) cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nEnable; } else if (nMarking == null && nEnable == null) { return null; } else { if (!nMarking.isEmpty() && !nEnable.isEmpty()) { if (setSubstraction(nMarking, dependent).size() < setSubstraction(nEnable, dependent).size()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nMarking; } else { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nEnable; } } else if (nMarking.isEmpty() && !nEnable.isEmpty()) { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nEnable; } else if (!nMarking.isEmpty() && nEnable.isEmpty()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(); } return nMarking; } else { return null; } } } // private HashSet<Transition> computeNecessaryUsingDependencyGraphs(State[] curStateArray, // Transition tran, HashSet<Transition> curEnabled, // HashMap<Transition, StaticSets> staticMap, // LhpnFile[] lpnList, Transition seedTran) { // if (Options.getDebugMode()) { //// System.out.println("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); // // Use breadth-first search to find the shorted path from the seed transition to an enabled transition. // LinkedList<Transition> exploredTransQueue = new LinkedList<Transition>(); // HashSet<Transition> allExploredTrans = new HashSet<Transition>(); // exploredTransQueue.add(tran); // //boolean foundEnabledTran = false; // HashSet<Transition> canEnable = new HashSet<Transition>(); // while(!exploredTransQueue.isEmpty()){ // Transition curTran = exploredTransQueue.poll(); // allExploredTrans.add(curTran); // if (cachedNecessarySets.containsKey(curTran)) { // if (Options.getDebugMode()) { // writeStringWithEndOfLineToPORDebugFile("Found transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" // + "'s necessary set in the cached necessary sets. Terminate BFS."); // return cachedNecessarySets.get(curTran); // canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // // Decide if canSetEnablingTrue set can help to enable curTran. // Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); // int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector(); // if (curTransition.getEnablingTree() != null // && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) { // canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue()); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to set the enabling of transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // printIntegerSet(staticMap.get(curTran).getEnableBySettingEnablingTrue(), lpnList, "Neighbors that can help to set the enabling transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // if (Options.getDebugMode()) { //// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); // for (Transition neighborTran : canEnable) { // if (curEnabled.contains(neighborTran)) { // if (!neighborTran.equals(seedTran)) { // HashSet<Transition> necessarySet = new HashSet<Transition>(); // necessarySet.add(neighborTran); // // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed? // cachedNecessarySets.put(tran, necessarySet); // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")."); // return necessarySet; // else if (neighborTran.equals(seedTran) && canEnable.size()==1) { // if (Options.getDebugMode()) { //// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() //// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() //// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() // + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel() // + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set."); // return null; //// if (exploredTransQueue.isEmpty()) { //// System.out.println("exploredTransQueue is empty. Return null necessary set."); //// writeStringWithNewLineToPORDebugFile("exploredTransQueue is empty. Return null necessary set."); //// return null; // if (!allExploredTrans.contains(neighborTran)) { // allExploredTrans.add(neighborTran); // exploredTransQueue.add(neighborTran); // canEnable.clear(); // return null; private void printCachedNecessarySets() { System.out.println("================ cached necessary sets ================="); for (Transition key : cachedNecessarySets.keySet()) { System.out.print(key.getLpn().getLabel() + "(" + key.getLabel() + ") => "); for (Transition necessary : cachedNecessarySets.get(key)) { System.out.print(necessary.getLpn().getLabel() + "(" + necessary.getLabel() + ") "); } System.out.println(""); } } private HashSet<Transition> setSubstraction( HashSet<Transition> left, HashSet<Transition> right) { HashSet<Transition> sub = new HashSet<Transition>(); for (Transition lpnTranPair : left) { if (!right.contains(lpnTranPair)) sub.add(lpnTranPair); } return sub; } public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); if(stateArray[lpnIndex].equals(curState)) {// (stateArray[lpnIndex] == curState) { isStateOnStack = true; break; } } return isStateOnStack; } private void printIntegerSet(HashSet<Transition> Trans, String setName) { if (!setName.isEmpty()) System.out.print(setName + ": "); if (Trans == null) { System.out.println("null"); } else if (Trans.isEmpty()) { System.out.println("empty"); } else { for (Transition lpnTranPair : Trans) { System.out.print(lpnTranPair.getLabel() + "(" + lpnTranPair.getLpn().getLabel() + "),"); } System.out.println(); } } private void printIntegerSet(ArrayList<HashSet<Transition>> transSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + ": "); if (transSet == null) { System.out.println("null"); } else if (transSet.isEmpty()) { System.out.println("empty"); } else { for (HashSet<Transition> lpnTranPairSet : transSet) { for (Transition lpnTranPair : lpnTranPairSet) System.out.print(lpnTranPair.getLpn().getLabel() + "(" + lpnTranPair.getLabel() + "),"); } System.out.println(); } } }
package cgeo.geocaching; import butterknife.ButterKnife; import butterknife.InjectView; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.activity.AbstractViewPagerActivity; import cgeo.geocaching.activity.Progress; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.gc.GCConnector; import cgeo.geocaching.connector.gc.GCConstants; import cgeo.geocaching.enumerations.CacheAttribute; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Units; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.network.HtmlImage; import cgeo.geocaching.network.Network; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.ui.AbstractCachingPageViewCreator; import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod; import cgeo.geocaching.ui.CacheDetailsCreator; import cgeo.geocaching.ui.CoordinatesFormatSwitcher; import cgeo.geocaching.ui.DecryptTextClickListener; import cgeo.geocaching.ui.EditNoteDialog; import cgeo.geocaching.ui.EditNoteDialog.EditNoteDialogListener; import cgeo.geocaching.ui.Formatter; import cgeo.geocaching.ui.HtmlImageCounter; import cgeo.geocaching.ui.ImagesList; import cgeo.geocaching.ui.IndexOutOfBoundsAvoidingTextView; import cgeo.geocaching.ui.LoggingUI; import cgeo.geocaching.ui.OwnerActionsClickListener; import cgeo.geocaching.ui.WeakReferenceHandler; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.ui.logs.CacheLogsViewCreator; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.ClipboardUtils; import cgeo.geocaching.utils.CryptUtils; import cgeo.geocaching.utils.GeoDirHandler; import cgeo.geocaching.utils.HtmlUtils; import cgeo.geocaching.utils.ImageUtils; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.MatcherWrapper; import cgeo.geocaching.utils.RunnableWithArgument; import cgeo.geocaching.utils.SimpleCancellableHandler; import cgeo.geocaching.utils.SimpleHandler; import cgeo.geocaching.utils.TextUtils; import cgeo.geocaching.utils.TranslationUtils; import cgeo.geocaching.utils.UnknownTagsHandler; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import android.R.color; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.Html; import android.text.Spannable; import android.text.Spanned; import android.text.format.DateUtils; import android.text.style.ForegroundColorSpan; import android.text.style.StrikethroughSpan; import android.text.style.StyleSpan; import android.util.TypedValue; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewParent; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.TextView.BufferType; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; /** * Activity to handle all single-cache-stuff. * * e.g. details, description, logs, waypoints, inventory... */ public class CacheDetailActivity extends AbstractViewPagerActivity<CacheDetailActivity.Page> implements CacheMenuHandler.ActivityInterface { private static final int MESSAGE_FAILED = -1; private static final int MESSAGE_SUCCEEDED = 1; private static final Pattern[] DARK_COLOR_PATTERNS = { Pattern.compile("((?<!bg)color)=\"#" + "(0[0-9]){3}" + "\"", Pattern.CASE_INSENSITIVE), Pattern.compile("((?<!bg)color)=\"" + "black" + "\"", Pattern.CASE_INSENSITIVE), Pattern.compile("((?<!bg)color)=\"#" + "000080" + "\"", Pattern.CASE_INSENSITIVE) }; private static final Pattern[] LIGHT_COLOR_PATTERNS = { Pattern.compile("((?<!bg)color)=\"#" + "([F][6-9A-F]){3}" + "\"", Pattern.CASE_INSENSITIVE), Pattern.compile("((?<!bg)color)=\"" + "white" + "\"", Pattern.CASE_INSENSITIVE) }; public static final String STATE_PAGE_INDEX = "cgeo.geocaching.pageIndex"; private Geocache cache; private final Progress progress = new Progress(); private SearchResult search; private final GeoDirHandler locationUpdater = new GeoDirHandler() { @Override public void updateGeoData(final IGeoData geo) { if (cacheDistanceView == null) { return; } if (geo.getCoords() != null && cache != null && cache.getCoords() != null) { cacheDistanceView.setText(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(cache.getCoords()))); cacheDistanceView.bringToFront(); } } }; private CharSequence clickedItemText = null; /** * If another activity is called and can modify the data of this activity, we refresh it on resume. */ private boolean refreshOnResume = false; // some views that must be available from everywhere // TODO: Reference can block GC? private TextView cacheDistanceView; protected ImagesList imagesList; /** * waypoint selected in context menu. This variable will be gone when the waypoint context menu is a fragment. */ private Waypoint selectedWaypoint; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.cachedetail_activity); // set title in code, as the activity needs a hard coded title due to the intent filters setTitle(res.getString(R.string.cache)); // get parameters final Bundle extras = getIntent().getExtras(); final Uri uri = getIntent().getData(); // try to get data from extras String name = null; String geocode = null; String guid = null; if (extras != null) { geocode = extras.getString(Intents.EXTRA_GEOCODE); name = extras.getString(Intents.EXTRA_NAME); guid = extras.getString(Intents.EXTRA_GUID); } // try to get data from URI if (geocode == null && guid == null && uri != null) { final String uriHost = uri.getHost().toLowerCase(Locale.US); final String uriPath = uri.getPath().toLowerCase(Locale.US); final String uriQuery = uri.getQuery(); if (uriQuery != null) { Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery); } else { Log.i("Opening URI: " + uriHost + uriPath); } if (uriHost.contains("geocaching.com")) { if (StringUtils.startsWith(uriPath, "/geocache/gc")) { geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US); } else { geocode = uri.getQueryParameter("wp"); guid = uri.getQueryParameter("guid"); if (StringUtils.isNotBlank(geocode)) { geocode = geocode.toUpperCase(Locale.US); guid = null; } else if (StringUtils.isNotBlank(guid)) { geocode = null; guid = guid.toLowerCase(Locale.US); } else { showToast(res.getString(R.string.err_detail_open)); finish(); return; } } } else if (uriHost.contains("coord.info")) { if (StringUtils.startsWith(uriPath, "/gc")) { geocode = uriPath.substring(1).toUpperCase(Locale.US); } else { showToast(res.getString(R.string.err_detail_open)); finish(); return; } } else if (uriHost.contains("opencaching.de")) { if (StringUtils.startsWith(uriPath, "/oc")) { geocode = uriPath.substring(1).toUpperCase(Locale.US); } else { geocode = uri.getQueryParameter("wp"); if (StringUtils.isNotBlank(geocode)) { geocode = geocode.toUpperCase(Locale.US); } else { showToast(res.getString(R.string.err_detail_open)); finish(); return; } } } else { showToast(res.getString(R.string.err_detail_open)); finish(); return; } } // no given data if (geocode == null && guid == null) { showToast(res.getString(R.string.err_detail_cache)); finish(); return; } final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress); try { String title = res.getString(R.string.cache); if (StringUtils.isNotBlank(name)) { title = name; } else if (null != geocode && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank() title = geocode; } progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.cancelMessage()); } catch (final RuntimeException e) { // nothing, we lost the window } final ImageView defaultNavigationImageView = (ImageView) findViewById(R.id.defaultNavigation); defaultNavigationImageView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { startDefaultNavigation2(); return true; } }); final int pageToOpen = savedInstanceState != null ? savedInstanceState.getInt(STATE_PAGE_INDEX, 0) : Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1; createViewPager(pageToOpen, new OnPageSelectedListener() { @Override public void onPageSelected(int position) { if (Settings.isOpenLastDetailsPage()) { Settings.setLastDetailsPage(position); } // lazy loading of cache images if (getPage(position) == Page.IMAGES) { loadCacheImages(); } } }); // Initialization done. Let's load the data with the given information. new LoadCacheThread(geocode, guid, loadCacheHandler).start(); } @Override public void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_PAGE_INDEX, getCurrentItem()); } @Override public void onResume() { super.onResume(); if (refreshOnResume) { notifyDataSetChanged(); refreshOnResume = false; } locationUpdater.startGeo(); } @Override public void onDestroy() { if (imagesList != null) { imagesList.removeAllViews(); } super.onDestroy(); } @Override public void onStop() { if (cache != null) { cache.setChangeNotificationHandler(null); } super.onStop(); } @Override public void onPause() { locationUpdater.stopGeo(); super.onPause(); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) { super.onCreateContextMenu(menu, view, info); final int viewId = view.getId(); switch (viewId) { case R.id.value: // coordinates, gc-code, name assert view instanceof TextView; clickedItemText = ((TextView) view).getText(); final String itemTitle = (String) ((TextView) ((View) view.getParent()).findViewById(R.id.name)).getText(); buildDetailsContextMenu(menu, itemTitle, true); break; case R.id.shortdesc: assert view instanceof TextView; clickedItemText = ((TextView) view).getText(); buildDetailsContextMenu(menu, res.getString(R.string.cache_description), false); break; case R.id.longdesc: assert view instanceof TextView; // combine short and long description final String shortDesc = cache.getShortDescription(); if (StringUtils.isBlank(shortDesc)) { clickedItemText = ((TextView) view).getText(); } else { clickedItemText = shortDesc + "\n\n" + ((TextView) view).getText(); } buildDetailsContextMenu(menu, res.getString(R.string.cache_description), false); break; case R.id.personalnote: assert view instanceof TextView; clickedItemText = ((TextView) view).getText(); buildDetailsContextMenu(menu, res.getString(R.string.cache_personal_note), true); break; case R.id.hint: assert view instanceof TextView; clickedItemText = ((TextView) view).getText(); buildDetailsContextMenu(menu, res.getString(R.string.cache_hint), false); break; case R.id.log: assert view instanceof TextView; clickedItemText = ((TextView) view).getText(); buildDetailsContextMenu(menu, res.getString(R.string.cache_logs), false); break; case R.id.waypoint: menu.setHeaderTitle(selectedWaypoint.getName() + " (" + res.getString(R.string.waypoint) + ")"); getMenuInflater().inflate(R.menu.waypoint_options, menu); final boolean isOriginalWaypoint = selectedWaypoint.getWaypointType().equals(WaypointType.ORIGINAL); menu.findItem(R.id.menu_waypoint_reset_cache_coords).setVisible(isOriginalWaypoint); menu.findItem(R.id.menu_waypoint_edit).setVisible(!isOriginalWaypoint); menu.findItem(R.id.menu_waypoint_duplicate).setVisible(!isOriginalWaypoint); final boolean userDefined = selectedWaypoint.isUserDefined() && !selectedWaypoint.getWaypointType().equals(WaypointType.ORIGINAL); menu.findItem(R.id.menu_waypoint_delete).setVisible(userDefined); final boolean hasCoords = selectedWaypoint.getCoords() != null; final MenuItem defaultNavigationMenu = menu.findItem(R.id.menu_waypoint_navigate_default); defaultNavigationMenu.setVisible(hasCoords); defaultNavigationMenu.setTitle(NavigationAppFactory.getDefaultNavigationApplication().getName()); menu.findItem(R.id.menu_waypoint_navigate).setVisible(hasCoords); menu.findItem(R.id.menu_waypoint_caches_around).setVisible(hasCoords); break; default: if (imagesList != null) { imagesList.onCreateContextMenu(menu, view); } break; } } private void buildDetailsContextMenu(ContextMenu menu, String fieldTitle, boolean copyOnly) { menu.setHeaderTitle(fieldTitle); getMenuInflater().inflate(R.menu.details_context, menu); menu.findItem(R.id.menu_translate_to_sys_lang).setVisible(!copyOnly); if (!copyOnly) { if (clickedItemText.length() > TranslationUtils.TRANSLATION_TEXT_LENGTH_WARN) { showToast(res.getString(R.string.translate_length_warning)); } menu.findItem(R.id.menu_translate_to_sys_lang).setTitle(res.getString(R.string.translate_to_sys_lang, Locale.getDefault().getDisplayLanguage())); } final boolean localeIsEnglish = StringUtils.equals(Locale.getDefault().getLanguage(), Locale.ENGLISH.getLanguage()); menu.findItem(R.id.menu_translate_to_english).setVisible(!copyOnly && !localeIsEnglish); } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { // detail fields case R.id.menu_copy: ClipboardUtils.copyToClipboard(clickedItemText); showToast(res.getString(R.string.clipboard_copy_ok)); return true; case R.id.menu_translate_to_sys_lang: TranslationUtils.startActivityTranslate(this, Locale.getDefault().getLanguage(), HtmlUtils.extractText(clickedItemText)); return true; case R.id.menu_translate_to_english: TranslationUtils.startActivityTranslate(this, Locale.ENGLISH.getLanguage(), HtmlUtils.extractText(clickedItemText)); return true; case R.id.menu_cache_share_field: final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, clickedItemText.toString()); startActivity(Intent.createChooser(intent, res.getText(R.string.cache_share_field))); return true; // waypoints case R.id.menu_waypoint_edit: if (selectedWaypoint != null) { EditWaypointActivity.startActivityEditWaypoint(this, cache, selectedWaypoint.getId()); refreshOnResume = true; } return true; case R.id.menu_waypoint_duplicate: if (cache.duplicateWaypoint(selectedWaypoint)) { DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); notifyDataSetChanged(); } return true; case R.id.menu_waypoint_delete: if (cache.deleteWaypoint(selectedWaypoint)) { DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); notifyDataSetChanged(); } return true; case R.id.menu_waypoint_navigate_default: if (selectedWaypoint != null) { NavigationAppFactory.startDefaultNavigationApplication(1, this, selectedWaypoint); } return true; case R.id.menu_waypoint_navigate: if (selectedWaypoint != null) { NavigationAppFactory.showNavigationMenu(this, null, selectedWaypoint, null); } return true; case R.id.menu_waypoint_caches_around: if (selectedWaypoint != null) { CacheListActivity.startActivityCoordinates(this, selectedWaypoint.getCoords()); } return true; case R.id.menu_waypoint_reset_cache_coords: if (ConnectorFactory.getConnector(cache).supportsOwnCoordinates()) { createResetCacheCoordinatesDialog(cache, selectedWaypoint).show(); } else { final ProgressDialog progressDialog = ProgressDialog.show(this, getString(R.string.cache), getString(R.string.waypoint_reset), true); final HandlerResetCoordinates handler = new HandlerResetCoordinates(this, progressDialog, false); new ResetCoordsThread(cache, handler, selectedWaypoint, true, false, progressDialog).start(); } return true; default: break; } if (imagesList != null && imagesList.onContextItemSelected(item)) { return true; } return onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { CacheMenuHandler.addMenuItems(this, menu, cache); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { CacheMenuHandler.onPrepareOptionsMenu(menu, cache); LoggingUI.onPrepareOptionsMenu(menu, cache); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (CacheMenuHandler.onMenuItemSelected(item, this, cache)) { return true; } final int menuItem = item.getItemId(); switch (menuItem) { case 0: // no menu selected, but a new sub menu shown return false; default: if (NavigationAppFactory.onMenuItemSelected(item, this, cache)) { return true; } if (LoggingUI.onMenuItemSelected(item, this, cache)) { refreshOnResume = true; return true; } } return true; } private final static class LoadCacheHandler extends SimpleCancellableHandler { public LoadCacheHandler(CacheDetailActivity activity, Progress progress) { super(activity, progress); } @Override public void handleRegularMessage(final Message msg) { if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) { updateStatusMsg((String) msg.obj); } else { final CacheDetailActivity activity = ((CacheDetailActivity) activityRef.get()); if (activity == null) { return; } if (activity.search == null) { showToast(R.string.err_dwld_details_failed); dismissProgress(); finishActivity(); return; } if (activity.search.getError() != null) { activity.showToast(activity.getResources().getString(R.string.err_dwld_details_failed) + " " + activity.search.getError().getErrorString(activity.getResources()) + "."); dismissProgress(); finishActivity(); return; } updateStatusMsg(activity.getResources().getString(R.string.cache_dialog_loading_details_status_render)); // Data loaded, we're ready to show it! activity.notifyDataSetChanged(); } } private void updateStatusMsg(final String msg) { CacheDetailActivity activity = ((CacheDetailActivity) activityRef.get()); if (activity == null) { return; } setProgressMessage(activity.getResources().getString(R.string.cache_dialog_loading_details) + "\n\n" + msg); } @Override public void handleCancel(final Object extra) { finishActivity(); } } private void notifyDataSetChanged() { if (search == null) { return; } cache = search.getFirstCacheFromResult(LoadFlags.LOAD_ALL_DB_ONLY); if (cache == null) { progress.dismiss(); showToast(res.getString(R.string.err_detail_cache_find_some)); finish(); return; } // allow cache to notify CacheDetailActivity when it changes so it can be reloaded cache.setChangeNotificationHandler(new ChangeNotificationHandler(this, progress)); // action bar: title and icon if (StringUtils.isNotBlank(cache.getName())) { setTitle(cache.getName() + " (" + cache.getGeocode() + ')'); } else { setTitle(cache.getGeocode()); } ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cache.getType().markerId), null, null, null); // reset imagesList so Images view page will be redrawn imagesList = null; reinitializeViewPager(); // rendering done! remove progress popup if any there invalidateOptionsMenuCompatible(); progress.dismiss(); } /** * Loads the cache with the given geocode or guid. */ private class LoadCacheThread extends Thread { private CancellableHandler handler = null; private String geocode; private String guid; public LoadCacheThread(final String geocode, final String guid, final CancellableHandler handlerIn) { handler = handlerIn; if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { showToast(res.getString(R.string.err_detail_cache_forgot)); progress.dismiss(); finish(); return; } this.geocode = geocode; this.guid = guid; } @Override public void run() { search = Geocache.searchByGeocode(geocode, StringUtils.isBlank(geocode) ? guid : null, 0, false, handler); handler.sendMessage(Message.obtain()); } } /** * Tries to navigate to the {@link Geocache} of this activity. */ private void startDefaultNavigation() { NavigationAppFactory.startDefaultNavigationApplication(1, this, cache); } /** * Tries to navigate to the {@link Geocache} of this activity. */ private void startDefaultNavigation2() { NavigationAppFactory.startDefaultNavigationApplication(2, this, cache); } /** * Wrapper for the referenced method in the xml-layout. */ public void goDefaultNavigation(@SuppressWarnings("unused") View view) { startDefaultNavigation(); } /** * referenced from XML view */ public void showNavigationMenu(@SuppressWarnings("unused") View view) { NavigationAppFactory.showNavigationMenu(this, cache, null, null, true, true); } private void loadCacheImages() { if (imagesList != null) { return; } final PageViewCreator creator = getViewCreator(Page.IMAGES); if (creator == null) { return; } final View imageView = creator.getView(); if (imageView == null) { return; } imagesList = new ImagesList(this, cache.getGeocode()); imagesList.loadImages(imageView, cache.getImages(), false); } public static void startActivity(final Context context, final String geocode) { final Intent detailIntent = new Intent(context, CacheDetailActivity.class); detailIntent.putExtra(Intents.EXTRA_GEOCODE, geocode); context.startActivity(detailIntent); } /** * Enum of all possible pages with methods to get the view and a title. */ public enum Page { DETAILS(R.string.detail), DESCRIPTION(R.string.cache_description), LOGS(R.string.cache_logs), LOGSFRIENDS(R.string.cache_logsfriends), WAYPOINTS(R.string.cache_waypoints), INVENTORY(R.string.cache_inventory), IMAGES(R.string.cache_images); final private int titleStringId; Page(final int titleStringId) { this.titleStringId = titleStringId; } } private class AttributeViewBuilder { private ViewGroup attributeIconsLayout; // layout for attribute icons private ViewGroup attributeDescriptionsLayout; // layout for attribute descriptions private boolean attributesShowAsIcons = true; // default: show icons /** * If the cache is from a non GC source, it might be without icons. Disable switching in those cases. */ private boolean noAttributeIconsFound = false; private int attributeBoxMaxWidth; public void fillView(final LinearLayout attributeBox) { // first ensure that the view is empty attributeBox.removeAllViews(); // maximum width for attribute icons is screen width - paddings of parents attributeBoxMaxWidth = Compatibility.getDisplayWidth(); ViewParent child = attributeBox; do { if (child instanceof View) { attributeBoxMaxWidth -= ((View) child).getPaddingLeft() + ((View) child).getPaddingRight(); } child = child.getParent(); } while (child != null); // delete views holding description / icons attributeDescriptionsLayout = null; attributeIconsLayout = null; attributeBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // toggle between attribute icons and descriptions toggleAttributeDisplay(attributeBox, attributeBoxMaxWidth); } }); // icons or text? // also show icons when noAttributeImagesFound == true. Explanation: // 1. no icons could be found in the first invocation of this method // 2. user refreshes cache from web // 3. now this method is called again // 4. attributeShowAsIcons is false but noAttributeImagesFound is true // => try to show them now if (attributesShowAsIcons || noAttributeIconsFound) { showAttributeIcons(attributeBox, attributeBoxMaxWidth); } else { showAttributeDescriptions(attributeBox); } } /** * lazy-creates the layout holding the icons of the caches attributes * and makes it visible */ private void showAttributeIcons(LinearLayout attribBox, int parentWidth) { if (attributeIconsLayout == null) { attributeIconsLayout = createAttributeIconsLayout(parentWidth); // no matching icons found? show text if (noAttributeIconsFound) { showAttributeDescriptions(attribBox); return; } } attribBox.removeAllViews(); attribBox.addView(attributeIconsLayout); attributesShowAsIcons = true; } /** * lazy-creates the layout holding the descriptions of the caches attributes * and makes it visible */ private void showAttributeDescriptions(LinearLayout attribBox) { if (attributeDescriptionsLayout == null) { attributeDescriptionsLayout = createAttributeDescriptionsLayout(); } attribBox.removeAllViews(); attribBox.addView(attributeDescriptionsLayout); attributesShowAsIcons = false; } /** * toggle attribute descriptions and icons */ private void toggleAttributeDisplay(LinearLayout attribBox, int parentWidth) { // Don't toggle when there are no icons to show. if (noAttributeIconsFound) { return; } // toggle if (attributesShowAsIcons) { showAttributeDescriptions(attribBox); } else { showAttributeIcons(attribBox, parentWidth); } } private ViewGroup createAttributeIconsLayout(int parentWidth) { final LinearLayout rows = new LinearLayout(CacheDetailActivity.this); rows.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); rows.setOrientation(LinearLayout.VERTICAL); LinearLayout attributeRow = newAttributeIconsRow(); rows.addView(attributeRow); noAttributeIconsFound = true; for (final String attributeName : cache.getAttributes()) { // check if another attribute icon fits in this row attributeRow.measure(0, 0); final int rowWidth = attributeRow.getMeasuredWidth(); final FrameLayout fl = (FrameLayout) getLayoutInflater().inflate(R.layout.attribute_image, null); final ImageView iv = (ImageView) fl.getChildAt(0); if ((parentWidth - rowWidth) < iv.getLayoutParams().width) { // make a new row attributeRow = newAttributeIconsRow(); rows.addView(attributeRow); } final boolean strikethru = !CacheAttribute.isEnabled(attributeName); final CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName)); if (attrib != null) { noAttributeIconsFound = false; Drawable d = res.getDrawable(attrib.drawableId); iv.setImageDrawable(d); // strike through? if (strikethru) { // generate strikethru image with same properties as attribute image final ImageView strikethruImage = new ImageView(CacheDetailActivity.this); strikethruImage.setLayoutParams(iv.getLayoutParams()); d = res.getDrawable(R.drawable.attribute__strikethru); strikethruImage.setImageDrawable(d); fl.addView(strikethruImage); } } else { final Drawable d = res.getDrawable(R.drawable.attribute_unknown); iv.setImageDrawable(d); } attributeRow.addView(fl); } return rows; } private LinearLayout newAttributeIconsRow() { final LinearLayout rowLayout = new LinearLayout(CacheDetailActivity.this); rowLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); rowLayout.setOrientation(LinearLayout.HORIZONTAL); return rowLayout; } private ViewGroup createAttributeDescriptionsLayout() { final LinearLayout descriptions = (LinearLayout) getLayoutInflater().inflate( R.layout.attribute_descriptions, null); final TextView attribView = (TextView) descriptions.getChildAt(0); final StringBuilder buffer = new StringBuilder(); for (String attributeName : cache.getAttributes()) { final boolean enabled = CacheAttribute.isEnabled(attributeName); // search for a translation of the attribute CacheAttribute attrib = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attributeName)); if (attrib != null) { attributeName = attrib.getL10n(enabled); } if (buffer.length() > 0) { buffer.append('\n'); } buffer.append(attributeName); } attribView.setText(buffer); return descriptions; } } /** * Creator for details-view. */ private class DetailsViewCreator extends AbstractCachingPageViewCreator<ScrollView> { /** * Reference to the details list, so that the helper-method can access it without an additional argument */ private LinearLayout detailsList; // TODO Do we need this thread-references? private RefreshCacheThread refreshThread; private Thread watchlistThread; @Override public ScrollView getDispatchedView() { if (cache == null) { // something is really wrong return null; } view = (ScrollView) getLayoutInflater().inflate(R.layout.cachedetail_details_page, null); // Start loading preview map if (Settings.isStoreOfflineMaps()) { new PreviewMapTask().execute((Void) null); } detailsList = (LinearLayout) view.findViewById(R.id.details_list); final CacheDetailsCreator details = new CacheDetailsCreator(CacheDetailActivity.this, detailsList); // cache name (full name) final Spannable span = (new Spannable.Factory()).newSpannable(Html.fromHtml(cache.getName()).toString()); if (cache.isDisabled() || cache.isArchived()) { // strike span.setSpan(new StrikethroughSpan(), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (cache.isArchived()) { span.setSpan(new ForegroundColorSpan(res.getColor(R.color.archived_cache_color)), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } registerForContextMenu(details.add(R.string.cache_name, span)); details.add(R.string.cache_type, cache.getType().getL10n()); details.addSize(cache); registerForContextMenu(details.add(R.string.cache_geocode, cache.getGeocode())); details.addCacheState(cache); details.addDistance(cache, cacheDistanceView); cacheDistanceView = details.getValueView(); details.addDifficulty(cache); details.addTerrain(cache); details.addRating(cache); // favorite count if (cache.getFavoritePoints() > 0) { details.add(R.string.cache_favorite, cache.getFavoritePoints() + "×"); } // own rating if (cache.getMyVote() > 0) { details.addStars(R.string.cache_own_rating, cache.getMyVote()); } // cache author if (StringUtils.isNotBlank(cache.getOwnerDisplayName()) || StringUtils.isNotBlank(cache.getOwnerUserId())) { final TextView ownerView = details.add(R.string.cache_owner, ""); if (StringUtils.isNotBlank(cache.getOwnerDisplayName())) { ownerView.setText(cache.getOwnerDisplayName(), TextView.BufferType.SPANNABLE); } else { // OwnerReal guaranteed to be not blank based on above ownerView.setText(cache.getOwnerUserId(), TextView.BufferType.SPANNABLE); } ownerView.setOnClickListener(new OwnerActionsClickListener(cache)); } // cache hidden final Date hiddenDate = cache.getHiddenDate(); if (hiddenDate != null) { final long time = hiddenDate.getTime(); if (time > 0) { String dateString = Formatter.formatFullDate(time); if (cache.isEventCache()) { dateString = DateUtils.formatDateTime(CgeoApplication.getInstance().getBaseContext(), time, DateUtils.FORMAT_SHOW_WEEKDAY) + ", " + dateString; } details.add(cache.isEventCache() ? R.string.cache_event : R.string.cache_hidden, dateString); } } // cache location if (StringUtils.isNotBlank(cache.getLocation())) { details.add(R.string.cache_location, cache.getLocation()); } // cache coordinates if (cache.getCoords() != null) { final TextView valueView = details.add(R.string.cache_coordinates, cache.getCoords().toString()); valueView.setOnClickListener(new CoordinatesFormatSwitcher(cache.getCoords())); registerForContextMenu(valueView); } // cache attributes if (!cache.getAttributes().isEmpty()) { new AttributeViewBuilder().fillView((LinearLayout) view.findViewById(R.id.attributes_innerbox)); view.findViewById(R.id.attributes_box).setVisibility(View.VISIBLE); } updateOfflineBox(view, cache, res, new RefreshCacheClickListener(), new DropCacheClickListener(), new StoreCacheClickListener()); // watchlist final Button buttonWatchlistAdd = (Button) view.findViewById(R.id.add_to_watchlist); final Button buttonWatchlistRemove = (Button) view.findViewById(R.id.remove_from_watchlist); buttonWatchlistAdd.setOnClickListener(new AddToWatchlistClickListener()); buttonWatchlistRemove.setOnClickListener(new RemoveFromWatchlistClickListener()); updateWatchlistBox(); // favorite points final Button buttonFavPointAdd = (Button) view.findViewById(R.id.add_to_favpoint); final Button buttonFavPointRemove = (Button) view.findViewById(R.id.remove_from_favpoint); buttonFavPointAdd.setOnClickListener(new FavoriteAddClickListener()); buttonFavPointRemove.setOnClickListener(new FavoriteRemoveClickListener()); updateFavPointBox(); // list final Button buttonChangeList = (Button) view.findViewById(R.id.change_list); buttonChangeList.setOnClickListener(new ChangeListClickListener()); updateListBox(); final IConnector connector = ConnectorFactory.getConnector(cache); final String license = connector.getLicenseText(cache); if (StringUtils.isNotBlank(license)) { view.findViewById(R.id.license_box).setVisibility(View.VISIBLE); final TextView licenseView = ((TextView) view.findViewById(R.id.license)); licenseView.setText(Html.fromHtml(license), BufferType.SPANNABLE); licenseView.setClickable(true); licenseView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance()); } else { view.findViewById(R.id.license_box).setVisibility(View.GONE); } return view; } private class StoreCacheClickListener implements View.OnClickListener { @Override public void onClick(View arg0) { if (progress.isShowing()) { showToast(res.getString(R.string.err_detail_still_working)); return; } if (Settings.getChooseList()) { // let user select list to store cache in new StoredList.UserInterface(CacheDetailActivity.this).promptForListSelection(R.string.list_title, new RunnableWithArgument<Integer>() { @Override public void run(final Integer selectedListId) { storeCache(selectedListId, new StoreCacheHandler(CacheDetailActivity.this, progress)); } }, true, StoredList.TEMPORARY_LIST_ID); } else { storeCache(StoredList.TEMPORARY_LIST_ID, new StoreCacheHandler(CacheDetailActivity.this, progress)); } } } private class RefreshCacheClickListener implements View.OnClickListener { @Override public void onClick(View arg0) { if (progress.isShowing()) { showToast(res.getString(R.string.err_detail_still_working)); return; } if (!Network.isNetworkConnected(getApplicationContext())) { showToast(getString(R.string.err_server)); return; } final RefreshCacheHandler refreshCacheHandler = new RefreshCacheHandler(CacheDetailActivity.this, progress); progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.cancelMessage()); if (refreshThread != null) { refreshThread.interrupt(); } refreshThread = new RefreshCacheThread(refreshCacheHandler); refreshThread.start(); } } private class RefreshCacheThread extends Thread { final private CancellableHandler handler; public RefreshCacheThread(final CancellableHandler handler) { this.handler = handler; } @Override public void run() { cache.refresh(cache.getListId(), handler); refreshThread = null; handler.sendEmptyMessage(0); } } private class DropCacheClickListener implements View.OnClickListener { @Override public void onClick(View arg0) { if (progress.isShowing()) { showToast(res.getString(R.string.err_detail_still_working)); return; } progress.show(CacheDetailActivity.this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null); new DropCacheThread(new ChangeNotificationHandler(CacheDetailActivity.this, progress)).start(); } } private class DropCacheThread extends Thread { private Handler handler; public DropCacheThread(Handler handler) { this.handler = handler; } @Override public void run() { cache.drop(this.handler); } } /** * Abstract Listener for add / remove buttons for watchlist */ private abstract class AbstractWatchlistClickListener implements View.OnClickListener { public void doExecute(int titleId, int messageId, Thread thread) { if (progress.isShowing()) { showToast(res.getString(R.string.err_watchlist_still_managing)); return; } progress.show(CacheDetailActivity.this, res.getString(titleId), res.getString(messageId), true, null); if (watchlistThread != null) { watchlistThread.interrupt(); } watchlistThread = thread; watchlistThread.start(); } } /** * Listener for "add to watchlist" button */ private class AddToWatchlistClickListener extends AbstractWatchlistClickListener { @Override public void onClick(View arg0) { doExecute(R.string.cache_dialog_watchlist_add_title, R.string.cache_dialog_watchlist_add_message, new WatchlistAddThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress))); } } /** * Listener for "remove from watchlist" button */ private class RemoveFromWatchlistClickListener extends AbstractWatchlistClickListener { @Override public void onClick(View arg0) { doExecute(R.string.cache_dialog_watchlist_remove_title, R.string.cache_dialog_watchlist_remove_message, new WatchlistRemoveThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress))); } } /** Thread to add this cache to the watchlist of the user */ private class WatchlistAddThread extends Thread { private final Handler handler; public WatchlistAddThread(Handler handler) { this.handler = handler; } @Override public void run() { watchlistThread = null; Message msg; if (ConnectorFactory.getConnector(cache).addToWatchlist(cache)) { msg = Message.obtain(handler, MESSAGE_SUCCEEDED); } else { msg = Message.obtain(handler, MESSAGE_FAILED); Bundle bundle = new Bundle(); bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_watchlist_failed)); msg.setData(bundle); } handler.sendMessage(msg); } } /** Thread to remove this cache from the watchlist of the user */ private class WatchlistRemoveThread extends Thread { private final Handler handler; public WatchlistRemoveThread(Handler handler) { this.handler = handler; } @Override public void run() { watchlistThread = null; Message msg; if (ConnectorFactory.getConnector(cache).removeFromWatchlist(cache)) { msg = Message.obtain(handler, MESSAGE_SUCCEEDED); } else { msg = Message.obtain(handler, MESSAGE_FAILED); Bundle bundle = new Bundle(); bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_watchlist_failed)); msg.setData(bundle); } handler.sendMessage(msg); } } /** Thread to add this cache to the favorite list of the user */ private class FavoriteAddThread extends Thread { private final Handler handler; public FavoriteAddThread(Handler handler) { this.handler = handler; } @Override public void run() { watchlistThread = null; Message msg; if (GCConnector.addToFavorites(cache)) { msg = Message.obtain(handler, MESSAGE_SUCCEEDED); } else { msg = Message.obtain(handler, MESSAGE_FAILED); Bundle bundle = new Bundle(); bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_favorite_failed)); msg.setData(bundle); } handler.sendMessage(msg); } } /** Thread to remove this cache to the favorite list of the user */ private class FavoriteRemoveThread extends Thread { private final Handler handler; public FavoriteRemoveThread(Handler handler) { this.handler = handler; } @Override public void run() { watchlistThread = null; Message msg; if (GCConnector.removeFromFavorites(cache)) { msg = Message.obtain(handler, MESSAGE_SUCCEEDED); } else { msg = Message.obtain(handler, MESSAGE_FAILED); Bundle bundle = new Bundle(); bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.err_favorite_failed)); msg.setData(bundle); } handler.sendMessage(msg); } } /** * Listener for "add to favorites" button */ private class FavoriteAddClickListener extends AbstractWatchlistClickListener { @Override public void onClick(View arg0) { doExecute(R.string.cache_dialog_favorite_add_title, R.string.cache_dialog_favorite_add_message, new FavoriteAddThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress))); } } /** * Listener for "remove from favorites" button */ private class FavoriteRemoveClickListener extends AbstractWatchlistClickListener { @Override public void onClick(View arg0) { doExecute(R.string.cache_dialog_favorite_remove_title, R.string.cache_dialog_favorite_remove_message, new FavoriteRemoveThread(new SimpleUpdateHandler(CacheDetailActivity.this, progress))); } } /** * Listener for "change list" button */ private class ChangeListClickListener implements View.OnClickListener { @Override public void onClick(View view) { new StoredList.UserInterface(CacheDetailActivity.this).promptForListSelection(R.string.list_title, new RunnableWithArgument<Integer>() { @Override public void run(final Integer selectedListId) { switchListById(selectedListId); } }, true, cache.getListId()); } } /** * move cache to another list * * @param listId * the ID of the list */ public void switchListById(int listId) { if (listId < 0) { return; } Settings.saveLastList(listId); DataStore.moveToList(cache, listId); updateListBox(); } /** * shows/hides buttons, sets text in watchlist box */ private void updateWatchlistBox() { final LinearLayout layout = (LinearLayout) view.findViewById(R.id.watchlist_box); final boolean supportsWatchList = cache.supportsWatchList(); layout.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE); if (!supportsWatchList) { return; } final Button buttonAdd = (Button) view.findViewById(R.id.add_to_watchlist); final Button buttonRemove = (Button) view.findViewById(R.id.remove_from_watchlist); final TextView text = (TextView) view.findViewById(R.id.watchlist_text); if (cache.isOnWatchlist() || cache.isOwner()) { buttonAdd.setVisibility(View.GONE); buttonRemove.setVisibility(View.VISIBLE); text.setText(R.string.cache_watchlist_on); } else { buttonAdd.setVisibility(View.VISIBLE); buttonRemove.setVisibility(View.GONE); text.setText(R.string.cache_watchlist_not_on); } // the owner of a cache has it always on his watchlist. Adding causes an error if (cache.isOwner()) { buttonAdd.setEnabled(false); buttonAdd.setVisibility(View.GONE); buttonRemove.setEnabled(false); buttonRemove.setVisibility(View.GONE); } } /** * shows/hides buttons, sets text in watchlist box */ private void updateFavPointBox() { final LinearLayout layout = (LinearLayout) view.findViewById(R.id.favpoint_box); final boolean supportsFavoritePoints = cache.supportsFavoritePoints(); layout.setVisibility(supportsFavoritePoints ? View.VISIBLE : View.GONE); if (!supportsFavoritePoints || cache.isOwner() || !Settings.isGCPremiumMember()) { return; } final Button buttonAdd = (Button) view.findViewById(R.id.add_to_favpoint); final Button buttonRemove = (Button) view.findViewById(R.id.remove_from_favpoint); final TextView text = (TextView) view.findViewById(R.id.favpoint_text); if (cache.isFavorite()) { buttonAdd.setVisibility(View.GONE); buttonRemove.setVisibility(View.VISIBLE); text.setText(R.string.cache_favpoint_on); } else { buttonAdd.setVisibility(View.VISIBLE); buttonRemove.setVisibility(View.GONE); text.setText(R.string.cache_favpoint_not_on); } // Add/remove to Favorites is only possible if the cache has been found if (!cache.isFound()) { buttonAdd.setEnabled(false); buttonAdd.setVisibility(View.GONE); buttonRemove.setEnabled(false); buttonRemove.setVisibility(View.GONE); } } /** * shows/hides/updates list box */ private void updateListBox() { final View box = view.findViewById(R.id.list_box); if (cache.isOffline()) { // show box box.setVisibility(View.VISIBLE); // update text final TextView text = (TextView) view.findViewById(R.id.list_text); final StoredList list = DataStore.getList(cache.getListId()); if (list != null) { text.setText(res.getString(R.string.cache_list_text) + " " + list.title); } else { // this should not happen text.setText(R.string.cache_list_unknown); } } else { // hide box box.setVisibility(View.GONE); } } private class PreviewMapTask extends AsyncTask<Void, Void, BitmapDrawable> { @Override protected BitmapDrawable doInBackground(Void... parameters) { try { // persistent preview from storage Bitmap image = decode(cache); if (image == null) { StaticMapsProvider.storeCachePreviewMap(cache); image = decode(cache); if (image == null) { return null; } } return ImageUtils.scaleBitmapToFitDisplay(image); } catch (final Exception e) { Log.w("CacheDetailActivity.PreviewMapTask", e); return null; } } private Bitmap decode(final Geocache cache) { return StaticMapsProvider.getPreviewMap(cache.getGeocode()); } @Override protected void onPostExecute(BitmapDrawable image) { if (image == null) { return; } try { final Bitmap bitmap = image.getBitmap(); if (bitmap == null || bitmap.getWidth() <= 10) { return; } final ImageView imageView = (ImageView) view.findViewById(R.id.map_preview); imageView.setImageDrawable(image); view.findViewById(R.id.map_preview_box).setVisibility(View.VISIBLE); } catch (final Exception e) { Log.e("CacheDetailActivity.PreviewMapTask", e); } } } } protected class DescriptionViewCreator extends AbstractCachingPageViewCreator<ScrollView> { @InjectView(R.id.personalnote) protected TextView personalNoteView; @Override public ScrollView getDispatchedView() { if (cache == null) { // something is really wrong return null; } view = (ScrollView) getLayoutInflater().inflate(R.layout.cachedetail_description_page, null); ButterKnife.inject(this, view); // cache short description if (StringUtils.isNotBlank(cache.getShortDescription())) { new LoadDescriptionTask(cache.getShortDescription(), view.findViewById(R.id.shortdesc), null, null).execute(); } // long description if (StringUtils.isNotBlank(cache.getDescription())) { if (Settings.isAutoLoadDescription()) { loadLongDescription(); } else { final Button showDesc = (Button) view.findViewById(R.id.show_description); showDesc.setVisibility(View.VISIBLE); showDesc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { loadLongDescription(); } }); } } // cache personal note setPersonalNote(personalNoteView, cache.getPersonalNote()); personalNoteView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance()); registerForContextMenu(personalNoteView); final Button personalNoteEdit = (Button) view.findViewById(R.id.edit_personalnote); personalNoteEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (cache.isOffline()) { editPersonalNote(cache, CacheDetailActivity.this); } else { warnPersonalNoteNeedsStoring(); } } }); final Button personalNoteUpload = (Button) view.findViewById(R.id.upload_personalnote); if (cache.isOffline() && ConnectorFactory.getConnector(cache).supportsPersonalNote()) { personalNoteUpload.setVisibility(View.VISIBLE); personalNoteUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (StringUtils.length(cache.getPersonalNote()) > GCConstants.PERSONAL_NOTE_MAX_CHARS) { warnPersonalNoteExceedsLimit(); } else { uploadPersonalNote(); } } }); } else { personalNoteUpload.setVisibility(View.GONE); } // cache hint and spoiler images final View hintBoxView = view.findViewById(R.id.hint_box); if (StringUtils.isNotBlank(cache.getHint()) || CollectionUtils.isNotEmpty(cache.getSpoilers())) { hintBoxView.setVisibility(View.VISIBLE); } else { hintBoxView.setVisibility(View.GONE); } final TextView hintView = ((TextView) view.findViewById(R.id.hint)); if (StringUtils.isNotBlank(cache.getHint())) { if (TextUtils.containsHtml(cache.getHint())) { hintView.setText(Html.fromHtml(cache.getHint(), new HtmlImage(cache.getGeocode(), false, cache.getListId(), false), null), TextView.BufferType.SPANNABLE); hintView.setText(CryptUtils.rot13((Spannable) hintView.getText())); } else { hintView.setText(CryptUtils.rot13(cache.getHint())); } hintView.setVisibility(View.VISIBLE); hintView.setClickable(true); hintView.setOnClickListener(new DecryptTextClickListener(hintView)); hintBoxView.setOnClickListener(new DecryptTextClickListener(hintView)); hintBoxView.setClickable(true); registerForContextMenu(hintView); } else { hintView.setVisibility(View.GONE); hintView.setClickable(false); hintView.setOnClickListener(null); hintBoxView.setClickable(false); hintBoxView.setOnClickListener(null); } final TextView spoilerlinkView = ((TextView) view.findViewById(R.id.hint_spoilerlink)); if (CollectionUtils.isNotEmpty(cache.getSpoilers())) { spoilerlinkView.setVisibility(View.VISIBLE); spoilerlinkView.setClickable(true); spoilerlinkView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (cache == null || CollectionUtils.isEmpty(cache.getSpoilers())) { showToast(res.getString(R.string.err_detail_no_spoiler)); return; } ImagesActivity.startActivitySpoilerImages(CacheDetailActivity.this, cache.getGeocode(), cache.getSpoilers()); } }); } else { spoilerlinkView.setVisibility(View.GONE); spoilerlinkView.setClickable(true); spoilerlinkView.setOnClickListener(null); } return view; } Thread currentThread; private void uploadPersonalNote() { final SimpleCancellableHandler myHandler = new SimpleCancellableHandler(CacheDetailActivity.this, progress); Message cancelMessage = myHandler.cancelMessage(res.getString(R.string.cache_personal_note_upload_cancelled)); progress.show(CacheDetailActivity.this, res.getString(R.string.cache_personal_note_uploading), res.getString(R.string.cache_personal_note_uploading), true, cancelMessage); if (currentThread != null) { currentThread.interrupt(); } currentThread = new UploadPersonalNoteThread(cache, myHandler); currentThread.start(); } private void loadLongDescription() { final Button showDesc = (Button) view.findViewById(R.id.show_description); showDesc.setVisibility(View.GONE); showDesc.setOnClickListener(null); view.findViewById(R.id.loading).setVisibility(View.VISIBLE); new LoadDescriptionTask(cache.getDescription(), view.findViewById(R.id.longdesc), view.findViewById(R.id.loading), view.findViewById(R.id.shortdesc)).execute(); } private void warnPersonalNoteNeedsStoring() { Dialogs.confirm(CacheDetailActivity.this, R.string.cache_personal_note_unstored, R.string.cache_personal_note_store, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); storeCache(StoredList.STANDARD_LIST_ID, new StoreCachePersonalNoteHandler(CacheDetailActivity.this, progress)); } }); } private void warnPersonalNoteExceedsLimit() { Dialogs.confirm(CacheDetailActivity.this, R.string.cache_personal_note_limit, getString(R.string.cache_personal_note_truncation, GCConstants.PERSONAL_NOTE_MAX_CHARS), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); uploadPersonalNote(); } }); } } /** * Loads the description in background. <br /> * <br /> * Params: * <ol> * <li>description string (String)</li> * <li>target description view (TextView)</li> * <li>loading indicator view (View, may be null)</li> * </ol> */ private class LoadDescriptionTask extends AsyncTask<Object, Void, Void> { private final View loadingIndicatorView; private final IndexOutOfBoundsAvoidingTextView descriptionView; private final String descriptionString; private Spanned description; private final View shortDescView; public LoadDescriptionTask(final String description, final View descriptionView, final View loadingIndicatorView, final View shortDescView) { assert descriptionView instanceof IndexOutOfBoundsAvoidingTextView; this.descriptionString = description; this.descriptionView = (IndexOutOfBoundsAvoidingTextView) descriptionView; this.loadingIndicatorView = loadingIndicatorView; this.shortDescView = shortDescView; } @Override protected Void doInBackground(Object... params) { try { // Fast preview: parse only HTML without loading any images final HtmlImageCounter imageCounter = new HtmlImageCounter(); final UnknownTagsHandler unknownTagsHandler = new UnknownTagsHandler(); description = Html.fromHtml(descriptionString, imageCounter, unknownTagsHandler); publishProgress(); boolean needsRefresh = false; if (imageCounter.getImageCount() > 0) { // Complete view: parse again with loading images - if necessary ! If there are any images causing problems the user can see at least the preview description = Html.fromHtml(descriptionString, new HtmlImage(cache.getGeocode(), true, cache.getListId(), false), unknownTagsHandler); needsRefresh = true; } // If description has an HTML construct which may be problematic to render, add a note at the end of the long description. // Technically, it may not be a table, but a pre, which has the same problems as a table, so the message is ok even though // sometimes technically incorrect. if (unknownTagsHandler.isProblematicDetected() && descriptionView != null) { final int startPos = description.length(); final IConnector connector = ConnectorFactory.getConnector(cache); final Spanned tableNote = Html.fromHtml(res.getString(R.string.cache_description_table_note, "<a href=\"" + cache.getUrl() + "\">" + connector.getName() + "</a>")); ((Editable) description).append("\n\n").append(tableNote); ((Editable) description).setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); needsRefresh = true; } if (needsRefresh) { publishProgress(); } } catch (final Exception e) { Log.e("LoadDescriptionTask: ", e); } return null; } @Override protected void onProgressUpdate(Void... values) { if (description == null) { showToast(res.getString(R.string.err_load_descr_failed)); return; } if (StringUtils.isNotBlank(descriptionString)) { try { descriptionView.setText(description, TextView.BufferType.SPANNABLE); } catch (final Exception e) { Log.e("Android bug setting text: ", e); // remove the formatting by converting to a simple string descriptionView.setText(description.toString()); } descriptionView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance()); fixTextColor(descriptionView, descriptionString); descriptionView.setVisibility(View.VISIBLE); registerForContextMenu(descriptionView); hideDuplicatedShortDescription(); } } /** * Hide the short description, if it is contained somewhere at the start of the long description. */ private void hideDuplicatedShortDescription() { if (shortDescView != null) { final String shortDescription = cache.getShortDescription(); if (StringUtils.isNotBlank(shortDescription)) { final int index = descriptionString.indexOf(shortDescription); if (index >= 0 && index < 200) { shortDescView.setVisibility(View.GONE); } } } } @Override protected void onPostExecute(Void result) { if (null != loadingIndicatorView) { loadingIndicatorView.setVisibility(View.GONE); } } /** * Handle caches with black font color in dark skin and white font color in light skin * by changing background color of the view * * @param view * containing the text * @param text * to be checked */ private void fixTextColor(final TextView view, final String text) { int backcolor; if (Settings.isLightSkin()) { backcolor = color.white; for (final Pattern pattern : LIGHT_COLOR_PATTERNS) { final MatcherWrapper matcher = new MatcherWrapper(pattern, text); if (matcher.find()) { view.setBackgroundResource(color.darker_gray); return; } } } else { backcolor = color.black; for (final Pattern pattern : DARK_COLOR_PATTERNS) { final MatcherWrapper matcher = new MatcherWrapper(pattern, text); if (matcher.find()) { view.setBackgroundResource(color.darker_gray); return; } } } view.setBackgroundResource(backcolor); } } private class WaypointsViewCreator extends AbstractCachingPageViewCreator<ListView> { private final int VISITED_INSET = (int) (6.6f * CgeoApplication.getInstance().getResources().getDisplayMetrics().density + 0.5f); @Override public ListView getDispatchedView() { if (cache == null) { // something is really wrong return null; } // sort waypoints: PP, Sx, FI, OWN final List<Waypoint> sortedWaypoints = new ArrayList<Waypoint>(cache.getWaypoints()); Collections.sort(sortedWaypoints, Waypoint.WAYPOINT_COMPARATOR); view = (ListView) getLayoutInflater().inflate(R.layout.cachedetail_waypoints_page, null); view.setClickable(true); View addWaypointButton = getLayoutInflater().inflate(R.layout.cachedetail_waypoints_footer, null); view.addFooterView(addWaypointButton); addWaypointButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditWaypointActivity.startActivityAddWaypoint(CacheDetailActivity.this, cache); refreshOnResume = true; } }); view.setAdapter(new ArrayAdapter<Waypoint>(CacheDetailActivity.this, R.layout.waypoint_item, sortedWaypoints) { @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (null == rowView) { rowView = getLayoutInflater().inflate(R.layout.waypoint_item, null); rowView.setClickable(true); rowView.setLongClickable(true); } WaypointViewHolder holder = (WaypointViewHolder) rowView.getTag(); if (null == holder) { holder = new WaypointViewHolder(rowView); } final Waypoint waypoint = getItem(position); fillViewHolder(rowView, holder, waypoint); return rowView; } }); return view; } protected void fillViewHolder(View rowView, final WaypointViewHolder holder, final Waypoint wpt) { // coordinates final TextView coordinatesView = holder.coordinatesView; if (null != wpt.getCoords()) { coordinatesView.setOnClickListener(new CoordinatesFormatSwitcher(wpt.getCoords())); coordinatesView.setText(wpt.getCoords().toString()); coordinatesView.setVisibility(View.VISIBLE); } else { coordinatesView.setVisibility(View.GONE); } // info final String waypointInfo = Formatter.formatWaypointInfo(wpt); final TextView infoView = holder.infoView; if (StringUtils.isNotBlank(waypointInfo)) { infoView.setText(waypointInfo); infoView.setVisibility(View.VISIBLE); } else { infoView.setVisibility(View.GONE); } // title final TextView nameView = holder.nameView; if (StringUtils.isNotBlank(wpt.getName())) { nameView.setText(StringEscapeUtils.unescapeHtml4(wpt.getName())); } else if (null != wpt.getCoords()) { nameView.setText(wpt.getCoords().toString()); } else { nameView.setText(res.getString(R.string.waypoint)); } setWaypointIcon(res, nameView, wpt); // visited if (wpt.isVisited()) { final TypedValue a = new TypedValue(); getTheme().resolveAttribute(R.attr.text_color_grey, a, true); if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) { // really should be just a color! nameView.setTextColor(a.data); } } // note final TextView noteView = holder.noteView; if (StringUtils.isNotBlank(wpt.getNote())) { noteView.setVisibility(View.VISIBLE); if (TextUtils.containsHtml(wpt.getNote())) { noteView.setText(Html.fromHtml(wpt.getNote()), TextView.BufferType.SPANNABLE); } else { noteView.setText(wpt.getNote()); } } else { noteView.setVisibility(View.GONE); } final View wpNavView = holder.wpNavView; wpNavView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NavigationAppFactory.startDefaultNavigationApplication(1, CacheDetailActivity.this, wpt); } }); wpNavView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { NavigationAppFactory.startDefaultNavigationApplication(2, CacheDetailActivity.this, wpt); return true; } }); registerForContextMenu(rowView); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectedWaypoint = wpt; openContextMenu(v); } }); rowView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { selectedWaypoint = wpt; EditWaypointActivity.startActivityEditWaypoint(CacheDetailActivity.this, cache, wpt.getId()); refreshOnResume = true; return true; } }); } private void setWaypointIcon(final Resources res, final TextView nameView, final Waypoint wpt) { final WaypointType waypointType = wpt.getWaypointType(); final Drawable icon; if (wpt.isVisited()) { LayerDrawable ld = new LayerDrawable(new Drawable[] { res.getDrawable(waypointType.markerId), res.getDrawable(R.drawable.tick) }); ld.setLayerInset(0, 0, 0, VISITED_INSET, VISITED_INSET); ld.setLayerInset(1, VISITED_INSET, VISITED_INSET, 0, 0); icon = ld; } else { icon = res.getDrawable(waypointType.markerId); } nameView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } } private class InventoryViewCreator extends AbstractCachingPageViewCreator<ListView> { @Override public ListView getDispatchedView() { if (cache == null) { // something is really wrong return null; } view = (ListView) getLayoutInflater().inflate(R.layout.cachedetail_inventory_page, null); // TODO: fix layout, then switch back to Android-resource and delete copied one // this copy is modified to respect the text color view.setAdapter(new ArrayAdapter<Trackable>(CacheDetailActivity.this, R.layout.simple_list_item_1, cache.getInventory())); view.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { final Object selection = arg0.getItemAtPosition(arg2); if (selection instanceof Trackable) { final Trackable trackable = (Trackable) selection; TrackableActivity.startActivity(CacheDetailActivity.this, trackable.getGuid(), trackable.getGeocode(), trackable.getName()); } } }); return view; } } private class ImagesViewCreator extends AbstractCachingPageViewCreator<View> { @Override public View getDispatchedView() { if (cache == null) { return null; // something is really wrong } view = getLayoutInflater().inflate(R.layout.cachedetail_images_page, null); if (imagesList == null && isCurrentPage(Page.IMAGES)) { loadCacheImages(); } return view; } } public static void startActivity(final Context context, final String geocode, final String cacheName) { final Intent cachesIntent = new Intent(context, CacheDetailActivity.class); cachesIntent.putExtra(Intents.EXTRA_GEOCODE, geocode); cachesIntent.putExtra(Intents.EXTRA_NAME, cacheName); context.startActivity(cachesIntent); } public static void startActivityGuid(final Context context, final String guid, final String cacheName) { final Intent cacheIntent = new Intent(context, CacheDetailActivity.class); cacheIntent.putExtra(Intents.EXTRA_GUID, guid); cacheIntent.putExtra(Intents.EXTRA_NAME, cacheName); context.startActivity(cacheIntent); } /** * A dialog to allow the user to select reseting coordinates local/remote/both. */ private AlertDialog createResetCacheCoordinatesDialog(final Geocache cache, final Waypoint wpt) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.waypoint_reset_cache_coords); final String[] items = new String[] { res.getString(R.string.waypoint_localy_reset_cache_coords), res.getString(R.string.waypoint_reset_local_and_remote_cache_coords) }; builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, final int which) { dialog.dismiss(); final ProgressDialog progressDialog = ProgressDialog.show(CacheDetailActivity.this, getString(R.string.cache), getString(R.string.waypoint_reset), true); final HandlerResetCoordinates handler = new HandlerResetCoordinates(CacheDetailActivity.this, progressDialog, which == 1); new ResetCoordsThread(cache, handler, wpt, which == 0 || which == 1, which == 1, progressDialog).start(); } }); return builder.create(); } private static class HandlerResetCoordinates extends WeakReferenceHandler<CacheDetailActivity> { private boolean remoteFinished = false; private boolean localFinished = false; private final ProgressDialog progressDialog; private final boolean resetRemote; protected HandlerResetCoordinates(CacheDetailActivity activity, ProgressDialog progressDialog, boolean resetRemote) { super(activity); this.progressDialog = progressDialog; this.resetRemote = resetRemote; } @Override public void handleMessage(Message msg) { if (msg.what == ResetCoordsThread.LOCAL) { localFinished = true; } else { remoteFinished = true; } if (localFinished && (remoteFinished || !resetRemote)) { progressDialog.dismiss(); final CacheDetailActivity activity = getActivity(); if (activity != null) { activity.notifyDataSetChanged(); } } } } private class ResetCoordsThread extends Thread { private final Geocache cache; private final Handler handler; private final boolean local; private final boolean remote; private final Waypoint wpt; private final ProgressDialog progress; public static final int LOCAL = 0; public static final int ON_WEBSITE = 1; public ResetCoordsThread(Geocache cache, Handler handler, final Waypoint wpt, boolean local, boolean remote, final ProgressDialog progress) { this.cache = cache; this.handler = handler; this.local = local; this.remote = remote; this.wpt = wpt; this.progress = progress; } @Override public void run() { if (local) { runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage(res.getString(R.string.waypoint_reset_cache_coords)); } }); cache.setCoords(wpt.getCoords()); cache.setUserModifiedCoords(false); cache.deleteWaypointForce(wpt); DataStore.saveChangedCache(cache); handler.sendEmptyMessage(LOCAL); } final IConnector con = ConnectorFactory.getConnector(cache); if (remote && con.supportsOwnCoordinates()) { runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage(res.getString(R.string.waypoint_coordinates_being_reset_on_website)); } }); final boolean result = con.deleteModifiedCoordinates(cache); runOnUiThread(new Runnable() { @Override public void run() { if (result) { showToast(getString(R.string.waypoint_coordinates_has_been_reset_on_website)); } else { showToast(getString(R.string.waypoint_coordinates_upload_error)); } handler.sendEmptyMessage(ON_WEBSITE); notifyDataSetChanged(); } }); } } } private class UploadPersonalNoteThread extends Thread { private Geocache cache = null; private CancellableHandler handler = null; public UploadPersonalNoteThread(Geocache cache, CancellableHandler handler) { this.cache = cache; this.handler = handler; } @Override public void run() { IConnector con = ConnectorFactory.getConnector(cache); if (con.supportsPersonalNote()) { con.uploadPersonalNote(cache); } Message msg = Message.obtain(); Bundle bundle = new Bundle(); bundle.putString(SimpleCancellableHandler.MESSAGE_TEXT, res.getString(R.string.cache_personal_note_upload_done)); msg.setData(bundle); handler.sendMessage(msg); } } @Override protected String getTitle(Page page) { // show number of waypoints directly in waypoint title if (page == Page.WAYPOINTS) { final int waypointCount = cache.getWaypoints().size(); return res.getQuantityString(R.plurals.waypoints, waypointCount, waypointCount); } return res.getString(page.titleStringId); } @Override protected Pair<List<? extends Page>, Integer> getOrderedPages() { final ArrayList<Page> pages = new ArrayList<Page>(); pages.add(Page.WAYPOINTS); pages.add(Page.DETAILS); final int detailsIndex = pages.size() - 1; pages.add(Page.DESCRIPTION); if (!cache.getLogs().isEmpty()) { pages.add(Page.LOGS); } if (CollectionUtils.isNotEmpty(cache.getFriendsLogs())) { pages.add(Page.LOGSFRIENDS); } if (CollectionUtils.isNotEmpty(cache.getInventory())) { pages.add(Page.INVENTORY); } if (CollectionUtils.isNotEmpty(cache.getImages())) { pages.add(Page.IMAGES); } return new ImmutablePair<List<? extends Page>, Integer>(pages, detailsIndex); } @Override protected AbstractViewPagerActivity.PageViewCreator createViewCreator(Page page) { switch (page) { case DETAILS: return new DetailsViewCreator(); case DESCRIPTION: return new DescriptionViewCreator(); case LOGS: return new CacheLogsViewCreator(this, true); case LOGSFRIENDS: return new CacheLogsViewCreator(this, false); case WAYPOINTS: return new WaypointsViewCreator(); case INVENTORY: return new InventoryViewCreator(); case IMAGES: return new ImagesViewCreator(); } throw new IllegalStateException(); // cannot happen as long as switch case is enum complete } static void updateOfflineBox(final View view, final Geocache cache, final Resources res, final OnClickListener refreshCacheClickListener, final OnClickListener dropCacheClickListener, final OnClickListener storeCacheClickListener) { // offline use final TextView offlineText = (TextView) view.findViewById(R.id.offline_text); final Button offlineRefresh = (Button) view.findViewById(R.id.offline_refresh); final Button offlineStore = (Button) view.findViewById(R.id.offline_store); if (cache.isOffline()) { final long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes String ago; if (diff < 15) { ago = res.getString(R.string.cache_offline_time_mins_few); } else if (diff < 50) { ago = res.getString(R.string.cache_offline_time_about) + " " + diff + " " + res.getString(R.string.cache_offline_time_mins); } else if (diff < 90) { ago = res.getString(R.string.cache_offline_time_about) + " " + res.getString(R.string.cache_offline_time_hour); } else if (diff < (48 * 60)) { ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / 60) + " " + res.getString(R.string.cache_offline_time_hours); } else { ago = res.getString(R.string.cache_offline_time_about) + " " + (diff / (24 * 60)) + " " + res.getString(R.string.cache_offline_time_days); } offlineText.setText(res.getString(R.string.cache_offline_stored) + "\n" + ago); offlineRefresh.setOnClickListener(refreshCacheClickListener); offlineStore.setText(res.getString(R.string.cache_offline_drop)); offlineStore.setClickable(true); offlineStore.setOnClickListener(dropCacheClickListener); } else { offlineText.setText(res.getString(R.string.cache_offline_not_ready)); offlineRefresh.setOnClickListener(refreshCacheClickListener); offlineStore.setText(res.getString(R.string.cache_offline_store)); offlineStore.setClickable(true); offlineStore.setOnClickListener(storeCacheClickListener); } offlineRefresh.setVisibility(cache.supportsRefresh() ? View.VISIBLE : View.GONE); offlineRefresh.setClickable(true); } public Geocache getCache() { return cache; } private static class StoreCacheHandler extends SimpleCancellableHandler { public StoreCacheHandler(CacheDetailActivity activity, Progress progress) { super(activity, progress); } @Override public void handleRegularMessage(Message msg) { if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) { updateStatusMsg(R.string.cache_dialog_offline_save_message, (String) msg.obj); } else { notifyDatasetChanged(activityRef); } } } private static final class RefreshCacheHandler extends SimpleCancellableHandler { public RefreshCacheHandler(CacheDetailActivity activity, Progress progress) { super(activity, progress); } @Override public void handleRegularMessage(Message msg) { if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) { updateStatusMsg(R.string.cache_dialog_refresh_message, (String) msg.obj); } else { notifyDatasetChanged(activityRef); } } } private static final class ChangeNotificationHandler extends SimpleHandler { public ChangeNotificationHandler(CacheDetailActivity activity, Progress progress) { super(activity, progress); } @Override public void handleMessage(Message msg) { notifyDatasetChanged(activityRef); } } private static final class SimpleUpdateHandler extends SimpleHandler { public SimpleUpdateHandler(CacheDetailActivity activity, Progress progress) { super(activity, progress); } @Override public void handleMessage(Message msg) { if (msg.what == MESSAGE_FAILED) { super.handleMessage(msg); } else { notifyDatasetChanged(activityRef); } } } private static void notifyDatasetChanged(WeakReference<AbstractActivity> activityRef) { CacheDetailActivity activity = ((CacheDetailActivity) activityRef.get()); if (activity != null) { activity.notifyDataSetChanged(); } } private StoreCacheThread storeThread; private class StoreCacheThread extends Thread { final private int listId; final private CancellableHandler handler; public StoreCacheThread(final int listId, final CancellableHandler handler) { this.listId = listId; this.handler = handler; } @Override public void run() { cache.store(listId, handler); storeThread = null; } } protected void storeCache(final int listId, final StoreCacheHandler storeCacheHandler) { progress.show(this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.cancelMessage()); if (storeThread != null) { storeThread.interrupt(); } storeThread = new StoreCacheThread(listId, storeCacheHandler); storeThread.start(); } private static final class StoreCachePersonalNoteHandler extends StoreCacheHandler { public StoreCachePersonalNoteHandler(CacheDetailActivity activity, Progress progress) { super(activity, progress); } @Override public void handleRegularMessage(Message msg) { if (UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) { updateStatusMsg(R.string.cache_dialog_offline_save_message, (String) msg.obj); } else { dismissProgress(); CacheDetailActivity activity = (CacheDetailActivity) activityRef.get(); if (activity != null) { editPersonalNote(activity.getCache(), activity); } } } } public static void editPersonalNote(final Geocache cache, final CacheDetailActivity activity) { if (cache.isOffline()) { EditNoteDialogListener editNoteDialogListener = new EditNoteDialogListener() { @Override public void onFinishEditNoteDialog(final String note) { cache.setPersonalNote(note); cache.parseWaypointsFromNote(); TextView personalNoteView = (TextView) activity.findViewById(R.id.personalnote); setPersonalNote(personalNoteView, note); DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); activity.notifyDataSetChanged(); } }; final FragmentManager fm = activity.getSupportFragmentManager(); final EditNoteDialog dialog = EditNoteDialog.newInstance(cache.getPersonalNote(), editNoteDialogListener); dialog.show(fm, "fragment_edit_note"); } } private static void setPersonalNote(final TextView personalNoteView, final String personalNote) { personalNoteView.setText(personalNote, TextView.BufferType.SPANNABLE); if (StringUtils.isNotBlank(personalNote)) { personalNoteView.setVisibility(View.VISIBLE); } else { personalNoteView.setVisibility(View.GONE); } } @Override public void navigateTo() { startDefaultNavigation(); } @Override public void showNavigationMenu() { NavigationAppFactory.showNavigationMenu(this, cache, null, null); } @Override public void cachesAround() { CacheListActivity.startActivityCoordinates(this, cache.getCoords()); } }
package cgeo.geocaching.ui; import butterknife.InjectView; import cgeo.geocaching.CacheDetailActivity; import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.Geocache; import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.enumerations.CacheListType; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.filter.IFilter; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.sorting.CacheComparator; import cgeo.geocaching.sorting.DistanceComparator; import cgeo.geocaching.sorting.EventDateComparator; import cgeo.geocaching.sorting.InverseComparator; import cgeo.geocaching.sorting.VisitComparator; import cgeo.geocaching.utils.AngleUtils; import cgeo.geocaching.utils.DateUtils; import cgeo.geocaching.utils.Log; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.HashCodeBuilder; import android.app.Activity; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.text.Spannable; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.text.style.StrikethroughSpan; import android.util.SparseArray; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class CacheListAdapter extends ArrayAdapter<Geocache> { private LayoutInflater inflater = null; private CacheComparator cacheComparator = null; private Geopoint coords; private float azimuth = 0; private long lastSort = 0L; private boolean selectMode = false; private IFilter currentFilter = null; private List<Geocache> originalList = null; private boolean isLiveList = Settings.isLiveList(); final private Set<CompassMiniView> compasses = new LinkedHashSet<CompassMiniView>(); final private Set<DistanceView> distances = new LinkedHashSet<DistanceView>(); final private CacheListType cacheListType; final private Resources res; /** Resulting list of caches */ final private List<Geocache> list; private boolean inverseSort = false; private static final int SWIPE_MIN_DISTANCE = 60; private static final int SWIPE_MAX_OFF_PATH = 100; private static final SparseArray<Drawable> gcIconDrawables = new SparseArray<Drawable>(); /** * time in milliseconds after which the list may be resorted due to position updates */ private static final int PAUSE_BETWEEN_LIST_SORT = 1000; private static final int[] RATING_BACKGROUND = new int[3]; static { if (Settings.isLightSkin()) { RATING_BACKGROUND[0] = R.drawable.favorite_background_red_light; RATING_BACKGROUND[1] = R.drawable.favorite_background_orange_light; RATING_BACKGROUND[2] = R.drawable.favorite_background_green_light; } else { RATING_BACKGROUND[0] = R.drawable.favorite_background_red_dark; RATING_BACKGROUND[1] = R.drawable.favorite_background_orange_dark; RATING_BACKGROUND[2] = R.drawable.favorite_background_green_dark; } } /** * view holder for the cache list adapter * */ protected static class ViewHolder extends AbstractViewHolder { @InjectView(R.id.checkbox) protected CheckBox checkbox; @InjectView(R.id.log_status_mark) protected ImageView logStatusMark; @InjectView(R.id.text) protected TextView text; @InjectView(R.id.distance) protected DistanceView distance; @InjectView(R.id.favorite) protected TextView favorite; @InjectView(R.id.info) protected TextView info; @InjectView(R.id.inventory) protected ImageView inventory; @InjectView(R.id.direction) protected CompassMiniView direction; @InjectView(R.id.dirimg) protected ImageView dirImg; public ViewHolder(View view) { super(view); } } public CacheListAdapter(final Activity activity, final List<Geocache> list, CacheListType cacheListType) { super(activity, 0, list); final IGeoData currentGeo = CgeoApplication.getInstance().currentGeo(); if (currentGeo != null) { coords = currentGeo.getCoords(); } this.res = activity.getResources(); this.list = list; this.cacheListType = cacheListType; if (cacheListType == CacheListType.HISTORY) { cacheComparator = new VisitComparator(); } final Drawable modifiedCoordinatesMarker = activity.getResources().getDrawable(R.drawable.marker_usermodifiedcoords); for (final CacheType cacheType : CacheType.values()) { // unmodified icon int hashCode = getIconHashCode(cacheType, false); gcIconDrawables.put(hashCode, activity.getResources().getDrawable(cacheType.markerId)); // icon with flag for user modified coordinates hashCode = getIconHashCode(cacheType, true); Drawable[] layers = new Drawable[2]; layers[0] = activity.getResources().getDrawable(cacheType.markerId); layers[1] = modifiedCoordinatesMarker; LayerDrawable ld = new LayerDrawable(layers); ld.setLayerInset(1, layers[0].getIntrinsicWidth() - layers[1].getIntrinsicWidth(), layers[0].getIntrinsicHeight() - layers[1].getIntrinsicHeight(), 0, 0); gcIconDrawables.put(hashCode, ld); } } private static int getIconHashCode(final CacheType cacheType, final boolean userModifiedOrFinal) { return new HashCodeBuilder() .append(cacheType) .append(userModifiedOrFinal) .toHashCode(); } /** * change the sort order * * @param comparator */ public void setComparator(final CacheComparator comparator) { cacheComparator = comparator; forceSort(); } public void resetInverseSort() { inverseSort = false; } public void toggleInverseSort() { inverseSort = !inverseSort; } public CacheComparator getCacheComparator() { return cacheComparator; } public Geocache findCacheByGeocode(String geocode) { for (int i = 0; i < getCount(); i++) { if (getItem(i).getGeocode().equalsIgnoreCase(geocode)) { return getItem(i); } } return null; } /** * Called when a new page of caches was loaded. */ public void reFilter() { if (currentFilter != null) { // Back up the list again originalList = new ArrayList<Geocache>(list); currentFilter.filter(list); } } /** * Called after a user action on the filter menu. */ public void setFilter(final IFilter filter) { // Backup current caches list if it isn't backed up yet if (originalList == null) { originalList = new ArrayList<Geocache>(list); } // If there is already a filter in place, this is a request to change or clear the filter, so we have to // replace the original cache list if (currentFilter != null) { list.clear(); list.addAll(originalList); } // Do the filtering or clear it if (filter != null) { filter.filter(list); } currentFilter = filter; notifyDataSetChanged(); } public boolean isFiltered() { return currentFilter != null; } public String getFilterName() { return currentFilter.getName(); } public int getCheckedCount() { int checked = 0; for (Geocache cache : list) { if (cache.isStatusChecked()) { checked++; } } return checked; } public void setSelectMode(final boolean selectMode) { this.selectMode = selectMode; if (!selectMode) { for (final Geocache cache : list) { cache.setStatusChecked(false); } } notifyDataSetChanged(); } public boolean isSelectMode() { return selectMode; } public void switchSelectMode() { setSelectMode(!isSelectMode()); } public void invertSelection() { for (Geocache cache : list) { cache.setStatusChecked(!cache.isStatusChecked()); } notifyDataSetChanged(); } public void forceSort() { if (CollectionUtils.isEmpty(list) || selectMode) { return; } if (isSortedByDistance()) { lastSort = 0; updateSortByDistance(); } else { Collections.sort(list, getPotentialInversion(cacheComparator)); } notifyDataSetChanged(); } public void setActualCoordinates(final Geopoint coords) { this.coords = coords; updateSortByDistance(); for (final DistanceView distance : distances) { distance.update(coords); } for (final CompassMiniView compass : compasses) { compass.updateCurrentCoords(coords); } } private void updateSortByDistance() { if (CollectionUtils.isEmpty(list)) { return; } if (selectMode) { return; } if ((System.currentTimeMillis() - lastSort) <= PAUSE_BETWEEN_LIST_SORT) { return; } if (!isSortedByDistance()) { return; } if (coords == null) { return; } final ArrayList<Geocache> oldList = new ArrayList<Geocache>(list); Collections.sort(list, getPotentialInversion(new DistanceComparator(coords, list))); // avoid an update if the list has not changed due to location update if (list.equals(oldList)) { return; } notifyDataSetChanged(); lastSort = System.currentTimeMillis(); } private Comparator<? super Geocache> getPotentialInversion(final CacheComparator comparator) { if (inverseSort) { return new InverseComparator(comparator); } return comparator; } private boolean isSortedByDistance() { return cacheComparator == null || cacheComparator instanceof DistanceComparator; } public void setActualHeading(final float direction) { if (Math.abs(AngleUtils.difference(azimuth, direction)) < 5) { return; } azimuth = direction; for (final CompassMiniView compass : compasses) { compass.updateAzimuth(azimuth); } } @Override public View getView(final int position, final View rowView, final ViewGroup parent) { if (inflater == null) { inflater = ((Activity) getContext()).getLayoutInflater(); } if (position > getCount()) { Log.w("CacheListAdapter.getView: Attempt to access missing item #" + position); return null; } final Geocache cache = getItem(position); View v = rowView; final ViewHolder holder; if (v == null) { v = inflater.inflate(R.layout.cacheslist_item, null); holder = new ViewHolder(v); } else { holder = (ViewHolder) v.getTag(); } final boolean lightSkin = Settings.isLightSkin(); final TouchListener touchLst = new TouchListener(cache); v.setOnClickListener(touchLst); v.setOnLongClickListener(touchLst); v.setOnTouchListener(touchLst); v.setLongClickable(true); if (selectMode) { holder.checkbox.setVisibility(View.VISIBLE); } else { holder.checkbox.setVisibility(View.GONE); } holder.checkbox.setChecked(cache.isStatusChecked()); holder.checkbox.setOnClickListener(new SelectionCheckBoxListener(cache)); distances.add(holder.distance); holder.distance.setContent(cache.getCoords()); compasses.add(holder.direction); holder.direction.setTargetCoords(cache.getCoords()); if (cache.isFound() && cache.isLogOffline()) { holder.logStatusMark.setImageResource(R.drawable.mark_green_orange); holder.logStatusMark.setVisibility(View.VISIBLE); } else if (cache.isFound()) { holder.logStatusMark.setImageResource(R.drawable.mark_green_more); holder.logStatusMark.setVisibility(View.VISIBLE); } else if (cache.isLogOffline()) { holder.logStatusMark.setImageResource(R.drawable.mark_orange); holder.logStatusMark.setVisibility(View.VISIBLE); } else { holder.logStatusMark.setVisibility(View.GONE); } Spannable spannable = null; if (cache.isDisabled() || cache.isArchived() || DateUtils.isPastEvent(cache)) { // strike spannable = Spannable.Factory.getInstance().newSpannable(cache.getName()); spannable.setSpan(new StrikethroughSpan(), 0, spannable.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (cache.isArchived()) { // red color if (spannable == null) { spannable = Spannable.Factory.getInstance().newSpannable(cache.getName()); } spannable.setSpan(new ForegroundColorSpan(res.getColor(R.color.archived_cache_color)), 0, spannable.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (spannable != null) { holder.text.setText(spannable, TextView.BufferType.SPANNABLE); } else { holder.text.setText(cache.getName()); } holder.text.setCompoundDrawablesWithIntrinsicBounds(getCacheIcon(cache), null, null, null); if (cache.getInventoryItems() > 0) { holder.inventory.setVisibility(View.VISIBLE); } else { holder.inventory.setVisibility(View.GONE); } if (cache.getDistance() != null) { holder.distance.setDistance(cache.getDistance()); } if (cache.getCoords() != null && coords != null) { holder.distance.update(coords); } // only show the direction if this is enabled in the settings if (isLiveList) { if (cache.getCoords() != null) { holder.direction.setVisibility(View.VISIBLE); holder.dirImg.setVisibility(View.GONE); holder.direction.updateAzimuth(azimuth); if (coords != null) { holder.direction.updateCurrentCoords(coords); } } else if (cache.getDirection() != null) { holder.direction.setVisibility(View.VISIBLE); holder.dirImg.setVisibility(View.GONE); holder.direction.updateAzimuth(azimuth); holder.direction.updateHeading(cache.getDirection()); } else if (StringUtils.isNotBlank(cache.getDirectionImg())) { holder.dirImg.setImageDrawable(DirectionImage.getDrawable(cache.getDirectionImg())); holder.dirImg.setVisibility(View.VISIBLE); holder.direction.setVisibility(View.GONE); } else { holder.dirImg.setVisibility(View.GONE); holder.direction.setVisibility(View.GONE); } } holder.favorite.setText(Integer.toString(cache.getFavoritePoints())); int favoriteBack; // set default background, neither vote nor rating may be available if (lightSkin) { favoriteBack = R.drawable.favorite_background_light; } else { favoriteBack = R.drawable.favorite_background_dark; } final float myVote = cache.getMyVote(); if (myVote > 0) { // use my own rating for display, if I have voted if (myVote >= 4) { favoriteBack = RATING_BACKGROUND[2]; } else if (myVote >= 3) { favoriteBack = RATING_BACKGROUND[1]; } else if (myVote > 0) { favoriteBack = RATING_BACKGROUND[0]; } } else { final float rating = cache.getRating(); if (rating >= 3.5) { favoriteBack = RATING_BACKGROUND[2]; } else if (rating >= 2.1) { favoriteBack = RATING_BACKGROUND[1]; } else if (rating > 0.0) { favoriteBack = RATING_BACKGROUND[0]; } } holder.favorite.setBackgroundResource(favoriteBack); if (cacheListType == CacheListType.HISTORY && cache.getVisitedDate() > 0) { holder.info.setText(Formatter.formatCacheInfoHistory(cache)); } else { holder.info.setText(Formatter.formatCacheInfoLong(cache, cacheListType)); } return v; } private static Drawable getCacheIcon(Geocache cache) { int hashCode = getIconHashCode(cache.getType(), cache.hasUserModifiedCoords() || cache.hasFinalDefined()); final Drawable drawable = gcIconDrawables.get(hashCode); if (drawable != null) { return drawable; } // fallback to mystery icon hashCode = getIconHashCode(CacheType.MYSTERY, cache.hasUserModifiedCoords() || cache.hasFinalDefined()); return gcIconDrawables.get(hashCode); } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); distances.clear(); compasses.clear(); } private static class SelectionCheckBoxListener implements View.OnClickListener { private final Geocache cache; public SelectionCheckBoxListener(Geocache cache) { this.cache = cache; } @Override public void onClick(View view) { assert view instanceof CheckBox; final boolean checkNow = ((CheckBox) view).isChecked(); cache.setStatusChecked(checkNow); } } private class TouchListener implements View.OnLongClickListener, View.OnClickListener, View.OnTouchListener { private boolean touch = true; private final GestureDetector gestureDetector; private final Geocache cache; public TouchListener(final Geocache cache) { this.cache = cache; final FlingGesture dGesture = new FlingGesture(cache); gestureDetector = new GestureDetector(getContext(), dGesture); } // tap on item @Override public void onClick(View view) { if (!touch) { touch = true; return; } if (isSelectMode()) { cache.setStatusChecked(!cache.isStatusChecked()); notifyDataSetChanged(); return; } // load cache details CacheDetailActivity.startActivity(getContext(), cache.getGeocode(), cache.getName()); } // long tap on item @Override public boolean onLongClick(View view) { if (!touch) { touch = true; return true; } return view.showContextMenu(); } // swipe on item @Override public boolean onTouch(View view, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { touch = false; return true; } return false; } } private class FlingGesture extends GestureDetector.SimpleOnGestureListener { private final Geocache cache; public FlingGesture(Geocache cache) { this.cache = cache; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) { return false; } // left to right swipe if ((e2.getX() - e1.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > Math.abs(velocityY)) { if (!selectMode) { switchSelectMode(); cache.setStatusChecked(true); } return true; } // right to left swipe if ((e1.getX() - e2.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > Math.abs(velocityY)) { if (selectMode) { switchSelectMode(); } return true; } } catch (Exception e) { Log.w("CacheListAdapter.FlingGesture.onFling", e); } return false; } } public List<Geocache> getFilteredList() { return list; } public List<Geocache> getCheckedCaches() { final ArrayList<Geocache> result = new ArrayList<Geocache>(); for (Geocache cache : list) { if (cache.isStatusChecked()) { result.add(cache); } } return result; } public List<Geocache> getCheckedOrAllCaches() { final List<Geocache> result = getCheckedCaches(); if (!result.isEmpty()) { return result; } return new ArrayList<Geocache>(list); } public int getCheckedOrAllCount() { final int checked = getCheckedCount(); if (checked > 0) { return checked; } return list.size(); } public void setInitialComparator() { // will be called repeatedly when coming back to the list, therefore check first for an already existing sorting if (cacheComparator != null) { return; } CacheComparator comparator = null; // a null comparator will automatically sort by distance if (cacheListType == CacheListType.HISTORY) { comparator = new VisitComparator(); } else { if (CollectionUtils.isNotEmpty(list)) { boolean eventsOnly = true; for (final Geocache cache : list) { if (!cache.isEventCache()) { eventsOnly = false; break; } } if (eventsOnly) { comparator = new EventDateComparator(); } } } setComparator(comparator); } }
package jlibs.xml.sax.sniff; import javax.xml.namespace.NamespaceContext; import java.io.PrintStream; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @author Santhosh Kumar T */ public class XPathResults implements Debuggable{ private NamespaceContext nsContext; private Map<String, Object> map; public XPathResults(NamespaceContext nsContext, List<XPath> xpaths){ this.nsContext = nsContext; map = new LinkedHashMap<String, Object>(xpaths.size()); for(XPath xpath: xpaths) map.put(xpath.toString(), xpath.result); } public NamespaceContext getNamespaceContext(){ return nsContext; } public Object getResult(XPath xpath){ return map.get(xpath.toString()); } private void print(PrintStream out, String xpath, Object result){ out.printf("XPath: %s%n", xpath); if(result instanceof Collection){ int i = 0; for(Object item: (Collection)result) out.printf(" %d: %s%n", ++i, item); }else out.printf(" %s\n", result); } public void printResult(PrintStream out, XPath xpath){ print(out, xpath.toString(), map.get(xpath.toString())); } public void print(PrintStream out){ for(Map.Entry<String, Object> entry: map.entrySet()){ print(out, entry.getKey(), entry.getValue()); out.println(); } } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; public final class MainPanel extends JPanel { public static final int HEADER_HEIGHT = 32; private MainPanel() { super(new BorderLayout()); JPanel p = new JPanel(new GridLayout(2, 1)); JTable table1 = makeTable(); // Bad: >>>> JTableHeader header = table1.getTableHeader(); // Dimension d = header.getPreferredSize(); // d.height = HEADER_HEIGHT; // header.setPreferredSize(d); // addColumn case test header.setPreferredSize(new Dimension(100, HEADER_HEIGHT)); p.add(makeTitledPanel("Bad: JTableHeader#setPreferredSize(...)", new JScrollPane(table1))); JTable table2 = makeTable(); JScrollPane scroll = new JScrollPane(table2); scroll.setColumnHeader(new JViewport() { @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.height = HEADER_HEIGHT; return d; } }); // table2.setTableHeader(new JTableHeader(table2.getColumnModel()) { // @Override public Dimension getPreferredSize() { // Dimension d = super.getPreferredSize(); // d.height = HEADER_HEIGHT; // return d; p.add(makeTitledPanel("Override getPreferredSize()", scroll)); JTextField info = new JTextField(); info.setEditable(false); JButton button = new JButton("addColumn"); button.addActionListener(e -> { table1.getColumnModel().addColumn(new TableColumn()); table2.getColumnModel().addColumn(new TableColumn()); info.setText(String.format("%s - %s", getDim(table1), getDim(table2))); }); Box box = Box.createHorizontalBox(); box.add(button); box.add(info); add(p); add(box, BorderLayout.SOUTH); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(320, 240)); } private static String getDim(JTable t) { JTableHeader h = t.getTableHeader(); Dimension d = h.getPreferredSize(); return String.format("%dx%d", d.width, d.height); } private static JTable makeTable() { JTable table = new JTable(new DefaultTableModel(2, 20)); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); return table; } private static Component makeTitledPanel(String title, Component c) { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder(title)); p.add(c); return p; } 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 controllers; import com.avaje.ebean.Ebean; import com.avaje.ebean.ExpressionList; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import models.User; import play.data.Form; import play.libs.Json; import play.mvc.Result; import utilities.ControllerHelper; import utilities.JsonHelper; import utilities.QueryHelper; import utilities.annotations.Authentication; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static play.mvc.Controller.request; import static play.mvc.Results.*; public class UserController { private static ObjectMapper jsonMapper = new ObjectMapper(); public static final ControllerHelper.Link allUsersLink = new ControllerHelper.Link("users", controllers.routes.UserController.getAll().url()); private static Form<User> form = Form.form(User.class); private static final String PASSWORD_FIELD_KEY = "password"; @Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN}) public static Result getAll() { ExpressionList<User> exp = QueryHelper.buildQuery(User.class, User.FIND.where()); List<JsonHelper.Tuple> tuples = exp.findList().stream().map(user -> new JsonHelper.Tuple(user, new ControllerHelper.Link("self", controllers.routes.UserController.get(user.getId()).url()))).collect(Collectors.toList()); // TODO: add links when available List<ControllerHelper.Link> links = new ArrayList<>(); links.add(new ControllerHelper.Link("self", controllers.routes.UserController.getAll().url())); links.add(new ControllerHelper.Link("total", controllers.routes.UserController.getTotal().url())); links.add(new ControllerHelper.Link("me", controllers.routes.UserController.currentUser().url())); try { JsonNode result = JsonHelper.createJsonNode(tuples, links, User.class); String[] totalQuery = request().queryString().get("total"); if (totalQuery != null && totalQuery.length == 1 && totalQuery[0].equals("true")) { ExpressionList<User> countExpression = QueryHelper.buildQuery(User.class, User.FIND.where(), true); String root = User.class.getAnnotation(JsonRootName.class).value(); ((ObjectNode) result.get(root)).put("total",countExpression.findRowCount()); } return ok(result); } catch(JsonProcessingException ex) { play.Logger.error(ex.getMessage(), ex); return internalServerError(); } } @Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN}) public static Result getTotal() { return ok(JsonHelper.addRootElement(Json.newObject().put("total", User.FIND.findRowCount()), User.class)); } @Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER}) public static Result get(Long id) { // Check if user has correct privileges User client = SecurityController.getUser(); if(User.Role.USER.equals(client.getRole()) && client.getId() != id) return unauthorized(); User user = User.FIND.byId(id); if(user == null) return notFound(); return ok(JsonHelper.createJsonNode(user, getAllLinks(id), User.class)); } @Authentication({User.Role.ADMIN}) public static Result create() { JsonNode body = request().body().asJson(); JsonNode strippedBody; try { strippedBody = JsonHelper.removeRootElement(body, User.class, false); } catch(JsonHelper.InvalidJSONException ex) { play.Logger.debug(ex.getMessage(), ex); return badRequest(ex.getMessage()); } Form<User> filledForm = form.bind(strippedBody); // Check password Form.Field passwordField = filledForm.field(PASSWORD_FIELD_KEY); String passwordError = User.validatePassword(passwordField.value()); if(passwordError != null) { filledForm.reject(PASSWORD_FIELD_KEY, passwordError); } if(filledForm.hasErrors()) { // maybe create info about what's wrong return badRequest(filledForm.errorsAsJson()); } User newUser = filledForm.get(); // Check if a user with this email address already exists if(User.findByEmail(newUser.getEmail()) != null) { return badRequest("Email address is already in use."); } // Create new user newUser.save(); return created(JsonHelper.createJsonNode(newUser, getAllLinks(newUser.getId()), User.class)); } @Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER}) public static Result update(Long id) { // Check if user has correct privileges User client = SecurityController.getUser(); if(!User.Role.ADMIN.equals(client.getRole()) && client.getId() != id) return unauthorized(); // Check if user exists User user = User.FIND.byId(id); if(user == null) return notFound(); // Check input JsonNode body = request().body().asJson(); JsonNode strippedBody; try { strippedBody = JsonHelper.removeRootElement(body, User.class, false); } catch(JsonHelper.InvalidJSONException ex) { play.Logger.debug(ex.getMessage(), ex); return badRequest(ex.getMessage()); } Form<User> filledForm = form.bind(strippedBody); // Check if password is long enough in filled form String password = filledForm.field(PASSWORD_FIELD_KEY).value(); if(password != null) { String error = User.validatePassword(password); if(error != null) { filledForm.reject(PASSWORD_FIELD_KEY, error); } } // Check rest of input if(filledForm.hasErrors()) { return badRequest(filledForm.errorsAsJson()); } // Update the user User updatedUser = filledForm.get(); updatedUser.setId(id); Set<String> updatedFields = filledForm.data().keySet(); if (updatedFields.contains("password")) { updatedFields.remove("password"); updatedFields.add("shaPassword"); } Ebean.update(updatedUser, updatedFields); return ok(JsonHelper.createJsonNode(updatedUser, getAllLinks(id), User.class)); } // no check needed public static Result currentUser() { User client = SecurityController.getUser(); if(client == null) { return unauthorized(); } return get(client.getId()); } @Authentication({User.Role.ADMIN}) public static Result deleteAll() { User client = SecurityController.getUser(); User.FIND.where().ne("id", client.getId()).findList().forEach(u -> u.delete()); return getAll(); } @Authentication({User.Role.ADMIN}) public static Result delete(Long id) { // Check if user exists User userToDelete = User.FIND.byId(id); if(userToDelete == null) { return notFound(); } // Delete the user userToDelete.delete(); // Add links to result ObjectNode root = jsonMapper.createObjectNode(); List<ControllerHelper.Link> links = new ArrayList<>(); links.add(Application.homeLink); links.add(allUsersLink); root.put("links", (JsonNode) jsonMapper.valueToTree(links)); return ok(root); } @Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER}) public static Result getUserAuthToken(Long id) { // Check if user has correct privileges User client = SecurityController.getUser(); if(client.getId() != id) { return unauthorized(); } // Return auth token to the client String authToken = client.getAuthToken(); ObjectNode authTokenJson = Json.newObject(); authTokenJson.put(SecurityController.AUTH_TOKEN, authToken); return ok(authTokenJson); } @Authentication({User.Role.ADMIN, User.Role.USER}) public static Result invalidateAuthToken(Long userId) { // Check if user has correct privileges User client = SecurityController.getUser(); if(!User.Role.ADMIN.equals(client.getRole()) && client.getId() != userId) { return unauthorized(); } User user = User.FIND.byId(userId); if(user == null) { // Return possible links ObjectNode root = jsonMapper.createObjectNode(); List<ControllerHelper.Link> links = new ArrayList<>(); links.add(Application.homeLink); links.add(allUsersLink); root.put("links", (JsonNode) jsonMapper.valueToTree(links)); return notFound(); } user.invalidateAuthToken(); user.save(); return ok(); } private static List<ControllerHelper.Link> getAllLinks(long id) { List<ControllerHelper.Link> links = new ArrayList<>(); links.add(new ControllerHelper.Link("self", controllers.routes.UserController.get(id).url())); links.add(new ControllerHelper.Link("getAuthToken", controllers.routes.UserController.getUserAuthToken(id).url())); links.add(new ControllerHelper.Link("invalidateAuthToken", controllers.routes.UserController.invalidateAuthToken(id).url())); return links; } }
package com.plugin.gcm; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; @SuppressLint("NewApi") public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = "GCMIntentService"; public GCMIntentService() { super("GCMIntentService"); } @Override public void onRegistered(Context context, String regId) { Log.v(TAG, "onRegistered: "+ regId); JSONObject json; try { json = new JSONObject().put("event", "registered"); json.put("regid", regId); Log.v(TAG, "onRegistered: " + json.toString()); // Send this JSON data to the JavaScript application above EVENT should be set to the msg type // In this case this is the registration ID PushPlugin.sendJavascript( json ); } catch( JSONException e) { // No message to the user is sent, JSON failed Log.e(TAG, "onRegistered: JSON exception"); } } @Override public void onUnregistered(Context context, String regId) { Log.d(TAG, "onUnregistered - regId: " + regId); } @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); if (extras != null) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } public void createNotification(Context context, Bundle extras) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(this); Intent notificationIntent = new Intent(this, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); int defaults = Notification.DEFAULT_ALL; if (extras.getString("defaults") != null) { try { defaults = Integer.parseInt(extras.getString("defaults")); } catch (NumberFormatException e) {} } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setDefaults(defaults) .setSmallIcon(context.getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setContentTitle(extras.getString("title")) .setTicker(extras.getString("title")) .setContentIntent(contentIntent) .setAutoCancel(true); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } if (extras.getString("bigview") != null) { boolean bigview = Boolean.parseBoolean(extras.getString("bigview")); if (bigview) { mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message)); } } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } int notId = 0; try { notId = Integer.parseInt(extras.getString("notId")); } catch(NumberFormatException e) { Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage()); } catch(Exception e) { Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage()); } mNotificationManager.notify((String) appName, notId, mBuilder.build()); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String)appName; } @Override public void onError(Context context, String errorId) { Log.e(TAG, "onError - errorId: " + errorId); } }
package com.badlogic.gdx.setup; import com.badlogic.gdx.setup.DependencyBank.ProjectType; import java.io.BufferedWriter; import java.io.IOException; import java.util.List; public class BuildScriptHelper { private static int indent = 0; public static void addBuildScript(List<ProjectType> projects, BufferedWriter wr) throws IOException { write(wr, "buildscript {"); //repos write(wr, "repositories {"); write(wr, DependencyBank.mavenCentral); write(wr, "maven { url \"" + DependencyBank.libGDXSnapshotsUrl + "\" }"); if (projects.contains(ProjectType.HTML)) { write(wr, DependencyBank.jCenter); } write(wr, "}"); //dependencies write(wr, "dependencies {"); if (projects.contains(ProjectType.HTML)) { write(wr, "classpath '" + DependencyBank.gwtPluginImport + "'"); } if (projects.contains(ProjectType.ANDROID)) { write(wr, "classpath '" + DependencyBank.androidPluginImport + "'"); } if (projects.contains(ProjectType.IOS)) { write(wr, "classpath '" + DependencyBank.roboVMPluginImport + "'"); } write(wr, "}"); write(wr, "}"); space(wr); } public static void addAllProjects(BufferedWriter wr) throws IOException { write(wr, "allprojects {"); write(wr, "apply plugin: \"eclipse\""); write(wr, "apply plugin: \"idea\""); space(wr); write(wr, "version = '1.0'"); write(wr, "ext {"); write(wr, "appName = '%APP_NAME%'"); write(wr, "gdxVersion = '" + DependencyBank.libgdxVersion + "'"); write(wr, "roboVMVersion = '" + DependencyBank.roboVMVersion + "'"); write(wr, "box2DLightsVersion = '" + DependencyBank.box2DLightsVersion + "'"); write(wr, "ashleyVersion = '" + DependencyBank.ashleyVersion + "'"); write(wr, "aiVersion = '" + DependencyBank.aiVersion + "'"); write(wr, "}"); space(wr); write(wr, "repositories {"); write(wr, DependencyBank.mavenCentral); write(wr, "maven { url \"" + DependencyBank.libGDXSnapshotsUrl + "\" }"); write(wr, "maven { url \"" + DependencyBank.libGDXReleaseUrl + "\" }"); write(wr, "}"); write(wr, "}"); } public static void addProject(ProjectType project, List<Dependency> dependencies, BufferedWriter wr) throws IOException { space(wr); write(wr, "project(\":" + project.getName() + "\") {"); for (String plugin : project.getPlugins()) { write(wr, "apply plugin: \"" + plugin + "\""); } space(wr); addConfigurations(project, wr); space(wr); addDependencies(project, dependencies, wr); write(wr, "}"); } private static void addDependencies(ProjectType project, List<Dependency> dependencyList, BufferedWriter wr) throws IOException { write(wr, "dependencies {"); if (!project.equals(ProjectType.CORE)) { write(wr, "compile project(\":" + ProjectType.CORE.getName() + "\")"); } for (Dependency dep : dependencyList) { if (dep.getDependencies(project) == null) continue; for (String moduleDependency : dep.getDependencies(project)) { if (moduleDependency == null) continue; if ((project.equals(ProjectType.ANDROID) || project.equals(ProjectType.IOS)) && moduleDependency.contains("native")) { write(wr, "natives \"" + moduleDependency + "\""); } else { write(wr, "compile \"" + moduleDependency + "\""); } } } write(wr, "}"); } private static void addConfigurations(ProjectType project, BufferedWriter wr) throws IOException { if (project.equals(ProjectType.IOS) || project.equals(ProjectType.ANDROID)) { write(wr, "configurations { natives }"); } } private static void write(BufferedWriter wr, String input) throws IOException { int delta = StringUtils.countMatches(input, '{') - StringUtils.countMatches(input, '}'); indent += delta *= 4; indent = clamp(indent); if (delta > 0) { wr.write(StringUtils.repeat(" ", clamp(indent - 4)) + input + "\n"); } else if (delta < 0) { wr.write(StringUtils.repeat(" ", clamp(indent)) + input + "\n"); } else { wr.write(StringUtils.repeat(" ", indent) + input + "\n"); } } private static void space(BufferedWriter wr) throws IOException { wr.write("\n"); } private static int clamp(int indent) { if (indent < 0) { return 0; } return indent; } static class StringUtils { public static int countMatches(String input, char match) { int count = 0; for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == match) { count++; } } return count; } public static String repeat(String toRepeat, int count) { String repeat = ""; for (int i = 0; i < count; i++) { repeat += toRepeat; } return repeat; } } }
package hudson.search; import hudson.util.EditDistance; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; /** * Web-bound object that serves QuickSilver-like search requests. * * @author Kohsuke Kawaguchi */ public class Search { public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException { for (Ancestor a : req.getAncestors()) { if (a.getObject() instanceof SearchableModelObject) { SearchableModelObject smo = (SearchableModelObject) a.getObject(); SearchIndex index = smo.getSearchIndex(); String query = req.getParameter("q"); SuggestedItem target = find(index, query); if(target!=null) { // found rsp.sendRedirect2(a.getUrl()+target.getUrl()); } } } // TODO: go to suggestion page throw new UnsupportedOperationException(); } //public static List<SearchItem> find(SearchIndex index, String tokenList) { // List<SearchItem> result = new ArrayList<SearchItem>(); // StringTokenizer tokens = new StringTokenizer(tokenList); // while(tokens.hasMoreTokens()) { // String token = tokens.nextToken(); // result.clear(); // index.find(token,result); // index = SearchIndex.EMPTY; // for (SearchItem r : result) // index = UnionSearchIndex.combine(index,r.getSearchIndex()); // return result; private enum Mode { FIND { void find(SearchIndex index, String token, List<SearchItem> result) { index.find(token, result); } }, SUGGEST { void find(SearchIndex index, String token, List<SearchItem> result) { index.suggest(token, result); } }; abstract void find(SearchIndex index, String token, List<SearchItem> result); } /** * Performs a search and returns the match, or null if no match was found. */ public static SuggestedItem find(SearchIndex index, String query) { List<SuggestedItem> r = find(Mode.FIND, index, query); if(r.isEmpty()) return null; else return r.get(0); } public static List<SuggestedItem> suggest(SearchIndex index, final String tokenList) { class Tag implements Comparable<Tag>{ SuggestedItem item; int distance; Tag(SuggestedItem i) { this.item = i; distance = EditDistance.editDistance(i.getPath(),tokenList); } public int compareTo(Tag that) { return this.distance-that.distance; } } List<Tag> buf = new ArrayList<Tag>(); List<SuggestedItem> items = find(Mode.SUGGEST, index, tokenList); // sort them for( SuggestedItem i : items) buf.add(new Tag(i)); Collections.sort(buf); items.clear(); for (Tag t : buf) items.add(t.item); return items; } private static List<SuggestedItem> find(Mode m, SearchIndex index, String tokenList) { List<SuggestedItem> front = new ArrayList<SuggestedItem>(); List<SuggestedItem> back = new ArrayList<SuggestedItem>(); List<SearchItem> items = new ArrayList<SearchItem>(); // items found in 1 step StringTokenizer tokens = new StringTokenizer(tokenList); if(!tokens.hasMoreTokens()) return front; // no tokens given // first token m.find(index,tokens.nextToken(),items); for (SearchItem i : items) front.add(new SuggestedItem(i)); // successive tokens while(tokens.hasMoreTokens()) { String token = tokens.nextToken(); back.clear(); for (SuggestedItem r : front) { items.clear(); m.find(r.item.getSearchIndex(),token,items); for (SearchItem i : items) back.add(new SuggestedItem(r,i)); } {// swap front and back List<SuggestedItem> t = front; front = back; back = t; } } return front; } }
//FILE: OptionsDlg.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // Mark Tsuchida (Layout, June 2014) // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.WindowConstants; import mmcorej.CMMCore; import org.micromanager.api.ScriptInterface; import org.micromanager.logging.LogFileManager; import org.micromanager.utils.GUIColors; import org.micromanager.utils.MMDialog; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.ReportingUtils; import org.micromanager.utils.UIMonitor; /** * Options dialog for MMStudio. * */ public class OptionsDlg extends MMDialog { private static final long serialVersionUID = 1L; private JTextField startupScriptFile_; private JTextField bufSizeField_; private JTextField logDeleteDaysField_; private JComboBox comboDisplayBackground_; private MMOptions opts_; private CMMCore core_; private Preferences mainPrefs_; private ScriptInterface parent_; private GUIColors guiColors_; /** * Create the dialog */ public OptionsDlg(MMOptions opts, CMMCore core, Preferences mainPrefs, ScriptInterface parent) { super(); parent_ = parent; opts_ = opts; core_ = core; mainPrefs_ = mainPrefs; guiColors_ = new GUIColors(); setResizable(false); setModal(true); setTitle("Micro-Manager Options"); if (opts_.displayBackground_.equals("Day")) { setBackground(java.awt.SystemColor.control); } else if (opts_.displayBackground_.equals("Night")) { setBackground(java.awt.Color.gray); } Preferences root = Preferences.userNodeForPackage(this.getClass()); setPrefsNode(root.node(root.absolutePath() + "/OptionsDlg")); Rectangle r = getBounds(); loadPosition(r.x, r.y); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { closeRequested(); } }); final JCheckBox debugLogEnabledCheckBox = new JCheckBox(); debugLogEnabledCheckBox.setText("Enable debug logging"); debugLogEnabledCheckBox.setToolTipText("Enable verbose logging for troubleshooting and debugging"); debugLogEnabledCheckBox.setSelected(opts_.debugLogEnabled_); debugLogEnabledCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { opts_.debugLogEnabled_ = debugLogEnabledCheckBox.isSelected(); core_.enableDebugLog(opts_.debugLogEnabled_); UIMonitor.enable(opts_.debugLogEnabled_); } }); final JCheckBox doNotAskForConfigFileCheckBox = new JCheckBox(); doNotAskForConfigFileCheckBox.setText("Do not ask for config file at startup"); doNotAskForConfigFileCheckBox.setSelected(opts_.doNotAskForConfigFile_); doNotAskForConfigFileCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { opts_.doNotAskForConfigFile_ = doNotAskForConfigFileCheckBox.isSelected(); } }); final JCheckBox deleteLogCheckBox = new JCheckBox(); deleteLogCheckBox.setText("Delete log files after"); deleteLogCheckBox.setSelected(opts_.deleteOldCoreLogs_); deleteLogCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { opts_.deleteOldCoreLogs_ = deleteLogCheckBox.isSelected(); } }); logDeleteDaysField_ = new JTextField(Integer.toString(opts_.deleteCoreLogAfterDays_), 2); final JButton deleteLogFilesButton = new JButton(); deleteLogFilesButton.setText("Delete Log Files Now"); deleteLogFilesButton.setToolTipText("Delete all CoreLog files except " + "for the current one"); deleteLogFilesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { LogFileManager.deleteLogFilesDaysOld(0, core_.getPrimaryLogFile()); } }); final JButton clearRegistryButton = new JButton(); clearRegistryButton.setText("Reset Preferences"); clearRegistryButton.setToolTipText("Clear all preference settings and restore defaults"); clearRegistryButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { boolean previouslyRegistered = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false); mainPrefs_.clear(); Preferences acqPrefs = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + AcqControlDlg.ACQ_SETTINGS_NODE); acqPrefs.clear(); // restore registration flag mainPrefs_.putBoolean(RegistrationDlg.REGISTRATION, previouslyRegistered); } catch (BackingStoreException exc) { ReportingUtils.showError(e); } } }); bufSizeField_ = new JTextField(Integer.toString(opts_.circularBufferSizeMB_), 5); comboDisplayBackground_ = new JComboBox(guiColors_.styleOptions); comboDisplayBackground_.setMaximumRowCount(2); comboDisplayBackground_.setSelectedItem(opts_.displayBackground_); comboDisplayBackground_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { changeBackground(); } }); startupScriptFile_ = new JTextField(opts_.startupScript_, 10); final JCheckBox autoreloadDevicesCheckBox = new JCheckBox(); autoreloadDevicesCheckBox.setText("Auto-reload devices (Danger!)"); autoreloadDevicesCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { opts_.autoreloadDevices_ = autoreloadDevicesCheckBox.isSelected(); } }); final JCheckBox closeOnExitCheckBox = new JCheckBox(); closeOnExitCheckBox.setText("Close app when quitting MM"); closeOnExitCheckBox.setSelected(opts_.closeOnExit_); closeOnExitCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { opts_.closeOnExit_ = closeOnExitCheckBox.isSelected(); MMStudioMainFrame.getInstance().setExitStrategy(opts_.closeOnExit_); } }); final JComboBox prefZoomCombo = new JComboBox(); prefZoomCombo.setModel(new DefaultComboBoxModel(new String[]{ "8%", "12%", "16%", "25%", "33%", "50%", "75%", "100%", "150%","200%","300%","400%","600%" })); double mag = opts_.windowMag_; int index = 0; if (mag == 0.25 / 3.0) { index = 0; } else if (mag == 0.125) { index = 1; } else if (mag == 0.16) { index = 2; } else if (mag == 0.25) { index = 3; } else if (mag == 0.33) { index = 4; } else if (mag == 0.5) { index = 5; } else if (mag == 0.75) { index = 6; } else if (mag == 1.0) { index = 7; } else if (mag == 1.5) { index = 8; } else if (mag == 2.0) { index = 9; } else if (mag == 3.0) { index = 10; } else if (mag == 4.0) { index = 11; } else if (mag == 6.0) { index = 12; } prefZoomCombo.setSelectedIndex(index); prefZoomCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switch (prefZoomCombo.getSelectedIndex()) { case (0): opts_.windowMag_ = 0.25 / 3.0; break; case (1): opts_.windowMag_ = 0.125; break; case (2): opts_.windowMag_ = 0.16; break; case (3): opts_.windowMag_ = 0.25; break; case (4): opts_.windowMag_ = 0.33; break; case (5): opts_.windowMag_ = 0.5; break; case (6): opts_.windowMag_ = 0.75; break; case (7): opts_.windowMag_ = 1.0; break; case (8): opts_.windowMag_ = 1.5; break; case (9): opts_.windowMag_ = 2.0; break; case (10): opts_.windowMag_ = 3.0; break; case (11): opts_.windowMag_ = 4.0; break; case (12): opts_.windowMag_ = 6.0; break; } } }); final JCheckBox metadataFileWithMultipageTiffCheckBox = new JCheckBox(); metadataFileWithMultipageTiffCheckBox.setText("Create metadata.txt file with Image Stack Files"); metadataFileWithMultipageTiffCheckBox.setSelected(opts_.mpTiffMetadataFile_); metadataFileWithMultipageTiffCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { opts_.mpTiffMetadataFile_ = metadataFileWithMultipageTiffCheckBox.isSelected(); } }); final JCheckBox separateFilesForPositionsMPTiffCheckBox = new JCheckBox(); separateFilesForPositionsMPTiffCheckBox.setText("Save XY positions in separate Image Stack Files"); separateFilesForPositionsMPTiffCheckBox.setSelected(opts_.mpTiffSeparateFilesForPositions_); separateFilesForPositionsMPTiffCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { opts_.mpTiffSeparateFilesForPositions_ = separateFilesForPositionsMPTiffCheckBox.isSelected(); } }); final JCheckBox syncExposureMainAndMDA = new JCheckBox(); syncExposureMainAndMDA.setText("Sync exposure between Main and MDA windows"); syncExposureMainAndMDA.setSelected(opts_.syncExposureMainAndMDA_); syncExposureMainAndMDA.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { opts_.syncExposureMainAndMDA_ = syncExposureMainAndMDA.isSelected(); } }); final JCheckBox hideMDAdisplay = new JCheckBox(); hideMDAdisplay.setText("Hide MDA display"); hideMDAdisplay.setSelected(opts_.hideMDADisplay_); hideMDAdisplay.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { opts_.hideMDADisplay_ = hideMDAdisplay.isSelected(); } }); final JButton closeButton = new JButton(); closeButton.setText("Close"); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent ev) { closeRequested(); } }); setLayout(new net.miginfocom.swing.MigLayout( "fill, insets dialog", "[fill]")); add(debugLogEnabledCheckBox, "wrap"); add(doNotAskForConfigFileCheckBox, "wrap"); add(new JLabel("Sequence Buffer Size:"), "split 3, gapright push"); add(bufSizeField_, "gapright related"); add(new JLabel("MB"), "wrap"); add(new JLabel("Display Background:"), "split 2, gapright push"); add(comboDisplayBackground_, "wrap"); add(new JLabel("Startup Script:"), "split 2, gapright push"); add(startupScriptFile_, "wrap"); add(deleteLogCheckBox, "split 3, gapright related"); add(logDeleteDaysField_, "gapright related"); add(new JLabel("days"), "gapright push, wrap"); add(deleteLogFilesButton, "sizegroup clearBtns, split 2"); add(clearRegistryButton, "sizegroup clearBtns, wrap"); add(autoreloadDevicesCheckBox, "wrap"); add(closeOnExitCheckBox, "wrap"); add(new JLabel("Preferred Image Window Zoom:"), "split 2, gapright push"); add(prefZoomCombo, "wrap"); add(metadataFileWithMultipageTiffCheckBox, "wrap"); add(separateFilesForPositionsMPTiffCheckBox, "wrap"); add(syncExposureMainAndMDA, "wrap"); add(hideMDAdisplay, "wrap"); add(closeButton, "gapleft push"); pack(); } private void changeBackground() { String background = (String) comboDisplayBackground_.getSelectedItem(); opts_.displayBackground_ = background; setBackground(guiColors_.background.get(background)); if (parent_ != null) // test for null just to avoid crashes (should never be null) { // set background and trigger redraw of parent and its descendant windows MMStudioMainFrame.getInstance().setBackgroundStyle(background); } } private void closeRequested() { int seqBufSize; int deleteLogDays; try { seqBufSize = NumberUtils.displayStringToInt(bufSizeField_.getText()); deleteLogDays = NumberUtils.displayStringToInt(logDeleteDaysField_.getText()); } catch (Exception ex) { ReportingUtils.showError(ex); return; } opts_.circularBufferSizeMB_ = seqBufSize; opts_.startupScript_ = startupScriptFile_.getText(); opts_.deleteCoreLogAfterDays_ = deleteLogDays; opts_.saveSettings(); savePosition(); parent_.makeActive(); dispose(); } }
package org.verapdf.cli; import java.io.IOException; import org.apache.log4j.Logger; import org.verapdf.ReleaseDetails; import org.verapdf.cli.commands.VeraCliArgParser; import org.verapdf.pdfa.validation.ProfileDirectory; import org.verapdf.pdfa.validation.Profiles; import org.verapdf.pdfa.validation.ValidationProfile; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; /** * @author <a href="mailto:carl@openpreservation.org">Carl Wilson</a> * */ public final class VeraPdfCli { private static final Logger LOGGER = Logger.getLogger(VeraPdfCli.class); private static final String APP_NAME = "veraPDF"; private static final ReleaseDetails RELEASE_DETAILS = ReleaseDetails .getInstance(); private static final String FLAVOURS_HEADING = APP_NAME + " supported PDF/A profiles:"; private static final ProfileDirectory PROFILES = Profiles .getVeraProfileDirectory(); private VeraPdfCli() { // disable default constructor } /** * Main CLI entry point, process the command line arguments * * @param args * Java.lang.String array of command line args, to be processed * using Apache commons CLI. */ public static void main(final String[] args) { VeraCliArgParser cliArgParser = new VeraCliArgParser(); JCommander jCommander = new JCommander(cliArgParser); jCommander.setProgramName(APP_NAME); try { jCommander.parse(args); } catch (ParameterException e) { System.err.println(e.getMessage()); showVersionInfo(); jCommander.usage(); System.exit(0); } if (args.length == 0 || cliArgParser.isHelp()) { showVersionInfo(); jCommander.usage(); System.exit(0); } messagesFromParser(cliArgParser); try { VeraPdfCliProcessor processor = VeraPdfCliProcessor.createProcessorFromArgs(cliArgParser); processor.processPaths(cliArgParser.getPdfPaths()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void logThrowableAndExit(final Throwable cause, final String message, final int retVal) { logThrowable(cause, message); System.exit(retVal); } private static void logThrowable(final Throwable cause, final String message) { LOGGER.fatal(message, cause); return; } private static void messagesFromParser(final VeraCliArgParser parser) { if (parser.listProfiles()) { listProfiles(); } if (parser.showVersion()) { showVersionInfo(); } } private static void listProfiles() { System.out.println(FLAVOURS_HEADING); for (ValidationProfile profile : PROFILES.getValidationProfiles()) { System.out.println(" " + profile.getPDFAFlavour().getId() + " - " + profile.getDetails().getName()); } System.out.println(); } private static void showVersionInfo() { System.out.println("Version: " + RELEASE_DETAILS.getVersion()); System.out.println("Built: " + RELEASE_DETAILS.getBuildDate()); System.out.println(RELEASE_DETAILS.getRights()); System.out.println(); } }
package com.carrotsearch.hppc; import java.util.Arrays; //import static com.carrotsearch.hppc.KTypeVTypeWormMap.*; /** * Java hash for primitives. * <p/>stdHash() is different from hash() because we want <b>standard Java</b> implementations. * @author broustant */ public class WormUtil { private static final int END_OF_CHAIN = 127; private static final boolean DEBUG_ENABLED = false; /** * Hashes a char. Improves distribution for Map or Set. */ public static int hash(char c) { return hash((short) c); } /** * Hashes a short. Improves distribution for Map or Set. */ public static int hash(short s) { s ^= (s >>> 10) ^ (s >>> 6); return s ^ (s >>> 4) ^ (s >>> 2); } /** * Hashes an int. Improves distribution for Map or Set. */ public static int hash(int i) { int h = i * -1640531527; return h ^ h >> 16; } /** * Hashes a long. Improves distribution for Map or Set. */ public static int hash(long l) { return hash((int) ((l >>> 32) ^ l)); } /** * Hashes a char. Improves distribution for Map or Set. */ public static int hash(Object o) { return hash(o.hashCode()); } /** * Adds a positive offset to the provided index, handling rotation around the circular array. * * @return The new index after addition. */ static int addOffset(int index, int offset, byte[] next) { if (DEBUG_ENABLED) { assert checkIndex(index, next); assert offset > 0 && offset < END_OF_CHAIN : "offset=" + offset; } index += offset; while (index >= next.length) { index -= next.length; } if (DEBUG_ENABLED) { assert checkIndex(index, next); } return index; } /** * Subtracts a positive offset to the provided index, handling rotation around the circular array. * * @return The new index after subtraction. */ static int subtractOffset(int index, int offset, byte[] next) { if (DEBUG_ENABLED) { assert checkIndex(index, next); assert offset > 0 && offset < END_OF_CHAIN : "offset=" + offset; } index -= offset; while (index < 0) { index += next.length; } if (DEBUG_ENABLED) { assert checkIndex(index, next); } return index; } static boolean checkIndex(int index, byte[] next) { assert index >= 0 && index < next.length : "index=" + index + ", array length=" + next.length; return true; } /** * Efficient immutable set of excluded indexes (immutable int set of expected small size). * <p/>Used when searching for a free bucket and attempting to move tail-of-chain entries * recursively. We must not move the entry chains for which we want to find a free bucket. * So {@link ExcludedIndexes} is immutable and can be stacked with {@link #union(ExcludedIndexes)} * during recursive calls. In addition the initial {@link #NONE} is a constant and does not stack * as it overrides {@link #union(ExcludedIndexes)}. */ static abstract class ExcludedIndexes { static final ExcludedIndexes NONE = new ExcludedIndexes() { @Override ExcludedIndexes union(ExcludedIndexes excludedIndexes) { return excludedIndexes; } @Override boolean isIndexExcluded(int index) { return false; } }; static ExcludedIndexes fromChain(int index, byte[] next) { int nextOffset = Math.abs(next[index]); if (DEBUG_ENABLED) { assert nextOffset != 0 : "nextOffset=0"; } return nextOffset == END_OF_CHAIN ? new SingletonExcludedIndex(index) : new MultipleExcludedIndexes(index, nextOffset, next); } ExcludedIndexes union(ExcludedIndexes excludedIndexes) { return new UnionExcludedIndexes(this, excludedIndexes); } abstract boolean isIndexExcluded(int index); } static class SingletonExcludedIndex extends ExcludedIndexes { final int excludedIndex; SingletonExcludedIndex(int excludedIndex) { this.excludedIndex = excludedIndex; } @Override boolean isIndexExcluded(int index) { return index == excludedIndex; } } static class MultipleExcludedIndexes extends ExcludedIndexes { final int[] excludedIndexes; final int size; MultipleExcludedIndexes(int index, int nextOffset, byte[] next) { if (DEBUG_ENABLED) { assert index >= 0 && index < next.length : "index=" + index + ", next.length=" + next.length; assert nextOffset > 0 && nextOffset < END_OF_CHAIN : "nextOffset=" + nextOffset; } int[] excludedIndexes = new int[8]; int size = 0; boolean shouldSort = false; excludedIndexes[size++] = index; do { int nextIndex = addOffset(index, nextOffset, next); if (nextIndex < index) { // Rolling on the circular buffer. We will need to sort to keep a sorted list of indexes. shouldSort = true; } if (DEBUG_ENABLED) { assert nextIndex >= 0 && nextIndex < next.length : "nextIndex=" + index + ", next.length=" + next.length; } if (size == excludedIndexes.length) { excludedIndexes = Arrays.copyOf(excludedIndexes, size * 2); } excludedIndexes[size++] = index = nextIndex; nextOffset = Math.abs(next[index]); if (DEBUG_ENABLED) { assert nextOffset > 0 : "nextOffset=" + nextOffset; } } while (nextOffset != END_OF_CHAIN); if (shouldSort) { Arrays.sort(excludedIndexes, 0, size); } this.excludedIndexes = excludedIndexes; this.size = size; } @Override boolean isIndexExcluded(int index) { return Arrays.binarySearch(excludedIndexes, 0, size, index) >= 0; } } static class UnionExcludedIndexes extends ExcludedIndexes { final ExcludedIndexes left; final ExcludedIndexes right; UnionExcludedIndexes(ExcludedIndexes left, ExcludedIndexes right) { this.left = left; this.right = right; } @Override boolean isIndexExcluded(int index) { return left.isIndexExcluded(index) || right.isIndexExcluded(index); } } }
package <%= group %>; /** * Class that can hold basic static things that are better not hard-coded * like mod details, texture paths, ID's... * @author <%= author %> * */ @SuppressWarnings("javadoc") public class Reference { // Mod info public static final String MOD_ID = "<%= modid %>"; public static final String MOD_NAME = "<%= modname %>"; public static final String MOD_VERSION = "@VERSION@"; public static final String MOD_BUILD_NUMBER = "@BUILD_NUMBER@"; public static final String MOD_CHANNEL = MOD_ID; public static final String MOD_MC_VERSION = "@MC_VERSION@"; public static final String GA_TRACKING_ID = "<%= trackingid %>"; public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/1.11/<%= modname %>.txt"; // Paths public static final String TEXTURE_PATH_GUI = "textures/gui/"; public static final String TEXTURE_PATH_SKINS = "textures/skins/"; public static final String TEXTURE_PATH_MODELS = "textures/models/"; public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; public static final String TEXTURE_PATH_ITEMS = "textures/items/"; public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; public static final String MODEL_PATH = "models/"; // MOD ID's public static final String MOD_FORGE = "forge"; public static final String MOD_FORGE_VERSION = "@FORGE_VERSION@"; public static final String MOD_FORGE_VERSION_MIN = "13.20.0.2282"; public static final String MOD_CYCLOPSCORE = "cyclopscore"; public static final String MOD_CYCLOPSCORE_VERSION = "@CYCLOPSCORE_VERSION@"; public static final String MOD_CYCLOPSCORE_VERSION_MIN = "0.10.6"; // Dependencies public static final String MOD_DEPENDENCIES = "required-after:" + MOD_FORGE + "@[" + MOD_FORGE_VERSION_MIN + ",);" + "required-after:" + MOD_CYCLOPSCORE + "@[" + MOD_CYCLOPSCORE_VERSION_MIN + ",);"; }
package hex.deeplearning; import hex.ConfusionMatrix; import hex.deeplearning.DeepLearningModel.DeepLearningParameters.ClassSamplingMethod; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import water.*; import water.fvec.Frame; import water.fvec.NFSFileVec; import water.parser.ParseDataset; import water.rapids.Env; import water.rapids.Exec; import water.util.Log; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Random; import static hex.ConfusionMatrix.buildCM; import static hex.deeplearning.DeepLearningModel.DeepLearningParameters; public class DeepLearningProstateTest extends TestUtil { @BeforeClass() public static void setup() { stall_till_cloudsize(1); } @Test public void run() throws Exception { runFraction(0.001f); } public void runFraction(float fraction) { long seed = 0xDECAF; Random rng = new Random(seed); String[] datasets = new String[2]; int[][] responses = new int[datasets.length][]; datasets[0] = "smalldata/logreg/prostate.csv"; responses[0] = new int[]{1,2,8}; //CAPSULE (binomial), AGE (regression), GLEASON (multi-class) datasets[1] = "smalldata/iris/iris.csv"; responses[1] = new int[]{4}; //Iris-type (multi-class) HashSet<Long> checkSums = new LinkedHashSet<>(); int testcount = 0; int count = 0; for (int i = 0; i < datasets.length; ++i) { final String dataset = datasets[i]; NFSFileVec nfs = NFSFileVec.make(find_test_file(dataset)); Frame frame = ParseDataset.parse(Key.make(), nfs._key); NFSFileVec vnfs = NFSFileVec.make(find_test_file(dataset)); Frame vframe = ParseDataset.parse(Key.make(), vnfs._key); try { for (boolean replicate : new boolean[]{ true, false, }) { for (boolean load_balance : new boolean[]{ // true, false, }) { for (boolean shuffle : new boolean[]{ true, false, }) { for (boolean balance_classes : new boolean[]{ true, false, }) { for (int resp : responses[i]) { boolean classification = !(i == 0 && resp == 2); for (ClassSamplingMethod csm : new ClassSamplingMethod[]{ ClassSamplingMethod.Stratified, ClassSamplingMethod.Uniform }) { for (int scoretraining : new int[]{ 200, 20, 0, }) { for (int scorevalidation : new int[]{ 200, 20, 0, }) { for (int vf : new int[]{ 0, //no validation 1, //same as source -1, //different validation frame }) { for (int n_folds : new int[]{ 0, }) { if (n_folds != 0 && vf != 0) continue; for (boolean keep_cv_splits : new boolean[]{false}) { //otherwise it leaks for (boolean override_with_best_model : new boolean[]{false, true}) { for (int train_samples_per_iteration : new int[]{ -2, //auto-tune -1, //N epochs per iteration 0, //1 epoch per iteration rng.nextInt(200), // <1 epoch per iteration 500, //>1 epoch per iteration }) { DeepLearningModel model1 = null, model2 = null, tmp_model = null; Key dest, dest_tmp; count++; if (fraction < rng.nextFloat()) continue; try { Scope.enter(); Log.info("**************************)"); Log.info("Starting test #" + count); Log.info("**************************)"); final double epochs = 7 + rng.nextDouble() + rng.nextInt(4); final int[] hidden = new int[]{1 + rng.nextInt(4), 1 + rng.nextInt(6)}; Frame valid = null; //no validation if (vf == 1) valid = frame; //use the same frame for validation else if (vf == -1) valid = vframe; //different validation frame (here: from the same file) // build the model, with all kinds of shuffling/rebalancing/sampling { Log.info("Using seed: " + seed); DeepLearningParameters p = new DeepLearningParameters(); p._destination_key = Key.make(Key.make().toString() + "first"); dest_tmp = p._destination_key; p._checkpoint = null; p._train = frame._key; p._response_column = frame._names[resp]; p._valid = valid==null ? null : valid._key; p._convert_to_enum = classification; p._hidden = hidden; // p.best_model_key = best_model_key; p._override_with_best_model = override_with_best_model; p._epochs = epochs; p._n_folds = n_folds; p._keep_cross_validation_splits = keep_cv_splits; p._seed = seed; p._train_samples_per_iteration = train_samples_per_iteration; p._force_load_balance = load_balance; p._replicate_training_data = replicate; p._shuffle_training_data = shuffle; p._score_training_samples = scoretraining; p._score_validation_samples = scorevalidation; p._classification_stop = -1; p._regression_stop = -1; p._balance_classes = classification && balance_classes; p._quiet_mode = true; p._score_validation_sampling = csm; // Log.info(new String(p.writeJSON(new AutoBuffer()).buf()).replace(",","\n")); DeepLearning dl = new DeepLearning(p); try { model1 = dl.trainModel().get(); checkSums.add(model1.checksum()); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { dl.remove(); } Log.info("Trained for " + model1.epoch_counter + " epochs."); assert( ((p._train_samples_per_iteration <= 0 || p._train_samples_per_iteration >= frame.numRows()) && model1.epoch_counter > epochs) || Math.abs(model1.epoch_counter - epochs)/epochs < 0.20 ); if (n_folds != 0) // test HTML of cv models { throw H2O.unimpl(); // for (Key k : model1.get_params().xval_models) { // DeepLearningModel cv_model = UKV.get(k); // StringBuilder sb = new StringBuilder(); // cv_model.generateHTML("cv", sb); // cv_model.delete_best_model(); // cv_model.delete(); } } // Do some more training via checkpoint restart // For n_folds, continue without n_folds (not yet implemented) - from now on, model2 will have n_folds=0... DeepLearningParameters p = new DeepLearningParameters(); tmp_model = DKV.get(dest_tmp).get(); //this actually *requires* frame to also still be in UKV (because of DataInfo...) Assert.assertTrue(tmp_model.model_info().get_processed_total() >= frame.numRows() * epochs); assert (tmp_model != null); p._destination_key = Key.make(); dest = p._destination_key; p._checkpoint = dest_tmp; p._n_folds = 0; p._valid = valid == null ? null : valid._key; p._response_column = frame._names[resp]; p._convert_to_enum = classification; p._override_with_best_model = override_with_best_model; p._epochs = epochs; p._seed = seed; p._train_samples_per_iteration = train_samples_per_iteration; p._balance_classes = classification && balance_classes; p._train = frame._key; DeepLearning dl = new DeepLearning(p); try { model1 = dl.trainModel().get(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { dl.remove(); } // score and check result (on full data) model2 = DKV.get(dest).get(); //this actually *requires* frame to also still be in DKV (because of DataInfo...) // score and check result of the best_model if (model2.actual_best_model_key != null) { final DeepLearningModel best_model = DKV.get(model2.actual_best_model_key).get(); if (override_with_best_model) { Assert.assertEquals(best_model.error(), model2.error(), 0); } } if (valid == null) valid = frame; double threshold = 0; if (model2._output.isClassifier()) { Frame pred = null, pred2 = null; try { pred = model2.score(valid); hex.ModelMetrics mm = hex.ModelMetrics.getFromDKV(model2, valid); double error = 0; // binary if (model2._output.nclasses() == 2) { assert (resp == 1); threshold = mm.auc().threshold(); error = mm.auc().err(); // check that auc.cm() is the right CM Assert.assertEquals(new ConfusionMatrix(mm.auc().cm(), new String[]{"0", "1"}).err(), error, 1e-15); // check that calcError() is consistent as well (for CM=null, AUC!=null) Assert.assertEquals(mm.cm().err(), error, 1e-15); } double CMerrorOrig = buildCM(valid.vecs()[resp].toEnum(), pred.vecs()[0].toEnum()).err(); // confirm that orig CM was made with threshold 0.5 // put pred2 into DKV, and allow access pred2 = new Frame(Key.make("pred2"), pred.names(), pred.vecs()); pred2.delete_and_lock(null); pred2.unlock(null); if (model2._output.nclasses() == 2) { // make labels with 0.5 threshold for binary classifier // ast is from this expression pred2[,1] = (pred2[,3]>=0.5) String ast = "(= ([ %pred2 \"null\" #0) (G ([ %pred2 \"null\" #2) #"+0.5+"))"; Env ev = Exec.exec(ast); try { pred2 = ev.popAry(); // pop0 pops w/o lowering refs, let remove_and_unlock handle cleanup } finally { if (ev!=null) ev.remove_and_unlock(); } double threshErr = buildCM(valid.vecs()[resp].toEnum(), pred2.vecs()[0].toEnum()).err(); Assert.assertEquals(threshErr, CMerrorOrig, 1e-15); // make labels with AUC-given threshold for best F1 // similar ast to the above ast = "(= ([ %pred2 \"null\" #0) (G ([ %pred2 \"null\" #2) #"+threshold+"))"; ev = Exec.exec(ast); try { pred2 = ev.popAry(); // pop0 pops w/o lowering refs, let remove_and_unlock handle cleanup } finally { if (ev != null) ev.remove_and_unlock(); } double threshErr2 = buildCM(valid.vecs()[resp].toEnum(), pred2.vecs()[0].toEnum()).err(); Assert.assertEquals(threshErr2, error, 1e-15); } } finally { if (pred != null) pred.delete(); if (pred2 != null) pred2.delete(); } } //classifier Log.info("Parameters combination " + count + ": PASS"); testcount++; } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { if (model1 != null) { model1.delete_xval_models(); model1.delete_best_model(); model1.delete(); } if (model2 != null) { model2.delete_xval_models(); model2.delete_best_model(); model2.delete(); } if (tmp_model != null) { tmp_model.delete_xval_models(); tmp_model.delete_best_model(); tmp_model.delete(); } Scope.exit(); } } } } } } } } } } } } } } } finally { frame.delete(); vframe.delete(); } } Assert.assertTrue(checkSums.size() == testcount); Log.info("\n\n============================================="); Log.info("Tested " + testcount + " out of " + count + " parameter combinations."); Log.info("============================================="); } public static class Mid extends DeepLearningProstateTest { @Test @Ignore public void run() throws Exception { runFraction(0.01f); } //for nightly tests } public static class Short extends DeepLearningProstateTest { @Test @Ignore public void run() throws Exception { runFraction(0.001f); } } }
package org.intermine.task; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.Target; import org.apache.tools.ant.Project; import org.apache.torque.task.TorqueSQLExec; import org.apache.torque.task.TorqueSQLTask; import java.io.File; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.ArrayList; import org.intermine.sql.Database; import org.intermine.sql.DatabaseFactory; /** * Generates and inserts SQL given database name, schema and temporary directory * * @author Mark Woodbridge */ public class BuildDbTask extends Task { protected static final String SEQUENCE_NAME = "serial"; protected File tempDir; protected Database database; protected String schemaFile; /** * Sets the database * @param database String used to identify Database (usually dataSourceName) */ public void setDatabase(String database) { try { this.database = DatabaseFactory.getDatabase(database); } catch (Exception e) { e.printStackTrace(); } } /** * Sets the directory for temporary files including sql output * @param tempDir the directory location */ public void setTempdir(File tempDir) { this.tempDir = tempDir; } /** * Adds the schemafile to be processed. * @param schemafile to be processed */ public void setSchemafile(String schemafile) { this.schemaFile = schemafile; } /** * @see Task#execute * @throws BuildException */ public void execute() throws BuildException { if (tempDir == null) { throw new BuildException("tempDir attribute is not set"); } if (database == null) { throw new BuildException("database attribute is not set or database is not present"); } if (schemaFile == null) { throw new BuildException("schemaFile attribute is not set"); } SQL sql = new SQL(); sql.setControlTemplate("sql/base/Control.vm"); sql.setOutputDirectory(tempDir); sql.setUseClasspath(true); //sql.setBasePathToDbProps("sql/base/"); sql.setSqlDbMap(tempDir + "/sqldb.map"); sql.setOutputFile("report.sql.generation"); sql.setTargetDatabase(database.getPlatform().toLowerCase()); // "postgresql" InputStream schemaFileInputStream = getClass().getClassLoader().getResourceAsStream(schemaFile); File tempFile; try { tempFile = File.createTempFile("schema", "xml", tempDir); PrintWriter writer = new PrintWriter(new FileWriter(tempFile)); BufferedReader reader = new BufferedReader(new InputStreamReader(schemaFileInputStream)); while (true) { String line = reader.readLine(); if (line == null) { break; } else { writer.println(line); } } writer.flush(); writer.close(); } catch (IOException e) { throw new BuildException("cannot create temporary file for BuildDbTask: " + e.getMessage()); } sql.setXmlFile(tempFile.getPath()); sql.execute(); InsertSQL isql = new InsertSQL(); isql.setDriver(database.getDriver()); // "org.postgresql.Driver" isql.setUrl(database.getURL()); // "jdbc:postgresql://localhost/test" isql.setUserid(database.getUser()); // "mark" isql.setPassword(database.getPassword()); isql.setAutocommit(true); TorqueSQLExec.OnError ea = new TorqueSQLExec.OnError(); ea.setValue("continue"); // "abort", "continue" or "stop" isql.setOnerror(ea); isql.setSqlDbMap(tempDir + "/sqldb.map"); isql.setSrcDir(tempDir.toString()); isql.execute(); try { Connection c = database.getConnection(); c.setAutoCommit(true); c.createStatement().execute("create sequence " + SEQUENCE_NAME); c.close(); } catch (SQLException e) { } tempFile.delete(); } } /** * Class to initialise sql generation task in absence of ant * * @author Mark Woodbridge */ class SQL extends TorqueSQLTask { /** * Default constructor */ public SQL() { project = new Project(); project.init(); target = new Target(); taskName = "torque-sql"; } } /** * Class to initialise sql insertion task in absence of ant * * @author Mark Woodbridge */ class InsertSQL extends TorqueSQLExec { /** * Default constructor */ public InsertSQL() { project = new Project(); project.init(); target = new Target(); taskName = "torque-insert-sql"; } }
package weave.servlets; import static weave.config.WeaveConfig.getConnectionConfig; import static weave.config.WeaveConfig.getDataConfig; import static weave.config.WeaveConfig.initWeaveConfig; import java.rmi.RemoteException; import java.security.InvalidParameterException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import org.postgis.Geometry; import org.postgis.PGgeometry; import org.postgis.Point; import weave.beans.AttributeColumnData; import weave.beans.GeometryStreamMetadata; import weave.beans.PGGeom; import weave.beans.WeaveJsonDataSet; import weave.beans.WeaveRecordList; import weave.config.ConnectionConfig.ConnectionInfo; import weave.config.DataConfig; import weave.config.DataConfig.DataEntity; import weave.config.DataConfig.DataEntityMetadata; import weave.config.DataConfig.DataEntityWithRelationships; import weave.config.DataConfig.DataType; import weave.config.DataConfig.EntityHierarchyInfo; import weave.config.DataConfig.EntityType; import weave.config.DataConfig.PrivateMetadata; import weave.config.DataConfig.PublicMetadata; import weave.config.WeaveContextParams; import weave.geometrystream.SQLGeometryStreamReader; import weave.utils.CSVParser; import weave.utils.ListUtils; import weave.utils.MapUtils; import weave.utils.SQLResult; import weave.utils.SQLUtils; import weave.utils.SQLUtils.WhereClause; import weave.utils.SQLUtils.WhereClause.ColumnFilter; import weave.utils.SQLUtils.WhereClause.NestedColumnFilters; import weave.utils.Strings; /** * This class connects to a database and gets data * uses xml configuration file to get connection/query info * * @author Andy Dufilie */ public class DataService extends WeaveServlet implements IWeaveEntityService { private static final long serialVersionUID = 1L; public static final int MAX_COLUMN_REQUEST_COUNT = 100; public DataService() { } public void init(ServletConfig config) throws ServletException { super.init(config); initWeaveConfig(WeaveContextParams.getInstance(config.getServletContext())); } // helper functions private DataEntity getColumnEntity(int columnId) throws RemoteException { DataEntity entity = getDataConfig().getEntity(columnId); if (entity == null) throw new RemoteException("No column with id " + columnId); String entityType = entity.publicMetadata.get(PublicMetadata.ENTITYTYPE); if (!Strings.equal(entityType, EntityType.COLUMN)) throw new RemoteException(String.format("Entity with id=%s is not a column (entityType: %s)", columnId, entityType)); return entity; } private void assertColumnHasPrivateMetadata(DataEntity columnEntity, String ... fields) throws RemoteException { for (String field : fields) { if (Strings.isEmpty(columnEntity.privateMetadata.get(field))) { String dataType = columnEntity.publicMetadata.get(PublicMetadata.DATATYPE); String description = (dataType != null && dataType.equals(DataType.GEOMETRY)) ? "Geometry column" : "Column"; throw new RemoteException(String.format("%s %s is missing private metadata %s", description, columnEntity.id, field)); } } } private boolean assertStreamingGeometryColumn(DataEntity entity, boolean throwException) throws RemoteException { try { String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); if (dataType == null || !dataType.equals(DataType.GEOMETRY)) throw new RemoteException(String.format("Column %s dataType is %s, not %s", entity.id, dataType, DataType.GEOMETRY)); assertColumnHasPrivateMetadata(entity, PrivateMetadata.CONNECTION, PrivateMetadata.SQLSCHEMA, PrivateMetadata.SQLTABLEPREFIX); return true; } catch (RemoteException e) { if (throwException) throw e; return false; } } // DataEntity info public EntityHierarchyInfo[] getHierarchyInfo(Map<String,String> publicMetadata) throws RemoteException { return getDataConfig().getEntityHierarchyInfo(publicMetadata); } public DataEntityWithRelationships[] getEntities(int[] ids) throws RemoteException { if (ids.length > DataConfig.MAX_ENTITY_REQUEST_COUNT) throw new RemoteException(String.format("You cannot request more than %s entities at a time.", DataConfig.MAX_ENTITY_REQUEST_COUNT)); // prevent user from receiving private metadata return getDataConfig().getEntitiesWithRelationships(ids, false); } public int[] findEntityIds(Map<String,String> publicMetadata, String[] wildcardFields) throws RemoteException { int[] ids = ListUtils.toIntArray( getDataConfig().searchPublicMetadata(publicMetadata, wildcardFields) ); Arrays.sort(ids); return ids; } public String[] findPublicFieldValues(String fieldName, String valueSearch) throws RemoteException { throw new RemoteException("Not implemented yet"); } // Columns private static ConnectionInfo getColumnConnectionInfo(DataEntity entity) throws RemoteException { String connName = entity.privateMetadata.get(PrivateMetadata.CONNECTION); ConnectionInfo connInfo = getConnectionConfig().getConnectionInfo(connName); if (connInfo == null) { String title = entity.publicMetadata.get(PublicMetadata.TITLE); throw new RemoteException(String.format("Connection named '%s' associated with column #%s (%s) no longer exists", connName, entity.id, title)); } return connInfo; } /** * This retrieves the data and the public metadata for a single attribute column. * @param columnId Either an entity ID (int) or a Map specifying public metadata values that uniquely identify a column. * @param minParam Used for filtering numeric data * @param maxParam Used for filtering numeric data * @param sqlParams Specifies parameters to be used in place of '?' placeholders that appear in the SQL query for the column. * @return The column data. * @throws RemoteException */ @SuppressWarnings("unchecked") public AttributeColumnData getColumn(Object columnId, double minParam, double maxParam, String[] sqlParams) throws RemoteException { DataEntity entity = null; if (columnId instanceof Number) { entity = getColumnEntity(((Number)columnId).intValue()); } else if (columnId instanceof Map) { @SuppressWarnings({ "rawtypes" }) Map metadata = (Map)columnId; metadata.put(PublicMetadata.ENTITYTYPE, EntityType.COLUMN); int[] ids = findEntityIds(metadata, null); if (ids.length == 0) throw new RemoteException("No column with id " + columnId); if (ids.length > 1) throw new RemoteException(String.format( "The specified metadata does not uniquely identify a column (%s matching columns found): %s", ids.length, columnId )); entity = getColumnEntity(ids[0]); } else throw new RemoteException("columnId must either be an Integer or a Map of public metadata values."); // if it's a geometry column, just return the metadata if (assertStreamingGeometryColumn(entity, false)) { GeometryStreamMetadata gsm = (GeometryStreamMetadata) getGeometryData(entity, GeomStreamComponent.TILE_DESCRIPTORS, null); AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.metadata = entity.publicMetadata; result.metadataTileDescriptors = gsm.metadataTileDescriptors; result.geometryTileDescriptors = gsm.geometryTileDescriptors; return result; } String query = entity.privateMetadata.get(PrivateMetadata.SQLQUERY); String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); ConnectionInfo connInfo = getColumnConnectionInfo(entity); List<String> keys = new ArrayList<String>(); List<Double> numericData = null; List<String> stringData = null; List<Object> thirdColumn = null; // hack for dimension slider format List<PGGeom> geometricData = null; // use config min,max or param min,max to filter the data double minValue = Double.NaN; double maxValue = Double.NaN; // override config min,max with param values if given if (!Double.isNaN(minParam)) { minValue = minParam; } else { try { minValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MIN)); } catch (Exception e) { } } if (!Double.isNaN(maxParam)) { maxValue = maxParam; } else { try { maxValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MAX)); } catch (Exception e) { } } if (Double.isNaN(minValue)) minValue = Double.NEGATIVE_INFINITY; if (Double.isNaN(maxValue)) maxValue = Double.POSITIVE_INFINITY; try { Connection conn = connInfo.getStaticReadOnlyConnection(); // use default sqlParams if not specified by query params if (sqlParams == null || sqlParams.length == 0) { String sqlParamsString = entity.privateMetadata.get(PrivateMetadata.SQLPARAMS); sqlParams = CSVParser.defaultParser.parseCSVRow(sqlParamsString, true); } SQLResult result = SQLUtils.getResultFromQuery(conn, query, sqlParams, false); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) { dataType = DataType.fromSQLType(result.columnTypes[1]); entity.publicMetadata.put(PublicMetadata.DATATYPE, dataType); // fill in missing metadata for the client } if (dataType.equalsIgnoreCase(DataType.NUMBER)) // special case: "number" => Double { numericData = new LinkedList<Double>(); } else if (dataType.equalsIgnoreCase(DataType.GEOMETRY)) { geometricData = new LinkedList<PGGeom>(); } else { stringData = new LinkedList<String>(); } // hack for dimension slider format if (result.columnTypes.length == 3) thirdColumn = new LinkedList<Object>(); Object keyObj, dataObj; double value; for (int i = 0; i < result.rows.length; i++) { keyObj = result.rows[i][0]; if (keyObj == null) continue; dataObj = result.rows[i][1]; if (dataObj == null) continue; if (numericData != null) { try { if (dataObj instanceof String) dataObj = Double.parseDouble((String)dataObj); value = ((Number)dataObj).doubleValue(); } catch (Exception e) { continue; } // filter the data based on the min,max values if (minValue <= value && value <= maxValue) numericData.add(value); else continue; } else if (geometricData != null) { // The dataObj must be cast to PGgeometry before an individual Geometry can be extracted. if (!(dataObj instanceof PGgeometry)) continue; Geometry geom = ((PGgeometry) dataObj).getGeometry(); int numPoints = geom.numPoints(); // Create PGGeom Bean here and fill it up! PGGeom bean = new PGGeom(); bean.type = geom.getType(); bean.xyCoords = new double[numPoints * 2]; for (int j = 0; j < numPoints; j++) { Point pt = geom.getPoint(j); bean.xyCoords[j * 2] = pt.x; bean.xyCoords[j * 2 + 1] = pt.y; } geometricData.add(bean); } else { stringData.add(dataObj.toString()); } // if we got here, it means a data value was added, so add the corresponding key keys.add(keyObj.toString()); // hack for dimension slider format if (thirdColumn != null) thirdColumn.add(result.rows[i][2]); } } catch (SQLException e) { System.err.println(query); e.printStackTrace(); throw new RemoteException(String.format("Unable to retrieve data for column %s", columnId)); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException("Unexpected error", e); } AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.metadata = entity.publicMetadata; result.keys = keys.toArray(new String[keys.size()]); if (numericData != null) result.data = numericData.toArray(); else if (geometricData != null) result.data = geometricData.toArray(); else result.data = stringData.toArray(); // hack for dimension slider if (thirdColumn != null) result.thirdColumn = thirdColumn.toArray(); return result; } /** * This function is intended for use with JsonRPC calls. * @param columnIds A list of column IDs. * @return A WeaveJsonDataSet containing all the data from the columns. * @throws RemoteException */ public WeaveJsonDataSet getDataSet(int[] columnIds) throws RemoteException { if (columnIds == null) columnIds = new int[0]; if (columnIds.length > MAX_COLUMN_REQUEST_COUNT) throw new RemoteException(String.format("You cannot request more than %s columns at a time.", MAX_COLUMN_REQUEST_COUNT)); WeaveJsonDataSet result = new WeaveJsonDataSet(); for (Integer columnId : columnIds) { try { AttributeColumnData columnData = getColumn(columnId, Double.NaN, Double.NaN, null); result.addColumnData(columnData); } catch (RemoteException e) { e.printStackTrace(); } } return result; } // geometry columns public byte[] getGeometryStreamMetadataTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.METADATA_TILES, tileIDs); } public byte[] getGeometryStreamGeometryTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.GEOMETRY_TILES, tileIDs); } private static enum GeomStreamComponent { TILE_DESCRIPTORS, METADATA_TILES, GEOMETRY_TILES }; private Object getGeometryData(DataEntity entity, GeomStreamComponent component, int[] tileIDs) throws RemoteException { assertStreamingGeometryColumn(entity, true); Connection conn = getColumnConnectionInfo(entity).getStaticReadOnlyConnection(); String schema = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String tablePrefix = entity.privateMetadata.get(PrivateMetadata.SQLTABLEPREFIX); try { switch (component) { case TILE_DESCRIPTORS: GeometryStreamMetadata result = new GeometryStreamMetadata(); result.metadataTileDescriptors = SQLGeometryStreamReader.getMetadataTileDescriptors(conn, schema, tablePrefix); result.geometryTileDescriptors = SQLGeometryStreamReader.getGeometryTileDescriptors(conn, schema, tablePrefix); return result; case METADATA_TILES: return SQLGeometryStreamReader.getMetadataTiles(conn, schema, tablePrefix, tileIDs); case GEOMETRY_TILES: return SQLGeometryStreamReader.getGeometryTiles(conn, schema, tablePrefix, tileIDs); default: throw new InvalidParameterException("Invalid GeometryStreamComponent param."); } } catch (Exception e) { e.printStackTrace(); throw new RemoteException(String.format("Unable to read geometry data (id=%s)", entity.id)); } } // Row query public WeaveRecordList getRows(String keyType, String[] keysArray) throws RemoteException { DataConfig dataConfig = getDataConfig(); DataEntityMetadata params = new DataEntityMetadata(); params.setPublicMetadata( PublicMetadata.ENTITYTYPE, EntityType.COLUMN, PublicMetadata.KEYTYPE, keyType ); List<Integer> columnIds = new ArrayList<Integer>( dataConfig.searchPublicMetadata(params.publicMetadata, null) ); if (columnIds.size() > MAX_COLUMN_REQUEST_COUNT) columnIds = columnIds.subList(0, MAX_COLUMN_REQUEST_COUNT); return DataService.getFilteredRows(ListUtils.toIntArray(columnIds), null, keysArray); } /** * Gets all column IDs referenced by this object and its nested objects. */ private static Collection<Integer> getReferencedColumnIds(NestedColumnFilters filters) { Set<Integer> ids = new HashSet<Integer>(); if (filters.cond != null) ids.add(((Number)filters.cond.f).intValue()); else for (NestedColumnFilters nested : (filters.and != null ? filters.and : filters.or)) ids.addAll(getReferencedColumnIds(nested)); return ids; } /** * Converts nested ColumnFilter.f values from a column ID to the corresponding SQL field name. * @param filters * @param entities * @return A copy of filters with field names in place of the column IDs. * @see ColumnFilter#f */ private static NestedColumnFilters convertColumnIdsToFieldNames(NestedColumnFilters filters, Map<Integer, DataEntity> entities) { if (filters == null) return null; NestedColumnFilters result = new NestedColumnFilters(); if (filters.cond != null) { result.cond = new ColumnFilter(); result.cond.v = filters.cond.v; result.cond.r = filters.cond.r; result.cond.f = entities.get(((Number)filters.cond.f).intValue()).privateMetadata.get(PrivateMetadata.SQLCOLUMN); } else { NestedColumnFilters[] in = (filters.and != null ? filters.and : filters.or); NestedColumnFilters[] out = new NestedColumnFilters[in.length]; for (int i = 0; i < in.length; i++) out[i] = convertColumnIdsToFieldNames(in[i], entities); if (filters.and == in) result.and = out; else result.or = out; } return result; } private static SQLResult getFilteredRowsFromSQL(Connection conn, String schema, String table, int[] columns, NestedColumnFilters filters, Map<Integer,DataEntity> entities) throws SQLException { String[] quotedFields = new String[columns.length]; for (int i = 0; i < columns.length; i++) quotedFields[i] = SQLUtils.quoteSymbol(conn, entities.get(columns[i]).privateMetadata.get(PrivateMetadata.SQLCOLUMN)); WhereClause<Object> where = WhereClause.fromFilters(conn, convertColumnIdsToFieldNames(filters, entities)); String query = String.format( "SELECT %s FROM %s %s", Strings.join(",", quotedFields), SQLUtils.quoteSchemaTable(conn, schema, table), where.clause ); return SQLUtils.getResultFromQuery(conn, query, where.params.toArray(), false); } @SuppressWarnings("unchecked") public static WeaveRecordList getFilteredRows(int[] columns, NestedColumnFilters filters, String[] keysArray) throws RemoteException { if (columns == null || columns.length == 0) throw new RemoteException("At least one column must be specified."); if (filters != null) filters.assertValid(); DataConfig dataConfig = getDataConfig(); WeaveRecordList result = new WeaveRecordList(); Map<Integer, DataEntity> entityLookup = new HashMap<Integer, DataEntity>(); { // get all column IDs whether or not they are to be selected. Set<Integer> allColumnIds = new HashSet<Integer>(); if (filters != null) allColumnIds.addAll(getReferencedColumnIds(filters)); for (int id : columns) allColumnIds.add(id); // get all corresponding entities for (DataEntity entity : dataConfig.getEntities(allColumnIds, true)) entityLookup.put(entity.id, entity); // check for missing columns for (int id : allColumnIds) if (entityLookup.get(id) == null) throw new RemoteException("No column with ID=" + id); // provide public metadata in the same order as the selected columns result.attributeColumnMetadata = new Map[columns.length]; for (int i = 0; i < columns.length; i++) result.attributeColumnMetadata[i] = entityLookup.get(columns[i]).publicMetadata; } String keyType = result.attributeColumnMetadata[0].get(PublicMetadata.KEYTYPE); // make sure all columns have same keyType for (int i = 1; i < columns.length; i++) if (!Strings.equal(keyType, result.attributeColumnMetadata[i].get(PublicMetadata.KEYTYPE))) throw new RemoteException("Specified columns must all have same keyType."); if (keysArray == null) { boolean canGenerateSQL = true; // check to see if all the columns are from the same SQL table. String connection = null; String sqlSchema = null; String sqlTable = null; for (DataEntity entity : entityLookup.values()) { String c = entity.privateMetadata.get(PrivateMetadata.CONNECTION); String s = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String t = entity.privateMetadata.get(PrivateMetadata.SQLTABLE); if (connection == null) connection = c; if (sqlSchema == null) sqlSchema = s; if (sqlTable == null) sqlTable = t; if (!Strings.equal(connection, c) || !Strings.equal(sqlSchema, s) || !Strings.equal(sqlTable, t)) { canGenerateSQL = false; break; } } if (canGenerateSQL) { Connection conn = getColumnConnectionInfo(entityLookup.get(columns[0])).getStaticReadOnlyConnection(); try { result.recordData = getFilteredRowsFromSQL(conn, sqlSchema, sqlTable, columns, filters, entityLookup).rows; } catch (SQLException e) { throw new RemoteException("getFilteredRows() failed.", e); } } } if (result.recordData == null) { throw new Error("Selecting across tables is not supported yet."); /* HashMap<String,Object[]> data = new HashMap<String,Object[]>(); if (keysArray != null) for (String key : keysArray) data.put(key, new Object[entities.length]); for (int colIndex = 0; colIndex < entities.length; colIndex++) { Object[] filters = fcrs[colIndex].filters; DataEntity info = entities[colIndex]; String sqlQuery = info.privateMetadata.get(PrivateMetadata.SQLQUERY); String sqlParams = info.privateMetadata.get(PrivateMetadata.SQLPARAMS); //if (dataWithKeysQuery.length() == 0) // throw new RemoteException(String.format("No SQL query is associated with column \"%s\" in dataTable \"%s\"", attributeColumnName, dataTableName)); String dataType = info.publicMetadata.get(PublicMetadata.DATATYPE); // use config min,max or param min,max to filter the data String infoMinStr = info.publicMetadata.get(PublicMetadata.MIN); String infoMaxStr = info.publicMetadata.get(PublicMetadata.MAX); double minValue = Double.NEGATIVE_INFINITY; double maxValue = Double.POSITIVE_INFINITY; // first try parsing config min,max values try { minValue = Double.parseDouble(infoMinStr); } catch (Exception e) { } try { maxValue = Double.parseDouble(infoMaxStr); } catch (Exception e) { } // override config min,max with param values if given // * columnInfoArray = config.getDataEntity(params); // * for each info in columnInfoArray // * get sql data // * for each row in sql data // * if key is in keys array, // * add this value to the result // * return result try { //timer.start(); boolean errorReported = false; Connection conn = getColumnConnectionInfo(info).getStaticReadOnlyConnection(); String[] sqlParamsArray = null; if (sqlParams != null && sqlParams.length() > 0) sqlParamsArray = CSVParser.defaultParser.parseCSV(sqlParams, true)[0]; SQLResult sqlResult = SQLUtils.getResultFromQuery(conn, sqlQuery, sqlParamsArray, false); //timer.lap("get row set"); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) dataType = DataType.fromSQLType(sqlResult.columnTypes[1]); boolean isNumeric = dataType != null && dataType.equalsIgnoreCase(DataType.NUMBER); Object keyObj, dataObj; for (int iRow = 0; iRow < sqlResult.rows.length; iRow++) { keyObj = sqlResult.rows[iRow][0]; dataObj = sqlResult.rows[iRow][1]; if (keyObj == null || dataObj == null) continue; keyObj = keyObj.toString(); if (data.containsKey(keyObj)) { // if row has been set to null, skip if (data.get(keyObj) == null) continue; } else { // if keys are specified and row is not present, skip if (keysArray != null) continue; } try { boolean passedFilters = true; // convert the data to the appropriate type, then filter by value if (isNumeric) { if (dataObj instanceof Number) // TEMPORARY SOLUTION - FIX ME { double doubleValue = ((Number)dataObj).doubleValue(); // filter the data based on the min,max values if (minValue <= doubleValue && doubleValue <= maxValue) { // filter the value if (filters != null) { passedFilters = false; for (Object range : filters) { Number min = (Number)((Object[])range)[0]; Number max = (Number)((Object[])range)[1]; if (min.doubleValue() <= doubleValue && doubleValue <= max.doubleValue()) { passedFilters = true; break; } } } } else passedFilters = false; } else passedFilters = false; } else { String stringValue = dataObj.toString(); dataObj = stringValue; // filter the value if (filters != null) { passedFilters = false; for (Object filter : filters) { if (filter.equals(stringValue)) { passedFilters = true; break; } } } } Object[] row = data.get(keyObj); if (passedFilters) { // add existing row if it has not been added yet if (!data.containsKey(keyObj)) { for (int i = 0; i < colIndex; i++) { Object[] prevFilters = fcrs[i].filters; if (prevFilters != null) { passedFilters = false; break; } } if (passedFilters) row = new Object[entities.length]; data.put((String)keyObj, row); } if (row != null) row[colIndex] = dataObj; } else { // remove existing row if value did not pass filters if (row != null || !data.containsKey(keyObj)) data.put((String)keyObj, null); } } catch (Exception e) { if (!errorReported) { errorReported = true; e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException(e.getMessage()); } } if (keysArray == null) { List<String> keys = new LinkedList<String>(); for (Entry<String,Object[]> entry : data.entrySet()) if (entry.getValue() != null) keys.add(entry.getKey()); keysArray = keys.toArray(new String[keys.size()]); } Object[][] rows = new Object[keysArray.length][]; for (int iKey = 0; iKey < keysArray.length; iKey++) rows[iKey] = data.get(keysArray[iKey]); result.recordData = rows; */ } result.keyType = keyType; result.recordKeys = keysArray; return result; } // backwards compatibility /** * Use getHierarchyInfo() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public EntityHierarchyInfo[] getDataTableList() throws RemoteException { return getDataConfig().getEntityHierarchyInfo(MapUtils.<String,String>fromPairs(PublicMetadata.ENTITYTYPE, EntityType.TABLE)); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getEntityChildIds(int parentId) throws RemoteException { return ListUtils.toIntArray( getDataConfig().getChildIds(parentId) ); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getParents(int childId) throws RemoteException { int[] ids = ListUtils.toIntArray( getDataConfig().getParentIds(childId) ); Arrays.sort(ids); return ids; } /** * Use findEntityIds() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getEntityIdsByMetadata(Map<String,String> publicMetadata, int entityType) throws RemoteException { publicMetadata.put(PublicMetadata.ENTITYTYPE, EntityType.fromInt(entityType)); return findEntityIds(publicMetadata, null); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public DataEntity[] getEntitiesById(int[] ids) throws RemoteException { return getEntities(ids); } /** * @param metadata The metadata query. * @return The id of the matching column. * @throws RemoteException Thrown if the metadata query does not match exactly one column. */ @Deprecated public AttributeColumnData getColumnFromMetadata(Map<String, String> metadata) throws RemoteException { if (metadata == null || metadata.size() == 0) throw new RemoteException("No metadata query parameters specified."); metadata.put(PublicMetadata.ENTITYTYPE, EntityType.COLUMN); final String DATATABLE = "dataTable"; final String NAME = "name"; // exclude these parameters from the query if (metadata.containsKey(NAME)) metadata.remove(PublicMetadata.TITLE); String minStr = metadata.remove(PublicMetadata.MIN); String maxStr = metadata.remove(PublicMetadata.MAX); String paramsStr = metadata.remove(PrivateMetadata.SQLPARAMS); DataConfig dataConfig = getDataConfig(); Collection<Integer> ids = dataConfig.searchPublicMetadata(metadata, null); // attempt recovery for backwards compatibility if (ids.size() == 0) { if (metadata.containsKey(DATATABLE) && metadata.containsKey(NAME)) { // try to find columns sqlTable==dataTable and sqlColumn=name Map<String,String> privateMetadata = new HashMap<String,String>(); String sqlTable = metadata.get(DATATABLE); String sqlColumn = metadata.get(NAME); for (int i = 0; i < 2; i++) { if (i == 1) sqlTable = sqlTable.toLowerCase(); privateMetadata.put(PrivateMetadata.SQLTABLE, sqlTable); privateMetadata.put(PrivateMetadata.SQLCOLUMN, sqlColumn); ids = dataConfig.searchPrivateMetadata(privateMetadata, null); if (ids.size() > 0) break; } } else if (metadata.containsKey(NAME) && Strings.equal(metadata.get(PublicMetadata.DATATYPE), DataType.GEOMETRY)) { metadata.put(PublicMetadata.TITLE, metadata.remove(NAME)); ids = dataConfig.searchPublicMetadata(metadata, null); } if (ids.size() == 0) throw new RemoteException("No column matches metadata query: " + metadata); } // warning if more than one column if (ids.size() > 1) { String message = String.format( "WARNING: Multiple columns (%s) match metadata query: %s", ids.size(), metadata ); System.err.println(message); //throw new RemoteException(message); } // return first column int id = ListUtils.getFirstSortedItem(ids, DataConfig.NULL); double min = Double.NaN, max = Double.NaN; try { min = (Double)cast(minStr, double.class); } catch (Throwable t) { } try { max = (Double)cast(maxStr, double.class); } catch (Throwable t) { } String[] sqlParams = CSVParser.defaultParser.parseCSVRow(paramsStr, true); return getColumn(id, min, max, sqlParams); } }
package oceania.gen; import java.util.ArrayList; import java.util.List; import java.util.Random; import oceania.blocks.Blocks; import oceania.blocks.tile.TileEntityAtlantiumDepulsor; import cpw.mods.fml.common.IWorldGenerator; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.IChunkProvider; public class WorldGenUnderwaterVillage implements IWorldGenerator { private boolean locationIsValidSpawn(World world, int x, int y, int z) { List<Integer> validDirt = new ArrayList<Integer>(); List<Integer> validWater = new ArrayList<Integer>(); validWater.add(world.getBlockId(x + 8, y + 7, z + 8)); validWater.add(world.getBlockId(x, y + 7, z)); validWater.add(world.getBlockId(x + 16, y + 7, z + 8)); validWater.add(world.getBlockId(x + 8, y + 7, z + 16)); validWater.add(world.getBlockId(x + 16, y + 7, z + 16)); validDirt.add(world.getBlockId(x + 8, y + 1, z + 8)); validDirt.add(world.getBlockId(x, y + 1, z)); validDirt.add(world.getBlockId(x + 16, y + 1, z + 8)); validDirt.add(world.getBlockId(x + 8, y + 1, z + 16)); validDirt.add(world.getBlockId(x + 16, y + 1, z + 16)); if (world.rand.nextInt(50) != 1) return false; for (int validID : validWater) { if (!(validID == Block.waterStill.blockID || validID == Block.waterMoving.blockID)) return false; } for (int validID : validDirt) { if (!(validID == Block.dirt.blockID || validID == Block.blockClay.blockID || validID == Block.sand.blockID)) return false; } return true; } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { int x = (chunkX * 16) + random.nextInt(16); int y = 0; int z = (chunkZ * 16) + random.nextInt(16); for (int count = 40; count <= 60; count++) { int blockID = world.getBlockId(x, count + 1, z); int blockAboveID = world.getBlockId(x, count + 2, z); if ((blockID == Block.sand.blockID || blockID == Block.dirt.blockID) && (blockAboveID == Block.waterStill.blockID || blockAboveID == Block.waterMoving.blockID)) { y = count - 1; break; } } if (world.getBiomeGenForCoords(x, z) != BiomeGenBase.ocean || !locationIsValidSpawn(world, x, y, z) || y == 0) { return; } world.setBlock(x + 0, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 0, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 0, y + 1, z + 6, Block.stoneBrick.blockID); world.setBlock(x + 0, y + 1, z + 7, Block.stoneBrick.blockID); world.setBlock(x + 0, y + 1, z + 8, Block.stoneBrick.blockID); world.setBlock(x + 0, y + 1, z + 9, Block.stoneBrick.blockID); world.setBlock(x + 0, y + 1, z + 10, Block.stoneBrick.blockID); world.setBlock(x + 0, y + 2, z + 6, 155, 2, 3); world.setBlock(x + 0, y + 2, z + 10, 155, 2, 3); world.setBlock(x + 0, y + 3, z + 6, 155, 2, 3); world.setBlock(x + 0, y + 3, z + 10, 155, 2, 3); world.setBlock(x + 0, y + 4, z + 6, 155, 2, 3); world.setBlock(x + 0, y + 4, z + 10, 155, 2, 3); world.setBlock(x + 0, y + 5, z + 6, Block.stoneBrick.blockID); world.setBlock(x + 0, y + 5, z + 7, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 0, y + 5, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 0, y + 5, z + 9, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 0, y + 5, z + 10, Block.stoneBrick.blockID); world.setBlock(x + 1, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 1, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 1, y + 1, z + 4, Block.stoneBrick.blockID); world.setBlock(x + 1, y + 1, z + 5, Block.stoneBrick.blockID); world.setBlock(x + 1, y + 1, z + 11, Block.stoneBrick.blockID); world.setBlock(x + 1, y + 1, z + 12, Block.stoneBrick.blockID); world.setBlock(x + 1, y + 2, z + 4, Block.glass.blockID); world.setBlock(x + 1, y + 2, z + 5, Block.glass.blockID); world.setBlock(x + 1, y + 2, z + 11, Block.glass.blockID); world.setBlock(x + 1, y + 2, z + 12, Block.glass.blockID); world.setBlock(x + 1, y + 3, z + 4, Block.glass.blockID); world.setBlock(x + 1, y + 3, z + 5, Block.glass.blockID); world.setBlock(x + 1, y + 3, z + 11, Block.glass.blockID); world.setBlock(x + 1, y + 3, z + 12, Block.glass.blockID); world.setBlock(x + 1, y + 4, z + 6, Block.glass.blockID); world.setBlock(x + 1, y + 4, z + 10, Block.glass.blockID); world.setBlock(x + 1, y + 5, z + 7, Block.glass.blockID); world.setBlock(x + 1, y + 5, z + 8, Block.glass.blockID); world.setBlock(x + 1, y + 5, z + 9, Block.glass.blockID); world.setBlock(x + 2, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 2, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 2, y + 1, z + 3, Block.stoneBrick.blockID); world.setBlock(x + 2, y + 1, z + 13, Block.stoneBrick.blockID); world.setBlock(x + 2, y + 2, z + 3, Block.glass.blockID); world.setBlock(x + 2, y + 2, z + 13, Block.glass.blockID); world.setBlock(x + 2, y + 3, z + 3, Block.glass.blockID); world.setBlock(x + 2, y + 3, z + 13, Block.glass.blockID); world.setBlock(x + 2, y + 4, z + 4, Block.glass.blockID); world.setBlock(x + 2, y + 4, z + 5, Block.glass.blockID); world.setBlock(x + 2, y + 4, z + 11, Block.glass.blockID); world.setBlock(x + 2, y + 4, z + 12, Block.glass.blockID); world.setBlock(x + 2, y + 5, z + 6, Block.glass.blockID); world.setBlock(x + 2, y + 5, z + 7, Block.glass.blockID); world.setBlock(x + 2, y + 5, z + 8, Block.glass.blockID); world.setBlock(x + 2, y + 5, z + 9, Block.glass.blockID); world.setBlock(x + 2, y + 5, z + 10, Block.glass.blockID); world.setBlock(x + 3, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 3, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 3, y + 1, z + 2, Block.stoneBrick.blockID); world.setBlock(x + 3, y + 1, z + 8, Blocks.blockDepulsor.blockID); TileEntityAtlantiumDepulsor tile = (TileEntityAtlantiumDepulsor) world.getBlockTileEntity(x + 3, y + 1, z + 8); tile.enderPearls = 32; world.setBlock(x + 3, y + 1, z + 14, Block.stoneBrick.blockID); world.setBlock(x + 3, y + 2, z + 2, Block.glass.blockID); world.setBlock(x + 3, y + 2, z + 14, Block.glass.blockID); world.setBlock(x + 3, y + 3, z + 2, Block.glass.blockID); world.setBlock(x + 3, y + 3, z + 14, Block.glass.blockID); world.setBlock(x + 3, y + 4, z + 3, Block.glass.blockID); world.setBlock(x + 3, y + 4, z + 13, Block.glass.blockID); world.setBlock(x + 3, y + 5, z + 4, Block.glass.blockID); world.setBlock(x + 3, y + 5, z + 5, Block.glass.blockID); world.setBlock(x + 3, y + 5, z + 11, Block.glass.blockID); world.setBlock(x + 3, y + 5, z + 12, Block.glass.blockID); world.setBlock(x + 3, y + 6, z + 6, Block.glass.blockID); world.setBlock(x + 3, y + 6, z + 7, Block.glass.blockID); world.setBlock(x + 3, y + 6, z + 8, Block.glass.blockID); world.setBlock(x + 3, y + 6, z + 9, Block.glass.blockID); world.setBlock(x + 3, y + 6, z + 10, Block.glass.blockID); world.setBlock(x + 4, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 4, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 4, y + 1, z + 1, Block.stoneBrick.blockID); world.setBlock(x + 4, y + 1, z + 7, Block.stoneBrick.blockID); world.setBlock(x + 4, y + 1, z + 8, Block.stoneBrick.blockID); world.setBlock(x + 4, y + 1, z + 9, Block.stoneBrick.blockID); world.setBlock(x + 4, y + 1, z + 15, Block.stoneBrick.blockID); world.setBlock(x + 4, y + 2, z + 1, Block.glass.blockID); world.setBlock(x + 4, y + 2, z + 15, Block.glass.blockID); world.setBlock(x + 4, y + 3, z + 1, Block.glass.blockID); world.setBlock(x + 4, y + 3, z + 15, Block.glass.blockID); world.setBlock(x + 4, y + 4, z + 2, Block.glass.blockID); world.setBlock(x + 4, y + 4, z + 14, Block.glass.blockID); world.setBlock(x + 4, y + 5, z + 3, Block.glass.blockID); world.setBlock(x + 4, y + 5, z + 13, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 5, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 6, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 7, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 8, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 9, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 10, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 11, Block.glass.blockID); world.setBlock(x + 4, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 5, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 5, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 5, y + 1, z + 1, Block.stoneBrick.blockID); world.setBlock(x + 5, y + 1, z + 6, Block.stoneBrick.blockID); world.setBlock(x + 5, y + 1, z + 7, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 5, y + 1, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 5, y + 1, z + 9, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 5, y + 1, z + 10, Block.stoneBrick.blockID); world.setBlock(x + 5, y + 1, z + 15, Block.stoneBrick.blockID); world.setBlock(x + 5, y + 2, z + 1, Block.glass.blockID); world.setBlock(x + 5, y + 2, z + 15, Block.glass.blockID); world.setBlock(x + 5, y + 3, z + 1, Block.glass.blockID); world.setBlock(x + 5, y + 3, z + 15, Block.glass.blockID); world.setBlock(x + 5, y + 4, z + 2, Block.glass.blockID); world.setBlock(x + 5, y + 4, z + 14, Block.glass.blockID); world.setBlock(x + 5, y + 5, z + 3, Block.glass.blockID); world.setBlock(x + 5, y + 5, z + 13, Block.glass.blockID); world.setBlock(x + 5, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 5, y + 6, z + 5, Block.glass.blockID); world.setBlock(x + 5, y + 6, z + 11, Block.glass.blockID); world.setBlock(x + 5, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 5, y + 7, z + 6, Block.glass.blockID); world.setBlock(x + 5, y + 7, z + 7, Block.glass.blockID); world.setBlock(x + 5, y + 7, z + 8, Block.glass.blockID); world.setBlock(x + 5, y + 7, z + 9, Block.glass.blockID); world.setBlock(x + 5, y + 7, z + 10, Block.glass.blockID); world.setBlock(x + 6, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 6, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 6, y + 1, z + 0, Block.stoneBrick.blockID); world.setBlock(x + 6, y + 1, z + 5, Block.stoneBrick.blockID); world.setBlock(x + 6, y + 1, z + 6, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 6, y + 1, z + 7, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 6, y + 1, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 6, y + 1, z + 9, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 6, y + 1, z + 10, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 6, y + 1, z + 11, Block.stoneBrick.blockID); world.setBlock(x + 6, y + 1, z + 16, Block.stoneBrick.blockID); world.setBlock(x + 6, y + 2, z + 0, Block.glass.blockID); world.setBlock(x + 6, y + 2, z + 16, Block.glass.blockID); world.setBlock(x + 6, y + 3, z + 0, Block.glass.blockID); world.setBlock(x + 6, y + 3, z + 16, Block.glass.blockID); world.setBlock(x + 6, y + 4, z + 1, Block.glass.blockID); world.setBlock(x + 6, y + 4, z + 15, Block.glass.blockID); world.setBlock(x + 6, y + 5, z + 2, Block.glass.blockID); world.setBlock(x + 6, y + 5, z + 14, Block.glass.blockID); world.setBlock(x + 6, y + 6, z + 3, Block.glass.blockID); world.setBlock(x + 6, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 6, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 6, y + 6, z + 13, Block.glass.blockID); world.setBlock(x + 6, y + 7, z + 5, Block.glass.blockID); world.setBlock(x + 6, y + 7, z + 6, Block.glass.blockID); world.setBlock(x + 6, y + 7, z + 7, Block.glass.blockID); world.setBlock(x + 6, y + 7, z + 8, Block.glass.blockID); world.setBlock(x + 6, y + 7, z + 9, Block.glass.blockID); world.setBlock(x + 6, y + 7, z + 10, Block.glass.blockID); world.setBlock(x + 6, y + 7, z + 11, Block.glass.blockID); world.setBlock(x + 7, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 7, Block.stoneBrick.blockID); world.setBlock(x + 7, y + 0, z + 8, Block.stoneBrick.blockID); world.setBlock(x + 7, y + 0, z + 9, Block.stoneBrick.blockID); world.setBlock(x + 7, y + 0, z + 10, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 7, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 7, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 7, y + 1, z + 0, Block.stoneBrick.blockID); world.setBlock(x + 7, y + 1, z + 4, Block.stoneBrick.blockID); world.setBlock(x + 7, y + 1, z + 5, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 7, y + 1, z + 6, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 7, y + 1, z + 10, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 7, y + 1, z + 11, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 7, y + 1, z + 12, Block.stoneBrick.blockID); world.setBlock(x + 7, y + 1, z + 16, Block.stoneBrick.blockID); world.setBlock(x + 7, y + 2, z + 0, Block.glass.blockID); world.setBlock(x + 7, y + 2, z + 16, Block.glass.blockID); world.setBlock(x + 7, y + 3, z + 0, Block.glass.blockID); world.setBlock(x + 7, y + 3, z + 16, Block.glass.blockID); world.setBlock(x + 7, y + 4, z + 1, Block.glass.blockID); world.setBlock(x + 7, y + 4, z + 15, Block.glass.blockID); world.setBlock(x + 7, y + 5, z + 2, Block.glass.blockID); world.setBlock(x + 7, y + 5, z + 14, Block.glass.blockID); world.setBlock(x + 7, y + 6, z + 3, Block.glass.blockID); world.setBlock(x + 7, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 7, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 7, y + 6, z + 13, Block.glass.blockID); world.setBlock(x + 7, y + 7, z + 5, Block.glass.blockID); world.setBlock(x + 7, y + 7, z + 6, Block.glass.blockID); world.setBlock(x + 7, y + 7, z + 7, Block.glass.blockID); world.setBlock(x + 7, y + 7, z + 8, Block.glass.blockID); world.setBlock(x + 7, y + 7, z + 9, Block.glass.blockID); world.setBlock(x + 7, y + 7, z + 10, Block.glass.blockID); world.setBlock(x + 7, y + 7, z + 11, Block.glass.blockID); world.setBlock(x + 8, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 7, Block.stoneBrick.blockID); world.setBlock(x + 8, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 9, Block.stoneBrick.blockID); world.setBlock(x + 8, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 8, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 8, y + 1, z + 0, Block.stoneBrick.blockID); world.setBlock(x + 8, y + 1, z + 4, Block.stoneBrick.blockID); world.setBlock(x + 8, y + 1, z + 5, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 8, y + 1, z + 6, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 8, y + 1, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 8, y + 1, z + 10, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 8, y + 1, z + 11, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 8, y + 1, z + 12, Block.stoneBrick.blockID); world.setBlock(x + 8, y + 1, z + 16, Block.stoneBrick.blockID); world.setBlock(x + 8, y + 2, z + 0, Block.glass.blockID); world.setBlock(x + 8, y + 2, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 8, y + 2, z + 16, Block.glass.blockID); world.setBlock(x + 8, y + 3, z + 0, Block.glass.blockID); world.setBlock(x + 8, y + 3, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 8, y + 3, z + 16, Block.glass.blockID); world.setBlock(x + 8, y + 4, z + 1, Block.glass.blockID); world.setBlock(x + 8, y + 4, z + 8, Blocks.blockChestSpawner.blockID); world.setBlockMetadataWithNotify(x + 8, y + 4, z + 8, 4, 3); world.setBlock(x + 8, y + 4, z + 15, Block.glass.blockID); world.setBlock(x + 8, y + 5, z + 2, Block.glass.blockID); world.setBlock(x + 8, y + 5, z + 14, Block.glass.blockID); world.setBlock(x + 8, y + 6, z + 3, Block.glass.blockID); world.setBlock(x + 8, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 8, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 8, y + 6, z + 13, Block.glass.blockID); world.setBlock(x + 8, y + 7, z + 5, Block.glass.blockID); world.setBlock(x + 8, y + 7, z + 6, Block.glass.blockID); world.setBlock(x + 8, y + 7, z + 7, Block.glass.blockID); world.setBlock(x + 8, y + 7, z + 8, Block.glass.blockID); world.setBlock(x + 8, y + 7, z + 9, Block.glass.blockID); world.setBlock(x + 8, y + 7, z + 10, Block.glass.blockID); world.setBlock(x + 8, y + 7, z + 11, Block.glass.blockID); world.setBlock(x + 9, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 7, Block.stoneBrick.blockID); world.setBlock(x + 9, y + 0, z + 8, Block.stoneBrick.blockID); world.setBlock(x + 9, y + 0, z + 9, Block.stoneBrick.blockID); world.setBlock(x + 9, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 9, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 9, y + 1, z + 0, Block.stoneBrick.blockID); world.setBlock(x + 9, y + 1, z + 4, Block.stoneBrick.blockID); world.setBlock(x + 9, y + 1, z + 5, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 9, y + 1, z + 6, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 9, y + 1, z + 10, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 9, y + 1, z + 11, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 9, y + 1, z + 12, Block.stoneBrick.blockID); world.setBlock(x + 9, y + 1, z + 16, Block.stoneBrick.blockID); world.setBlock(x + 9, y + 2, z + 0, Block.glass.blockID); world.setBlock(x + 9, y + 2, z + 16, Block.glass.blockID); world.setBlock(x + 9, y + 3, z + 0, Block.glass.blockID); world.setBlock(x + 9, y + 3, z + 16, Block.glass.blockID); world.setBlock(x + 9, y + 4, z + 1, Block.glass.blockID); world.setBlock(x + 9, y + 4, z + 15, Block.glass.blockID); world.setBlock(x + 9, y + 5, z + 2, Block.glass.blockID); world.setBlock(x + 9, y + 5, z + 14, Block.glass.blockID); world.setBlock(x + 9, y + 6, z + 3, Block.glass.blockID); world.setBlock(x + 9, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 9, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 9, y + 6, z + 13, Block.glass.blockID); world.setBlock(x + 9, y + 7, z + 5, Block.glass.blockID); world.setBlock(x + 9, y + 7, z + 6, Block.glass.blockID); world.setBlock(x + 9, y + 7, z + 7, Block.glass.blockID); world.setBlock(x + 9, y + 7, z + 8, Block.glass.blockID); world.setBlock(x + 9, y + 7, z + 9, Block.glass.blockID); world.setBlock(x + 9, y + 7, z + 10, Block.glass.blockID); world.setBlock(x + 9, y + 7, z + 11, Block.glass.blockID); world.setBlock(x + 10, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 10, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 10, y + 1, z + 0, Block.stoneBrick.blockID); world.setBlock(x + 10, y + 1, z + 5, Block.stoneBrick.blockID); world.setBlock(x + 10, y + 1, z + 6, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 10, y + 1, z + 7, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 10, y + 1, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 10, y + 1, z + 9, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 10, y + 1, z + 10, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 10, y + 1, z + 11, Block.stoneBrick.blockID); world.setBlock(x + 10, y + 1, z + 16, Block.stoneBrick.blockID); world.setBlock(x + 10, y + 2, z + 0, Block.glass.blockID); world.setBlock(x + 10, y + 2, z + 16, Block.glass.blockID); world.setBlock(x + 10, y + 3, z + 0, Block.glass.blockID); world.setBlock(x + 10, y + 3, z + 16, Block.glass.blockID); world.setBlock(x + 10, y + 4, z + 1, Block.glass.blockID); world.setBlock(x + 10, y + 4, z + 15, Block.glass.blockID); world.setBlock(x + 10, y + 5, z + 2, Block.glass.blockID); world.setBlock(x + 10, y + 5, z + 14, Block.glass.blockID); world.setBlock(x + 10, y + 6, z + 3, Block.glass.blockID); world.setBlock(x + 10, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 10, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 10, y + 6, z + 13, Block.glass.blockID); world.setBlock(x + 10, y + 7, z + 5, Block.glass.blockID); world.setBlock(x + 10, y + 7, z + 6, Block.glass.blockID); world.setBlock(x + 10, y + 7, z + 7, Block.glass.blockID); world.setBlock(x + 10, y + 7, z + 8, Block.glass.blockID); world.setBlock(x + 10, y + 7, z + 9, Block.glass.blockID); world.setBlock(x + 10, y + 7, z + 10, Block.glass.blockID); world.setBlock(x + 10, y + 7, z + 11, Block.glass.blockID); world.setBlock(x + 11, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 11, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 11, y + 1, z + 1, Block.stoneBrick.blockID); world.setBlock(x + 11, y + 1, z + 6, Block.stoneBrick.blockID); world.setBlock(x + 11, y + 1, z + 7, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 11, y + 1, z + 8, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 11, y + 1, z + 9, Blocks.blockLimestone.blockID, 1, 3); world.setBlock(x + 11, y + 1, z + 10, Block.stoneBrick.blockID); world.setBlock(x + 11, y + 1, z + 15, Block.stoneBrick.blockID); world.setBlock(x + 11, y + 2, z + 1, Block.glass.blockID); world.setBlock(x + 11, y + 2, z + 15, Block.glass.blockID); world.setBlock(x + 11, y + 3, z + 1, Block.glass.blockID); world.setBlock(x + 11, y + 3, z + 15, Block.glass.blockID); world.setBlock(x + 11, y + 4, z + 2, Block.glass.blockID); world.setBlock(x + 11, y + 4, z + 14, Block.glass.blockID); world.setBlock(x + 11, y + 5, z + 3, Block.glass.blockID); world.setBlock(x + 11, y + 5, z + 13, Block.glass.blockID); world.setBlock(x + 11, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 11, y + 6, z + 5, Block.glass.blockID); world.setBlock(x + 11, y + 6, z + 11, Block.glass.blockID); world.setBlock(x + 11, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 11, y + 7, z + 6, Block.glass.blockID); world.setBlock(x + 11, y + 7, z + 7, Block.glass.blockID); world.setBlock(x + 11, y + 7, z + 8, Block.glass.blockID); world.setBlock(x + 11, y + 7, z + 9, Block.glass.blockID); world.setBlock(x + 11, y + 7, z + 10, Block.glass.blockID); world.setBlock(x + 12, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 12, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 12, y + 1, z + 1, Block.stoneBrick.blockID); world.setBlock(x + 12, y + 1, z + 7, Block.stoneBrick.blockID); world.setBlock(x + 12, y + 1, z + 8, Block.stoneBrick.blockID); world.setBlock(x + 12, y + 1, z + 9, Block.stoneBrick.blockID); world.setBlock(x + 12, y + 1, z + 15, Block.stoneBrick.blockID); world.setBlock(x + 12, y + 2, z + 1, Block.glass.blockID); world.setBlock(x + 12, y + 2, z + 15, Block.glass.blockID); world.setBlock(x + 12, y + 3, z + 1, Block.glass.blockID); world.setBlock(x + 12, y + 3, z + 15, Block.glass.blockID); world.setBlock(x + 12, y + 4, z + 2, Block.glass.blockID); world.setBlock(x + 12, y + 4, z + 14, Block.glass.blockID); world.setBlock(x + 12, y + 5, z + 3, Block.glass.blockID); world.setBlock(x + 12, y + 5, z + 13, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 4, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 5, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 6, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 7, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 8, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 9, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 10, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 11, Block.glass.blockID); world.setBlock(x + 12, y + 6, z + 12, Block.glass.blockID); world.setBlock(x + 13, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 13, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 13, y + 1, z + 2, Block.stoneBrick.blockID); world.setBlock(x + 13, y + 1, z + 14, Block.stoneBrick.blockID); world.setBlock(x + 13, y + 2, z + 2, Block.glass.blockID); world.setBlock(x + 13, y + 2, z + 14, Block.glass.blockID); world.setBlock(x + 13, y + 3, z + 2, Block.glass.blockID); world.setBlock(x + 13, y + 3, z + 14, Block.glass.blockID); world.setBlock(x + 13, y + 4, z + 3, Block.glass.blockID); world.setBlock(x + 13, y + 4, z + 13, Block.glass.blockID); world.setBlock(x + 13, y + 5, z + 4, Block.glass.blockID); world.setBlock(x + 13, y + 5, z + 5, Block.glass.blockID); world.setBlock(x + 13, y + 5, z + 11, Block.glass.blockID); world.setBlock(x + 13, y + 5, z + 12, Block.glass.blockID); world.setBlock(x + 13, y + 6, z + 6, Block.glass.blockID); world.setBlock(x + 13, y + 6, z + 7, Block.glass.blockID); world.setBlock(x + 13, y + 6, z + 8, Block.glass.blockID); world.setBlock(x + 13, y + 6, z + 9, Block.glass.blockID); world.setBlock(x + 13, y + 6, z + 10, Block.glass.blockID); world.setBlock(x + 14, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 14, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 14, y + 1, z + 3, Block.stoneBrick.blockID); world.setBlock(x + 14, y + 1, z + 13, Block.stoneBrick.blockID); world.setBlock(x + 14, y + 2, z + 3, Block.glass.blockID); world.setBlock(x + 14, y + 2, z + 13, Block.glass.blockID); world.setBlock(x + 14, y + 3, z + 3, Block.glass.blockID); world.setBlock(x + 14, y + 3, z + 13, Block.glass.blockID); world.setBlock(x + 14, y + 4, z + 4, Block.glass.blockID); world.setBlock(x + 14, y + 4, z + 5, Block.glass.blockID); world.setBlock(x + 14, y + 4, z + 11, Block.glass.blockID); world.setBlock(x + 14, y + 4, z + 12, Block.glass.blockID); world.setBlock(x + 14, y + 5, z + 6, Block.glass.blockID); world.setBlock(x + 14, y + 5, z + 7, Block.glass.blockID); world.setBlock(x + 14, y + 5, z + 8, Block.glass.blockID); world.setBlock(x + 14, y + 5, z + 9, Block.glass.blockID); world.setBlock(x + 14, y + 5, z + 10, Block.glass.blockID); world.setBlock(x + 15, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 15, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 15, y + 1, z + 4, Block.stoneBrick.blockID); world.setBlock(x + 15, y + 1, z + 5, Block.stoneBrick.blockID); world.setBlock(x + 15, y + 1, z + 11, Block.stoneBrick.blockID); world.setBlock(x + 15, y + 1, z + 12, Block.stoneBrick.blockID); world.setBlock(x + 15, y + 2, z + 4, Block.glass.blockID); world.setBlock(x + 15, y + 2, z + 5, Block.glass.blockID); world.setBlock(x + 15, y + 2, z + 11, Block.glass.blockID); world.setBlock(x + 15, y + 2, z + 12, Block.glass.blockID); world.setBlock(x + 15, y + 3, z + 4, Block.glass.blockID); world.setBlock(x + 15, y + 3, z + 5, Block.glass.blockID); world.setBlock(x + 15, y + 3, z + 11, Block.glass.blockID); world.setBlock(x + 15, y + 3, z + 12, Block.glass.blockID); world.setBlock(x + 15, y + 4, z + 6, Block.glass.blockID); world.setBlock(x + 15, y + 4, z + 7, Block.glass.blockID); world.setBlock(x + 15, y + 4, z + 8, Block.glass.blockID); world.setBlock(x + 15, y + 4, z + 9, Block.glass.blockID); world.setBlock(x + 15, y + 4, z + 10, Block.glass.blockID); world.setBlock(x + 16, y + 0, z + 0, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 1, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 2, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 3, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 4, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 5, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 6, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 7, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 8, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 9, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 10, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 11, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 12, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 13, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 14, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 15, Block.dirt.blockID); world.setBlock(x + 16, y + 0, z + 16, Block.dirt.blockID); world.setBlock(x + 16, y + 1, z + 6, Block.stoneBrick.blockID); world.setBlock(x + 16, y + 1, z + 7, Block.stoneBrick.blockID); world.setBlock(x + 16, y + 1, z + 8, Block.stoneBrick.blockID); world.setBlock(x + 16, y + 1, z + 9, Block.stoneBrick.blockID); world.setBlock(x + 16, y + 1, z + 10, Block.stoneBrick.blockID); world.setBlock(x + 16, y + 2, z + 6, Block.glass.blockID); world.setBlock(x + 16, y + 2, z + 7, Block.glass.blockID); world.setBlock(x + 16, y + 2, z + 8, Block.glass.blockID); world.setBlock(x + 16, y + 2, z + 9, Block.glass.blockID); world.setBlock(x + 16, y + 2, z + 10, Block.glass.blockID); world.setBlock(x + 16, y + 3, z + 6, Block.glass.blockID); world.setBlock(x + 16, y + 3, z + 7, Block.glass.blockID); world.setBlock(x + 16, y + 3, z + 8, Block.glass.blockID); world.setBlock(x + 16, y + 3, z + 9, Block.glass.blockID); world.setBlock(x + 16, y + 3, z + 10, Block.glass.blockID); world.setBlock(x + 0, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 0, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 7, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 8, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 8, Block.glowStone.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 1, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 7, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 8, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 9, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 2, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 7, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 9, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 3, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 4, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 5, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 6, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 7, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 7, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 7, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 7, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 7, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 7, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 8, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 8, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 8, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 7, y + 2, z + 8, Blocks.blockLimestone.blockID, 0, 3); world.setBlock(x + 8, y + 2, z + 7, Blocks.blockLimestone.blockID, 0, 3); world.setBlock(x + 8, y + 2, z + 9, Blocks.blockLimestone.blockID, 0, 3); world.setBlock(x + 9, y + 2, z + 8, Blocks.blockLimestone.blockID, 0, 3); world.setBlock(x + 9, y + 2, z + 7, Block.glowStone.blockID); world.setBlock(x + 7, y + 2, z + 7, Block.glowStone.blockID); world.setBlock(x + 7, y + 2, z + 9, Block.glowStone.blockID); world.setBlock(x + 9, y + 2, z + 9, Block.glowStone.blockID); world.setBlock(x + 8, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 8, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 8, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 9, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 9, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 9, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 9, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 9, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 9, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 10, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 11, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 12, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 7, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 8, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 9, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 13, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 7, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 8, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 9, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 14, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 6, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 7, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 8, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 9, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 10, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 15, y + 1, z + 16, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 0, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 1, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 2, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 3, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 4, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 5, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 11, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 12, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 13, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 14, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 15, Block.sand.blockID, 0, 3); world.setBlock(x + 16, y + 1, z + 16, Block.sand.blockID, 0, 3); y++; // Air //world.setBlock(x + 0, y + 1, z + 7, 0); //world.setBlock(x + 0, y + 1, z + 8, 0); //world.setBlock(x + 0, y + 1, z + 9, 0); world.setBlock(x + 0, y + 1, z + 17, 0); //world.setBlock(x + 0, y + 2, z + 7, 0); //world.setBlock(x + 0, y + 2, z + 8, 0); //world.setBlock(x + 0, y + 2, z + 9, 0); world.setBlock(x + 0, y + 2, z + 17, 0); world.setBlock(x + 0, y + 3, z + 17, 0); world.setBlock(x + 0, y + 4, z + 17, 0); world.setBlock(x + 0, y + 5, z + 17, 0); world.setBlock(x + 0, y + 6, z + 17, 0); world.setBlock(x + 1, y + 1, z + 6, 0); world.setBlock(x + 1, y + 1, z + 7, 0); world.setBlock(x + 1, y + 1, z + 8, 0); world.setBlock(x + 1, y + 1, z + 9, 0); world.setBlock(x + 1, y + 1, z + 10, 0); world.setBlock(x + 1, y + 1, z + 17, 0); world.setBlock(x + 1, y + 2, z + 6, 0); world.setBlock(x + 1, y + 2, z + 7, 0); world.setBlock(x + 1, y + 2, z + 8, 0); world.setBlock(x + 1, y + 2, z + 9, 0); world.setBlock(x + 1, y + 2, z + 10, 0); ; world.setBlock(x + 1, y + 2, z + 17, 0); world.setBlock(x + 1, y + 3, z + 7, 0); world.setBlock(x + 1, y + 3, z + 8, 0); world.setBlock(x + 1, y + 3, z + 9, 0); world.setBlock(x + 1, y + 3, z + 17, 0); world.setBlock(x + 1, y + 4, z + 17, 0); world.setBlock(x + 1, y + 5, z + 17, 0); world.setBlock(x + 1, y + 6, z + 17, 0); world.setBlock(x + 2, y + 1, z + 4, 0); world.setBlock(x + 2, y + 1, z + 5, 0); world.setBlock(x + 2, y + 1, z + 6, 0); world.setBlock(x + 2, y + 1, z + 7, 0); world.setBlock(x + 2, y + 1, z + 8, 0); world.setBlock(x + 2, y + 1, z + 9, 0); world.setBlock(x + 2, y + 1, z + 10, 0); world.setBlock(x + 2, y + 1, z + 11, 0); world.setBlock(x + 2, y + 1, z + 12, 0); world.setBlock(x + 2, y + 1, z + 17, 0); world.setBlock(x + 2, y + 2, z + 4, 0); world.setBlock(x + 2, y + 2, z + 5, 0); world.setBlock(x + 2, y + 2, z + 6, 0); world.setBlock(x + 2, y + 2, z + 7, 0); world.setBlock(x + 2, y + 2, z + 8, 0); world.setBlock(x + 2, y + 2, z + 9, 0); world.setBlock(x + 2, y + 2, z + 10, 0); world.setBlock(x + 2, y + 2, z + 11, 0); world.setBlock(x + 2, y + 2, z + 12, 0); world.setBlock(x + 2, y + 2, z + 17, 0); world.setBlock(x + 2, y + 3, z + 6, 0); world.setBlock(x + 2, y + 3, z + 7, 0); world.setBlock(x + 2, y + 3, z + 8, 0); world.setBlock(x + 2, y + 3, z + 9, 0); world.setBlock(x + 2, y + 3, z + 10, 0); world.setBlock(x + 2, y + 3, z + 17, 0); world.setBlock(x + 2, y + 4, z + 17, 0); world.setBlock(x + 2, y + 5, z + 17, 0); world.setBlock(x + 2, y + 6, z + 17, 0); world.setBlock(x + 3, y + 1, z + 3, 0); world.setBlock(x + 3, y + 1, z + 4, 0); world.setBlock(x + 3, y + 1, z + 5, 0); world.setBlock(x + 3, y + 1, z + 6, 0); world.setBlock(x + 3, y + 1, z + 7, 0); world.setBlock(x + 3, y + 1, z + 8, 0); world.setBlock(x + 3, y + 1, z + 9, 0); world.setBlock(x + 3, y + 1, z + 10, 0); world.setBlock(x + 3, y + 1, z + 11, 0); world.setBlock(x + 3, y + 1, z + 12, 0); world.setBlock(x + 3, y + 1, z + 13, 0); world.setBlock(x + 3, y + 1, z + 17, 0); world.setBlock(x + 3, y + 2, z + 3, 0); world.setBlock(x + 3, y + 2, z + 4, 0); world.setBlock(x + 3, y + 2, z + 5, 0); world.setBlock(x + 3, y + 2, z + 6, 0); world.setBlock(x + 3, y + 2, z + 7, 0); world.setBlock(x + 3, y + 2, z + 8, 0); world.setBlock(x + 3, y + 2, z + 9, 0); world.setBlock(x + 3, y + 2, z + 10, 0); world.setBlock(x + 3, y + 2, z + 11, 0); world.setBlock(x + 3, y + 2, z + 12, 0); world.setBlock(x + 3, y + 2, z + 13, 0); world.setBlock(x + 3, y + 2, z + 17, 0); world.setBlock(x + 3, y + 3, z + 4, 0); world.setBlock(x + 3, y + 3, z + 5, 0); world.setBlock(x + 3, y + 3, z + 6, 0); world.setBlock(x + 3, y + 3, z + 7, 0); world.setBlock(x + 3, y + 3, z + 8, 0); world.setBlock(x + 3, y + 3, z + 9, 0); world.setBlock(x + 3, y + 3, z + 10, 0); world.setBlock(x + 3, y + 3, z + 11, 0); world.setBlock(x + 3, y + 3, z + 12, 0); world.setBlock(x + 3, y + 3, z + 17, 0); world.setBlock(x + 3, y + 4, z + 6, 0); world.setBlock(x + 3, y + 4, z + 7, 0); world.setBlock(x + 3, y + 4, z + 8, 0); world.setBlock(x + 3, y + 4, z + 9, 0); world.setBlock(x + 3, y + 4, z + 10, 0); world.setBlock(x + 3, y + 4, z + 17, 0); world.setBlock(x + 3, y + 5, z + 17, 0); world.setBlock(x + 3, y + 6, z + 17, 0); world.setBlock(x + 4, y + 1, z + 2, 0); world.setBlock(x + 4, y + 1, z + 3, 0); world.setBlock(x + 4, y + 1, z + 4, 0); world.setBlock(x + 4, y + 1, z + 5, 0); world.setBlock(x + 4, y + 1, z + 6, 0); world.setBlock(x + 4, y + 1, z + 7, 0); world.setBlock(x + 4, y + 1, z + 8, 0); world.setBlock(x + 4, y + 1, z + 9, 0); world.setBlock(x + 4, y + 1, z + 10, 0); world.setBlock(x + 4, y + 1, z + 11, 0); world.setBlock(x + 4, y + 1, z + 12, 0); world.setBlock(x + 4, y + 1, z + 13, 0); world.setBlock(x + 4, y + 1, z + 14, 0); world.setBlock(x + 4, y + 1, z + 17, 0); world.setBlock(x + 4, y + 2, z + 2, 0); world.setBlock(x + 4, y + 2, z + 3, 0); world.setBlock(x + 4, y + 2, z + 4, 0); world.setBlock(x + 4, y + 2, z + 5, 0); world.setBlock(x + 4, y + 2, z + 6, 0); world.setBlock(x + 4, y + 2, z + 7, 0); world.setBlock(x + 4, y + 2, z + 8, 0); world.setBlock(x + 4, y + 2, z + 9, 0); world.setBlock(x + 4, y + 2, z + 10, 0); world.setBlock(x + 4, y + 2, z + 11, 0); world.setBlock(x + 4, y + 2, z + 12, 0); world.setBlock(x + 4, y + 2, z + 13, 0); world.setBlock(x + 4, y + 2, z + 14, 0); world.setBlock(x + 4, y + 2, z + 17, 0); world.setBlock(x + 4, y + 3, z + 3, 0); world.setBlock(x + 4, y + 3, z + 4, 0); world.setBlock(x + 4, y + 3, z + 5, 0); world.setBlock(x + 4, y + 3, z + 6, 0); world.setBlock(x + 4, y + 3, z + 7, 0); world.setBlock(x + 4, y + 3, z + 8, 0); world.setBlock(x + 4, y + 3, z + 9, 0); world.setBlock(x + 4, y + 3, z + 10, 0); world.setBlock(x + 4, y + 3, z + 11, 0); world.setBlock(x + 4, y + 3, z + 12, 0); world.setBlock(x + 4, y + 3, z + 13, 0); world.setBlock(x + 4, y + 3, z + 17, 0); world.setBlock(x + 4, y + 4, z + 4, 0); world.setBlock(x + 4, y + 4, z + 5, 0); world.setBlock(x + 4, y + 4, z + 6, 0); world.setBlock(x + 4, y + 4, z + 7, 0); world.setBlock(x + 4, y + 4, z + 8, 0); world.setBlock(x + 4, y + 4, z + 9, 0); world.setBlock(x + 4, y + 4, z + 10, 0); world.setBlock(x + 4, y + 4, z + 11, 0); world.setBlock(x + 4, y + 4, z + 12, 0); world.setBlock(x + 4, y + 4, z + 17, 0); world.setBlock(x + 4, y + 5, z + 17, 0); world.setBlock(x + 4, y + 6, z + 17, 0); world.setBlock(x + 5, y + 1, z + 2, 0); world.setBlock(x + 5, y + 1, z + 3, 0); world.setBlock(x + 5, y + 1, z + 4, 0); world.setBlock(x + 5, y + 1, z + 5, 0); world.setBlock(x + 5, y + 1, z + 6, 0); world.setBlock(x + 5, y + 1, z + 7, 0); world.setBlock(x + 5, y + 1, z + 8, 0); world.setBlock(x + 5, y + 1, z + 9, 0); world.setBlock(x + 5, y + 1, z + 10, 0); world.setBlock(x + 5, y + 1, z + 11, 0); world.setBlock(x + 5, y + 1, z + 12, 0); world.setBlock(x + 5, y + 1, z + 13, 0); world.setBlock(x + 5, y + 1, z + 14, 0); world.setBlock(x + 5, y + 1, z + 17, 0); world.setBlock(x + 5, y + 2, z + 2, 0); world.setBlock(x + 5, y + 2, z + 3, 0); world.setBlock(x + 5, y + 2, z + 4, 0); world.setBlock(x + 5, y + 2, z + 5, 0); world.setBlock(x + 5, y + 2, z + 6, 0); world.setBlock(x + 5, y + 2, z + 7, 0); world.setBlock(x + 5, y + 2, z + 8, 0); world.setBlock(x + 5, y + 2, z + 9, 0); world.setBlock(x + 5, y + 2, z + 10, 0); world.setBlock(x + 5, y + 2, z + 11, 0); world.setBlock(x + 5, y + 2, z + 12, 0); world.setBlock(x + 5, y + 2, z + 13, 0); world.setBlock(x + 5, y + 2, z + 14, 0); world.setBlock(x + 5, y + 2, z + 17, 0); world.setBlock(x + 5, y + 3, z + 3, 0); world.setBlock(x + 5, y + 3, z + 4, 0); world.setBlock(x + 5, y + 3, z + 5, 0); world.setBlock(x + 5, y + 3, z + 6, 0); world.setBlock(x + 5, y + 3, z + 7, 0); world.setBlock(x + 5, y + 3, z + 8, 0); world.setBlock(x + 5, y + 3, z + 9, 0); world.setBlock(x + 5, y + 3, z + 10, 0); world.setBlock(x + 5, y + 3, z + 11, 0); world.setBlock(x + 5, y + 3, z + 12, 0); world.setBlock(x + 5, y + 3, z + 13, 0); world.setBlock(x + 5, y + 3, z + 17, 0); world.setBlock(x + 5, y + 4, z + 4, 0); world.setBlock(x + 5, y + 4, z + 5, 0); world.setBlock(x + 5, y + 4, z + 6, 0); world.setBlock(x + 5, y + 4, z + 7, 0); world.setBlock(x + 5, y + 4, z + 8, 0); world.setBlock(x + 5, y + 4, z + 9, 0); world.setBlock(x + 5, y + 4, z + 10, 0); world.setBlock(x + 5, y + 4, z + 11, 0); world.setBlock(x + 5, y + 4, z + 12, 0); world.setBlock(x + 5, y + 4, z + 17, 0); world.setBlock(x + 5, y + 5, z + 6, 0); world.setBlock(x + 5, y + 5, z + 7, 0); world.setBlock(x + 5, y + 5, z + 8, 0); world.setBlock(x + 5, y + 5, z + 9, 0); world.setBlock(x + 5, y + 5, z + 10, 0); world.setBlock(x + 5, y + 5, z + 17, 0); world.setBlock(x + 5, y + 6, z + 17, 0); world.setBlock(x + 6, y + 1, z + 1, 0); world.setBlock(x + 6, y + 1, z + 2, 0); world.setBlock(x + 6, y + 1, z + 3, 0); world.setBlock(x + 6, y + 1, z + 4, 0); world.setBlock(x + 6, y + 1, z + 5, 0); world.setBlock(x + 6, y + 1, z + 6, 0); world.setBlock(x + 6, y + 1, z + 7, 0); world.setBlock(x + 6, y + 1, z + 8, 0); world.setBlock(x + 6, y + 1, z + 9, 0); world.setBlock(x + 6, y + 1, z + 10, 0); world.setBlock(x + 6, y + 1, z + 11, 0); world.setBlock(x + 6, y + 1, z + 12, 0); world.setBlock(x + 6, y + 1, z + 13, 0); world.setBlock(x + 6, y + 1, z + 14, 0); world.setBlock(x + 6, y + 1, z + 15, 0); world.setBlock(x + 6, y + 1, z + 17, 0); world.setBlock(x + 6, y + 2, z + 1, 0); world.setBlock(x + 6, y + 2, z + 2, 0); world.setBlock(x + 6, y + 2, z + 3, 0); world.setBlock(x + 6, y + 2, z + 4, 0); world.setBlock(x + 6, y + 2, z + 5, 0); world.setBlock(x + 6, y + 2, z + 6, 0); world.setBlock(x + 6, y + 2, z + 7, 0); world.setBlock(x + 6, y + 2, z + 8, 0); world.setBlock(x + 6, y + 2, z + 9, 0); world.setBlock(x + 6, y + 2, z + 10, 0); world.setBlock(x + 6, y + 2, z + 11, 0); world.setBlock(x + 6, y + 2, z + 12, 0); world.setBlock(x + 6, y + 2, z + 13, 0); world.setBlock(x + 6, y + 2, z + 14, 0); world.setBlock(x + 6, y + 2, z + 15, 0); world.setBlock(x + 6, y + 2, z + 17, 0); world.setBlock(x + 6, y + 3, z + 2, 0); world.setBlock(x + 6, y + 3, z + 3, 0); world.setBlock(x + 6, y + 3, z + 4, 0); world.setBlock(x + 6, y + 3, z + 5, 0); world.setBlock(x + 6, y + 3, z + 6, 0); world.setBlock(x + 6, y + 3, z + 7, 0); world.setBlock(x + 6, y + 3, z + 8, 0); world.setBlock(x + 6, y + 3, z + 9, 0); world.setBlock(x + 6, y + 3, z + 10, 0); world.setBlock(x + 6, y + 3, z + 11, 0); world.setBlock(x + 6, y + 3, z + 12, 0); world.setBlock(x + 6, y + 3, z + 13, 0); world.setBlock(x + 6, y + 3, z + 14, 0); world.setBlock(x + 6, y + 3, z + 17, 0); world.setBlock(x + 6, y + 4, z + 3, 0); world.setBlock(x + 6, y + 4, z + 4, 0); world.setBlock(x + 6, y + 4, z + 5, 0); world.setBlock(x + 6, y + 4, z + 6, 0); world.setBlock(x + 6, y + 4, z + 7, 0); world.setBlock(x + 6, y + 4, z + 8, 0); world.setBlock(x + 6, y + 4, z + 9, 0); world.setBlock(x + 6, y + 4, z + 10, 0); world.setBlock(x + 6, y + 4, z + 11, 0); world.setBlock(x + 6, y + 4, z + 12, 0); world.setBlock(x + 6, y + 4, z + 13, 0); world.setBlock(x + 6, y + 4, z + 17, 0); world.setBlock(x + 6, y + 5, z + 5, 0); world.setBlock(x + 6, y + 5, z + 6, 0); world.setBlock(x + 6, y + 5, z + 7, 0); world.setBlock(x + 6, y + 5, z + 8, 0); world.setBlock(x + 6, y + 5, z + 9, 0); world.setBlock(x + 6, y + 5, z + 10, 0); world.setBlock(x + 6, y + 5, z + 11, 0); world.setBlock(x + 6, y + 5, z + 17, 0); world.setBlock(x + 6, y + 6, z + 17, 0); world.setBlock(x + 7, y + 1, z + 1, 0); world.setBlock(x + 7, y + 1, z + 2, 0); world.setBlock(x + 7, y + 1, z + 3, 0); world.setBlock(x + 7, y + 1, z + 4, 0); world.setBlock(x + 7, y + 1, z + 5, 0); world.setBlock(x + 7, y + 1, z + 6, 0); world.setBlock(x + 7, y + 1, z + 10, 0); world.setBlock(x + 7, y + 1, z + 11, 0); world.setBlock(x + 7, y + 1, z + 12, 0); world.setBlock(x + 7, y + 1, z + 13, 0); world.setBlock(x + 7, y + 1, z + 14, 0); world.setBlock(x + 7, y + 1, z + 15, 0); world.setBlock(x + 7, y + 1, z + 17, 0); world.setBlock(x + 7, y + 2, z + 1, 0); world.setBlock(x + 7, y + 2, z + 2, 0); world.setBlock(x + 7, y + 2, z + 3, 0); world.setBlock(x + 7, y + 2, z + 4, 0); world.setBlock(x + 7, y + 2, z + 5, 0); world.setBlock(x + 7, y + 2, z + 6, 0); world.setBlock(x + 7, y + 2, z + 7, 0); world.setBlock(x + 7, y + 2, z + 8, 0); world.setBlock(x + 7, y + 2, z + 9, 0); world.setBlock(x + 7, y + 2, z + 10, 0); world.setBlock(x + 7, y + 2, z + 11, 0); world.setBlock(x + 7, y + 2, z + 12, 0); world.setBlock(x + 7, y + 2, z + 13, 0); world.setBlock(x + 7, y + 2, z + 14, 0); world.setBlock(x + 7, y + 2, z + 15, 0); world.setBlock(x + 7, y + 2, z + 17, 0); world.setBlock(x + 7, y + 3, z + 2, 0); world.setBlock(x + 7, y + 3, z + 3, 0); world.setBlock(x + 7, y + 3, z + 4, 0); world.setBlock(x + 7, y + 3, z + 5, 0); world.setBlock(x + 7, y + 3, z + 6, 0); world.setBlock(x + 7, y + 3, z + 7, 0); world.setBlock(x + 7, y + 3, z + 8, 0); world.setBlock(x + 7, y + 3, z + 9, 0); world.setBlock(x + 7, y + 3, z + 10, 0); world.setBlock(x + 7, y + 3, z + 11, 0); world.setBlock(x + 7, y + 3, z + 12, 0); world.setBlock(x + 7, y + 3, z + 13, 0); world.setBlock(x + 7, y + 3, z + 14, 0); world.setBlock(x + 7, y + 3, z + 17, 0); world.setBlock(x + 7, y + 4, z + 3, 0); world.setBlock(x + 7, y + 4, z + 4, 0); world.setBlock(x + 7, y + 4, z + 5, 0); world.setBlock(x + 7, y + 4, z + 6, 0); world.setBlock(x + 7, y + 4, z + 7, 0); world.setBlock(x + 7, y + 4, z + 8, 0); world.setBlock(x + 7, y + 4, z + 9, 0); world.setBlock(x + 7, y + 4, z + 10, 0); world.setBlock(x + 7, y + 4, z + 11, 0); world.setBlock(x + 7, y + 4, z + 12, 0); world.setBlock(x + 7, y + 4, z + 13, 0); world.setBlock(x + 7, y + 4, z + 17, 0); world.setBlock(x + 7, y + 5, z + 5, 0); world.setBlock(x + 7, y + 5, z + 6, 0); world.setBlock(x + 7, y + 5, z + 7, 0); world.setBlock(x + 7, y + 5, z + 8, 0); world.setBlock(x + 7, y + 5, z + 9, 0); world.setBlock(x + 7, y + 5, z + 10, 0); world.setBlock(x + 7, y + 5, z + 11, 0); world.setBlock(x + 7, y + 5, z + 17, 0); world.setBlock(x + 7, y + 6, z + 17, 0); world.setBlock(x + 8, y + 1, z + 1, 0); world.setBlock(x + 8, y + 1, z + 2, 0); world.setBlock(x + 8, y + 1, z + 3, 0); world.setBlock(x + 8, y + 1, z + 4, 0); world.setBlock(x + 8, y + 1, z + 5, 0); world.setBlock(x + 8, y + 1, z + 6, 0); world.setBlock(x + 8, y + 1, z + 10, 0); world.setBlock(x + 8, y + 1, z + 11, 0); world.setBlock(x + 8, y + 1, z + 12, 0); world.setBlock(x + 8, y + 1, z + 13, 0); world.setBlock(x + 8, y + 1, z + 14, 0); world.setBlock(x + 8, y + 1, z + 15, 0); world.setBlock(x + 8, y + 1, z + 17, 0); world.setBlock(x + 8, y + 2, z + 1, 0); world.setBlock(x + 8, y + 2, z + 2, 0); world.setBlock(x + 8, y + 2, z + 3, 0); world.setBlock(x + 8, y + 2, z + 4, 0); world.setBlock(x + 8, y + 2, z + 5, 0); world.setBlock(x + 8, y + 2, z + 6, 0); world.setBlock(x + 8, y + 2, z + 7, 0); world.setBlock(x + 8, y + 2, z + 9, 0); world.setBlock(x + 8, y + 2, z + 10, 0); world.setBlock(x + 8, y + 2, z + 11, 0); world.setBlock(x + 8, y + 2, z + 12, 0); world.setBlock(x + 8, y + 2, z + 13, 0); world.setBlock(x + 8, y + 2, z + 14, 0); world.setBlock(x + 8, y + 2, z + 15, 0); world.setBlock(x + 8, y + 2, z + 17, 0); world.setBlock(x + 8, y + 3, z + 2, 0); world.setBlock(x + 8, y + 3, z + 3, 0); world.setBlock(x + 8, y + 3, z + 4, 0); world.setBlock(x + 8, y + 3, z + 5, 0); world.setBlock(x + 8, y + 3, z + 6, 0); world.setBlock(x + 8, y + 3, z + 7, 0); world.setBlock(x + 8, y + 3, z + 9, 0); world.setBlock(x + 8, y + 3, z + 10, 0); world.setBlock(x + 8, y + 3, z + 11, 0); world.setBlock(x + 8, y + 3, z + 12, 0); world.setBlock(x + 8, y + 3, z + 13, 0); world.setBlock(x + 8, y + 3, z + 14, 0); world.setBlock(x + 8, y + 3, z + 17, 0); world.setBlock(x + 8, y + 4, z + 3, 0); world.setBlock(x + 8, y + 4, z + 4, 0); world.setBlock(x + 8, y + 4, z + 5, 0); world.setBlock(x + 8, y + 4, z + 6, 0); world.setBlock(x + 8, y + 4, z + 7, 0); world.setBlock(x + 8, y + 4, z + 8, 0); world.setBlock(x + 8, y + 4, z + 9, 0); world.setBlock(x + 8, y + 4, z + 10, 0); world.setBlock(x + 8, y + 4, z + 11, 0); world.setBlock(x + 8, y + 4, z + 12, 0); world.setBlock(x + 8, y + 4, z + 13, 0); world.setBlock(x + 8, y + 4, z + 17, 0); world.setBlock(x + 8, y + 5, z + 5, 0); world.setBlock(x + 8, y + 5, z + 6, 0); world.setBlock(x + 8, y + 5, z + 7, 0); world.setBlock(x + 8, y + 5, z + 8, 0); world.setBlock(x + 8, y + 5, z + 9, 0); world.setBlock(x + 8, y + 5, z + 10, 0); world.setBlock(x + 8, y + 5, z + 11, 0); world.setBlock(x + 8, y + 5, z + 17, 0); world.setBlock(x + 8, y + 6, z + 17, 0); world.setBlock(x + 9, y + 1, z + 1, 0); world.setBlock(x + 9, y + 1, z + 2, 0); world.setBlock(x + 9, y + 1, z + 3, 0); world.setBlock(x + 9, y + 1, z + 4, 0); world.setBlock(x + 9, y + 1, z + 5, 0); world.setBlock(x + 9, y + 1, z + 6, 0); world.setBlock(x + 9, y + 1, z + 10, 0); world.setBlock(x + 9, y + 1, z + 11, 0); world.setBlock(x + 9, y + 1, z + 12, 0); world.setBlock(x + 9, y + 1, z + 13, 0); world.setBlock(x + 9, y + 1, z + 14, 0); world.setBlock(x + 9, y + 1, z + 15, 0); world.setBlock(x + 9, y + 1, z + 17, 0); world.setBlock(x + 9, y + 2, z + 1, 0); world.setBlock(x + 9, y + 2, z + 2, 0); world.setBlock(x + 9, y + 2, z + 3, 0); world.setBlock(x + 9, y + 2, z + 4, 0); world.setBlock(x + 9, y + 2, z + 5, 0); world.setBlock(x + 9, y + 2, z + 6, 0); world.setBlock(x + 9, y + 2, z + 7, 0); world.setBlock(x + 9, y + 2, z + 8, 0); world.setBlock(x + 9, y + 2, z + 9, 0); world.setBlock(x + 9, y + 2, z + 10, 0); world.setBlock(x + 9, y + 2, z + 11, 0); world.setBlock(x + 9, y + 2, z + 12, 0); world.setBlock(x + 9, y + 2, z + 13, 0); world.setBlock(x + 9, y + 2, z + 14, 0); world.setBlock(x + 9, y + 2, z + 15, 0); world.setBlock(x + 9, y + 2, z + 17, 0); world.setBlock(x + 9, y + 3, z + 2, 0); world.setBlock(x + 9, y + 3, z + 3, 0); world.setBlock(x + 9, y + 3, z + 4, 0); world.setBlock(x + 9, y + 3, z + 5, 0); world.setBlock(x + 9, y + 3, z + 6, 0); world.setBlock(x + 9, y + 3, z + 7, 0); world.setBlock(x + 9, y + 3, z + 8, 0); world.setBlock(x + 9, y + 3, z + 9, 0); world.setBlock(x + 9, y + 3, z + 10, 0); world.setBlock(x + 9, y + 3, z + 11, 0); world.setBlock(x + 9, y + 3, z + 12, 0); world.setBlock(x + 9, y + 3, z + 13, 0); world.setBlock(x + 9, y + 3, z + 14, 0); world.setBlock(x + 9, y + 3, z + 17, 0); world.setBlock(x + 9, y + 4, z + 3, 0); world.setBlock(x + 9, y + 4, z + 4, 0); world.setBlock(x + 9, y + 4, z + 5, 0); world.setBlock(x + 9, y + 4, z + 6, 0); world.setBlock(x + 9, y + 4, z + 7, 0); world.setBlock(x + 9, y + 4, z + 8, 0); world.setBlock(x + 9, y + 4, z + 9, 0); world.setBlock(x + 9, y + 4, z + 10, 0); world.setBlock(x + 9, y + 4, z + 11, 0); world.setBlock(x + 9, y + 4, z + 12, 0); world.setBlock(x + 9, y + 4, z + 13, 0); world.setBlock(x + 9, y + 4, z + 17, 0); world.setBlock(x + 9, y + 5, z + 5, 0); world.setBlock(x + 9, y + 5, z + 6, 0); world.setBlock(x + 9, y + 5, z + 7, 0); world.setBlock(x + 9, y + 5, z + 8, 0); world.setBlock(x + 9, y + 5, z + 9, 0); world.setBlock(x + 9, y + 5, z + 10, 0); world.setBlock(x + 9, y + 5, z + 11, 0); world.setBlock(x + 9, y + 5, z + 17, 0); world.setBlock(x + 9, y + 6, z + 17, 0); world.setBlock(x + 10, y + 1, z + 1, 0); world.setBlock(x + 10, y + 1, z + 2, 0); world.setBlock(x + 10, y + 1, z + 3, 0); world.setBlock(x + 10, y + 1, z + 4, 0); world.setBlock(x + 10, y + 1, z + 5, 0); world.setBlock(x + 10, y + 1, z + 6, 0); world.setBlock(x + 10, y + 1, z + 7, 0); world.setBlock(x + 10, y + 1, z + 8, 0); world.setBlock(x + 10, y + 1, z + 9, 0); world.setBlock(x + 10, y + 1, z + 10, 0); world.setBlock(x + 10, y + 1, z + 11, 0); world.setBlock(x + 10, y + 1, z + 12, 0); world.setBlock(x + 10, y + 1, z + 13, 0); world.setBlock(x + 10, y + 1, z + 14, 0); world.setBlock(x + 10, y + 1, z + 15, 0); world.setBlock(x + 10, y + 1, z + 17, 0); world.setBlock(x + 10, y + 2, z + 1, 0); world.setBlock(x + 10, y + 2, z + 2, 0); world.setBlock(x + 10, y + 2, z + 3, 0); world.setBlock(x + 10, y + 2, z + 4, 0); world.setBlock(x + 10, y + 2, z + 5, 0); world.setBlock(x + 10, y + 2, z + 6, 0); world.setBlock(x + 10, y + 2, z + 7, 0); world.setBlock(x + 10, y + 2, z + 8, 0); world.setBlock(x + 10, y + 2, z + 9, 0); world.setBlock(x + 10, y + 2, z + 10, 0); world.setBlock(x + 10, y + 2, z + 11, 0); world.setBlock(x + 10, y + 2, z + 12, 0); world.setBlock(x + 10, y + 2, z + 13, 0); world.setBlock(x + 10, y + 2, z + 14, 0); world.setBlock(x + 10, y + 2, z + 15, 0); world.setBlock(x + 10, y + 2, z + 17, 0); world.setBlock(x + 10, y + 3, z + 2, 0); world.setBlock(x + 10, y + 3, z + 3, 0); world.setBlock(x + 10, y + 3, z + 4, 0); world.setBlock(x + 10, y + 3, z + 5, 0); world.setBlock(x + 10, y + 3, z + 6, 0); world.setBlock(x + 10, y + 3, z + 7, 0); world.setBlock(x + 10, y + 3, z + 8, 0); world.setBlock(x + 10, y + 3, z + 9, 0); world.setBlock(x + 10, y + 3, z + 10, 0); world.setBlock(x + 10, y + 3, z + 11, 0); world.setBlock(x + 10, y + 3, z + 12, 0); world.setBlock(x + 10, y + 3, z + 13, 0); world.setBlock(x + 10, y + 3, z + 14, 0); world.setBlock(x + 10, y + 3, z + 17, 0); world.setBlock(x + 10, y + 4, z + 3, 0); world.setBlock(x + 10, y + 4, z + 4, 0); world.setBlock(x + 10, y + 4, z + 5, 0); world.setBlock(x + 10, y + 4, z + 6, 0); world.setBlock(x + 10, y + 4, z + 7, 0); world.setBlock(x + 10, y + 4, z + 8, 0); world.setBlock(x + 10, y + 4, z + 9, 0); world.setBlock(x + 10, y + 4, z + 10, 0); world.setBlock(x + 10, y + 4, z + 11, 0); world.setBlock(x + 10, y + 4, z + 12, 0); world.setBlock(x + 10, y + 4, z + 13, 0); world.setBlock(x + 10, y + 4, z + 17, 0); world.setBlock(x + 10, y + 5, z + 5, 0); world.setBlock(x + 10, y + 5, z + 6, 0); world.setBlock(x + 10, y + 5, z + 7, 0); world.setBlock(x + 10, y + 5, z + 8, 0); world.setBlock(x + 10, y + 5, z + 9, 0); world.setBlock(x + 10, y + 5, z + 10, 0); world.setBlock(x + 10, y + 5, z + 11, 0); world.setBlock(x + 10, y + 5, z + 17, 0); world.setBlock(x + 10, y + 6, z + 17, 0); world.setBlock(x + 11, y + 1, z + 2, 0); world.setBlock(x + 11, y + 1, z + 3, 0); world.setBlock(x + 11, y + 1, z + 4, 0); world.setBlock(x + 11, y + 1, z + 5, 0); world.setBlock(x + 11, y + 1, z + 6, 0); world.setBlock(x + 11, y + 1, z + 7, 0); world.setBlock(x + 11, y + 1, z + 8, 0); world.setBlock(x + 11, y + 1, z + 9, 0); world.setBlock(x + 11, y + 1, z + 10, 0); world.setBlock(x + 11, y + 1, z + 11, 0); world.setBlock(x + 11, y + 1, z + 12, 0); world.setBlock(x + 11, y + 1, z + 13, 0); world.setBlock(x + 11, y + 1, z + 14, 0); world.setBlock(x + 11, y + 1, z + 17, 0); world.setBlock(x + 11, y + 2, z + 2, 0); world.setBlock(x + 11, y + 2, z + 3, 0); world.setBlock(x + 11, y + 2, z + 4, 0); world.setBlock(x + 11, y + 2, z + 5, 0); world.setBlock(x + 11, y + 2, z + 6, 0); world.setBlock(x + 11, y + 2, z + 7, 0); world.setBlock(x + 11, y + 2, z + 8, 0); world.setBlock(x + 11, y + 2, z + 9, 0); world.setBlock(x + 11, y + 2, z + 10, 0); world.setBlock(x + 11, y + 2, z + 11, 0); world.setBlock(x + 11, y + 2, z + 12, 0); world.setBlock(x + 11, y + 2, z + 13, 0); world.setBlock(x + 11, y + 2, z + 14, 0); world.setBlock(x + 11, y + 2, z + 17, 0); world.setBlock(x + 11, y + 3, z + 3, 0); world.setBlock(x + 11, y + 3, z + 4, 0); world.setBlock(x + 11, y + 3, z + 5, 0); world.setBlock(x + 11, y + 3, z + 6, 0); world.setBlock(x + 11, y + 3, z + 7, 0); world.setBlock(x + 11, y + 3, z + 8, 0); world.setBlock(x + 11, y + 3, z + 9, 0); world.setBlock(x + 11, y + 3, z + 10, 0); world.setBlock(x + 11, y + 3, z + 11, 0); world.setBlock(x + 11, y + 3, z + 12, 0); world.setBlock(x + 11, y + 3, z + 13, 0); world.setBlock(x + 11, y + 3, z + 17, 0); world.setBlock(x + 11, y + 4, z + 4, 0); world.setBlock(x + 11, y + 4, z + 5, 0); world.setBlock(x + 11, y + 4, z + 6, 0); world.setBlock(x + 11, y + 4, z + 7, 0); world.setBlock(x + 11, y + 4, z + 8, 0); world.setBlock(x + 11, y + 4, z + 9, 0); world.setBlock(x + 11, y + 4, z + 10, 0); world.setBlock(x + 11, y + 4, z + 11, 0); world.setBlock(x + 11, y + 4, z + 12, 0); world.setBlock(x + 11, y + 4, z + 17, 0); world.setBlock(x + 11, y + 5, z + 6, 0); world.setBlock(x + 11, y + 5, z + 7, 0); world.setBlock(x + 11, y + 5, z + 8, 0); world.setBlock(x + 11, y + 5, z + 9, 0); world.setBlock(x + 11, y + 5, z + 10, 0); world.setBlock(x + 11, y + 5, z + 17, 0); world.setBlock(x + 11, y + 6, z + 17, 0); world.setBlock(x + 12, y + 1, z + 2, 0); world.setBlock(x + 12, y + 1, z + 3, 0); world.setBlock(x + 12, y + 1, z + 4, 0); world.setBlock(x + 12, y + 1, z + 5, 0); world.setBlock(x + 12, y + 1, z + 6, 0); world.setBlock(x + 12, y + 1, z + 7, 0); world.setBlock(x + 12, y + 1, z + 8, 0); world.setBlock(x + 12, y + 1, z + 9, 0); world.setBlock(x + 12, y + 1, z + 10, 0); world.setBlock(x + 12, y + 1, z + 11, 0); world.setBlock(x + 12, y + 1, z + 12, 0); world.setBlock(x + 12, y + 1, z + 13, 0); world.setBlock(x + 12, y + 1, z + 14, 0); world.setBlock(x + 12, y + 1, z + 17, 0); world.setBlock(x + 12, y + 2, z + 2, 0); world.setBlock(x + 12, y + 2, z + 3, 0); world.setBlock(x + 12, y + 2, z + 4, 0); world.setBlock(x + 12, y + 2, z + 5, 0); world.setBlock(x + 12, y + 2, z + 6, 0); world.setBlock(x + 12, y + 2, z + 7, 0); world.setBlock(x + 12, y + 2, z + 8, 0); world.setBlock(x + 12, y + 2, z + 9, 0); world.setBlock(x + 12, y + 2, z + 10, 0); world.setBlock(x + 12, y + 2, z + 11, 0); world.setBlock(x + 12, y + 2, z + 12, 0); world.setBlock(x + 12, y + 2, z + 13, 0); world.setBlock(x + 12, y + 2, z + 14, 0); world.setBlock(x + 12, y + 2, z + 17, 0); world.setBlock(x + 12, y + 3, z + 3, 0); world.setBlock(x + 12, y + 3, z + 4, 0); world.setBlock(x + 12, y + 3, z + 5, 0); world.setBlock(x + 12, y + 3, z + 6, 0); world.setBlock(x + 12, y + 3, z + 7, 0); world.setBlock(x + 12, y + 3, z + 8, 0); world.setBlock(x + 12, y + 3, z + 9, 0); world.setBlock(x + 12, y + 3, z + 10, 0); world.setBlock(x + 12, y + 3, z + 11, 0); world.setBlock(x + 12, y + 3, z + 12, 0); world.setBlock(x + 12, y + 3, z + 13, 0); world.setBlock(x + 12, y + 3, z + 17, 0); world.setBlock(x + 12, y + 4, z + 4, 0); world.setBlock(x + 12, y + 4, z + 5, 0); world.setBlock(x + 12, y + 4, z + 6, 0); world.setBlock(x + 12, y + 4, z + 7, 0); world.setBlock(x + 12, y + 4, z + 8, 0); world.setBlock(x + 12, y + 4, z + 9, 0); world.setBlock(x + 12, y + 4, z + 10, 0); world.setBlock(x + 12, y + 4, z + 11, 0); world.setBlock(x + 12, y + 4, z + 12, 0); world.setBlock(x + 12, y + 4, z + 17, 0); world.setBlock(x + 12, y + 5, z + 17, 0); world.setBlock(x + 12, y + 6, z + 17, 0); world.setBlock(x + 13, y + 1, z + 3, 0); world.setBlock(x + 13, y + 1, z + 4, 0); world.setBlock(x + 13, y + 1, z + 5, 0); world.setBlock(x + 13, y + 1, z + 6, 0); world.setBlock(x + 13, y + 1, z + 7, 0); world.setBlock(x + 13, y + 1, z + 8, 0); world.setBlock(x + 13, y + 1, z + 9, 0); world.setBlock(x + 13, y + 1, z + 10, 0); world.setBlock(x + 13, y + 1, z + 11, 0); world.setBlock(x + 13, y + 1, z + 12, 0); world.setBlock(x + 13, y + 1, z + 13, 0); world.setBlock(x + 13, y + 1, z + 17, 0); world.setBlock(x + 13, y + 2, z + 3, 0); world.setBlock(x + 13, y + 2, z + 4, 0); world.setBlock(x + 13, y + 2, z + 5, 0); world.setBlock(x + 13, y + 2, z + 6, 0); world.setBlock(x + 13, y + 2, z + 7, 0); world.setBlock(x + 13, y + 2, z + 8, 0); world.setBlock(x + 13, y + 2, z + 9, 0); world.setBlock(x + 13, y + 2, z + 10, 0); world.setBlock(x + 13, y + 2, z + 11, 0); world.setBlock(x + 13, y + 2, z + 12, 0); world.setBlock(x + 13, y + 2, z + 13, 0); world.setBlock(x + 13, y + 2, z + 17, 0); world.setBlock(x + 13, y + 3, z + 4, 0); world.setBlock(x + 13, y + 3, z + 5, 0); world.setBlock(x + 13, y + 3, z + 6, 0); world.setBlock(x + 13, y + 3, z + 7, 0); world.setBlock(x + 13, y + 3, z + 8, 0); world.setBlock(x + 13, y + 3, z + 9, 0); world.setBlock(x + 13, y + 3, z + 10, 0); world.setBlock(x + 13, y + 3, z + 11, 0); world.setBlock(x + 13, y + 3, z + 12, 0); world.setBlock(x + 13, y + 3, z + 17, 0); world.setBlock(x + 13, y + 4, z + 6, 0); world.setBlock(x + 13, y + 4, z + 7, 0); world.setBlock(x + 13, y + 4, z + 8, 0); world.setBlock(x + 13, y + 4, z + 9, 0); world.setBlock(x + 13, y + 4, z + 10, 0); world.setBlock(x + 13, y + 4, z + 17, 0); world.setBlock(x + 13, y + 5, z + 17, 0); world.setBlock(x + 13, y + 6, z + 17, 0); world.setBlock(x + 14, y + 1, z + 4, 0); world.setBlock(x + 14, y + 1, z + 5, 0); world.setBlock(x + 14, y + 1, z + 6, 0); world.setBlock(x + 14, y + 1, z + 7, 0); world.setBlock(x + 14, y + 1, z + 8, 0); world.setBlock(x + 14, y + 1, z + 9, 0); world.setBlock(x + 14, y + 1, z + 10, 0); world.setBlock(x + 14, y + 1, z + 11, 0); world.setBlock(x + 14, y + 1, z + 12, 0); world.setBlock(x + 14, y + 1, z + 17, 0); world.setBlock(x + 14, y + 2, z + 4, 0); world.setBlock(x + 14, y + 2, z + 5, 0); world.setBlock(x + 14, y + 2, z + 6, 0); world.setBlock(x + 14, y + 2, z + 7, 0); world.setBlock(x + 14, y + 2, z + 8, 0); world.setBlock(x + 14, y + 2, z + 9, 0); world.setBlock(x + 14, y + 2, z + 10, 0); world.setBlock(x + 14, y + 2, z + 11, 0); world.setBlock(x + 14, y + 2, z + 12, 0); world.setBlock(x + 14, y + 2, z + 17, 0); world.setBlock(x + 14, y + 3, z + 6, 0); world.setBlock(x + 14, y + 3, z + 7, 0); world.setBlock(x + 14, y + 3, z + 8, 0); world.setBlock(x + 14, y + 3, z + 9, 0); world.setBlock(x + 14, y + 3, z + 10, 0); world.setBlock(x + 14, y + 3, z + 17, 0); world.setBlock(x + 14, y + 4, z + 17, 0); world.setBlock(x + 14, y + 5, z + 17, 0); world.setBlock(x + 14, y + 6, z + 17, 0); world.setBlock(x + 15, y + 1, z + 6, 0); world.setBlock(x + 15, y + 1, z + 7, 0); world.setBlock(x + 15, y + 1, z + 8, 0); world.setBlock(x + 15, y + 1, z + 9, 0); world.setBlock(x + 15, y + 1, z + 10, 0); world.setBlock(x + 15, y + 1, z + 17, 0); world.setBlock(x + 15, y + 2, z + 6, 0); world.setBlock(x + 15, y + 2, z + 7, 0); world.setBlock(x + 15, y + 2, z + 8, 0); world.setBlock(x + 15, y + 2, z + 9, 0); world.setBlock(x + 15, y + 2, z + 10, 0); world.setBlock(x + 15, y + 2, z + 17, 0); world.setBlock(x + 15, y + 3, z + 17, 0); world.setBlock(x + 15, y + 4, z + 17, 0); world.setBlock(x + 15, y + 5, z + 17, 0); world.setBlock(x + 15, y + 6, z + 17, 0); world.setBlock(x + 16, y + 1, z + 17, 0); world.setBlock(x + 16, y + 2, z + 17, 0); world.setBlock(x + 16, y + 3, z + 17, 0); world.setBlock(x + 16, y + 4, z + 17, 0); world.setBlock(x + 16, y + 5, z + 17, 0); world.setBlock(x + 16, y + 6, z + 17, 0); world.setBlock(x + 17, y + 1, z + 0, 0); world.setBlock(x + 17, y + 1, z + 1, 0); world.setBlock(x + 17, y + 1, z + 2, 0); world.setBlock(x + 17, y + 1, z + 3, 0); world.setBlock(x + 17, y + 1, z + 4, 0); world.setBlock(x + 17, y + 1, z + 5, 0); world.setBlock(x + 17, y + 1, z + 6, 0); world.setBlock(x + 17, y + 1, z + 7, 0); world.setBlock(x + 17, y + 1, z + 8, 0); world.setBlock(x + 17, y + 1, z + 9, 0); world.setBlock(x + 17, y + 1, z + 10, 0); world.setBlock(x + 17, y + 1, z + 11, 0); world.setBlock(x + 17, y + 1, z + 12, 0); world.setBlock(x + 17, y + 1, z + 13, 0); world.setBlock(x + 17, y + 1, z + 14, 0); world.setBlock(x + 17, y + 1, z + 15, 0); world.setBlock(x + 17, y + 1, z + 16, 0); world.setBlock(x + 17, y + 1, z + 17, 0); world.setBlock(x + 17, y + 2, z + 0, 0); world.setBlock(x + 17, y + 2, z + 1, 0); world.setBlock(x + 17, y + 2, z + 2, 0); world.setBlock(x + 17, y + 2, z + 3, 0); world.setBlock(x + 17, y + 2, z + 4, 0); world.setBlock(x + 17, y + 2, z + 5, 0); world.setBlock(x + 17, y + 2, z + 6, 0); world.setBlock(x + 17, y + 2, z + 7, 0); world.setBlock(x + 17, y + 2, z + 8, 0); world.setBlock(x + 17, y + 2, z + 9, 0); world.setBlock(x + 17, y + 2, z + 10, 0); world.setBlock(x + 17, y + 2, z + 11, 0); world.setBlock(x + 17, y + 2, z + 12, 0); world.setBlock(x + 17, y + 2, z + 13, 0); world.setBlock(x + 17, y + 2, z + 14, 0); world.setBlock(x + 17, y + 2, z + 15, 0); world.setBlock(x + 17, y + 2, z + 16, 0); world.setBlock(x + 17, y + 2, z + 17, 0); world.setBlock(x + 17, y + 3, z + 0, 0); world.setBlock(x + 17, y + 3, z + 1, 0); world.setBlock(x + 17, y + 3, z + 2, 0); world.setBlock(x + 17, y + 3, z + 3, 0); world.setBlock(x + 17, y + 3, z + 4, 0); world.setBlock(x + 17, y + 3, z + 5, 0); world.setBlock(x + 17, y + 3, z + 6, 0); world.setBlock(x + 17, y + 3, z + 7, 0); world.setBlock(x + 17, y + 3, z + 8, 0); world.setBlock(x + 17, y + 3, z + 9, 0); world.setBlock(x + 17, y + 3, z + 10, 0); world.setBlock(x + 17, y + 3, z + 11, 0); world.setBlock(x + 17, y + 3, z + 12, 0); world.setBlock(x + 17, y + 3, z + 13, 0); world.setBlock(x + 17, y + 3, z + 14, 0); world.setBlock(x + 17, y + 3, z + 15, 0); world.setBlock(x + 17, y + 3, z + 16, 0); world.setBlock(x + 17, y + 3, z + 17, 0); world.setBlock(x + 17, y + 4, z + 0, 0); world.setBlock(x + 17, y + 4, z + 1, 0); world.setBlock(x + 17, y + 4, z + 2, 0); world.setBlock(x + 17, y + 4, z + 3, 0); world.setBlock(x + 17, y + 4, z + 4, 0); world.setBlock(x + 17, y + 4, z + 5, 0); world.setBlock(x + 17, y + 4, z + 6, 0); world.setBlock(x + 17, y + 4, z + 7, 0); world.setBlock(x + 17, y + 4, z + 8, 0); world.setBlock(x + 17, y + 4, z + 9, 0); world.setBlock(x + 17, y + 4, z + 10, 0); world.setBlock(x + 17, y + 4, z + 11, 0); world.setBlock(x + 17, y + 4, z + 12, 0); world.setBlock(x + 17, y + 4, z + 13, 0); world.setBlock(x + 17, y + 4, z + 14, 0); world.setBlock(x + 17, y + 4, z + 15, 0); world.setBlock(x + 17, y + 4, z + 16, 0); world.setBlock(x + 17, y + 4, z + 17, 0); world.setBlock(x + 17, y + 5, z + 0, 0); world.setBlock(x + 17, y + 5, z + 1, 0); world.setBlock(x + 17, y + 5, z + 2, 0); world.setBlock(x + 17, y + 5, z + 3, 0); world.setBlock(x + 17, y + 5, z + 4, 0); world.setBlock(x + 17, y + 5, z + 5, 0); world.setBlock(x + 17, y + 5, z + 6, 0); world.setBlock(x + 17, y + 5, z + 7, 0); world.setBlock(x + 17, y + 5, z + 8, 0); world.setBlock(x + 17, y + 5, z + 9, 0); world.setBlock(x + 17, y + 5, z + 10, 0); world.setBlock(x + 17, y + 5, z + 11, 0); world.setBlock(x + 17, y + 5, z + 12, 0); world.setBlock(x + 17, y + 5, z + 13, 0); world.setBlock(x + 17, y + 5, z + 14, 0); world.setBlock(x + 17, y + 5, z + 15, 0); world.setBlock(x + 17, y + 5, z + 16, 0); world.setBlock(x + 17, y + 5, z + 17, 0); world.setBlock(x + 17, y + 6, z + 0, 0); world.setBlock(x + 17, y + 6, z + 1, 0); world.setBlock(x + 17, y + 6, z + 2, 0); world.setBlock(x + 17, y + 6, z + 3, 0); world.setBlock(x + 17, y + 6, z + 4, 0); world.setBlock(x + 17, y + 6, z + 5, 0); world.setBlock(x + 17, y + 6, z + 6, 0); world.setBlock(x + 17, y + 6, z + 7, 0); world.setBlock(x + 17, y + 6, z + 8, 0); world.setBlock(x + 17, y + 6, z + 9, 0); world.setBlock(x + 17, y + 6, z + 10, 0); world.setBlock(x + 17, y + 6, z + 11, 0); world.setBlock(x + 17, y + 6, z + 12, 0); world.setBlock(x + 17, y + 6, z + 13, 0); world.setBlock(x + 17, y + 6, z + 14, 0); world.setBlock(x + 17, y + 6, z + 15, 0); world.setBlock(x + 17, y + 6, z + 16, 0); world.setBlock(x + 17, y + 6, z + 17, 0); } }
package model; import java.util.ArrayList; import java.util.List; import com.jaunt.*; public class Scraper { private String html; private Elements ef2p; private Elements ep2p; private World world; public Scraper(String html) { this.html = html; } public List<World> init() throws ResponseException, NotFound { List<World> worlds = new ArrayList<World>(); UserAgent userAgent = new UserAgent(); userAgent.visit(this.html); ef2p = userAgent.doc.findEvery("<tr class='server-list__row'"); ep2p = userAgent.doc.findEvery("<tr class='server-list__row server-list__row--members'>"); for (Element e: ef2p) { String id; if (e.getElement(0).getElement(0).getText().length() == 12) { id = "30" + e.getElement(0).getElement(0).getText().substring(11, 12); } else { id = "3" + e.getElement(0).getElement(0).getText().substring(11, 13); } int population = Integer.parseInt(e.getElement(1).getText().substring(0, e.getElement(1).getText().length() - " players".length())); String country = e.getElement(2).getText(); world = new World(id, false, population, country); worlds.add(world); } for (Element e: ep2p) { String id; if (e.getElement(0).getElement(0).getText().length() == 12) { id = "30" + e.getElement(0).getElement(0).getText().substring(11, 12); } else { id = "3" + e.getElement(0).getElement(0).getText().substring(11, 13); } int population = Integer.parseInt(e.getElement(1).getText().substring(0, e.getElement(1).getText().length() - " players".length())); String country = e.getElement(2).getText(); world = new World(id, true, population, country); worlds.add(world); } return worlds; } public List<Integer> updateWorlds() throws ResponseException, NumberFormatException, NotFound { List<Integer> worldPop = new ArrayList<Integer>(); UserAgent userAgent = new UserAgent(); userAgent.visit(this.html); ef2p = userAgent.doc.findEvery("<tr class='server-list__row'"); ep2p = userAgent.doc.findEvery("<tr class='server-list__row server-list__row--members'>"); for (Element e: ef2p) { int population = 0; if (e.getElement(1).getText().length() >= 0) { population = Integer.parseInt(e.getElement(1).getText().substring(0, e.getElement(1).getText().length() - " players".length())); } worldPop.add(population); } for (Element e: ep2p) { int population = 0; if (e.getElement(1).getText().length() >= 0) { population = Integer.parseInt(e.getElement(1).getText().substring(0, e.getElement(1).getText().length() - " players".length())); } worldPop.add(population); } return worldPop; } }
package org.intermine.web.logic.widget; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.io.IOException; import java.lang.reflect.Constructor; import java.text.DecimalFormat; import java.text.FieldPosition; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.intermine.api.profile.InterMineBag; import org.intermine.objectstore.ObjectStore; import org.intermine.util.TypeUtil; import org.intermine.web.logic.widget.config.GraphWidgetConfig; import org.jfree.chart.ChartColor; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.JFreeChart; import org.jfree.chart.StandardChartTheme; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.chart.imagemap.ImageMapUtilities; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.ItemLabelAnchor; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYSplineRenderer; import org.jfree.chart.servlet.ServletUtilities; import org.jfree.chart.title.TextTitle; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.Dataset; import org.jfree.data.general.PieDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.ui.RectangleInsets; import org.jfree.ui.TextAnchor; /** * @author "Xavier Watkins" * */ public class GraphWidget extends Widget { private static final Logger LOG = Logger.getLogger(GraphWidget.class); private int notAnalysed = 0; private DataSetLdr dataSetLdr; private InterMineBag bag; private ObjectStore os; private String fileName = null; private String imageMap = null; private String selectedExtraAttribute; private static final ChartColor BLUE = new ChartColor(47, 114, 255); private static final ChartColor LIGHT_BLUE = new ChartColor(159, 192, 255); private static final ChartColor DARK_BLUE = new ChartColor(39, 77, 216); private Dataset graphDataSet; /** * @param config config for widget * @param interMineBag bag for widget * @param os objectstore * @param selectedExtraAttribute extra attribute */ public GraphWidget(GraphWidgetConfig config, InterMineBag interMineBag, ObjectStore os, String selectedExtraAttribute) { super(config); this.bag = interMineBag; this.os = os; this.selectedExtraAttribute = selectedExtraAttribute; process(); } /** * {@inheritDoc} */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public List getElementInList() { return new Vector(); } /** * {@inheritDoc} */ @Override public void process() { String dataSetLoader = config.getDataSetLoader(); Class<?> clazz = TypeUtil.instantiate(dataSetLoader); try { Constructor<?> constr = clazz.getConstructor(new Class[] {InterMineBag.class, ObjectStore.class, String.class}); dataSetLdr = (DataSetLdr) constr.newInstance(new Object[] {bag, os, selectedExtraAttribute}); notAnalysed = bag.getSize() - dataSetLdr.getWidgetTotal(); } catch (Exception err) { LOG.warn("Error rendering graph widget.", err); return; } if (dataSetLdr == null || dataSetLdr.getDataSet() == null) { LOG.warn("No data found for graph widget"); return; } BarRenderer.setDefaultShadowsVisible(false); JFreeChart chart = null; graphDataSet = dataSetLdr.getDataSet(); String graphType = ((GraphWidgetConfig) config).getGraphType(); ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme()); if (StringUtils.isNotEmpty(graphType) && "ScatterPlot".equals(graphType)) { chart = ChartFactory.createScatterPlot( config.getTitle(), ((GraphWidgetConfig) config).getDomainLabel(), ((GraphWidgetConfig) config).getRangeLabel(), (XYDataset) graphDataSet, PlotOrientation.VERTICAL, true, true, false); XYPlot plot = chart.getXYPlot(); XYItemRenderer xyrenderer = plot.getRenderer(); StandardXYItemRenderer regressionRenderer = new StandardXYItemRenderer(); regressionRenderer.setBaseSeriesVisibleInLegend(false); plot.setDataset(1, regress((XYDataset) graphDataSet)); plot.setRenderer(1, regressionRenderer); xyrenderer.setSeriesStroke(0, new BasicStroke(3.0f)); xyrenderer.setSeriesStroke(1, new BasicStroke(3.0f)); xyrenderer.setSeriesPaint(0, BLUE); xyrenderer.setSeriesPaint(1, LIGHT_BLUE); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); DivNumberFormat formatter = new DivNumberFormat(1000); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setNumberFormatOverride(formatter); } else if (StringUtils.isNotEmpty(graphType) && "XYLineChart".equals(graphType)) { chart = ChartFactory.createXYLineChart(config.getTitle(), ((GraphWidgetConfig) config).getDomainLabel(), ((GraphWidgetConfig) config).getRangeLabel(), (XYDataset) graphDataSet, PlotOrientation.VERTICAL, true, true, false); XYPlot plot = chart.getXYPlot(); XYItemRenderer xyrenderer = plot.getRenderer(); xyrenderer.setSeriesStroke(0, new BasicStroke(3.0f)); xyrenderer.setSeriesStroke(1, new BasicStroke(3.0f)); xyrenderer.setSeriesPaint(0, BLUE); xyrenderer.setSeriesPaint(1, LIGHT_BLUE); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); DivNumberFormat formatter = new DivNumberFormat(1000); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setNumberFormatOverride(formatter); } else if (StringUtils.isNotEmpty(graphType) && "PieChart".equals(graphType)) { chart = ChartFactory.createPieChart( config.getTitle(), (PieDataset) graphDataSet, true, true, false); PiePlot plot = (PiePlot) chart.getPlot(); plot.setNoDataMessage("No data available"); plot.setCircular(true); plot.setLabelGap(0.02); plot.setBackgroundPaint(Color.white); Font labelFont = new Font("SansSerif", Font.BOLD, 12); plot.setLabelFont(labelFont); plot.setMaximumLabelWidth(0.20d); @SuppressWarnings("rawtypes") List keys = ((PieDataset) graphDataSet).getKeys(); int mod = (keys.size() % 3 == 1) ? 2 : 3; int i = 0; for (Object key: keys) { Color paint; switch (i++ % mod) { case 0: paint = BLUE; break; case 1: paint = LIGHT_BLUE; break; case 2: paint = DARK_BLUE; break; default: paint = BLUE; } plot.setSectionPaint((Comparable<?>) key, paint); } } else if (StringUtils.isNotEmpty(graphType) && "StackedBarChart".equals(graphType)) { chart = ChartFactory.createStackedBarChart(config.getTitle(), // chart title ((GraphWidgetConfig) config).getDomainLabel(), // domain axis label ((GraphWidgetConfig) config).getRangeLabel(), // range axis label (CategoryDataset) graphDataSet, // data PlotOrientation.HORIZONTAL, true, true, // include legend,tooltips? false // URLs? ); CategoryPlot categoryPlot = chart.getCategoryPlot(); CategoryItemRenderer categoryRenderer = categoryPlot.getRenderer(); categoryRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition( ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT)); categoryRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition( ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT)); ((GraphWidgetConfig) config).setHeight(400); formatBarCharts(categoryPlot); setURLGen(categoryRenderer); /* regular bar chart */ } else { chart = ChartFactory.createBarChart(config.getTitle(), // chart title ((GraphWidgetConfig) config).getDomainLabel(), ((GraphWidgetConfig) config).getRangeLabel(), (CategoryDataset) graphDataSet, // data PlotOrientation.VERTICAL, true, true, // tooltips? false // URLs? ); if (selectedExtraAttribute != null && !selectedExtraAttribute.startsWith("any")) { TextTitle subtitleText = new TextTitle(selectedExtraAttribute); subtitleText.setFont(new Font("SansSerif", Font.ITALIC, 10)); chart.addSubtitle(subtitleText); } CategoryPlot categoryPlot = chart.getCategoryPlot(); CategoryItemRenderer categoryRenderer = new BarRenderer(); ((BarRenderer) categoryRenderer).setItemMargin(0); categoryRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition( ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER)); categoryRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition( ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER)); categoryPlot.setRenderer(categoryRenderer); // rotate the category labels categoryPlot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions .createUpRotationLabelPositions(Math.PI / 6.0)); setURLGen(categoryRenderer); ((BarRenderer) categoryRenderer).setNegativeItemLabelPositionFallback( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT)); formatBarCharts(categoryPlot); } if (chart.getTitle() != null) { chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12)); } chart.setPadding(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); // this would speed up chart rendering, but it wouldn't look as nice. // chart.setAntiAlias(false); ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); // generate the image and imagemap try { fileName = ServletUtilities.saveChartAsPNG(chart, ((GraphWidgetConfig) config).getWidth(), ((GraphWidgetConfig) config).getHeight(), info, ((GraphWidgetConfig) config).getSession()); } catch (IOException e) { throw new RuntimeException("error rendering html", e); } imageMap = ImageMapUtilities.getImageMap("chart" + fileName, info); } private void setURLGen(CategoryItemRenderer categoryRenderer) { if (config.getLink() == null) { return; } CategoryURLGenerator categoryUrlGen = null; // set series 0 to have URLgenerator specified in config file // set series 1 to have no URL generator. try { Class<?> clazz2 = TypeUtil.instantiate(config.getLink()); Constructor<?> urlGenConstructor = clazz2.getConstructor(new Class[] {String.class, String.class}); categoryUrlGen = (CategoryURLGenerator) urlGenConstructor .newInstance(new Object[] {bag.getName(), selectedExtraAttribute}); } catch (Exception err) { err.printStackTrace(); return; } // renderer.setItemURLGenerator(null); categoryRenderer.setSeriesItemURLGenerator(0, categoryUrlGen); categoryRenderer.setSeriesItemURLGenerator(1, categoryUrlGen); } private void formatBarCharts(CategoryPlot categoryPlot) { if (categoryPlot != null) { // display values for each column CategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator(); categoryPlot.getRenderer().setBaseItemLabelsVisible(true); categoryPlot.getRenderer().setBaseItemLabelGenerator(generator); categoryPlot.getRenderer().setBaseToolTipGenerator(new ToolTipGenerator()); NumberAxis rangeAxis = (NumberAxis) categoryPlot.getRangeAxis(); rangeAxis.setUpperMargin(0.15); rangeAxis.setLowerMargin(0.15); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); Font labelFont = new Font("SansSerif", Font.BOLD, 12); categoryPlot.getDomainAxis().setLabelFont(labelFont); rangeAxis.setLabelPaint(Color.darkGray); rangeAxis.setLabelFont(labelFont); categoryPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(10.0f); categoryPlot.getRenderer().setSeriesPaint(0, BLUE); categoryPlot.getRenderer().setSeriesPaint(1, LIGHT_BLUE); categoryPlot.getRenderer().setSeriesPaint(2, DARK_BLUE); categoryPlot.getRenderer().setSeriesOutlineStroke(1, new BasicStroke(0.0F)); categoryPlot.setBackgroundPaint(Color.white); categoryPlot.setDomainGridlinePaint(Color.LIGHT_GRAY); categoryPlot.setDomainGridlinesVisible(true); categoryPlot.setRangeGridlinePaint(Color.LIGHT_GRAY); // StandardChartTheme legacyTheme // = (StandardChartTheme) StandardChartTheme.createLegacyTheme(); // legacyTheme.applyToCategoryPlot((CategoryPlot) categoryPlot); } } /** * {@inheritDoc} */ @Override public List<List<String>> getExportResults(String[] selected) throws Exception { // TODO Auto-generated method stub return null; } /** * {@inheritDoc} */ @Override public List<List<String[]>> getFlattenedResults() { // TODO Auto-generated method stub return null; } /** * {@inheritDoc} */ @Override public boolean getHasResults() { return (dataSetLdr != null && dataSetLdr.getResults() != null && dataSetLdr.getResults().size() > 0); } /** * {@inheritDoc} */ @Override public void setNotAnalysed(int notAnalysed) { this.notAnalysed = notAnalysed; } /** * {@inheritDoc} */ @Override public int getNotAnalysed() { return notAnalysed; } /** * Get the HTML that will display the graph and imagemap * @return the HTML as a String */ public String getHtml() { // IE doesn't support base64, so for now we are just going to pass back location of png file String img = "<img src=\"loadTmpImg.do?fileName=" + fileName + "\" width=\"" + ((GraphWidgetConfig) config).getWidth() + "\" height=\"" + ((GraphWidgetConfig) config).getHeight() + "\" usemap=\"#chart" + fileName + "\">"; StringBuffer sb = new StringBuffer(img); sb.append(imageMap); return sb.toString(); } public List<List<Object>> getResults() { Dataset dataSet = dataSetLdr.getDataSet(); if (dataSet == null) { LOG.warn("no data found for graph widget."); return null; } List<List<Object>> ret = new LinkedList<List<Object>>(); if (graphDataSet instanceof CategoryDataset) { CategoryDataset ds = (CategoryDataset) dataSet; List<Object> rowKeys = ds.getRowKeys(); List<Object> labels = new LinkedList<Object>(); labels.add(""); // Dummy label labels.addAll(rowKeys); ret.add(labels); int colCount = ds.getColumnCount(); for (int i = 0; i < colCount; i++) { List<Object> row = new LinkedList<Object>(); row.add(ds.getColumnKey(i)); for (Object rowKey: rowKeys) { int rIdx = ds.getRowIndex((Comparable) rowKey); row.add(ds.getValue(rIdx, i)); } ret.add(row); } } else if (graphDataSet instanceof XYDataset) { XYDataset ds = (XYDataset) graphDataSet; List<Object> headers = new LinkedList<Object>(); headers.add(""); int sc = ds.getSeriesCount(); if (sc > 1) { throw new RuntimeException("Can't do that, sorry"); } for (int i = 0; i < sc; i++) { headers.add(ds.getSeriesKey(i)); } ret.add(headers); int ic = ds.getItemCount(0); String graphType = ((GraphWidgetConfig) config).getGraphType(); boolean stringify = !"ScatterPlot".equals(graphType); for (int i = 0; i < ic; i++) { List<Object> row = new LinkedList<Object>(); Double x = ds.getXValue(0, i); row.add(stringify ? Double.toString(x) : x); row.add(ds.getYValue(0, i)); ret.add(row); } } else if (graphDataSet instanceof PieDataset) { PieDataset ds = (PieDataset) graphDataSet; List<Object> headers = new LinkedList<Object>(); headers.add(((GraphWidgetConfig) config).getDomainLabel()); headers.add(((GraphWidgetConfig) config).getRangeLabel()); ret.add(headers); int total = dataSetLdr.getWidgetTotal(); for (Object key: ds.getKeys()) { List<Object> row = new LinkedList<Object>(); row.add(key.toString()); row.add(ds.getValue((Comparable) key)); ret.add(row); } } else { throw new RuntimeException("Unknown data-set type"); } return ret; } private static XYDataset regress(XYDataset data) { // Determine bounds double xMin = Double.MAX_VALUE, xMax = 0; for (int i = 0; i < data.getSeriesCount(); i++) { for (int j = 0; j < data.getItemCount(i); j++) { double x = data.getXValue(i, j); if (x < xMin) { xMin = x; } if (x > xMax) { xMax = x; } } } // Create 2-point series for each of the original series XYSeriesCollection coll = new XYSeriesCollection(); for (int i = 0; i < data.getSeriesCount(); i++) { int n = data.getItemCount(i); double sx = 0, sy = 0, sxx = 0, sxy = 0; for (int j = 0; j < n; j++) { double x = data.getXValue(i, j); double y = data.getYValue(i, j); sx += x; sy += y; sxx += x * x; sxy += x * y; } double b = (n * sxy - sx * sy) / (n * sxx - sx * sx); double a = sy / n - b * sx / n; XYSeries regr = new XYSeries(data.getSeriesKey(i)); regr.add(xMin, a + b * xMin); regr.add(xMax, a + b * xMax); coll.addSeries(regr); } return coll; } /** * class used to format the p-values on the graph * @author julie */ public class DivNumberFormat extends DecimalFormat { /** * Generated serial-id. */ private static final long serialVersionUID = 8247038065756921184L; private int magnitude; /** * @param magnitude what to multiply the p-value by */ public DivNumberFormat(int magnitude) { this.magnitude = magnitude; } /** * @param number number to format * @param result buffer to put the result in * @param fieldPosition the field position * @return the format */ @Override public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) { return super.format(number * magnitude, result, fieldPosition); } /** * @param number number to format * @param result buffer to put the result in * @param fieldPosition the field position * @return the format */ @Override public StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition) { return super.format(number * magnitude, result, fieldPosition); } } }
package com.yahoo.jdisc.core; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.Version; import org.osgi.framework.hooks.bundle.CollisionHook; import org.osgi.framework.hooks.bundle.EventHook; import org.osgi.framework.hooks.bundle.FindHook; import org.osgi.framework.launch.Framework; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.logging.Logger; /** * A bundle {@link CollisionHook} that contains a set of bundles that are allowed to collide with bundles * that are about to be installed. This class also implements a {@link FindHook} to provide a consistent * view of bundles such that the two sets of duplicate bundles are invisible to each other. * In order to clean up when bundles are uninstalled, this is also a bundle {@link EventHook}. * * Thread safe * * @author gjoranv */ public class BundleCollisionHook implements CollisionHook, EventHook, FindHook { private static Logger log = Logger.getLogger(BundleCollisionHook.class.getName()); private ServiceRegistration<?> registration; private Map<Bundle, BsnVersion> allowedDuplicates = new HashMap<>(5); public void start(BundleContext context) { if (registration != null) { throw new IllegalStateException(); } String[] serviceClasses = {CollisionHook.class.getName(), EventHook.class.getName(), FindHook.class.getName()}; registration = context.registerService(serviceClasses, this, null); } public void stop() { registration.unregister(); registration = null; } /** * Adds a collection of bundles to the allowed duplicates. */ synchronized void allowDuplicateBundles(Collection<Bundle> bundles) { for (var bundle : bundles) { allowedDuplicates.put(bundle, new BsnVersion(bundle)); } } /** * Cleans up the allowed duplicates when a bundle is uninstalled. */ @Override public void event(BundleEvent event, Collection<BundleContext> contexts) { if (event.getType() != BundleEvent.UNINSTALLED) return; synchronized (this) { allowedDuplicates.remove(event.getBundle()); } } /** * Removes duplicates of the allowed duplicate bundles from the given collision candidates. */ @Override public synchronized void filterCollisions(int operationType, Bundle target, Collection<Bundle> collisionCandidates) { Set<Bundle> whitelistedCandidates = new HashSet<>(); for (var bundle : collisionCandidates) { // This is O(n), but n should be small here, plus this is only called when bundles collide. if (allowedDuplicates.containsValue(new BsnVersion(bundle))) { whitelistedCandidates.add(bundle); } } collisionCandidates.removeAll(whitelistedCandidates); } /** * Filters out the set of bundles that should not be visible to the bundle associated with the given context. * If the given context represents one of the allowed duplicates, this method filters out all bundles * that are duplicates of the allowed duplicates. Otherwise this method filters out the allowed duplicates, * so they are not visible to other bundles. */ @Override public synchronized void find(BundleContext context, Collection<Bundle> bundles) { Set<Bundle> bundlesToHide = new HashSet<>(); if (allowedDuplicates.containsKey(context.getBundle())) { for (var bundle : bundles) { // isDuplicate... is O(n), but n should be small here, plus this is only run for duplicate bundles. if (isDuplicateOfAllowedDuplicates(bundle)) { bundlesToHide.add(bundle); } } } else { for (var bundle : bundles) { if (allowedDuplicates.containsKey(bundle)) { bundlesToHide.add(bundle); } } } logHiddenBundles(context, bundlesToHide); bundles.removeAll(bundlesToHide); } private boolean isDuplicateOfAllowedDuplicates(Bundle bundle) { return ! allowedDuplicates.containsKey(bundle) && allowedDuplicates.containsValue(new BsnVersion(bundle)); } private void logHiddenBundles(BundleContext requestingContext, Set<Bundle> hiddenBundles) { if (hiddenBundles.isEmpty()) { log.fine(() -> "No bundles to hide from bundle " + requestingContext.getBundle()); } else { if (requestingContext.getBundle() instanceof Framework) { log.fine(() -> "Requesting bundle is the Framework, so hidden bundles will be visible: " + hiddenBundles); } else { log.info("Hiding bundles from bundle '" + requestingContext.getBundle() + "': " + hiddenBundles); } } } static class BsnVersion { private final String symbolicName; private final Version version; BsnVersion(Bundle bundle) { this.symbolicName = bundle.getSymbolicName(); this.version = bundle.getVersion(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BsnVersion that = (BsnVersion) o; return Objects.equals(symbolicName, that.symbolicName) && version.equals(that.version); } @Override public int hashCode() { return Objects.hash(symbolicName, version); } } }
package org.jetbrains.jps.javac; import com.intellij.execution.process.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.io.BaseOutputReader; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.ChannelGroupFuture; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.util.AttributeKey; import io.netty.util.concurrent.ImmediateEventExecutor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.jps.api.CanceledStatus; import org.jetbrains.jps.builders.java.JavaCompilingTool; import org.jetbrains.jps.cmdline.ClasspathBootstrap; import org.jetbrains.jps.incremental.GlobalContextKey; import javax.tools.*; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; /** * @author Eugene Zhuravlev */ public class ExternalJavacManager extends ProcessAdapter { private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.javac.ExternalJavacServer"); public static final GlobalContextKey<ExternalJavacManager> KEY = GlobalContextKey.create("_external_javac_server_"); public static final int DEFAULT_SERVER_PORT = 7878; public static final String STDOUT_LINE_PREFIX = "JAVAC_PROCESS[STDOUT]"; public static final String STDERR_LINE_PREFIX = "JAVAC_PROCESS[STDERR]"; private static final AttributeKey<UUID> PROCESS_ID_KEY = AttributeKey.valueOf("ExternalJavacServer.ProcessId"); private static final Key<Integer> PROCESS_HASH = Key.create("ExternalJavacServer.SdkHomePath"); private final File myWorkingDir; private final ChannelRegistrar myChannelRegistrar; private int myListenPort = DEFAULT_SERVER_PORT; private final Map<UUID, CompileSession> mySessions = Collections.synchronizedMap(new HashMap<>()); private final Map<UUID, ExternalJavacProcessHandler> myRunningProcesses = Collections.synchronizedMap(new HashMap<>()); private final Map<UUID, Channel> myConnections = Collections.synchronizedMap(new HashMap<>()); // processId->channel private final Executor myExecutor; private boolean myOwnExecutor; private final long myKeepAliveTimeout; /** * @deprecated: use {@link #ExternalJavacManager(File, Executor)} instead with explicit executor parameter */ @Deprecated public ExternalJavacManager(@NotNull final File workingDir) { this(workingDir, ConcurrencyUtil.newSingleThreadExecutor("Javac server event loop pool")); myOwnExecutor = true; } public ExternalJavacManager(@NotNull final File workingDir, @NotNull Executor executor) { this(workingDir, executor, 5 * 60 * 1000L /* 5 minutes default*/); } public ExternalJavacManager(@NotNull final File workingDir, @NotNull Executor executor, long keepAliveTimeout) { myWorkingDir = workingDir; myChannelRegistrar = new ChannelRegistrar(); myExecutor = executor; myKeepAliveTimeout = keepAliveTimeout; } public void start(int listenPort) { final ChannelHandler compilationRequestsHandler = new CompilationRequestsHandler(); final ServerBootstrap bootstrap = new ServerBootstrap() .group(new NioEventLoopGroup(1, myExecutor)) .channel(NioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline().addLast(myChannelRegistrar, new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(JavacRemoteProto.Message.getDefaultInstance()), new ProtobufVarint32LengthFieldPrepender(), new ProtobufEncoder(), compilationRequestsHandler); } }); try { final InetAddress loopback = InetAddress.getByName(null); myChannelRegistrar.add(bootstrap.bind(loopback, listenPort).syncUninterruptibly().channel()); myListenPort = listenPort; } catch (UnknownHostException e) { throw new RuntimeException(e); } } /** * @deprecated Use {@link #forkJavac(String, int, List, List, CompilationPaths, Collection, Map, DiagnosticOutputConsumer, OutputFileConsumer, JavaCompilingTool, CanceledStatus, boolean)} instead */ @Deprecated public boolean forkJavac(String javaHome, int heapSize, List<String> vmOptions, List<String> options, Collection<? extends File> platformCp, Collection<? extends File> classpath, Collection<? extends File> upgradeModulePath, Collection<? extends File> modulePath, Collection<? extends File> sourcePath, Collection<? extends File> files, Map<File, Set<File>> outs, DiagnosticOutputConsumer diagnosticSink, OutputFileConsumer outputSink, JavaCompilingTool compilingTool, CanceledStatus cancelStatus) { return forkJavac( javaHome, heapSize, vmOptions, options, CompilationPaths.create(platformCp, classpath, upgradeModulePath, modulePath, sourcePath), files, outs, diagnosticSink, outputSink, compilingTool, cancelStatus, false ).get(); } public ExternalJavacRunResult forkJavac(String javaHome, int heapSize, List<String> vmOptions, List<String> options, CompilationPaths paths, Collection<? extends File> files, Map<File, Set<File>> outs, DiagnosticOutputConsumer diagnosticSink, OutputFileConsumer outputSink, JavaCompilingTool compilingTool, CanceledStatus cancelStatus, final boolean keepProcessAlive) { try { final ExternalJavacProcessHandler running = findRunningProcess(processHash(javaHome, vmOptions, compilingTool)); final ExternalJavacProcessHandler processHandler = running != null && running.lock()? running : launchExternalJavacProcess( javaHome, heapSize, myListenPort, myWorkingDir, vmOptions, compilingTool, running == null && keepProcessAlive ); final Channel channel = lookupChannel(processHandler.getProcessId()); if (channel != null) { final CompileSession session = new CompileSession( processHandler.getProcessId(), new ExternalJavacMessageHandler(diagnosticSink, outputSink, getEncodingName(options)), cancelStatus ); mySessions.put(session.getId(), session); channel.writeAndFlush(JavacProtoUtil.toMessage(session.getId(), JavacProtoUtil.createCompilationRequest( options, files, paths.getClasspath(), paths.getPlatformClasspath(), paths.getModulePath(), paths.getUpgradeModulePath(), paths.getSourcePath(), outs ))); return session; } else { LOG.warn("Failed to connect to javac process"); } } catch (Throwable e) { LOG.info(e); diagnosticSink.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, e.getMessage())); } return ExternalJavacRunResult.FAILURE; } // returns true if all process handlers terminated @TestOnly public boolean waitForAllProcessHandlers(long time, @NotNull TimeUnit unit) { final Collection<ExternalJavacProcessHandler> processes; synchronized (myRunningProcesses) { processes = new ArrayList<>(myRunningProcesses.values()); } for (ProcessHandler handler : processes) { if (!handler.waitFor(unit.toMillis(time))) { return false; } } return true; } @TestOnly public boolean awaitNettyThreadPoolTermination(long time, @NotNull TimeUnit unit) { if (myOwnExecutor && myExecutor instanceof ExecutorService) { try { return ((ExecutorService)myExecutor).awaitTermination(time, unit); } catch (InterruptedException ignored) { } } return true; } private ExternalJavacProcessHandler findRunningProcess(int processHash) { LOG.debug("findRunningProcess: looking for hash " + processHash); List<ExternalJavacProcessHandler> idleProcesses = null; try { synchronized (myRunningProcesses) { for (Map.Entry<UUID, ExternalJavacProcessHandler> entry : myRunningProcesses.entrySet()) { final ExternalJavacProcessHandler process = entry.getValue(); final Integer hash = PROCESS_HASH.get(process); if (hash != null && hash == processHash) { LOG.debug("findRunningProcess: returning process " + process.getProcessId() + " for hash " + processHash); return process; } if (process.getIdleTime() > myKeepAliveTimeout) { if (idleProcesses == null) { idleProcesses = new ArrayList<>(); } LOG.debug("findRunningProcess: adding " + process.getProcessId() + " to idle list"); idleProcesses.add(process); } } } LOG.debug("findRunningProcess: no running process for " + hashCode() + " is found"); return null; } finally { if (idleProcesses != null) { for (ExternalJavacProcessHandler process : idleProcesses) { shutdownProcess(process); } } } } private static int processHash(String sdkHomePath, List<String> vmOptions, JavaCompilingTool tool) { return Objects.hash(sdkHomePath.replace(File.separatorChar, '/'), vmOptions, tool.getId()); } @Nullable private static String getEncodingName(List<String> options) { int p = options.indexOf("-encoding"); return p >= 0 && p < options.size() - 1 ? options.get(p + 1) : null; } public boolean isRunning() { return !myChannelRegistrar.isEmpty(); } public void stop() { synchronized (myConnections) { for (Map.Entry<UUID, Channel> entry : myConnections.entrySet()) { entry.getValue().writeAndFlush(JavacProtoUtil.toMessage(entry.getKey(), JavacProtoUtil.createShutdownRequest())); } } myChannelRegistrar.close().awaitUninterruptibly(); if (myOwnExecutor && myExecutor instanceof ExecutorService) { final ExecutorService service = (ExecutorService)myExecutor; service.shutdown(); try { service.awaitTermination(15, TimeUnit.SECONDS); } catch (InterruptedException ignored) { } } } public void shutdownIdleProcesses() { List<ExternalJavacProcessHandler> idleProcesses = null; synchronized (myRunningProcesses) { for (ExternalJavacProcessHandler process : myRunningProcesses.values()) { final long idle = process.getIdleTime(); if (idle > myKeepAliveTimeout) { if (idleProcesses == null) { idleProcesses = new ArrayList<>(); } idleProcesses.add(process); } } } if (idleProcesses != null) { for (ExternalJavacProcessHandler process : idleProcesses) { shutdownProcess(process); } } } private boolean shutdownProcess(ExternalJavacProcessHandler process) { UUID processId = process.getProcessId(); LOG.debug("shutdownProcess: shutting down " + processId); final Channel conn = myConnections.get(processId); if (conn != null && process.lock()) { LOG.debug("shutdownProcess: sending shutdown request to " + processId); conn.writeAndFlush(JavacProtoUtil.toMessage(processId, JavacProtoUtil.createShutdownRequest())); return true; } return false; } private ExternalJavacProcessHandler launchExternalJavacProcess(String sdkHomePath, int heapSize, int port, File workingDir, List<String> vmOptions, JavaCompilingTool compilingTool, final boolean keepProcessAlive) throws Exception { final UUID processId = UUID.randomUUID(); final List<String> cmdLine = new ArrayList<>(); appendParam(cmdLine, getVMExecutablePath(sdkHomePath)); appendParam(cmdLine, "-Djava.awt.headless=true"); //appendParam(cmdLine, "-XX:MaxPermSize=150m"); //appendParam(cmdLine, "-XX:ReservedCodeCacheSize=64m"); if (heapSize > 0) { // if the value is zero or negative, use JVM default memory settings final int xms = heapSize / 2; if (xms > 32) { appendParam(cmdLine, "-Xms" + xms + "m"); } appendParam(cmdLine, "-Xmx" + heapSize + "m"); } // debugging //appendParam(cmdLine, "-XX:+HeapDumpOnOutOfMemoryError"); //appendParam(cmdLine, "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5009"); // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language copyProperty(cmdLine, "file.encoding"); copyProperty(cmdLine, "user.language"); copyProperty(cmdLine, "user.country"); copyProperty(cmdLine, "user.region"); copyProperty(cmdLine, "io.netty.noUnsafe"); appendParam(cmdLine, "-D" + ExternalJavacProcess.JPS_JAVA_COMPILING_TOOL_PROPERTY + "=" + compilingTool.getId()); // this will disable standard extensions to ensure javac is loaded from the right tools.jar appendParam(cmdLine, "-Djava.ext.dirs="); appendParam(cmdLine, "-Dlog4j.defaultInitOverride=true"); for (String option : vmOptions) { appendParam(cmdLine, option); } appendParam(cmdLine, "-classpath"); List<File> cp = ClasspathBootstrap.getExternalJavacProcessClasspath(sdkHomePath, compilingTool); appendParam(cmdLine, cp.stream().map(File::getPath).collect(Collectors.joining(File.pathSeparator))); appendParam(cmdLine, ExternalJavacProcess.class.getName()); appendParam(cmdLine, processId.toString()); appendParam(cmdLine, "127.0.0.1"); appendParam(cmdLine, Integer.toString(port)); appendParam(cmdLine, Boolean.toString(keepProcessAlive)); // keep in memory after build finished appendParam(cmdLine, FileUtil.toSystemIndependentName(workingDir.getPath())); if (LOG.isDebugEnabled()) { LOG.debug("starting external compiler: " + cmdLine); } FileUtil.createDirectory(workingDir); final int processHash = processHash(sdkHomePath, vmOptions, compilingTool); final ExternalJavacProcessHandler processHandler = createProcessHandler(processId, new ProcessBuilder(cmdLine).directory(workingDir).start(), StringUtil.join(cmdLine, " "), keepProcessAlive); PROCESS_HASH.set(processHandler, processHash); processHandler.lock(); myRunningProcesses.put(processId, processHandler); LOG.debug("external compiler process registered: id=" + processId + ", hash=" + processHash); processHandler.addProcessListener(this); processHandler.startNotify(); return processHandler; } @Override public void processTerminated(@NotNull ProcessEvent event) { final UUID processId = ((ExternalJavacProcessHandler)event.getProcessHandler()).getProcessId(); LOG.debug("process " + processId + " terminated"); myRunningProcesses.remove(processId); if (myConnections.get(processId) == null) { // only if connection has never been established // otherwise we rely on the fact that ExternalJavacProcess always closes connection before shutdown and clean sessions on ChannelUnregister event cleanSessions(processId); } } private void cleanSessions(UUID processId) { synchronized (mySessions) { for (Iterator<Map.Entry<UUID, CompileSession>> it = mySessions.entrySet().iterator(); it.hasNext(); ) { final CompileSession session = it.next().getValue(); if (processId.equals(session.getProcessId())) { session.setDone(); it.remove(); } } } } @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { final String text = event.getText(); if (!StringUtil.isEmptyOrSpaces(text)) { if (LOG.isTraceEnabled()) { LOG.trace("text from javac: " + text); } String prefix = null; if (outputType == ProcessOutputTypes.STDOUT) { prefix = STDOUT_LINE_PREFIX; } else if (outputType == ProcessOutputTypes.STDERR) { prefix = STDERR_LINE_PREFIX; } if (prefix != null) { List<DiagnosticOutputConsumer> consumers = null; final UUID processId = ((ExternalJavacProcessHandler)event.getProcessHandler()).getProcessId(); synchronized (mySessions) { for (CompileSession session : mySessions.values()) { if (processId.equals(session.getProcessId())) { if (consumers == null) { consumers = new ArrayList<>(); } consumers.add(session.myHandler.getDiagnosticSink()); } } } if (consumers != null) { final String msg = prefix + ": " + text; for (DiagnosticOutputConsumer consumer : consumers) { consumer.outputLineAvailable(msg); } } } } } protected ExternalJavacProcessHandler createProcessHandler(UUID processId, @NotNull Process process, @NotNull String commandLine, boolean keepProcessAlive) { return new ExternalJavacProcessHandler(processId, process, commandLine, keepProcessAlive); } private static void appendParam(List<? super String> cmdLine, String parameter) { if (SystemInfo.isWindows) { if (parameter.contains("\"")) { parameter = StringUtil.replace(parameter, "\"", "\\\""); } else if (parameter.length() == 0) { parameter = "\"\""; } } cmdLine.add(parameter); } private static void copyProperty(List<? super String> cmdLine, String name) { String value = System.getProperty(name); if (value != null) { appendParam(cmdLine, "-D" + name + '=' + value); } } private static String getVMExecutablePath(String sdkHome) { return sdkHome + "/bin/java"; } protected static class ExternalJavacProcessHandler extends BaseOSProcessHandler { private long myIdleSince; private final UUID myProcessId; private final boolean myKeepProcessAlive; private boolean myIsBusy; protected ExternalJavacProcessHandler(UUID processId, @NotNull Process process, @NotNull String commandLine, boolean keepProcessAlive) { super(process, commandLine, null); myProcessId = processId; myKeepProcessAlive = keepProcessAlive; } public UUID getProcessId() { return myProcessId; } public synchronized long getIdleTime() { final long idleSince = myIdleSince; return idleSince <= 0L? 0L : (System.currentTimeMillis() - idleSince); } public synchronized void unlock() { myIdleSince = System.currentTimeMillis(); myIsBusy = false; } public synchronized boolean lock() { myIdleSince = 0L; return !myIsBusy && (myIsBusy = true); } public boolean isKeepProcessAlive() { return myKeepProcessAlive; } @NotNull @Override protected BaseOutputReader.Options readerOptions() { // if keepAlive requested, that means the process will be waiting considerable periods of time without any output return myKeepProcessAlive? BaseOutputReader.Options.BLOCKING : super.readerOptions(); } } @ChannelHandler.Sharable private class CompilationRequestsHandler extends SimpleChannelInboundHandler<JavacRemoteProto.Message> { @Override public void channelInactive(ChannelHandlerContext context) throws Exception { try { final Channel channel = context.channel(); final UUID processId = channel.attr(PROCESS_ID_KEY).get(); if (processId != null) { cleanSessions(processId); myConnections.remove(processId); } } finally { super.channelInactive(context); } } @Override public void channelRead0(final ChannelHandlerContext context, JavacRemoteProto.Message message) throws Exception { // in case of REQUEST_ACK this is a process ID, otherwise this is a sessionId final UUID msgUuid = JavacProtoUtil.fromProtoUUID(message.getSessionId()); CompileSession session = mySessions.get(msgUuid); final ExternalJavacMessageHandler handler = session != null? session.myHandler : null; final JavacRemoteProto.Message.Type messageType = message.getMessageType(); JavacRemoteProto.Message reply = null; try { if (messageType == JavacRemoteProto.Message.Type.RESPONSE) { final JavacRemoteProto.Message.Response response = message.getResponse(); final JavacRemoteProto.Message.Response.Type responseType = response.getResponseType(); if (responseType == JavacRemoteProto.Message.Response.Type.REQUEST_ACK) { // in this case msgUuid is a process ID, so we need to save the channel, associated with the process final Channel channel = context.channel(); channel.attr(PROCESS_ID_KEY).set(msgUuid); synchronized (myConnections) { myConnections.put(msgUuid, channel); myConnections.notifyAll(); } } else if (handler != null) { final boolean terminateOk = handler.handleMessage(message); if (terminateOk) { session.setDone(); mySessions.remove(session.getId()); final ExternalJavacProcessHandler process = myRunningProcesses.get(session.getProcessId()); if (process != null) { process.unlock(); } } else if (session.isCancelRequested()) { reply = JavacProtoUtil.toMessage(msgUuid, JavacProtoUtil.createCancelRequest()); } } else { reply = JavacProtoUtil.toMessage(msgUuid, JavacProtoUtil.createCancelRequest()); } } else { reply = JavacProtoUtil.toMessage(msgUuid, JavacProtoUtil.createFailure("Unsupported message: " + messageType.name(), null)); } } finally { if (reply != null) { context.channel().writeAndFlush(reply); } } } } private Channel lookupChannel(UUID processId) { Channel channel = null; synchronized (myConnections) { channel = myConnections.get(processId); LOG.debug("lookupChannel: channel for " + processId + " is " + channel); while (channel == null) { if (!myRunningProcesses.containsKey(processId)) { LOG.debug("lookupChannel: no process for " + processId); break; // the process is already gone } try { myConnections.wait(300L); } catch (InterruptedException ignored) { } channel = myConnections.get(processId); LOG.debug("lookupChannel: after wait channel for " + processId + " is " + channel); } } return channel; } @ChannelHandler.Sharable private static final class ChannelRegistrar extends ChannelInboundHandlerAdapter { private final ChannelGroup openChannels = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); public boolean isEmpty() { return openChannels.isEmpty(); } public void add(@NotNull Channel serverChannel) { assert serverChannel instanceof ServerChannel; openChannels.add(serverChannel); } @Override public void channelActive(ChannelHandlerContext context) throws Exception { // we don't need to remove channel on close - ChannelGroup do it openChannels.add(context.channel()); super.channelActive(context); } public ChannelGroupFuture close() { EventLoopGroup eventLoopGroup = null; for (Channel channel : openChannels) { if (channel instanceof ServerChannel) { eventLoopGroup = channel.eventLoop().parent(); break; } } try { return openChannels.close(); } finally { if (eventLoopGroup != null) { eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS); } } } } private class CompileSession extends ExternalJavacRunResult{ private final UUID myId; private final UUID myProcessId; private final CanceledStatus myCancelStatus; private final ExternalJavacMessageHandler myHandler; private final Semaphore myDone = new Semaphore(); CompileSession(@NotNull UUID processId, @NotNull ExternalJavacMessageHandler handler, CanceledStatus cancelStatus) { myProcessId = processId; myCancelStatus = cancelStatus; myId = UUID.randomUUID(); myHandler = handler; myDone.down(); } @NotNull public UUID getId() { return myId; } @NotNull public UUID getProcessId() { return myProcessId; } @Override public boolean isDone() { return myDone.isUp(); } public void setDone() { myDone.up(); } public boolean isTerminatedSuccessfully() { return myHandler.isTerminatedSuccessfully(); } boolean isCancelRequested() { return myCancelStatus.isCanceled(); } @NotNull @Override public Boolean get() { while (true) { try { if (myDone.waitForUnsafe(300L)) { break; } } catch (InterruptedException ignored) { } notifyCancelled(); } boolean successfully = isTerminatedSuccessfully(); if (!successfully) { LOG.debug("Javac compile session " + myId + " in process " + myProcessId + "didn't terminate successfully"); } return successfully; } @NotNull @Override public Boolean get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, TimeoutException { if (!myDone.waitForUnsafe(unit.toMillis(timeout))) { notifyCancelled(); // if execution continues, just notify about timeout throw new TimeoutException(); } boolean successfully = isTerminatedSuccessfully(); if (!successfully) { LOG.debug("Javac compile session " + myId + " in process " + myProcessId + "didn't terminate successfully"); } return successfully; } private void notifyCancelled() { if (isCancelRequested() && myRunningProcesses.containsKey(myProcessId)) { final Channel channel = myConnections.get(myProcessId); if (channel != null) { channel.writeAndFlush(JavacProtoUtil.toMessage(myId, JavacProtoUtil.createCancelRequest())); } } } } }
package com.alibaba.jstorm.task; import backtype.storm.generated.GlobalStreamId; import java.util.*; public class DownstreamTasks { private Map<GlobalStreamId, List<CommunicationTree>> expandingTrees = new HashMap<GlobalStreamId, List<CommunicationTree>>(); private Map<GlobalStreamId, List<CommunicationTree>> nonExpandingTrees = new HashMap<GlobalStreamId, List<CommunicationTree>>(); private Map<Integer, Map<GlobalStreamId, Set<Integer>>> downstreamTaskCache = new HashMap<Integer, Map<GlobalStreamId, Set<Integer>>>(); public int getMapping(GlobalStreamId streamId, int taskId, int targetId) { if (nonExpandingTrees.containsKey(streamId)) { List<CommunicationTree> trees = nonExpandingTrees.get(streamId); for (CommunicationTree tree : trees) { if (tree.rootTasks().contains(targetId)) { TreeSet<Integer> childTasks = tree.getChildTasks(taskId); if (!childTasks.isEmpty()) { childTasks.first(); } } } } return targetId; } public boolean isSkip(GlobalStreamId streamId, int taskId, int targetId) { if (expandingTrees.containsKey(streamId)) { List<CommunicationTree> trees = expandingTrees.get(streamId); for (CommunicationTree tree : trees) { TreeSet<Integer> childTasks = tree.getChildTasks(taskId); if (!childTasks.isEmpty() && childTasks.contains(targetId)) { return false; } } return true; } return false; } /** * Add a collective tree * @param id stream id * @param tree tree */ public void addCollectiveTree(GlobalStreamId id, CommunicationTree tree) { // we keep the expanding trees and non expanding trees in two separate maps if (tree.isExpandingTree()) { List<CommunicationTree> trees = expandingTrees.get(id); if (trees == null) { trees = new ArrayList<CommunicationTree>(); expandingTrees.put(id, trees); } trees.add(tree); } else { List<CommunicationTree> trees = nonExpandingTrees.get(id); if (trees == null) { trees = new ArrayList<CommunicationTree>(); nonExpandingTrees.put(id, trees); } trees.add(tree); } } /** * Get all the downstream tasks of a given task * @param taskId task id * @return a map of all the downstream tasks, keyed by the stream and component id */ public Map<GlobalStreamId, Set<Integer>> allDownStreamTasks(int taskId) { if (downstreamTaskCache.containsKey(taskId)) { return downstreamTaskCache.get(taskId); } else { Map<GlobalStreamId, Set<Integer>> allTasks = new HashMap<GlobalStreamId, Set<Integer>>(); for (Map.Entry<GlobalStreamId, List<CommunicationTree>> e : expandingTrees.entrySet()) { GlobalStreamId id = e.getKey(); List<CommunicationTree> treeList = e.getValue(); TreeSet<Integer> treeSet = new TreeSet<Integer>(); for (CommunicationTree t : treeList) { treeSet.addAll(t.getChildTasks(taskId)); } allTasks.put(id, treeSet); } for (Map.Entry<GlobalStreamId, List<CommunicationTree>> e : nonExpandingTrees.entrySet()) { GlobalStreamId id = e.getKey(); List<CommunicationTree> treeList = e.getValue(); Set<Integer> treeSet = allTasks.get(id); if (treeSet == null) { treeSet = new TreeSet<Integer>(); allTasks.put(id, treeSet); } for (CommunicationTree t : treeList) { treeSet.addAll(t.getChildTasks(taskId)); } } downstreamTaskCache.put(taskId, allTasks); return allTasks; } } }
package com.fsck.k9.ui.messageview; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.widget.Toast; import com.fsck.k9.K9; import com.fsck.k9.R; import com.fsck.k9.helper.FileHelper; import com.fsck.k9.helper.UrlEncodingHelper; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.provider.AttachmentProvider.AttachmentProviderColumns; import org.apache.commons.io.IOUtils; class DownloadImageTask extends AsyncTask<String, Void, String> { private static final String[] ATTACHMENT_PROJECTION = new String[] { AttachmentProviderColumns._ID, AttachmentProviderColumns.DISPLAY_NAME }; private static final int DISPLAY_NAME_INDEX = 1; private final Context context; public DownloadImageTask(Context context) { this.context = context.getApplicationContext(); } @Override protected String doInBackground(String... params) { String urlString = params[0]; try { boolean externalImage = urlString.startsWith("http"); String filename = null; String mimeType = null; InputStream in = null; try { if (externalImage) { URL url = new URL(urlString); URLConnection conn = url.openConnection(); in = conn.getInputStream(); String path = url.getPath(); // Try to get the filename from the URL int start = path.lastIndexOf("/"); if (start != -1 && start + 1 < path.length()) { filename = UrlEncodingHelper.decodeUtf8(path.substring(start + 1)); } else { // Use a dummy filename if necessary filename = "saved_image"; } // Get the MIME type if we couldn't find a file extension if (filename.indexOf('.') == -1) { mimeType = conn.getContentType(); } } else { ContentResolver contentResolver = context.getContentResolver(); Uri uri = Uri.parse(urlString); // Get the filename from AttachmentProvider Cursor cursor = contentResolver.query(uri, ATTACHMENT_PROJECTION, null, null, null); if (cursor != null) { try { if (cursor.moveToNext()) { filename = cursor.getString(DISPLAY_NAME_INDEX); } } finally { cursor.close(); } } // Use a dummy filename if necessary if (filename == null) { filename = "saved_image"; } // Get the MIME type if we couldn't find a file extension if (filename.indexOf('.') == -1) { mimeType = contentResolver.getType(uri); } in = contentResolver.openInputStream(uri); } filename = getFileNameWithExtension(filename, mimeType); String sanitized = FileHelper.sanitizeFilename(filename); File directory = new File(K9.getAttachmentDefaultPath()); File file = FileHelper.createUniqueFile(directory, sanitized); FileOutputStream out = new FileOutputStream(file); try { IOUtils.copy(in, out); out.flush(); } finally { out.close(); } return file.getName(); } finally { if (in != null) { in.close(); } } } catch (Exception e) { e.printStackTrace(); return null; } } private String getFileNameWithExtension(String filename, String mimeType) { if (filename.indexOf('.') != -1) { return filename; } // Use JPEG as fallback String extension = "jpeg"; if (mimeType != null) { String extensionFromMimeType = MimeUtility.getExtensionByMimeType(mimeType); if (extensionFromMimeType != null) { extension = extensionFromMimeType; } } return filename + "." + extension; } @Override protected void onPostExecute(String filename) { String text; if (filename == null) { text = context.getString(R.string.image_saving_failed); } else { text = context.getString(R.string.image_saved_as, filename); } Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } }
package squeek.applecore.example; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import squeek.applecore.api.food.FoodValues; import squeek.applecore.api.food.IEdible; import squeek.applecore.api.food.ItemFoodProxy; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Optional; @Optional.Interface(iface = "squeek.applecore.api.food.IEdible", modid = "AppleCore") public class ItemNonStandardFood extends Item implements IEdible { public ItemNonStandardFood() { } @Optional.Method(modid = "AppleCore") @Override public FoodValues getFoodValues(ItemStack itemStack) { return new FoodValues(1, 1f); } // This needs to be abstracted into an Optional method, // otherwise the ItemFoodProxy reference will cause problems @Optional.Method(modid = "AppleCore") public void onEatenCompatibility(ItemStack itemStack, EntityPlayer player) { // one possible compatible method player.getFoodStats().func_151686_a(new ItemFoodProxy(this), itemStack); // another possible compatible method: // new ItemFoodProxy(this).onEaten(itemStack, player); } @Override public ItemStack onEaten(ItemStack itemStack, World world, EntityPlayer player) { --itemStack.stackSize; if (Loader.isModLoaded("AppleCore")) { onEatenCompatibility(itemStack, player); } else { // this method is not compatible with AppleCore player.getFoodStats().addStats(1, 1f); } world.playSoundAtEntity(player, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); return itemStack; } @Override public EnumAction getItemUseAction(ItemStack itemStack) { return EnumAction.eat; } @Override public int getMaxItemUseDuration(ItemStack itemStack) { return 32; } @Override public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { if (player.canEat(true)) { player.setItemInUse(itemStack, getMaxItemUseDuration(itemStack)); } return itemStack; } }
package org.broadinstitute.sting.utils; /** * BaseUtils contains some basic utilities for manipulating nucleotides. * * @author Kiran Garimella */ public class BaseUtils { /** Private constructor. No instantiating this class! */ private BaseUtils() {} /** * Converts a simple base to a base index * * @param base [AaCcGgTt] * @return 0, 1, 2, 3, or -1 if the base can't be understood */ static public int simpleBaseToBaseIndex(char base) { switch (base) { case 'A': case 'a': return 0; case 'C': case 'c': return 1; case 'G': case 'g': return 2; case 'T': case 't': return 3; default: return -1; } } /** * Converts a base index to a simple base * * @param baseIndex 0, 1, 2, 3 * @return A, C, G, T, or '.' if the index can't be understood */ static public char baseIndexToSimpleBase(int baseIndex) { switch (baseIndex) { case 0: return 'A'; case 1: return 'C'; case 2: return 'G'; case 3: return 'T'; default: return '.'; } } /** * Converts a base index to a base index representing its cross-talk partner * * @param baseIndex 0, 1, 2, 3 * @return 1, 0, 3, 2, or -1 if the index can't be understood */ static public int crossTalkPartnerIndex(int baseIndex) { switch (baseIndex) { case 0: return 1; // A -> C case 1: return 0; // C -> A case 2: return 3; // G -> T case 3: return 2; // T -> G default: return -1; } } /** * Converts a base to the base representing its cross-talk partner * * @param base [AaCcGgTt] * @return C, A, T, G, or '.' if the base can't be understood */ static public char crossTalkPartnerBase(char base) { return baseIndexToSimpleBase(crossTalkPartnerIndex(simpleBaseToBaseIndex(base))); } /** * Return the complement of a base index. * * @param baseIndex the base index (0:A, 1:C, 2:G, 3:T) * @return the complementary base index */ static public byte complementIndex(int baseIndex) { switch (baseIndex) { case 0: return 3; // a -> t case 1: return 2; // c -> g case 2: return 1; // g -> c case 3: return 0; // t -> a default: return -1; // wtf? } } /** * Return the complement of a base. * * @param base the base [AaCcGgTt] * @return the complementary base */ static public byte simpleComplement(char base) { switch (base) { case 'A': case 'a': return 'T'; case 'C': case 'c': return 'G'; case 'G': case 'g': return 'C'; case 'T': case 't': return 'A'; default: return '.'; } } /** * Reverse complement a byte array of bases (that is, chars casted to bytes, *not* base indices in byte form) * * @param bases the byte array of bases * @return the reverse complement of the base byte array */ static public byte[] simpleReverseComplement(byte[] bases) { byte[] rcbases = new byte[bases.length]; for (int i = 0; i < bases.length; i++) { rcbases[i] = simpleComplement((char) bases[bases.length - 1]); } return rcbases; } /** * Reverse complement a String of bases. Preserves ambiguous bases. * * @param bases the String of bases * @return the reverse complement of the String */ static public String simpleReverseComplement(String bases) { char[] rcbases = new char[bases.length()]; for (int i = 0; i < bases.length(); i++) { char base = bases.charAt(bases.length() - 1); char rcbase = (base == 'N' || base == '.') ? base : (char) simpleComplement(base); rcbases[i] = rcbase; } return new String(rcbases); } /** * Reverse a byte array of bases * @param bases the byte array of bases * @return the reverse of the base byte array */ static public byte[] reverse(byte[] bases) { byte[] rcbases = new byte[bases.length]; for (int i = 0; i < bases.length; i++) { rcbases[i] = bases[bases.length - 1]; } return rcbases; } }
package scrollfullscreen.ui.adapter; import android.view.View; import android.widget.AbsListView; import scrollfullscreen.ScrollDetector; /** * Adapter for ListView, GridView * <p> * Dispatch AbsListView.OnScrollListener to ScrollDetector.onScrollChanged. * Because ListView's OnScrollChangedListener don't respond true height. * </p> */ public class ListViewAdapter implements AbsListView.OnScrollListener { private ScrollDetector scrollDetector; private AbsListView.OnScrollListener proxyOnScrollListener; private static final int UNDEFINED_FIRST_VISIBLE_ITEM_VALUE = Integer.MIN_VALUE; private int previousFirstVisibleItem = UNDEFINED_FIRST_VISIBLE_ITEM_VALUE; private static final int UNDEFINED_ROW_HEIGHT = Integer.MIN_VALUE; private int rowHeight = UNDEFINED_ROW_HEIGHT; private int scrollState; private ListViewAdapter(ScrollDetector scrollDetector) { this.scrollDetector = scrollDetector; } private void setRowHeight(int rowHeight) { this.rowHeight = rowHeight; } private void setProxyOnScrollListener(AbsListView.OnScrollListener proxyOnScrollListener) { this.proxyOnScrollListener = proxyOnScrollListener; } /** * Dummy for proxy * * @param view * @param scrollState */ @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (proxyOnScrollListener != null) { proxyOnScrollListener.onScrollStateChanged(view, scrollState); } this.scrollState = scrollState; } /** * Dispatch AbsListView.OnScrollListener to ScrollDetector.onScrollChanged * * @param view * @param firstVisibleItem * @param visibleItemCount * @param totalItemCount */ @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (proxyOnScrollListener != null) { proxyOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } // Calculate row height // NOTE: this method optimized for that all rows are same height if (rowHeight == UNDEFINED_ROW_HEIGHT && view.getAdapter().getCount() > 0) { int viewCount = view.getAdapter().getCount(); // ListView includes headers and footers in view count // Choose center of views for pick up row view int viewCountCenter = viewCount / 2; View rowView = view.getAdapter().getView(viewCountCenter, null, null); rowView.measure(0, 0); int measuredRowHeight = rowView.getMeasuredHeight(); if (measuredRowHeight > 0) { rowHeight = measuredRowHeight; } } if (previousFirstVisibleItem != UNDEFINED_FIRST_VISIBLE_ITEM_VALUE) { if (scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { scrollDetector.onScrollChanged(0, firstVisibleItem * rowHeight, 0, previousFirstVisibleItem * rowHeight); } } previousFirstVisibleItem = firstVisibleItem; } /** * Reset current states */ public void reset() { previousFirstVisibleItem = UNDEFINED_FIRST_VISIBLE_ITEM_VALUE; scrollDetector.reset(); } /** * Provide ListViewAdapter instance */ public static class Builder { ListViewAdapter listViewAdapter; /** * Constructor * @param scrollDetector */ public Builder(ScrollDetector scrollDetector) { listViewAdapter = new ListViewAdapter(scrollDetector); } /** * Specify listView row height * <p>It's optional. If this parameter is not specified, this module will measure row height automatically.</p> * * @param rowHeight * @return */ public Builder rowHeight(int rowHeight) { listViewAdapter.setRowHeight(rowHeight); return this; } /** * Proxy scroll method to your OnScrollListener * <p>If you always used your AbsListView.OnScrollListener (e.g. for paging), * you would use this method for proxy scroll event</p> * @param onScrollListener * @return */ public Builder proxyTo(AbsListView.OnScrollListener onScrollListener) { listViewAdapter.setProxyOnScrollListener(onScrollListener); return this; } /** * Creates a ListViewAdapter with the arguments supplied to this builder. * @return ListViewAdapter instance */ public ListViewAdapter build() { return listViewAdapter; } } }
package com.facebook.litho.processor; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; 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.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.facebook.common.internal.ImmutableList; import com.facebook.litho.annotations.Event; import com.facebook.litho.annotations.FromEvent; import com.facebook.litho.annotations.OnCreateInitialState; import com.facebook.litho.annotations.OnCreateTreeProp; import com.facebook.litho.annotations.OnEvent; import com.facebook.litho.annotations.OnLoadStyle; import com.facebook.litho.annotations.OnUpdateState; import com.facebook.litho.annotations.Param; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.litho.annotations.State; import com.facebook.litho.annotations.TreeProp; import com.facebook.litho.javapoet.JPUtil; import com.facebook.litho.processor.GetTreePropsForChildrenMethodBuilder.CreateTreePropMethodData; import com.facebook.litho.specmodels.model.ClassNames; import com.facebook.litho.specmodels.model.PropDefaultModel; import com.facebook.litho.specmodels.processor.PropDefaultsExtractor; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import static com.facebook.litho.processor.Utils.capitalize; import static com.facebook.litho.processor.Visibility.PRIVATE; import static com.facebook.litho.specmodels.generator.GeneratorConstants.DELEGATE_FIELD_NAME; import static com.facebook.litho.specmodels.generator.GeneratorConstants.SPEC_INSTANCE_NAME; import static java.util.Arrays.asList; import static javax.lang.model.type.TypeKind.ARRAY; import static javax.lang.model.type.TypeKind.DECLARED; import static javax.lang.model.type.TypeKind.DOUBLE; import static javax.lang.model.type.TypeKind.FLOAT; import static javax.lang.model.type.TypeKind.TYPEVAR; import static javax.lang.model.type.TypeKind.VOID; public class Stages { public static final String IMPL_CLASS_NAME_SUFFIX = "Impl"; private static final String INNER_IMPL_BUILDER_CLASS_NAME = "Builder"; private static final String STATE_UPDATE_IMPL_NAME_SUFFIX = "StateUpdate"; public static final String STATE_CONTAINER_IMPL_NAME_SUFFIX = "StateContainerImpl"; public static final String STATE_CONTAINER_IMPL_MEMBER = "mStateContainerImpl"; private static final String REQUIRED_PROPS_NAMES = "REQUIRED_PROPS_NAMES"; private static final String REQUIRED_PROPS_COUNT = "REQUIRED_PROPS_COUNT"; private static final int ON_STYLE_PROPS = 1; private static final int ON_CREATE_INITIAL_STATE = 1; private final boolean mSupportState; public enum StaticFlag { STATIC, NOT_STATIC } public enum StyleableFlag { STYLEABLE, NOT_STYLEABLE } // Using these names in props might cause conflicts with the method names in the // component's generated layout builder class so we trigger a more user-friendly // error if the component tries to use them. This list should be kept in sync // with BaseLayoutBuilder. private static final String[] RESERVED_PROP_NAMES = new String[] { "withLayout", "key", "loadingEventHandler", }; private static final Class<Annotation>[] TREE_PROP_ANNOTATIONS = new Class[] { TreeProp.class, }; private static final Class<Annotation>[] PROP_ANNOTATIONS = new Class[] { Prop.class, }; private static final Class<Annotation>[] STATE_ANNOTATIONS = new Class[] { State.class, }; private final ProcessingEnvironment mProcessingEnv; private final TypeElement mSourceElement; private final String mQualifiedClassName; private final Class<Annotation>[] mStageAnnotations; private final Class<Annotation>[] mInterStagePropAnnotations; private final Class<Annotation>[] mParameterAnnotations; private final TypeSpec.Builder mClassTypeSpec; private final List<TypeVariableName> mTypeVariables; private final List<TypeElement> mEventDeclarations; private final Map<String, String> mPropJavadocs; private final String mSimpleClassName; private String mSourceDelegateAccessorName = DELEGATE_FIELD_NAME; private List<VariableElement> mProps; private List<VariableElement> mOnCreateInitialStateDefinedProps; private ImmutableList<PropDefaultModel> mPropDefaults; private List<VariableElement> mTreeProps; private final Map<String, VariableElement> mStateMap = new LinkedHashMap<>(); // Map of name to VariableElement, for members of the inner implementation class, in order private LinkedHashMap<String, VariableElement> mImplMembers; private List<Parameter> mImplParameters; private final Map<String, TypeMirror> mExtraStateMembers; // List of methods that have @OnEvent on it. private final List<ExecutableElement> mOnEventMethods; // List of methods annotated with @OnUpdateState. private final List<ExecutableElement> mOnUpdateStateMethods; private final List<ExecutableElement> mOnCreateTreePropsMethods; // List of methods that define stages (e.g. OnCreateLayout) private List<ExecutableElement> mStages; public TypeElement getSourceElement() { return mSourceElement; } public Stages( ProcessingEnvironment processingEnv, TypeElement sourceElement, String qualifiedClassName, Class<Annotation>[] stageAnnotations, Class<Annotation>[] interStagePropAnnotations, TypeSpec.Builder typeSpec, List<TypeVariableName> typeVariables, boolean supportState, Map<String, TypeMirror> extraStateMembers, List<TypeElement> eventDeclarations, Map<String, String> propJavadocs) { mProcessingEnv = processingEnv; mSourceElement = sourceElement; mQualifiedClassName = qualifiedClassName; mStageAnnotations = stageAnnotations; mInterStagePropAnnotations = interStagePropAnnotations; mClassTypeSpec = typeSpec; mTypeVariables = typeVariables; mEventDeclarations = eventDeclarations; mPropJavadocs = propJavadocs; final List<Class<Annotation>> parameterAnnotations = new ArrayList<>(); parameterAnnotations.addAll(asList(PROP_ANNOTATIONS)); parameterAnnotations.addAll(asList(STATE_ANNOTATIONS)); parameterAnnotations.addAll(asList(mInterStagePropAnnotations)); parameterAnnotations.addAll(asList(TREE_PROP_ANNOTATIONS)); mParameterAnnotations = parameterAnnotations.toArray( new Class[parameterAnnotations.size()]); mSupportState = supportState; mSimpleClassName = Utils.getSimpleClassName(mQualifiedClassName); mOnEventMethods = Utils.getAnnotatedMethods(mSourceElement, OnEvent.class); mOnUpdateStateMethods = Utils.getAnnotatedMethods(mSourceElement, OnUpdateState.class); mOnCreateTreePropsMethods = Utils.getAnnotatedMethods(mSourceElement, OnCreateTreeProp.class); mExtraStateMembers = extraStateMembers; validateOnEventMethods(); populatePropDefaults(); populateStages(); validateAnnotatedParameters(); populateOnCreateInitialStateDefinedProps(); populateProps(); populateTreeProps(); if (mSupportState) { populateStateMap(); } validatePropDefaults(); populateImplMembers(); populateImplParameters(); validateStyleOutputs(); } private boolean isInterStagePropAnnotationValidInStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); final int stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } // This logic relies on the fact that there are prop annotations for each stage (except for // some number at the end) return interStagePropIndex < stageIndex; } private boolean doesInterStagePropAnnotationMatchStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); // Null stage is allowed and indicates prop int stageIndex = -1; if (stage != null) { stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } } return interStagePropIndex == stageIndex; } private void validateOnEventMethods() { final Map<String, Boolean> existsMap = new HashMap<>(); for (ExecutableElement element : mOnEventMethods) { if (existsMap.containsKey(element.getSimpleName().toString())) { throw new ComponentsProcessingException( element, "@OnEvent declared methods must have unique names"); } final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final TypeMirror returnType = Utils.getAnnotationParameter( mProcessingEnv, eventClass.asElement(), Event.class, "returnType"); if (!mProcessingEnv.getTypeUtils().isSameType(element.getReturnType(), returnType)) { throw new ComponentsProcessingException( element, "Method " + element.getSimpleName() + " must return " + returnType + ", since that is what " + eventClass + " expects."); } final List<? extends VariableElement> parameters = Utils.getEnclosedFields((TypeElement) eventClass.asElement()); for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) { boolean hasMatchingParameter = false; for (VariableElement parameter : parameters) { if (parameter.getSimpleName().equals(v.getSimpleName()) && parameter.asType().toString().equals(v.asType().toString())) { hasMatchingParameter = true; break; } } if (!hasMatchingParameter) { throw new ComponentsProcessingException( v, v.getSimpleName() + " of this type is not a member of " + eventClass); } return; } existsMap.put(element.getSimpleName().toString(), true); } } /** * Ensures that the declared events don't clash with the predefined ones. */ private void validateEventDeclarations() { for (TypeElement eventDeclaration : mEventDeclarations) { final Event eventAnnotation = eventDeclaration.getAnnotation(Event.class); if (eventAnnotation == null) { throw new ComponentsProcessingException( eventDeclaration, "Events must be declared with the @Event annotation, event is: " + eventDeclaration); } final List<? extends VariableElement> fields = Utils.getEnclosedFields(eventDeclaration); for (VariableElement field : fields) { if (!field.getModifiers().contains(Modifier.PUBLIC) || field.getModifiers().contains(Modifier.FINAL)) { throw new ComponentsProcessingException( field, "Event fields must be declared as public non-final"); } } } } private void validateStyleOutputs() { final ExecutableElement delegateMethod = Utils.getAnnotatedMethod( mSourceElement, OnLoadStyle.class); if (delegateMethod == null) { return; } final List<? extends VariableElement> parameters = delegateMethod.getParameters(); if (parameters.size() < ON_STYLE_PROPS) { throw new ComponentsProcessingException( delegateMethod, "The @OnLoadStyle method should have an ComponentContext" + "followed by Output parameters matching component create."); } final TypeName firstParamType = ClassName.get(parameters.get(0).asType()); if (!firstParamType.equals(ClassNames.COMPONENT_CONTEXT)) { throw new ComponentsProcessingException( parameters.get(0), "The first argument of the @OnLoadStyle method should be an ComponentContext."); } for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final TypeMirror outputType = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT); if (outputType == null) { throw new ComponentsProcessingException( parameters.get(i), "The @OnLoadStyle method should have only have Output arguments matching " + "component create."); } final Types typeUtils = mProcessingEnv.getTypeUtils(); final String name = v.getSimpleName().toString(); boolean matchesProp = false; for (Element prop : mProps) { if (!prop.getSimpleName().toString().equals(name)) { continue; } matchesProp = true; if (!typeUtils.isAssignable(prop.asType(), outputType)) { throw new ComponentsProcessingException( v, "Searching for prop \"" + name + "\" of type " + ClassName.get(outputType) + " but found prop with the same name of type " + ClassName.get(prop.asType())); } } if (!matchesProp) { throw new ComponentsProcessingException( v, "Output named '" + v.getSimpleName() + "' does not match any prop " + "in the component."); } } } private void validateAnnotatedParameters() { final List<PrintableException> exceptions = new ArrayList<>(); final Map<String, VariableElement> variableNameToElementMap = new HashMap<>(); final Map<String, Class<? extends Annotation>> outputVariableToStage = new HashMap<>(); for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage == null) { continue; } // Enforce #5: getSpecDefinedParameters will verify that parameters don't have duplicate // annotations for (VariableElement v : getSpecDefinedParameters(stage)) { try { final String variableName = v.getSimpleName().toString(); final Annotation interStagePropAnnotation = getInterStagePropAnnotation(v); final boolean isOutput = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT) != null; if (isOutput) { outputVariableToStage.put(variableName, stageAnnotation); } // Enforce if (interStagePropAnnotation != null) { final Class<? extends Annotation> outputStage = outputVariableToStage.get(variableName); if (!doesInterStagePropAnnotationMatchStage( interStagePropAnnotation.annotationType(), outputStage)) { throw new ComponentsProcessingException( v, "Inter-stage prop declaration is incorrect, the same name and type must be " + "used in every method where the inter-stage prop is declared."); } } // Enforce if (interStagePropAnnotation != null && !isInterStagePropAnnotationValidInStage( interStagePropAnnotation.annotationType(), stageAnnotation)) { throw new ComponentsProcessingException( v, "Inter-stage create must refer to previous stages."); } final VariableElement existingType = variableNameToElementMap.get(variableName); if (existingType != null && !isSameType(existingType.asType(), v.asType())) { // We have a type mis-match. This is allowed, provided that the previous type is an // outputand the new type is an prop, and the type argument of the output matches the // prop. In the future, we may want to allow stages to modify outputs from previous // stages, but for now we disallow it. // Enforce #1 and #2 if ((getInterStagePropAnnotation(v) == null || Utils.getGenericTypeArgument(existingType.asType(), ClassNames.OUTPUT) == null) && Utils.getGenericTypeArgument(existingType.asType(), ClassNames.DIFF) == null) { throw new ComponentsProcessingException( v, "Inconsistent type for '" + variableName + "': '" + existingType.asType() + "' and '" + v.asType() + "'"); } } else if (existingType == null) { // We haven't see a parameter with this name yet. Therefore it must be either @Prop, // @State or an output. final boolean isFromProp = getParameterAnnotation(v, PROP_ANNOTATIONS) != null; final boolean isFromState = getParameterAnnotation(v, STATE_ANNOTATIONS) != null; final boolean isFromTreeProp = getParameterAnnotation(v, TREE_PROP_ANNOTATIONS) != null; if (isFromState && !mSupportState) { throw new ComponentsProcessingException( v, "State is not supported in this kind of Spec."); } if (!isFromProp && !isFromState && !isOutput && !isFromTreeProp) { throw new ComponentsProcessingException( v, "Inter-stage prop declared without source."); } } // Enforce final Prop propAnnotation = v.getAnnotation(Prop.class); if (propAnnotation != null) { for (String reservedPropName : RESERVED_PROP_NAMES) { if (reservedPropName.equals(variableName)) { throw new ComponentsProcessingException( v, "'" + reservedPropName + "' is a reserved prop name used by " + "the component's layout builder. Please use another name."); } } // Enforce final boolean hasDefaultValue = hasDefaultValue(v); if (hasDefaultValue && !propAnnotation.optional()) { throw new ComponentsProcessingException( v, "Prop is not optional but has a declared default value."); } // Enforce if (existingType != null) { final Prop existingPropAnnotation = existingType.getAnnotation(Prop.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The prop '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this prop is declared identically."); } } } // Enforce TypeName typeName; try { typeName = ClassName.get(v.asType()); } catch (IllegalArgumentException e) { throw new ComponentsProcessingException( v, "Prop type does not exist"); } // Enforce final List<ClassName> illegalPropTypes = Arrays.asList( ClassNames.COMPONENT_LAYOUT, ClassNames.COMPONENT_LAYOUT_BUILDER, ClassNames.COMPONENT_LAYOUT_CONTAINER_BUILDER, ClassNames.COMPONENT_BUILDER, ClassNames.COMPONENT_BUILDER_WITH_LAYOUT, ClassNames.REFERENCE_BUILDER); if (illegalPropTypes.contains(typeName)) { throw new ComponentsProcessingException( v, "Props may not be declared with the following types:" + illegalPropTypes); } } variableNameToElementMap.put(variableName, v); } catch (PrintableException e) { exceptions.add(e); } } } if (!exceptions.isEmpty()) { throw new MultiPrintableException(exceptions); } } private boolean hasSameAnnotations(VariableElement v1, VariableElement v2) { final List<? extends AnnotationMirror> v1Annotations = v1.getAnnotationMirrors(); final List<? extends AnnotationMirror> v2Annotations = v2.getAnnotationMirrors(); if (v1Annotations.size() != v2Annotations.size()) { return false; } final int count = v1Annotations.size(); for (int i = 0; i < count; i++) { final AnnotationMirror a1 = v1Annotations.get(i); final AnnotationMirror a2 = v2Annotations.get(i); // Some object in this hierarchy don't implement equals correctly. // They do however produce very nice strings representations which we can compare instead. if (!a1.toString().equals(a2.toString())) { return false; } } return true; } public void validateStatic() { validateStaticFields(); validateStaticMethods(); } private void validateStaticFields() { for (Element element : mSourceElement.getEnclosedElements()) { if (element.getKind() == ElementKind.FIELD && !element.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( element, "Field " + element.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } private void validateStaticMethods() { for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null && !stage.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( stage, "Method " + stage.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } /** * Gather a list of VariableElement that are the props to this component */ private void populateProps() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getProps(stage)) { // Validation unnecessary - already handled by validateAnnotatedParameters final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mProps = new ArrayList<>(variableNameToElementMap.values()); addCreateInitialStateDefinedProps(mProps); } /** * Gather a list of VariableElement that are the state to this component */ private void populateStateMap() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getState(stage)) { final String variableName = v.getSimpleName().toString(); if (mStateMap.containsKey(variableName)) { VariableElement existingType = mStateMap.get(variableName); final State existingPropAnnotation = existingType.getAnnotation(State.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The state '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this state is declared identically."); } } } mStateMap.put( variableName, v); } } } private void populateTreeProps() { final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : Utils.getParametersWithAnnotation(stage, TreeProp.class)) { final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mTreeProps = new ArrayList<>(variableNameToElementMap.values()); } /** * Get the list of stages (OnInflate, OnMeasure, OnMount) that are defined for this component. */ private void populateStages() { mStages = new ArrayList<>(); for (Class<Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null) { mStages.add(stage); } } if (mOnEventMethods != null) { mStages.addAll(mOnEventMethods); } mStages.addAll(mOnCreateTreePropsMethods); } /** * @param prop The prop to determine if it has a default or not. * @return Returns true if the prop has a default, false otherwise. */ private boolean hasDefaultValue(VariableElement prop) { final String name = prop.getSimpleName().toString(); final TypeName type = TypeName.get(prop.asType()); for (PropDefaultModel propDefault : mPropDefaults) { if (propDefault.mName.equals(name) && propDefault.mType.equals(type)) { return true; } } return false; } /** * Fail if any elements that exist in mPropDefaults do not exist in mProps. */ private void validatePropDefaults() { for (PropDefaultModel propDefault : mPropDefaults) { final ImmutableList<Modifier> modifiers = propDefault.mModifiers; if (!modifiers.contains(Modifier.STATIC) || !modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.PRIVATE)) { throw new RuntimeException( "Defaults for props (fields annotated with " + PropDefault.class + ") must be " + "non-private, static, and final. This is not the case for " + propDefault.mName); } if (!hasValidNameAndType(propDefault)) { throw new RuntimeException( "Prop defaults (fields annotated with " + PropDefault.class + ") should have the " + "same name and type as the prop that they set the default for. This is not the " + "case for " + propDefault.mName); } } } /** * @return true if the given prop default matches the name and type of a prop, false otherwise. */ private boolean hasValidNameAndType(PropDefaultModel propDefault) { for (VariableElement prop : mProps) { if (prop.getSimpleName().toString().equals(propDefault.mName) && TypeName.get(prop.asType()).equals(propDefault.mType)) { return true; } } return false; } /** * Gather a list of parameters from the given element that are props to this component. */ private static List<VariableElement> getProps(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, Prop.class); } /** * Gather a list of parameters from the given element that are state to this component. */ private static List<VariableElement> getState(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, State.class); } /** * Gather a list of parameters from the given element that are defined by the spec. That is, they * aren't one of the parameters predefined for a given method. For example, OnCreateLayout has a * predefined parameter of type LayoutContext. Spec-defined parameters are annotated with one of * our prop annotations or are of type {@link com.facebook.litho.Output}. */ private List<VariableElement> getSpecDefinedParameters(ExecutableElement element) { return getSpecDefinedParameters(element, true); } private List<VariableElement> getSpecDefinedParameters( ExecutableElement element, boolean shouldIncludeOutputs) { final ArrayList<VariableElement> specDefinedParameters = new ArrayList<>(); for (VariableElement v : element.getParameters()) { final boolean isAnnotatedParameter = getParameterAnnotation(v) != null; final boolean isInterStageOutput = Utils.getGenericTypeArgument( v.asType(), ClassNames.OUTPUT) != null; if (isAnnotatedParameter && isInterStageOutput) { throw new ComponentsProcessingException( v, "Variables that are both prop and output are forbidden."); } else if (isAnnotatedParameter || (shouldIncludeOutputs && isInterStageOutput)) { specDefinedParameters.add(v); } } return specDefinedParameters; } private void populateOnCreateInitialStateDefinedProps() { final ExecutableElement onCreateInitialState = Utils.getAnnotatedMethod( getSourceElement(), OnCreateInitialState.class); if (onCreateInitialState == null) { mOnCreateInitialStateDefinedProps = new ArrayList<>(); } else { mOnCreateInitialStateDefinedProps = getSpecDefinedParameters(onCreateInitialState, false); } } /** * Get the @FromLayout, @FromMeasure, etc annotation on this element (@Prop isn't * considered - use getParameterAnnotation if you want to consider them) */ private Annotation getInterStagePropAnnotation(VariableElement element) { return getParameterAnnotation(element, mInterStagePropAnnotations); } /** * Get the annotation, if any, present on a parameter. Annotations are restricted to our whitelist * of parameter annotations: e.g. {@link Prop}, {@link State} etc) */ private Annotation getParameterAnnotation(VariableElement element) { return getParameterAnnotation(element, mParameterAnnotations); } /** * Get the annotation, if any, present on a parameter. Annotations are restricted to the specified * whitelist. If there is a duplicate we will issue an error. */ private Annotation getParameterAnnotation( VariableElement element, Class<Annotation>[] possibleAnnotations) { final ArrayList<Annotation> annotations = new ArrayList<>(); for (Class<Annotation> annotationClass : possibleAnnotations) { final Annotation annotation = element.getAnnotation(annotationClass); if (annotation != null) { annotations.add(annotation); } } if (annotations.isEmpty()) { return null; } else if (annotations.size() == 1) { return annotations.get(0); } else { throw new ComponentsProcessingException( element, "Duplicate parameter annotation: '" + annotations.get(0) + "' and '" + annotations.get(1) + "'"); } } /** * Generate javadoc block describing component props. */ public void generateJavadoc() { for (VariableElement v : mProps) { final Prop propAnnotation = v.getAnnotation(Prop.class); final String propTag = propAnnotation.optional() ? "@prop-optional" : "@prop-required"; final String javadoc = mPropJavadocs != null ? mPropJavadocs.get(v.getSimpleName().toString()) : ""; final String sanitizedJavadoc = javadoc != null ? javadoc.replace('\n', ' ') : null; // Adds javadoc with following format: // @prop-required name type javadoc. // This can be changed later to use clear demarcation for fields. // This is a block tag and cannot support inline tags like "{@link something}". mClassTypeSpec.addJavadoc( "$L $L $L $L\n", propTag, v.getSimpleName().toString(), Utils.getTypeName(v.asType()), sanitizedJavadoc); } } /** * Generate a method for this component which either lazily instantiates a singleton reference or * return this depending on whether this lifecycle is static or not. */ public void generateGetter(boolean isStatic) { final ClassName className = ClassName.bestGuess(mQualifiedClassName); if (isStatic) { mClassTypeSpec.addField( FieldSpec .builder(className, SPEC_INSTANCE_NAME, Modifier.PRIVATE, Modifier.STATIC) .initializer("null") .build()); mClassTypeSpec.addMethod( MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC) .addModifiers(Modifier.STATIC) .addModifiers(Modifier.SYNCHRONIZED) .returns(className) .beginControlFlow("if ($L == null)", SPEC_INSTANCE_NAME) .addStatement("$L = new $T()", SPEC_INSTANCE_NAME, className) .endControlFlow() .addStatement("return $L", SPEC_INSTANCE_NAME) .build()); } else { mClassTypeSpec.addMethod( MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC) .returns(className) .addStatement("return this") .build()); } } public void generateSourceDelegate(boolean initialized) { final ClassName specClassName = ClassName.get(mSourceElement); generateSourceDelegate(initialized, specClassName); } public void generateSourceDelegate(boolean initialized, TypeName specTypeName) { final FieldSpec.Builder builder = FieldSpec .builder(specTypeName, DELEGATE_FIELD_NAME) .addModifiers(Modifier.PRIVATE); if (initialized) { builder.initializer("new $T()", specTypeName); } mClassTypeSpec.addField(builder.build()); } private MethodSpec generateMakeShallowCopy(ClassName componentClassName, boolean hasDeepCopy) { final List<String> componentsInImpl = findComponentsInImpl(componentClassName); final List<String> interStageComponentVariables = getInterStageVariableNames(); if (componentsInImpl.isEmpty() && interStageComponentVariables.isEmpty() && mOnUpdateStateMethods.isEmpty()) { return null; } final String implClassName = getImplClassName(); return new ShallowCopyMethodSpecBuilder() .componentsInImpl(componentsInImpl) .interStageVariables(interStageComponentVariables) .implClassName(implClassName) .hasDeepCopy(hasDeepCopy) .stateContainerImplClassName(getStateContainerImplClassName()) .build(); } private List<String> findComponentsInImpl(ClassName listComponent) { final List<String> componentsInImpl = new ArrayList<>(); for (String key : mImplMembers.keySet()) { final VariableElement element = mImplMembers.get(key); final Name declaredClassName = Utils.getDeclaredClassNameWithoutGenerics(element); if (declaredClassName != null && ClassName.bestGuess(declaredClassName.toString()).equals(listComponent)) { componentsInImpl.add(element.getSimpleName().toString()); } } return componentsInImpl; } /** * Generate a private constructor to enforce singleton-ity. */ public void generateConstructor() { mClassTypeSpec.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build()); } /** * Generates a method to create the initial values for parameters annotated with {@link State}. * This method also validates that the delegate method only tries to assign an initial value to * State annotated parameters. */ public void generateCreateInitialState( ExecutableElement from, ClassName contextClass, ClassName componentClass) { verifyParametersForCreateInitialState(contextClass, from); final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = null; methodDescription.name = "createInitialState"; methodDescription.parameterTypes = new TypeName[] {contextClass}; generateDelegate(methodDescription, from, componentClass); } private void verifyParametersForCreateInitialState( ClassName contextClass, ExecutableElement executableElement) { final List<VariableElement> parameters = (List<VariableElement>) executableElement.getParameters(); if (parameters.size() < ON_CREATE_INITIAL_STATE + 1) { throw new ComponentsProcessingException( executableElement, "The @OnCreateInitialState method should have an " + contextClass + "followed by Output parameters matching state parameters."); } final TypeName firstParamType = ClassName.get(parameters.get(0).asType()); if (!firstParamType.equals(contextClass)) { throw new ComponentsProcessingException( parameters.get(0), "The first argument of the @OnCreateInitialState method should be an " + contextClass + "."); } for (int i = ON_CREATE_INITIAL_STATE, size = parameters.size(); i < size; i++) { final VariableElement element = parameters.get(i); final TypeMirror elementInnerClassType = Utils.getGenericTypeArgument(element.asType(), ClassNames.OUTPUT); if (elementInnerClassType != null) { final String paramName = element.getSimpleName().toString(); VariableElement implParameter = mStateMap.get(paramName); if (implParameter == null || implParameter.getAnnotation(State.class) == null) { throw new ComponentsProcessingException( executableElement, "Only parameters annotated with @State can be initialized in @OnCreateInitialState," + " parameter without annotation is: " + paramName); } } } } /** * Generate a method implementation that delegates to another method that takes annotated props. * * @param from description of method signature to be generated * @param to method to which to delegate * @param propsClass Component / Delegate. The base class of the inner implementation object * @throws java.io.IOException If one of the writer methods throw */ public void generateDelegate( MethodDescription from, ExecutableElement to, ClassName propsClass) { generateDelegate( from, to, Collections.<TypeName>emptyList(), Collections.<String, String>emptyMap(), propsClass); } public void generateDelegate( MethodDescription from, ExecutableElement to, List<TypeName> expectedTypes, ClassName propsClass) { generateDelegate( from, to, expectedTypes, Collections.<String, String>emptyMap(), propsClass); } /** * Generate a method implementation that delegates to another method that takes annotated props. * * @param from description of method signature to be generated * @param to method to which to delegate * @param propsClass Component / Delegate. The base class of the inner implementation object * @throws java.io.IOException If one of the writer methods throw */ public void generateDelegate( MethodDescription from, ExecutableElement to, List<TypeName> expectedTypes, Map<String, String> parameterTranslation, ClassName propsClass) { final Visibility visibility; if (Arrays.asList(from.accessType).contains(Modifier.PRIVATE)) { visibility = Visibility.PRIVATE; } else if (Arrays.asList(from.accessType).contains(Modifier.PROTECTED)) { visibility = Visibility.PROTECTED; } else if (Arrays.asList(from.accessType).contains(Modifier.PUBLIC)) { visibility = Visibility.PUBLIC; } else { visibility = Visibility.PACKAGE; } final List<Parameter> toParams = getParams(to); final List<Parameter> fromParams = new ArrayList<>(); for (int i = 0; i < from.parameterTypes.length; i++) { fromParams.add(new Parameter(from.parameterTypes[i], toParams.get(i).name)); } final List<PrintableException> errors = new ArrayList<>(); for (int i = 0; i < expectedTypes.size(); i++) { if (!toParams.get(i).type.equals(expectedTypes.get(i))) { errors.add(new ComponentsProcessingException( to.getParameters().get(i), "Expected " + expectedTypes.get(i))); } } if (!errors.isEmpty()) { throw new MultiPrintableException(errors); } writeMethodSpec(new DelegateMethodSpecBuilder() .implClassName(getImplClassName()) .abstractImplType(propsClass) .implParameters(mImplParameters) .checkedExceptions( from.exceptions == null ? new ArrayList<TypeName>() : Arrays.asList(from.exceptions)) .overridesSuper( from.annotations != null && Arrays.asList(from.annotations).contains(Override.class)) .parameterTranslation(parameterTranslation) .visibility(visibility) .fromName(from.name) .fromReturnType(from.returnType == null ? TypeName.VOID : from.returnType) .fromParams(fromParams) .target(mSourceDelegateAccessorName) .toName(to.getSimpleName().toString()) .stateParams(mStateMap.keySet()) .toReturnType(ClassName.get(to.getReturnType())) .toParams(toParams) .build()); } /** * Returns {@code true} if the given types match. */ public boolean isSameType(TypeMirror a, TypeMirror b) { return mProcessingEnv.getTypeUtils().isSameType(a, b); } /** * Generate an onEvent implementation that delegates to the @OnEvent-annotated method. */ public void generateOnEventHandlers(ClassName componentClassName, ClassName contextClassName) { for (ExecutableElement element : mOnEventMethods) { generateOnEventHandler(element, contextClassName); } } /** * Generate the static methods of the Component that can be called to update its state. */ public void generateOnStateUpdateMethods( ClassName contextClass, ClassName componentClassName, ClassName stateContainerClassName, ClassName stateUpdateInterface, Stages.StaticFlag staticFlag) { for (ExecutableElement element : mOnUpdateStateMethods) { validateOnStateUpdateMethodDeclaration(element); generateStateUpdateClass( element, componentClassName, stateContainerClassName, stateUpdateInterface, staticFlag); generateOnStateUpdateMethods(element, contextClass, componentClassName); } } /** * Validate that the declaration of a method annotated with {@link OnUpdateState} is correct: * <ul> * <li>1. Method parameters annotated with {@link Param} don't have the same name as parameters * annotated with {@link State} or {@link Prop}.</li> * <li>2. Method parameters not annotated with {@link Param} must be of type * com.facebook.litho.StateValue.</li> * <li>3. Names of method parameters not annotated with {@link Param} must match the name of * a parameter annotated with {@link State}.</li> * <li>4. Type of method parameters not annotated with {@link Param} must match the type of * a parameter with the same name annotated with {@link State}.</li> * </ul> */ private void validateOnStateUpdateMethodDeclaration(ExecutableElement element) { final List<VariableElement> annotatedParams = Utils.getParametersWithAnnotation(element, Param.class); // Check for (VariableElement annotatedParam : annotatedParams) { if (mStateMap.get(annotatedParam.getSimpleName().toString()) != null) { throw new ComponentsProcessingException( annotatedParam, "Parameters annotated with @Param should not have the same name as a parameter " + "annotated with @State or @Prop"); } } final List<VariableElement> params = (List<VariableElement>) element.getParameters(); for (VariableElement param : params) { if (annotatedParams.contains(param)) { continue; } final TypeMirror paramType = param.asType(); // Check if (paramType.getKind() != DECLARED) { throw new ComponentsProcessingException( param, "Parameters not annotated with @Param must be of type " + "com.facebook.litho.StateValue"); } final DeclaredType paramDeclaredType = (DeclaredType) param.asType(); final String paramDeclaredTypeName = paramDeclaredType .asElement() .getSimpleName() .toString(); if (!paramDeclaredTypeName.equals(ClassNames.STATE_VALUE.simpleName())) { throw new ComponentsProcessingException( "All state parameters must be of type com.facebook.litho.StateValue, " + param.getSimpleName() + " is of type " + param.asType()); } VariableElement stateMatchingParam = mStateMap.get(param.getSimpleName().toString()); // Check if (stateMatchingParam == null || stateMatchingParam.getAnnotation(State.class) == null) { throw new ComponentsProcessingException( param, "Names of parameters of type StateValue must match the name of a parameter annotated " + "with @State"); } // Check final List<TypeMirror> typeArguments = (List<TypeMirror>) paramDeclaredType.getTypeArguments(); if (typeArguments.isEmpty()) { throw new ComponentsProcessingException( param, "Type parameter for a parameter of type StateValue should match the type of " + "a parameter with the same name annotated with @State"); } final TypeMirror typeArgument = typeArguments.get(0); final TypeName stateMatchingParamTypeName = ClassName.get(stateMatchingParam.asType()); if (stateMatchingParamTypeName.isPrimitive()) { TypeName stateMatchingParamBoxedType = stateMatchingParamTypeName.box(); if (!stateMatchingParamBoxedType.equals(TypeName.get(typeArgument))) { throw new ComponentsProcessingException( param, "Type parameter for a parameter of type StateValue should match the type of " + "a parameter with the same name annotated with @State"); } } } } /** * Generate an EventHandler factory methods */ public void generateEventHandlerFactories( ClassName contextClassName, ClassName componentClassName) { for (ExecutableElement element : mOnEventMethods) { generateEventHandlerFactory( element, contextClassName, componentClassName); } } // ExecutableElement.hashCode may be different in different runs of the // processor. getElementId() is deterministic and ensures that the output is // the same across multiple runs. private int getElementId(ExecutableElement el) { return (mQualifiedClassName.hashCode() * 31 + el.getSimpleName().hashCode()) * 31 + el.asType().toString().hashCode(); } /** * Generate a dispatchOnEvent() implementation for the component. */ public void generateDispatchOnEvent( ClassName contextClassName) { final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("dispatchOnEvent") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(TypeName.OBJECT) .addParameter( ParameterSpec.builder(ClassNames.EVENT_HANDLER, "eventHandler", Modifier.FINAL).build()) .addParameter( ParameterSpec.builder(ClassNames.OBJECT, "eventState", Modifier.FINAL).build()); methodBuilder.addStatement("int id = eventHandler.id"); methodBuilder.beginControlFlow("switch($L)", "id"); final String implInstanceName = "_" + getImplInstanceName(); for (ExecutableElement element : mOnEventMethods) { methodBuilder.beginControlFlow("case $L:", getElementId(element)); final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final String eventName = eventClass.toString(); methodBuilder.addStatement( "$L $L = ($L) $L", eventName, implInstanceName, eventName, "eventState"); final CodeBlock.Builder eventHandlerParams = CodeBlock.builder(); eventHandlerParams.indent(); int i = 0; eventHandlerParams.add("\n($T) eventHandler.params[$L],", contextClassName, i++); for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) { eventHandlerParams.add( "\n" + implInstanceName + ".$L,", v.getSimpleName().toString()); } for (VariableElement v : Utils.getParametersWithAnnotation(element, Param.class)) { eventHandlerParams.add("\n($T) eventHandler.params[$L],", ClassName.get(v.asType()), i); i++; } eventHandlerParams.add("\n$L", "eventHandler.mHasEventDispatcher"); eventHandlerParams.unindent(); if (element.getReturnType().getKind() != VOID) { methodBuilder.addStatement( "return do$L($L)", capitalize(element.getSimpleName().toString()), eventHandlerParams.build()); } else { methodBuilder.addStatement( "do$L($L)", capitalize(element.getSimpleName().toString()), eventHandlerParams.build()); methodBuilder.addStatement("return null"); } methodBuilder.endControlFlow(); } methodBuilder.addStatement("default: \nreturn null"); methodBuilder.endControlFlow(); writeMethodSpec(methodBuilder.build()); } private void generateEventHandlerFactory( ExecutableElement element, ClassName contextClassName, ClassName componentClassName) { final List<VariableElement> eventParamElements = Utils.getParametersWithAnnotation(element, Param.class); final List<Parameter> eventParams = new ArrayList<>(); final List<String> typeParameters = new ArrayList<>(); for (VariableElement e : eventParamElements) { eventParams.add(new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString())); for (TypeMirror typeParam : getTypeVarArguments(e.asType())) { typeParameters.add(typeParam.toString()); } } final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final TypeName eventClassName = ClassName.bestGuess(((TypeElement) eventClass.asElement()).getQualifiedName().toString()); writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder() .eventId(getElementId(element)) .eventName(element.getSimpleName().toString()) .contextClass(contextClassName) .eventHandlerClassName( ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName)) .eventParams(eventParams) .typeParameters(typeParameters) .build()); writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder() .eventId(getElementId(element)) .eventName(element.getSimpleName().toString()) .contextClass(componentClassName) .eventHandlerClassName( ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName)) .eventParams(eventParams) .typeParameters(typeParameters) .build()); } private void generateOnEventHandler( ExecutableElement element, ClassName contextClassName) { if (element.getParameters().size() == 0 || !ClassName.get(element.getParameters().get(0).asType()).equals(contextClassName)) { throw new ComponentsProcessingException( element, "The first parameter for an onEvent method should be of type " +contextClassName.toString()); } final String evenHandlerName = element.getSimpleName().toString(); final List<Parameter> fromParams = new ArrayList<>(); fromParams.add(new Parameter( contextClassName, element.getParameters().get(0).getSimpleName().toString())); final List<VariableElement> fromParamElements = Utils.getParametersWithAnnotation(element, FromEvent.class); fromParamElements.addAll(Utils.getParametersWithAnnotation(element, Param.class)); for (VariableElement v : fromParamElements) { fromParams.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); } writeMethodSpec(new DelegateMethodSpecBuilder() .implClassName(getImplClassName()) .abstractImplType(ClassNames.HAS_EVENT_DISPATCHER_CLASSNAME) .implParameters(mImplParameters) .visibility(PRIVATE) .fromName("do" + capitalize(evenHandlerName)) .fromParams(fromParams) .target(mSourceDelegateAccessorName) .toName(evenHandlerName) .toParams(getParams(element)) .fromReturnType(ClassName.get(element.getReturnType())) .toReturnType(ClassName.get(element.getReturnType())) .stateParams(mStateMap.keySet()) .build()); } private void generateOnStateUpdateMethods( ExecutableElement element, ClassName contextClass, ClassName componentClass) { final String methodName = element.getSimpleName().toString(); final List<VariableElement> updateMethodParamElements = Utils.getParametersWithAnnotation(element, Param.class); final OnStateUpdateMethodSpecBuilder builder = new OnStateUpdateMethodSpecBuilder() .componentClass(componentClass) .lifecycleImplClass(mSimpleClassName) .stateUpdateClassName(getStateUpdateClassName(element)); for (VariableElement e : updateMethodParamElements) { builder.updateMethodParam( new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString())); List<TypeMirror> genericArgs = getTypeVarArguments(e.asType()); if (genericArgs != null) { for (TypeMirror genericArg : genericArgs) { builder.typeParameter(genericArg.toString()); } } } writeMethodSpec(builder .updateMethodName(methodName) .async(false) .contextClass(contextClass) .build()); writeMethodSpec(builder .updateMethodName(methodName + "Async") .async(true) .contextClass(contextClass) .build()); } static List<TypeMirror> getTypeVarArguments(TypeMirror diffType) { List<TypeMirror> typeVarArguments = new ArrayList<>(); if (diffType.getKind() == DECLARED) { final DeclaredType parameterDeclaredType = (DeclaredType) diffType; final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments(); for (TypeMirror typeArgument : typeArguments) { if (typeArgument.getKind() == TYPEVAR) { typeVarArguments.add(typeArgument); } } } return typeVarArguments; } public static List<TypeMirror> getGenericTypeArguments(TypeMirror diffType) { if (diffType.getKind() == DECLARED) { final DeclaredType parameterDeclaredType = (DeclaredType) diffType; final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments(); return (List<TypeMirror>) typeArguments; } return null; } public static List<Parameter> getParams(ExecutableElement e) { final List<Parameter> params = new ArrayList<>(); for (VariableElement v : e.getParameters()) { params.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); } return params; } /** * Generates a class that implements {@link com.facebook.litho.ComponentLifecycle} given * a method annotated with {@link OnUpdateState}. The class constructor takes as params all the * params annotated with {@link Param} on the method and keeps them in class members. * @param element The method annotated with {@link OnUpdateState} */ private void generateStateUpdateClass( ExecutableElement element, ClassName componentClassName, ClassName stateContainerClassName, ClassName updateStateInterface, StaticFlag staticFlag) { final String stateUpdateClassName = getStateUpdateClassName(element); final TypeName implClassName = ClassName.bestGuess(getImplClassName()); final StateUpdateImplClassBuilder stateUpdateImplClassBuilder = new StateUpdateImplClassBuilder() .withTarget(mSourceDelegateAccessorName) .withSpecOnUpdateStateMethodName(element.getSimpleName().toString()) .withComponentImplClassName(implClassName) .withComponentClassName(componentClassName) .withComponentStateUpdateInterface(updateStateInterface) .withStateContainerClassName(stateContainerClassName) .withStateContainerImplClassName(ClassName.bestGuess(getStateContainerImplClassName())) .withStateUpdateImplClassName(stateUpdateClassName) .withSpecOnUpdateStateMethodParams(getParams(element)) .withStateValueParams(getStateValueParams(element)) .withStaticFlag(staticFlag); final List<VariableElement> parametersVarElements = Utils.getParametersWithAnnotation(element, Param.class); final List<Parameter> parameters = new ArrayList<>(); for (VariableElement v : parametersVarElements) { parameters.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); for (TypeMirror typeVar : getTypeVarArguments(v.asType())) { stateUpdateImplClassBuilder.typeParameter(typeVar.toString()); } } stateUpdateImplClassBuilder.withParamsForStateUpdate(parameters); writeInnerTypeSpec(stateUpdateImplClassBuilder.build()); } /** * Generate an onLoadStyle implementation. */ public void generateOnLoadStyle() { final ExecutableElement delegateMethod = Utils.getAnnotatedMethod( mSourceElement, OnLoadStyle.class); if (delegateMethod == null) { return; } final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onLoadStyle") .addAnnotation( AnnotationSpec .builder(SuppressWarnings.class) .addMember("value", "$S", "unchecked").build()) .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .addParameter(ClassNames.COMPONENT_CONTEXT, "_context") .addParameter( ParameterSpec.builder( ParameterizedTypeName.get( ClassNames.COMPONENT, WildcardTypeName.subtypeOf(Object.class)), "_component") .build()); final List<? extends VariableElement> parameters = delegateMethod.getParameters(); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final TypeName typeName = ClassName.get(v.asType()); methodBuilder.addStatement( "$L $L = ($L) $L", typeName, v.getSimpleName(), typeName, "acquireOutput()"); } final CodeBlock.Builder delegateParameters = CodeBlock.builder().indent(); delegateParameters.add("\n_context"); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { delegateParameters.add(",\n$L", parameters.get(i).getSimpleName()); } delegateParameters.unindent(); methodBuilder.addStatement( "this.$L.$L($L)", mSourceDelegateAccessorName, delegateMethod.getSimpleName(), delegateParameters.build()); final String implClassName = getImplClassName(); final String implInstanceName = "_" + getImplInstanceName(); methodBuilder.addStatement( "$L " + implInstanceName + "= ($L) _component", implClassName, implClassName); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final String name = v.getSimpleName().toString(); methodBuilder.beginControlFlow("if ($L.get() != null)", name); methodBuilder.addStatement( "$L.$L = $L.get()", implInstanceName, name, name); methodBuilder.endControlFlow(); methodBuilder.addStatement("releaseOutput($L)", name); } writeMethodSpec(methodBuilder.build()); } /** * Find variables annotated with {@link PropDefault} */ private void populatePropDefaults() { mPropDefaults = PropDefaultsExtractor.getPropDefaults(mSourceElement); } public void generateComponentImplClass(Stages.StaticFlag isStatic) { generateStateContainerImplClass(isStatic, ClassNames.STATE_CONTAINER_COMPONENT); final String implClassName = getImplClassName(); final ClassName stateContainerImplClass = ClassName.bestGuess(getSimpleClassName() + STATE_CONTAINER_IMPL_NAME_SUFFIX); final TypeSpec.Builder implClassBuilder = TypeSpec.classBuilder(implClassName) .addModifiers(Modifier.PRIVATE) .superclass( ParameterizedTypeName.get( ClassNames.COMPONENT, ClassName.bestGuess(getSimpleClassName()))) .addSuperinterface(Cloneable.class); if (isStatic.equals(Stages.StaticFlag.STATIC)) { implClassBuilder.addModifiers(Modifier.STATIC); implClassBuilder.addTypeVariables(mTypeVariables); } implClassBuilder.addField(stateContainerImplClass, STATE_CONTAINER_IMPL_MEMBER); implClassBuilder.addMethod(generateStateContainerGetter(ClassNames.STATE_CONTAINER_COMPONENT)); generateComponentClassProps(implClassBuilder, ClassNames.EVENT_HANDLER); MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addStatement("super(get())") .addStatement(STATE_CONTAINER_IMPL_MEMBER + " = new $T()", stateContainerImplClass); implClassBuilder.addMethod(constructorBuilder.build()); implClassBuilder.addMethod( MethodSpec.methodBuilder("getSimpleName") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(ClassNames.STRING) .addStatement("return \"" + getSimpleClassName() + "\"") .build()); final MethodSpec equalsBuilder = generateEqualsMethodDefinition(true); implClassBuilder.addMethod(equalsBuilder); final MethodSpec copyInterStage = generateCopyInterStageImpl(implClassName); if (copyInterStage != null) { implClassBuilder.addMethod(copyInterStage); } for (ExecutableElement element : mOnUpdateStateMethods) { final String stateUpdateClassName = getStateUpdateClassName(element); final List<Parameter> parameters = getParamsWithAnnotation(element, Param.class); implClassBuilder.addMethod( new CreateStateUpdateInstanceMethodSpecBuilder() .parameters(parameters) .stateUpdateClass(stateUpdateClassName) .build()); } final MethodSpec makeShallowCopy = generateMakeShallowCopy(ClassNames.COMPONENT, /* hasDeepCopy */ false); if (makeShallowCopy != null) { implClassBuilder.addMethod(makeShallowCopy); } writeInnerTypeSpec(implClassBuilder.build()); } public void generateLazyStateUpdateMethods( ClassName context, ClassName componentClass, TypeName stateUpdateType, TypeName stateContainerComponent) { for (VariableElement state : mStateMap.values()) { if (state.getAnnotation(State.class).canUpdateLazily()) { writeMethodSpec(new OnLazyStateUpdateMethodSpecBuilder() .contextClass(context) .componentClass(componentClass) .stateUpdateType(stateUpdateType) .stateName(state.getSimpleName().toString()) .stateType(ClassName.get(state.asType())) .withStateContainerClassName(stateContainerComponent) .implClass(getImplClassName()) .lifecycleImplClass(mSimpleClassName) .build()); } } } private void generateStateContainerImplClass( Stages.StaticFlag isStatic, ClassName stateContainerClassName) { final TypeSpec.Builder stateContainerImplClassBuilder = TypeSpec .classBuilder(getStateContainerImplClassName()) .addSuperinterface(stateContainerClassName); if (isStatic.equals(Stages.StaticFlag.STATIC)) { stateContainerImplClassBuilder.addModifiers(Modifier.STATIC, Modifier.PRIVATE); stateContainerImplClassBuilder.addTypeVariables(mTypeVariables); } for (String stateName : mStateMap.keySet()) { VariableElement v = mStateMap.get(stateName); stateContainerImplClassBuilder.addField(getPropFieldSpec(v, true)); } writeInnerTypeSpec(stateContainerImplClassBuilder.build()); } private static MethodSpec generateStateContainerGetter(ClassName stateContainerClassName) { return MethodSpec.methodBuilder("getStateContainer") .addModifiers(Modifier.PROTECTED) .addAnnotation(Override.class) .returns(stateContainerClassName) .addStatement("return " + STATE_CONTAINER_IMPL_MEMBER) .build(); } public void generateReferenceImplClass( Stages.StaticFlag isStatic, TypeMirror referenceType) { final TypeSpec.Builder implClassBuilder = TypeSpec.classBuilder(getImplClassName()) .addModifiers(Modifier.PRIVATE) .superclass( ParameterizedTypeName.get( ClassNames.REFERENCE, ClassName.get(referenceType))); if (isStatic.equals(Stages.StaticFlag.STATIC)) { implClassBuilder.addModifiers(Modifier.STATIC); } generateComponentClassProps(implClassBuilder, null); implClassBuilder.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addStatement("super(get())") .build()); implClassBuilder.addMethod( MethodSpec.methodBuilder("getSimpleName") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(ClassNames.STRING) .addStatement("return \"" + getSimpleClassName() + "\"") .build()); final MethodSpec equalsBuilder = generateEqualsMethodDefinition(false); implClassBuilder.addMethod(equalsBuilder); writeInnerTypeSpec(implClassBuilder.build()); } public void generateTransferState( ClassName contextClassName, ClassName componentClassName, ClassName stateContainerClassName) { if (!mStateMap.isEmpty()) { MethodSpec methodSpec = new TransferStateSpecBuilder() .contextClassName(contextClassName) .componentClassName(componentClassName) .componentImplClassName(getImplClassName()) .stateContainerClassName(stateContainerClassName) .stateContainerImplClassName(getStateContainerImplClassName()) .stateParameters(mStateMap.keySet()) .build(); mClassTypeSpec.addMethod(methodSpec); } } public void generateHasState() { if (mStateMap.isEmpty()) { return; } MethodSpec hasStateMethod = MethodSpec.methodBuilder("hasState") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(TypeName.BOOLEAN) .addStatement("return true") .build(); mClassTypeSpec.addMethod(hasStateMethod); } public void generateListComponentImplClass(Stages.StaticFlag isStatic) { generateStateContainerImplClass(isStatic, SectionClassNames.STATE_CONTAINER_SECTION); final ClassName stateContainerImplClass = ClassName.bestGuess(getSimpleClassName() + STATE_CONTAINER_IMPL_NAME_SUFFIX); final TypeSpec.Builder stateClassBuilder = TypeSpec.classBuilder(getImplClassName()) .addModifiers(Modifier.PRIVATE) .superclass( ParameterizedTypeName.get( SectionClassNames.SECTION, ClassName.bestGuess(getSimpleClassName()))) .addSuperinterface(Cloneable.class); if (isStatic.equals(Stages.StaticFlag.STATIC)) { stateClassBuilder.addModifiers(Modifier.STATIC); } stateClassBuilder.addField(stateContainerImplClass, STATE_CONTAINER_IMPL_MEMBER); stateClassBuilder.addMethod(generateStateContainerGetter(SectionClassNames.STATE_CONTAINER_SECTION)); generateComponentClassProps(stateClassBuilder, ClassNames.EVENT_HANDLER); stateClassBuilder.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addStatement("super(get())") .addStatement(STATE_CONTAINER_IMPL_MEMBER + " = new $T()", stateContainerImplClass) .build()); final MethodSpec equalsBuilder = generateEqualsMethodDefinition(false); stateClassBuilder.addMethod(equalsBuilder); for (ExecutableElement element : mOnUpdateStateMethods) { final String stateUpdateClassName = getStateUpdateClassName(element); final List<Parameter> parameters = getParamsWithAnnotation(element, Param.class); stateClassBuilder.addMethod( new CreateStateUpdateInstanceMethodSpecBuilder() .parameters(parameters) .stateUpdateClass(stateUpdateClassName) .build()); } final MethodSpec makeShallowCopy = generateMakeShallowCopy(SectionClassNames.SECTION, /* hasDeepCopy */ true); if (makeShallowCopy != null) { stateClassBuilder.addMethod(makeShallowCopy); } writeInnerTypeSpec(stateClassBuilder.build()); } private MethodSpec generateEqualsMethodDefinition(boolean shouldCheckId) { final String implClassName = getImplClassName(); final String implInstanceName = getImplInstanceName(); MethodSpec.Builder equalsBuilder = MethodSpec.methodBuilder("equals") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addParameter(TypeName.OBJECT, "other") .beginControlFlow("if (this == other)") .addStatement("return true") .endControlFlow() .beginControlFlow("if (other == null || getClass() != other.getClass())") .addStatement("return false") .endControlFlow() .addStatement(implClassName + " " + implInstanceName + " = (" + implClassName + ") other"); if (shouldCheckId) { equalsBuilder .beginControlFlow( "if (this.getId() == " + implInstanceName + ".getId())") .addStatement("return true") .endControlFlow(); } for (VariableElement v : mImplMembers.values()) { if (!isState(v)) { addCompareStatement(implInstanceName, v, equalsBuilder, false); } } for (VariableElement v : mStateMap.values()) { addCompareStatement(implInstanceName, v, equalsBuilder, true); } equalsBuilder.addStatement("return true"); return equalsBuilder.build(); } private static void addCompareStatement( String implInstanceName, VariableElement v, MethodSpec.Builder equalsBuilder, boolean isState) { final TypeMirror variableType = v.asType(); final TypeMirror outputTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.OUTPUT); final TypeMirror diffTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.DIFF); final TypeKind variableKind = diffTypeMirror != null ? diffTypeMirror.getKind() : variableType.getKind(); String qualifiedName = ""; if (variableType instanceof DeclaredType) { final DeclaredType declaredType = (DeclaredType) variableType; qualifiedName = ((TypeElement) declaredType.asElement()).getQualifiedName().toString(); } final String stateContainerMember = isState ? "." + STATE_CONTAINER_IMPL_MEMBER : ""; final CharSequence thisVarName = isState ? STATE_CONTAINER_IMPL_MEMBER + "." + v.getSimpleName() : v.getSimpleName(); if (outputTypeMirror == null) { if (variableKind == FLOAT) { equalsBuilder .beginControlFlow( "if (Float.compare($L, " + implInstanceName + stateContainerMember + ".$L) != 0)", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (variableKind == DOUBLE) { equalsBuilder .beginControlFlow( "if (Double.compare($L, " + implInstanceName + stateContainerMember + ".$L) != 0)", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (variableType.getKind() == ARRAY) { equalsBuilder .beginControlFlow( "if (!Arrays.equals($L, " + implInstanceName + stateContainerMember + ".$L))", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (variableType.getKind().isPrimitive()) { equalsBuilder .beginControlFlow( "if ($L != " + implInstanceName + stateContainerMember + ".$L)", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (qualifiedName.equals(ClassNames.REFERENCE)) { equalsBuilder .beginControlFlow( "if (Reference.shouldUpdate($L, " + implInstanceName + stateContainerMember + ".$L))", thisVarName, v.getSimpleName(), v.getSimpleName(), v.getSimpleName(), v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else { equalsBuilder .beginControlFlow( "if ($L != null ? !$L.equals(" + implInstanceName + stateContainerMember + ".$L) : " + implInstanceName + stateContainerMember + ".$L != null)", thisVarName, thisVarName, v.getSimpleName(), v.getSimpleName()) .addStatement("return false") .endControlFlow(); } } } private boolean isState(VariableElement v) { for (VariableElement find : mStateMap.values()) { if (find.getSimpleName().equals(v.getSimpleName())) { return true; } } return false; } private void generateComponentClassProps( TypeSpec.Builder implClassBuilder, ClassName eventHandlerClassName) { for (VariableElement v : mImplMembers.values()) { implClassBuilder.addField(getPropFieldSpec(v, false)); } if (mExtraStateMembers != null) { for (String key : mExtraStateMembers.keySet()) { final TypeMirror variableType = mExtraStateMembers.get(key); final FieldSpec.Builder fieldBuilder = FieldSpec.builder(TypeName.get(variableType), key); implClassBuilder.addField(fieldBuilder.build()); } } for (TypeElement event : mEventDeclarations) { implClassBuilder.addField(FieldSpec.builder( eventHandlerClassName, getEventHandlerInstanceName(event.getSimpleName().toString())) .build()); } } private FieldSpec getPropFieldSpec(VariableElement v, boolean isStateProp) { final TypeMirror variableType = v.asType(); TypeMirror wrappingTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.OUTPUT); if (wrappingTypeMirror == null) { wrappingTypeMirror = Utils.getGenericTypeArgument(variableType, ClassNames.DIFF); } final TypeName variableClassName = JPUtil.getTypeFromMirror( wrappingTypeMirror != null ? wrappingTypeMirror : variableType); final FieldSpec.Builder fieldBuilder = FieldSpec.builder( variableClassName, v.getSimpleName().toString()); if (!isInterStageComponentVariable(v)) { if (isStateProp) { fieldBuilder.addAnnotation(State.class); } else { fieldBuilder.addAnnotation(Prop.class); } } final boolean hasDefaultValue = hasDefaultValue(v); if (hasDefaultValue) { fieldBuilder.initializer( "$L.$L", mSourceElement.getSimpleName().toString(), v.getSimpleName().toString()); } return fieldBuilder.build(); } public void generateIsPureRender() { final MethodSpec.Builder shouldUpdateComponent = MethodSpec.methodBuilder("isPureRender") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addStatement("return true"); mClassTypeSpec.addMethod(shouldUpdateComponent.build()); } public void generateCallsShouldUpdateOnMount() { final MethodSpec.Builder isFast = MethodSpec.methodBuilder("callsShouldUpdateOnMount") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addStatement("return true"); mClassTypeSpec.addMethod(isFast.build()); } public void generateShouldUpdateMethod( ExecutableElement shouldUpdateElement, ClassName comparedInstancesClassName) { final ClassName implClass = ClassName.bestGuess(getImplClassName()); final MethodSpec.Builder shouldUpdateComponent = MethodSpec.methodBuilder("shouldUpdate") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addParameter(comparedInstancesClassName, "previous") .addParameter(comparedInstancesClassName, "next"); final List<? extends VariableElement> shouldUpdateParams = shouldUpdateElement.getParameters(); final int shouldUpdateParamSize = shouldUpdateParams.size(); if (shouldUpdateParamSize > 0) { shouldUpdateComponent .addStatement( "$L previousImpl = ($L) previous", implClass, implClass) .addStatement( "$L nextImpl = ($L) next", implClass, implClass); } final CodeBlock.Builder delegateParameters = CodeBlock.builder(); delegateParameters.indent(); int i = 0; final CodeBlock.Builder releaseDiffs = CodeBlock.builder(); for (VariableElement variableElement : shouldUpdateParams) { final Name variableElementName = variableElement.getSimpleName(); final TypeMirror variableElementType = variableElement.asType(); final VariableElement componentMember = findPropVariableForName(variableElementName); if (componentMember == null) { throw new ComponentsProcessingException( variableElement, "Arguments for ShouldUpdate should match declared Props"); } final TypeMirror innerType = Utils.getGenericTypeArgument( variableElementType, ClassNames.DIFF); if (innerType == null) { throw new ComponentsProcessingException( variableElement, "Arguments for ShouldUpdate should be of type Diff " + componentMember.asType()); } final TypeName typeName; final TypeName innerTypeName = JPUtil.getTypeFromMirror(innerType); if (componentMember.asType().getKind().isPrimitive()) { typeName = JPUtil.getTypeFromMirror(componentMember.asType()).box(); } else { typeName = JPUtil.getTypeFromMirror(componentMember.asType()); } if (!typeName.equals(innerTypeName)) { throw new ComponentsProcessingException( variableElement, "Diff Type parameter does not match Prop " + componentMember); } shouldUpdateComponent .addStatement( "$L $L = acquireDiff(previousImpl.$L, nextImpl.$L)", variableElementType, variableElementName, variableElementName, variableElementName); if (i != 0) { delegateParameters.add(",\n"); } delegateParameters.add(variableElementName.toString()); i++; releaseDiffs.addStatement( "releaseDiff($L)", variableElementName); } delegateParameters.unindent(); shouldUpdateComponent.addStatement( "boolean shouldUpdate = $L.$L(\n$L)", mSourceDelegateAccessorName, shouldUpdateElement.getSimpleName(), delegateParameters.build()); shouldUpdateComponent.addCode(releaseDiffs.build()); shouldUpdateComponent.addStatement( "return shouldUpdate"); mClassTypeSpec.addMethod(shouldUpdateComponent.build()); } public void generateTreePropsMethods(ClassName contextClassName, ClassName componentClassName) { verifyOnCreateTreePropsForChildren(contextClassName); if (!mTreeProps.isEmpty()) { final PopulateTreePropsMethodBuilder builder = new PopulateTreePropsMethodBuilder(); builder.componentClassName = componentClassName; builder.lifecycleImplClass = getImplClassName(); for (VariableElement treeProp : mTreeProps) { builder.treeProps.add( new Parameter(ClassName.get(treeProp.asType()), treeProp.getSimpleName().toString())); } mClassTypeSpec.addMethod(builder.build()); } if (mOnCreateTreePropsMethods.isEmpty()) { return; } final GetTreePropsForChildrenMethodBuilder builder = new GetTreePropsForChildrenMethodBuilder(); builder.lifecycleImplClass = getImplClassName(); builder.delegateName = getSourceDelegateAccessorName(); builder.contextClassName = contextClassName; builder.componentClassName = componentClassName; for (ExecutableElement executable : mOnCreateTreePropsMethods) { final CreateTreePropMethodData method = new CreateTreePropMethodData(); method.parameters = getParams(executable); method.returnType = ClassName.get(executable.getReturnType()); method.name = executable.getSimpleName().toString(); builder.createTreePropMethods.add(method); } mClassTypeSpec.addMethod(builder.build()); } private void verifyOnCreateTreePropsForChildren(ClassName contextClassName) { for (ExecutableElement method : mOnCreateTreePropsMethods) { if (method.getReturnType().getKind().equals(TypeKind.VOID)) { throw new ComponentsProcessingException( method, "@OnCreateTreeProp annotated method" + method.getSimpleName() + "cannot have a void return type"); } final List<? extends VariableElement> params = method.getParameters(); if (params.isEmpty() || !ClassName.get(params.get(0).asType()).equals(contextClassName)) { throw new ComponentsProcessingException( method, "The first argument of an @OnCreateTreeProp method should be the " + contextClassName.simpleName()); } } } private VariableElement findPropVariableForName(Name variableElementName) { for (VariableElement prop : mProps) { if (prop.getSimpleName().equals(variableElementName)) { return prop; } } return null; } private MethodSpec generateCopyInterStageImpl(String implClassName) { final List<String> elementList = getInterStageVariableNames(); if (elementList.isEmpty()) { return null; } final String implInstanceName = getImplInstanceName(); final MethodSpec.Builder copyInterStageComponentBuilder = MethodSpec .methodBuilder("copyInterStageImpl") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(TypeName.VOID) .addParameter( ParameterizedTypeName.get( ClassNames.COMPONENT, ClassName.bestGuess(getSimpleClassName())), "impl") .addStatement( "$L " + implInstanceName + " = ($L) impl", implClassName, implClassName); for (String s : elementList) { copyInterStageComponentBuilder .addStatement( "$L = " + implInstanceName + ".$L", s, s); } return copyInterStageComponentBuilder.build(); } private List<String> getInterStageVariableNames() { final List<String> elementList = new ArrayList<>(); for (VariableElement v : mImplMembers.values()) { if (isInterStageComponentVariable(v)) { elementList.add(v.getSimpleName().toString()); } } return elementList; } private static boolean isInterStageComponentVariable(VariableElement variableElement) { final TypeMirror variableType = variableElement.asType(); final TypeMirror outputTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.OUTPUT); return outputTypeMirror != null; } private static boolean isStateProp(VariableElement variableElement) { return variableElement.getAnnotation(State.class) != null; } public void generateListEvents() { for (TypeElement event : mEventDeclarations) { generateEvent( event, ClassNames.EVENT_HANDLER, SectionClassNames.SECTION_LIFECYCLE, SectionClassNames.SECTION_CONTEXT, "getSectionScope"); } } private static String getEventHandlerInstanceName(String eventHandlerClassName) { return Character.toLowerCase(eventHandlerClassName.charAt(0)) + eventHandlerClassName.substring(1) + "Handler"; } private void generateEvent( TypeElement eventDeclaration, ClassName eventHandlerClassName, ClassName lifecycleClassName, ClassName contextClassName, String scopeMethodName) { final String eventName = eventDeclaration.getSimpleName().toString(); writeMethodSpec(MethodSpec.methodBuilder("get" + eventName + "Handler") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(eventHandlerClassName) .addParameter(contextClassName, "context") .addCode( CodeBlock.builder() .beginControlFlow("if (context.$L() == null)", scopeMethodName) .addStatement("return null") .endControlFlow() .build()) .addStatement( "return (($L.$T) context.$L()).$L", getSimpleClassName(), ClassName.bestGuess(getImplClassName()), scopeMethodName, getEventHandlerInstanceName(eventName)) .build()); // Override the method that the component will call to fire the event. final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] {}; methodDescription.accessType = Modifier.STATIC; methodDescription.name = "dispatch" + eventName; methodDescription.parameterTypes = new TypeName[] { ClassName.bestGuess(mQualifiedClassName) }; final TypeMirror returnType = Utils.getAnnotationParameter(mProcessingEnv, eventDeclaration, Event.class, "returnType"); if (returnType != null) { methodDescription.returnType = TypeName.get(returnType); } generateEventDispatcher( methodDescription, eventDeclaration.getTypeParameters(), eventDeclaration, eventHandlerClassName, lifecycleClassName); } /** * Generate an event dispatcher method for the given event. * * @param fixedMethod description of method signature to be generated * @param typeParameters * @param element method the event will call to dispatch * @param eventHandlerClassName @throws IOException If one of the writer methods throw */ private void generateEventDispatcher( MethodDescription fixedMethod, List<? extends TypeParameterElement> typeParameters, TypeElement element, ClassName eventHandlerClassName, ClassName lifecycleClassName) { final List<? extends VariableElement> parameters = Utils.getEnclosedFields(element); final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(fixedMethod.name); if (fixedMethod.annotations != null) { for (Class annotation : fixedMethod.annotations) { methodBuilder.addAnnotation(annotation); } } for (TypeParameterElement typeParameterElement : typeParameters) { methodBuilder.addTypeVariable( TypeVariableName.get(typeParameterElement.getSimpleName().toString())); } if (fixedMethod.accessType != null) { methodBuilder.addModifiers(fixedMethod.accessType); } methodBuilder.addParameter(eventHandlerClassName, "_eventHandler"); for (VariableElement v : parameters) { methodBuilder.addParameter(ClassName.get(v.asType()), v.getSimpleName().toString()); } // Add the event parameters to a implParameters. // This should come from a pool. final ClassName className = ClassName.get(element); methodBuilder.addStatement( "$T _eventState = new $T()", className, className); for (VariableElement v : parameters) { final String variableName = v.getSimpleName().toString(); methodBuilder.addStatement("_eventState.$L = $L", variableName, variableName); } methodBuilder.addStatement( "$T _lifecycle = _eventHandler.mHasEventDispatcher.getEventDispatcher()", ClassNames.EVENT_DISPATCHER); final TypeName returnType = fixedMethod.returnType; if (returnType != null && !returnType.equals(ClassName.VOID)) { methodBuilder.addStatement( "return ($L) _lifecycle.dispatchOnEvent(_eventHandler, _eventState)", returnType); methodBuilder.returns(returnType); } else { methodBuilder.addStatement("_lifecycle.dispatchOnEvent(_eventHandler, _eventState)"); } writeMethodSpec(methodBuilder.build()); } /** * Generate a builder method for a given declared parameters. */ private Collection<MethodSpec> generatePropsBuilderMethods( VariableElement element, TypeName propsBuilderClassName, int requiredIndex, ClassName componentClassName) { final Prop propAnnotation = element.getAnnotation(Prop.class); final ResType resType = propAnnotation.resType(); switch (resType) { case STRING: assertOfType(element, TypeName.get(String.class), TypeName.get(CharSequence.class)); break; case STRING_ARRAY: assertOfType(element, TypeName.get(String[].class)); break; case INT: assertOfType(element, TypeName.get(int.class), TypeName.get(Integer.class)); break; case INT_ARRAY: assertOfType(element, TypeName.get(int[].class)); break; case BOOL: assertOfType(element, TypeName.get(boolean.class), TypeName.get(Boolean.class)); break; case COLOR: assertOfType(element, TypeName.get(int.class), TypeName.get(Integer.class)); break; case DIMEN_SIZE: assertOfType( element, TypeName.get(int.class), TypeName.get(Integer.class), TypeName.get(float.class), TypeName.get(Float.class)); break; case DIMEN_TEXT: assertOfType( element, TypeName.get(int.class), TypeName.get(Integer.class), TypeName.get(float.class), TypeName.get(Float.class)); break; case DIMEN_OFFSET: assertOfType( element, TypeName.get(int.class), TypeName.get(Integer.class), TypeName.get(float.class), TypeName.get(Float.class)); break; case FLOAT: assertOfType(element, TypeName.get(float.class), TypeName.get(Float.class)); break; case DRAWABLE: assertOfType(element, ParameterizedTypeName.get(ClassNames.REFERENCE, ClassNames.DRAWABLE)); break; } TypeMirror typeMirror = element.asType(); final TypeMirror diffTypeMirror = Utils.getGenericTypeArgument(typeMirror, ClassNames.DIFF); if (diffTypeMirror != null) { typeMirror = diffTypeMirror; } final TypeName type = JPUtil.getTypeFromMirror(typeMirror); final String name = element.getSimpleName().toString(); final PropParameter propParameter = new PropParameter( new Parameter(type, name), propAnnotation.optional(), resType, getNonComponentAnnotations(element)); return new PropsBuilderMethodsSpecBuilder() .index(requiredIndex) .propParameter(propParameter) .implName(getImplMemberInstanceName()) .requiredSetName("mRequired") .builderClass(propsBuilderClassName) .componentClassName(componentClassName) .build(); } private void assertOfType(VariableElement element, TypeName... types) { final TypeName elementType = JPUtil.getTypeFromMirror(element.asType()); for (TypeName type : types) { if (type.toString().equals(elementType.toString())) { return; } } throw new ComponentsProcessingException( element, "Expected parameter of one of types" + Arrays.toString(types) + ". Found " + elementType); } private List<ClassName> getNonComponentAnnotations(VariableElement element) { final List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors(); final List<ClassName> annotations = new ArrayList<>(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (annotationMirror.getAnnotationType().toString().startsWith("com.facebook.litho")) { continue; } if (annotationMirror.getElementValues().size() > 0) { throw new ComponentsProcessingException( element, "Currently only non-component annotations without parameters are supported"); } annotations.add(ClassName.bestGuess(annotationMirror.getAnnotationType().toString())); } return annotations; } public void generateReferenceBuilder(StaticFlag isStatic, TypeName genericType) { generateBuilder( isStatic, StyleableFlag.NOT_STYLEABLE, ClassNames.REFERENCE, genericType, INNER_IMPL_BUILDER_CLASS_NAME, new TypeName[]{genericType}, ClassNames.COMPONENT_CONTEXT, null, null, false, false); generateBuilderPool( ClassName.bestGuess(INNER_IMPL_BUILDER_CLASS_NAME), "m" + INNER_IMPL_BUILDER_CLASS_NAME + "Pool", mTypeVariables.isEmpty() || isStatic == StaticFlag.STATIC ? StaticFlag.STATIC : StaticFlag.NOT_STATIC, StyleableFlag.NOT_STYLEABLE, ClassNames.COMPONENT_CONTEXT); writeMethodSpec(MethodSpec.methodBuilder("create") .addModifiers(Modifier.PUBLIC) .returns(ClassName.bestGuess(INNER_IMPL_BUILDER_CLASS_NAME)) .addParameter(ClassNames.COMPONENT_CONTEXT, "context") .addStatement( "return new$L(context, new $T())", INNER_IMPL_BUILDER_CLASS_NAME, ClassName.bestGuess(getImplClassName())) .addModifiers(isStatic == StaticFlag.STATIC ? Modifier.STATIC : Modifier.FINAL) .build()); } public void generateListBuilder(StaticFlag isStatic, TypeName genericType) { generateBuilder( isStatic, StyleableFlag.NOT_STYLEABLE, SectionClassNames.SECTION, genericType, INNER_IMPL_BUILDER_CLASS_NAME, new TypeName[]{genericType}, SectionClassNames.SECTION_CONTEXT, ClassNames.EVENT_HANDLER, SectionClassNames.SECTION, true, true); generateBuilderPool( ClassName.bestGuess(INNER_IMPL_BUILDER_CLASS_NAME), "m" + INNER_IMPL_BUILDER_CLASS_NAME + "Pool", mTypeVariables.isEmpty() || isStatic == StaticFlag.STATIC ? StaticFlag.STATIC : StaticFlag.NOT_STATIC, StyleableFlag.NOT_STYLEABLE, SectionClassNames.SECTION_CONTEXT);
import java.util.*; public class VacuumRobot { // instructions public static final String LEFT_COMMAND = "L"; public static final String RIGHT_COMMAND = "R"; public static final String NEW_LINE = "\n"; private static final String INITIAL_INPUT = ""; private static final String OVERRIDE_CODE = "2"; private static final int OVERRIDE_LOCATION = 0; public VacuumRobot (Map map, Vector<String> instructions, boolean debug) { _theMap = map; _computer = new Intcode(instructions, INITIAL_INPUT, debug); _debug = debug; /* * "Force the vacuum robot to wake up by changing the value in your * ASCII program at address 0 from 1 to 2." * * Check it's 1 before changing? Maybe add a test-and-set/override? */ _computer.changeInstruction(OVERRIDE_LOCATION, OVERRIDE_CODE); } private Map _theMap; private Intcode _computer; private boolean _debug; }
package Fragments; import android.app.Activity; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.text.Html; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.kaltura.kalturaplayertoolkit.R; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link LoginFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link LoginFragment#newInstance} factory method to * create an instance of this fragment. */ public class LoginFragment extends Fragment { private static final String TAG = LoginFragment.class.getSimpleName(); private OnFragmentInteractionListener mListener; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment LoginFragment. */ // TODO: Rename and change types and number of parameters public static LoginFragment newInstance(String param1, String param2) { LoginFragment fragment = new LoginFragment(); // Bundle args = new Bundle(); // args.putString(ARG_PARAM1, param1); // args.putString(ARG_PARAM2, param2); // fragment.setArguments(args); return fragment; } public LoginFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { //retain value } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View fragmentView = inflater.inflate(R.layout.fragment_login, container, false); Intent intent = getActivity().getIntent(); // check if this intent is started via browser if ( Intent.ACTION_VIEW.equals( intent.getAction() ) ) { Uri uri = intent.getData(); String[] params = null; try { params = URLDecoder.decode(uri.toString(), "UTF-8").split(":="); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ( params!=null && params.length > 1 ) { String iframeUrl = params[1]; intent.putExtra(getString(R.string.prop_iframe_url), iframeUrl); loadPlayerFragment(); } else { Log.w(TAG, "didn't load iframe, invalid iframeUrl parameter was passed"); } } TextView infoMsg = (TextView)fragmentView.findViewById(R.id.infoMsg); Spanned spanned = Html.fromHtml(getString(R.string.main_message)); infoMsg.setMovementMethod(LinkMovementMethod.getInstance()); infoMsg.setText(spanned); Button demoBtn = (Button)fragmentView.findViewById(R.id.demoBtn); demoBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { loadPlayerFragment(); } }); return fragmentView; } private void loadPlayerFragment(){ // Create fragment and give it an argument specifying the article it should show PlayerFragment newFragment = new PlayerFragment(); Bundle args = new Bundle(); // args.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(args); FragmentTransaction transaction = getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } }
package com.facebook.litho.processor; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; 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.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.facebook.common.internal.ImmutableList; import com.facebook.litho.annotations.Event; import com.facebook.litho.annotations.FromEvent; import com.facebook.litho.annotations.OnCreateInitialState; import com.facebook.litho.annotations.OnCreateTreeProp; import com.facebook.litho.annotations.OnEvent; import com.facebook.litho.annotations.OnLoadStyle; import com.facebook.litho.annotations.OnUpdateState; import com.facebook.litho.annotations.Param; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.litho.annotations.State; import com.facebook.litho.annotations.TreeProp; import com.facebook.litho.javapoet.JPUtil; import com.facebook.litho.processor.GetTreePropsForChildrenMethodBuilder.CreateTreePropMethodData; import com.facebook.litho.specmodels.model.ClassNames; import com.facebook.litho.specmodels.model.PropDefaultModel; import com.facebook.litho.specmodels.processor.PropDefaultsExtractor; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import static com.facebook.litho.processor.Utils.capitalize; import static com.facebook.litho.processor.Visibility.PRIVATE; import static com.facebook.litho.specmodels.generator.GeneratorConstants.DELEGATE_FIELD_NAME; import static com.facebook.litho.specmodels.generator.GeneratorConstants.SPEC_INSTANCE_NAME; import static java.util.Arrays.asList; import static javax.lang.model.type.TypeKind.ARRAY; import static javax.lang.model.type.TypeKind.DECLARED; import static javax.lang.model.type.TypeKind.DOUBLE; import static javax.lang.model.type.TypeKind.FLOAT; import static javax.lang.model.type.TypeKind.TYPEVAR; import static javax.lang.model.type.TypeKind.VOID; public class Stages { public static final String IMPL_CLASS_NAME_SUFFIX = "Impl"; private static final String INNER_IMPL_BUILDER_CLASS_NAME = "Builder"; private static final String STATE_UPDATE_IMPL_NAME_SUFFIX = "StateUpdate"; public static final String STATE_CONTAINER_IMPL_NAME_SUFFIX = "StateContainerImpl"; public static final String STATE_CONTAINER_IMPL_MEMBER = "mStateContainerImpl"; private static final String REQUIRED_PROPS_NAMES = "REQUIRED_PROPS_NAMES"; private static final String REQUIRED_PROPS_COUNT = "REQUIRED_PROPS_COUNT"; private static final int ON_STYLE_PROPS = 1; private static final int ON_CREATE_INITIAL_STATE = 1; private final boolean mSupportState; public enum StaticFlag { STATIC, NOT_STATIC } public enum StyleableFlag { STYLEABLE, NOT_STYLEABLE } // Using these names in props might cause conflicts with the method names in the // component's generated layout builder class so we trigger a more user-friendly // error if the component tries to use them. This list should be kept in sync // with BaseLayoutBuilder. private static final String[] RESERVED_PROP_NAMES = new String[] { "withLayout", "key", "loadingEventHandler", }; private static final Class<Annotation>[] TREE_PROP_ANNOTATIONS = new Class[] { TreeProp.class, }; private static final Class<Annotation>[] PROP_ANNOTATIONS = new Class[] { Prop.class, }; private static final Class<Annotation>[] STATE_ANNOTATIONS = new Class[] { State.class, }; private final ProcessingEnvironment mProcessingEnv; private final TypeElement mSourceElement; private final String mQualifiedClassName; private final Class<Annotation>[] mStageAnnotations; private final Class<Annotation>[] mInterStagePropAnnotations; private final Class<Annotation>[] mParameterAnnotations; private final TypeSpec.Builder mClassTypeSpec; private final List<TypeVariableName> mTypeVariables; private final List<TypeElement> mEventDeclarations; private final Map<String, String> mPropJavadocs; private final String mSimpleClassName; private String mSourceDelegateAccessorName = DELEGATE_FIELD_NAME; private List<VariableElement> mProps; private List<VariableElement> mOnCreateInitialStateDefinedProps; private ImmutableList<PropDefaultModel> mPropDefaults; private List<VariableElement> mTreeProps; private final Map<String, VariableElement> mStateMap = new LinkedHashMap<>(); // Map of name to VariableElement, for members of the inner implementation class, in order private LinkedHashMap<String, VariableElement> mImplMembers; private List<Parameter> mImplParameters; private final Map<String, TypeMirror> mExtraStateMembers; // List of methods that have @OnEvent on it. private final List<ExecutableElement> mOnEventMethods; // List of methods annotated with @OnUpdateState. private final List<ExecutableElement> mOnUpdateStateMethods; private final List<ExecutableElement> mOnCreateTreePropsMethods; // List of methods that define stages (e.g. OnCreateLayout) private List<ExecutableElement> mStages; public TypeElement getSourceElement() { return mSourceElement; } public Stages( ProcessingEnvironment processingEnv, TypeElement sourceElement, String qualifiedClassName, Class<Annotation>[] stageAnnotations, Class<Annotation>[] interStagePropAnnotations, TypeSpec.Builder typeSpec, List<TypeVariableName> typeVariables, boolean supportState, Map<String, TypeMirror> extraStateMembers, List<TypeElement> eventDeclarations, Map<String, String> propJavadocs) { mProcessingEnv = processingEnv; mSourceElement = sourceElement; mQualifiedClassName = qualifiedClassName; mStageAnnotations = stageAnnotations; mInterStagePropAnnotations = interStagePropAnnotations; mClassTypeSpec = typeSpec; mTypeVariables = typeVariables; mEventDeclarations = eventDeclarations; mPropJavadocs = propJavadocs; final List<Class<Annotation>> parameterAnnotations = new ArrayList<>(); parameterAnnotations.addAll(asList(PROP_ANNOTATIONS)); parameterAnnotations.addAll(asList(STATE_ANNOTATIONS)); parameterAnnotations.addAll(asList(mInterStagePropAnnotations)); parameterAnnotations.addAll(asList(TREE_PROP_ANNOTATIONS)); mParameterAnnotations = parameterAnnotations.toArray( new Class[parameterAnnotations.size()]); mSupportState = supportState; mSimpleClassName = Utils.getSimpleClassName(mQualifiedClassName); mOnEventMethods = Utils.getAnnotatedMethods(mSourceElement, OnEvent.class); mOnUpdateStateMethods = Utils.getAnnotatedMethods(mSourceElement, OnUpdateState.class); mOnCreateTreePropsMethods = Utils.getAnnotatedMethods(mSourceElement, OnCreateTreeProp.class); mExtraStateMembers = extraStateMembers; validateOnEventMethods(); populatePropDefaults(); populateStages(); validateAnnotatedParameters(); populateOnCreateInitialStateDefinedProps(); populateProps(); populateTreeProps(); if (mSupportState) { populateStateMap(); } validatePropDefaults(); populateImplMembers(); populateImplParameters(); validateStyleOutputs(); } private boolean isInterStagePropAnnotationValidInStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); final int stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } // This logic relies on the fact that there are prop annotations for each stage (except for // some number at the end) return interStagePropIndex < stageIndex; } private boolean doesInterStagePropAnnotationMatchStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); // Null stage is allowed and indicates prop int stageIndex = -1; if (stage != null) { stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } } return interStagePropIndex == stageIndex; } private void validateOnEventMethods() { final Map<String, Boolean> existsMap = new HashMap<>(); for (ExecutableElement element : mOnEventMethods) { if (existsMap.containsKey(element.getSimpleName().toString())) { throw new ComponentsProcessingException( element, "@OnEvent declared methods must have unique names"); } final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final TypeMirror returnType = Utils.getAnnotationParameter( mProcessingEnv, eventClass.asElement(), Event.class, "returnType"); if (!mProcessingEnv.getTypeUtils().isSameType(element.getReturnType(), returnType)) { throw new ComponentsProcessingException( element, "Method " + element.getSimpleName() + " must return " + returnType + ", since that is what " + eventClass + " expects."); } final List<? extends VariableElement> parameters = Utils.getEnclosedFields((TypeElement) eventClass.asElement()); for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) { boolean hasMatchingParameter = false; for (VariableElement parameter : parameters) { if (parameter.getSimpleName().equals(v.getSimpleName()) && parameter.asType().toString().equals(v.asType().toString())) { hasMatchingParameter = true; break; } } if (!hasMatchingParameter) { throw new ComponentsProcessingException( v, v.getSimpleName() + " of this type is not a member of " + eventClass); } return; } existsMap.put(element.getSimpleName().toString(), true); } } /** * Ensures that the declared events don't clash with the predefined ones. */ private void validateEventDeclarations() { for (TypeElement eventDeclaration : mEventDeclarations) { final Event eventAnnotation = eventDeclaration.getAnnotation(Event.class); if (eventAnnotation == null) { throw new ComponentsProcessingException( eventDeclaration, "Events must be declared with the @Event annotation, event is: " + eventDeclaration); } final List<? extends VariableElement> fields = Utils.getEnclosedFields(eventDeclaration); for (VariableElement field : fields) { if (!field.getModifiers().contains(Modifier.PUBLIC) || field.getModifiers().contains(Modifier.FINAL)) { throw new ComponentsProcessingException( field, "Event fields must be declared as public non-final"); } } } } private void validateStyleOutputs() { final ExecutableElement delegateMethod = Utils.getAnnotatedMethod( mSourceElement, OnLoadStyle.class); if (delegateMethod == null) { return; } final List<? extends VariableElement> parameters = delegateMethod.getParameters(); if (parameters.size() < ON_STYLE_PROPS) { throw new ComponentsProcessingException( delegateMethod, "The @OnLoadStyle method should have an ComponentContext" + "followed by Output parameters matching component create."); } final TypeName firstParamType = ClassName.get(parameters.get(0).asType()); if (!firstParamType.equals(ClassNames.COMPONENT_CONTEXT)) { throw new ComponentsProcessingException( parameters.get(0), "The first argument of the @OnLoadStyle method should be an ComponentContext."); } for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final TypeMirror outputType = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT); if (outputType == null) { throw new ComponentsProcessingException( parameters.get(i), "The @OnLoadStyle method should have only have Output arguments matching " + "component create."); } final Types typeUtils = mProcessingEnv.getTypeUtils(); final String name = v.getSimpleName().toString(); boolean matchesProp = false; for (Element prop : mProps) { if (!prop.getSimpleName().toString().equals(name)) { continue; } matchesProp = true; if (!typeUtils.isAssignable(prop.asType(), outputType)) { throw new ComponentsProcessingException( v, "Searching for prop \"" + name + "\" of type " + ClassName.get(outputType) + " but found prop with the same name of type " + ClassName.get(prop.asType())); } } if (!matchesProp) { throw new ComponentsProcessingException( v, "Output named '" + v.getSimpleName() + "' does not match any prop " + "in the component."); } } } private void validateAnnotatedParameters() { final List<PrintableException> exceptions = new ArrayList<>(); final Map<String, VariableElement> variableNameToElementMap = new HashMap<>(); final Map<String, Class<? extends Annotation>> outputVariableToStage = new HashMap<>(); for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage == null) { continue; } // Enforce #5: getSpecDefinedParameters will verify that parameters don't have duplicate // annotations for (VariableElement v : getSpecDefinedParameters(stage)) { try { final String variableName = v.getSimpleName().toString(); final Annotation interStagePropAnnotation = getInterStagePropAnnotation(v); final boolean isOutput = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT) != null; if (isOutput) { outputVariableToStage.put(variableName, stageAnnotation); } // Enforce if (interStagePropAnnotation != null) { final Class<? extends Annotation> outputStage = outputVariableToStage.get(variableName); if (!doesInterStagePropAnnotationMatchStage( interStagePropAnnotation.annotationType(), outputStage)) { throw new ComponentsProcessingException( v, "Inter-stage prop declaration is incorrect, the same name and type must be " + "used in every method where the inter-stage prop is declared."); } } // Enforce if (interStagePropAnnotation != null && !isInterStagePropAnnotationValidInStage( interStagePropAnnotation.annotationType(), stageAnnotation)) { throw new ComponentsProcessingException( v, "Inter-stage create must refer to previous stages."); } final VariableElement existingType = variableNameToElementMap.get(variableName); if (existingType != null && !isSameType(existingType.asType(), v.asType())) { // We have a type mis-match. This is allowed, provided that the previous type is an // outputand the new type is an prop, and the type argument of the output matches the // prop. In the future, we may want to allow stages to modify outputs from previous // stages, but for now we disallow it. // Enforce #1 and #2 if ((getInterStagePropAnnotation(v) == null || Utils.getGenericTypeArgument(existingType.asType(), ClassNames.OUTPUT) == null) && Utils.getGenericTypeArgument(existingType.asType(), ClassNames.DIFF) == null) { throw new ComponentsProcessingException( v, "Inconsistent type for '" + variableName + "': '" + existingType.asType() + "' and '" + v.asType() + "'"); } } else if (existingType == null) { // We haven't see a parameter with this name yet. Therefore it must be either @Prop, // @State or an output. final boolean isFromProp = getParameterAnnotation(v, PROP_ANNOTATIONS) != null; final boolean isFromState = getParameterAnnotation(v, STATE_ANNOTATIONS) != null; final boolean isFromTreeProp = getParameterAnnotation(v, TREE_PROP_ANNOTATIONS) != null; if (isFromState && !mSupportState) { throw new ComponentsProcessingException( v, "State is not supported in this kind of Spec."); } if (!isFromProp && !isFromState && !isOutput && !isFromTreeProp) { throw new ComponentsProcessingException( v, "Inter-stage prop declared without source."); } } // Enforce final Prop propAnnotation = v.getAnnotation(Prop.class); if (propAnnotation != null) { for (String reservedPropName : RESERVED_PROP_NAMES) { if (reservedPropName.equals(variableName)) { throw new ComponentsProcessingException( v, "'" + reservedPropName + "' is a reserved prop name used by " + "the component's layout builder. Please use another name."); } } // Enforce final boolean hasDefaultValue = hasDefaultValue(v); if (hasDefaultValue && !propAnnotation.optional()) { throw new ComponentsProcessingException( v, "Prop is not optional but has a declared default value."); } // Enforce if (existingType != null) { final Prop existingPropAnnotation = existingType.getAnnotation(Prop.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The prop '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this prop is declared identically."); } } } // Enforce TypeName typeName; try { typeName = ClassName.get(v.asType()); } catch (IllegalArgumentException e) { throw new ComponentsProcessingException( v, "Prop type does not exist"); } // Enforce final List<ClassName> illegalPropTypes = Arrays.asList( ClassNames.COMPONENT_LAYOUT, ClassNames.COMPONENT_LAYOUT_BUILDER, ClassNames.COMPONENT_LAYOUT_CONTAINER_BUILDER, ClassNames.COMPONENT_BUILDER, ClassNames.COMPONENT_BUILDER_WITH_LAYOUT, ClassNames.REFERENCE_BUILDER); if (illegalPropTypes.contains(typeName)) { throw new ComponentsProcessingException( v, "Props may not be declared with the following types:" + illegalPropTypes); } } variableNameToElementMap.put(variableName, v); } catch (PrintableException e) { exceptions.add(e); } } } if (!exceptions.isEmpty()) { throw new MultiPrintableException(exceptions); } } private boolean hasSameAnnotations(VariableElement v1, VariableElement v2) { final List<? extends AnnotationMirror> v1Annotations = v1.getAnnotationMirrors(); final List<? extends AnnotationMirror> v2Annotations = v2.getAnnotationMirrors(); if (v1Annotations.size() != v2Annotations.size()) { return false; } final int count = v1Annotations.size(); for (int i = 0; i < count; i++) { final AnnotationMirror a1 = v1Annotations.get(i); final AnnotationMirror a2 = v2Annotations.get(i); // Some object in this hierarchy don't implement equals correctly. // They do however produce very nice strings representations which we can compare instead. if (!a1.toString().equals(a2.toString())) { return false; } } return true; } public void validateStatic() { validateStaticFields(); validateStaticMethods(); } private void validateStaticFields() { for (Element element : mSourceElement.getEnclosedElements()) { if (element.getKind() == ElementKind.FIELD && !element.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( element, "Field " + element.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } private void validateStaticMethods() { for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null && !stage.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( stage, "Method " + stage.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } /** * Gather a list of VariableElement that are the props to this component */ private void populateProps() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getProps(stage)) { // Validation unnecessary - already handled by validateAnnotatedParameters final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mProps = new ArrayList<>(variableNameToElementMap.values()); addCreateInitialStateDefinedProps(mProps); } /** * Gather a list of VariableElement that are the state to this component */ private void populateStateMap() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getState(stage)) { final String variableName = v.getSimpleName().toString(); if (mStateMap.containsKey(variableName)) { VariableElement existingType = mStateMap.get(variableName); final State existingPropAnnotation = existingType.getAnnotation(State.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The state '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this state is declared identically."); } } } mStateMap.put( variableName, v); } } } private void populateTreeProps() { final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : Utils.getParametersWithAnnotation(stage, TreeProp.class)) { final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mTreeProps = new ArrayList<>(variableNameToElementMap.values()); } /** * Get the list of stages (OnInflate, OnMeasure, OnMount) that are defined for this component. */ private void populateStages() { mStages = new ArrayList<>(); for (Class<Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null) { mStages.add(stage); } } if (mOnEventMethods != null) { mStages.addAll(mOnEventMethods); } mStages.addAll(mOnCreateTreePropsMethods); } /** * @param prop The prop to determine if it has a default or not. * @return Returns true if the prop has a default, false otherwise. */ private boolean hasDefaultValue(VariableElement prop) { final String name = prop.getSimpleName().toString(); final TypeName type = TypeName.get(prop.asType()); for (PropDefaultModel propDefault : mPropDefaults) { if (propDefault.mName.equals(name) && propDefault.mType.equals(type)) { return true; } } return false; } /** * Fail if any elements that exist in mPropDefaults do not exist in mProps. */ private void validatePropDefaults() { for (PropDefaultModel propDefault : mPropDefaults) { final ImmutableList<Modifier> modifiers = propDefault.mModifiers; if (!modifiers.contains(Modifier.STATIC) || !modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.PRIVATE)) { throw new RuntimeException( "Defaults for props (fields annotated with " + PropDefault.class + ") must be " + "non-private, static, and final. This is not the case for " + propDefault.mName); } if (!hasValidNameAndType(propDefault)) { throw new RuntimeException( "Prop defaults (fields annotated with " + PropDefault.class + ") should have the " + "same name and type as the prop that they set the default for. This is not the " + "case for " + propDefault.mName); } } } /** * @return true if the given prop default matches the name and type of a prop, false otherwise. */ private boolean hasValidNameAndType(PropDefaultModel propDefault) { for (VariableElement prop : mProps) { if (prop.getSimpleName().toString().equals(propDefault.mName) && TypeName.get(prop.asType()).equals(propDefault.mType)) { return true; } } return false; } /** * Gather a list of parameters from the given element that are props to this component. */ private static List<VariableElement> getProps(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, Prop.class); } /** * Gather a list of parameters from the given element that are state to this component. */ private static List<VariableElement> getState(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, State.class); } /** * Gather a list of parameters from the given element that are defined by the spec. That is, they * aren't one of the parameters predefined for a given method. For example, OnCreateLayout has a * predefined parameter of type LayoutContext. Spec-defined parameters are annotated with one of * our prop annotations or are of type {@link com.facebook.litho.Output}. */ private List<VariableElement> getSpecDefinedParameters(ExecutableElement element) { return getSpecDefinedParameters(element, true); } private List<VariableElement> getSpecDefinedParameters( ExecutableElement element, boolean shouldIncludeOutputs) { final ArrayList<VariableElement> specDefinedParameters = new ArrayList<>(); for (VariableElement v : element.getParameters()) { final boolean isAnnotatedParameter = getParameterAnnotation(v) != null; final boolean isInterStageOutput = Utils.getGenericTypeArgument( v.asType(), ClassNames.OUTPUT) != null; if (isAnnotatedParameter && isInterStageOutput) { throw new ComponentsProcessingException( v, "Variables that are both prop and output are forbidden."); } else if (isAnnotatedParameter || (shouldIncludeOutputs && isInterStageOutput)) { specDefinedParameters.add(v); } } return specDefinedParameters; } private void populateOnCreateInitialStateDefinedProps() { final ExecutableElement onCreateInitialState = Utils.getAnnotatedMethod( getSourceElement(), OnCreateInitialState.class); if (onCreateInitialState == null) { mOnCreateInitialStateDefinedProps = new ArrayList<>(); } else { mOnCreateInitialStateDefinedProps = getSpecDefinedParameters(onCreateInitialState, false); } } /** * Get the @FromLayout, @FromMeasure, etc annotation on this element (@Prop isn't * considered - use getParameterAnnotation if you want to consider them) */ private Annotation getInterStagePropAnnotation(VariableElement element) { return getParameterAnnotation(element, mInterStagePropAnnotations); } /** * Get the annotation, if any, present on a parameter. Annotations are restricted to our whitelist * of parameter annotations: e.g. {@link Prop}, {@link State} etc) */ private Annotation getParameterAnnotation(VariableElement element) { return getParameterAnnotation(element, mParameterAnnotations); } /** * Get the annotation, if any, present on a parameter. Annotations are restricted to the specified * whitelist. If there is a duplicate we will issue an error. */ private Annotation getParameterAnnotation( VariableElement element, Class<Annotation>[] possibleAnnotations) { final ArrayList<Annotation> annotations = new ArrayList<>(); for (Class<Annotation> annotationClass : possibleAnnotations) { final Annotation annotation = element.getAnnotation(annotationClass); if (annotation != null) { annotations.add(annotation); } } if (annotations.isEmpty()) { return null; } else if (annotations.size() == 1) { return annotations.get(0); } else { throw new ComponentsProcessingException( element, "Duplicate parameter annotation: '" + annotations.get(0) + "' and '" + annotations.get(1) + "'"); } } /** * Generate javadoc block describing component props. */ public void generateJavadoc() { for (VariableElement v : mProps) { final Prop propAnnotation = v.getAnnotation(Prop.class); final String propTag = propAnnotation.optional() ? "@prop-optional" : "@prop-required"; final String javadoc = mPropJavadocs != null ? mPropJavadocs.get(v.getSimpleName().toString()) : ""; final String sanitizedJavadoc = javadoc != null ? javadoc.replace('\n', ' ') : null; // Adds javadoc with following format: // @prop-required name type javadoc. // This can be changed later to use clear demarcation for fields. // This is a block tag and cannot support inline tags like "{@link something}". mClassTypeSpec.addJavadoc( "$L $L $L $L\n", propTag, v.getSimpleName().toString(), Utils.getTypeName(v.asType()), sanitizedJavadoc); } } /** * Generate a method for this component which either lazily instantiates a singleton reference or * return this depending on whether this lifecycle is static or not. */ public void generateGetter(boolean isStatic) { final ClassName className = ClassName.bestGuess(mQualifiedClassName); if (isStatic) { mClassTypeSpec.addField( FieldSpec .builder(className, SPEC_INSTANCE_NAME, Modifier.PRIVATE, Modifier.STATIC) .initializer("null") .build()); mClassTypeSpec.addMethod( MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC) .addModifiers(Modifier.STATIC) .addModifiers(Modifier.SYNCHRONIZED) .returns(className) .beginControlFlow("if ($L == null)", SPEC_INSTANCE_NAME) .addStatement("$L = new $T()", SPEC_INSTANCE_NAME, className) .endControlFlow() .addStatement("return $L", SPEC_INSTANCE_NAME) .build()); } else { mClassTypeSpec.addMethod( MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC) .returns(className) .addStatement("return this") .build()); } } public void generateSourceDelegate(boolean initialized) { final ClassName specClassName = ClassName.get(mSourceElement); generateSourceDelegate(initialized, specClassName); } public void generateSourceDelegate(boolean initialized, TypeName specTypeName) { final FieldSpec.Builder builder = FieldSpec .builder(specTypeName, DELEGATE_FIELD_NAME) .addModifiers(Modifier.PRIVATE); if (initialized) { builder.initializer("new $T()", specTypeName); } mClassTypeSpec.addField(builder.build()); } private MethodSpec generateMakeShallowCopy(ClassName componentClassName, boolean hasDeepCopy) { final List<String> componentsInImpl = findComponentsInImpl(componentClassName); final List<String> interStageComponentVariables = getInterStageVariableNames(); if (componentsInImpl.isEmpty() && interStageComponentVariables.isEmpty() && mOnUpdateStateMethods.isEmpty()) { return null; } final String implClassName = getImplClassName(); return new ShallowCopyMethodSpecBuilder() .componentsInImpl(componentsInImpl) .interStageVariables(interStageComponentVariables) .implClassName(implClassName) .hasDeepCopy(hasDeepCopy) .stateContainerImplClassName(getStateContainerImplClassName()) .build(); } private List<String> findComponentsInImpl(ClassName listComponent) { final List<String> componentsInImpl = new ArrayList<>(); for (String key : mImplMembers.keySet()) { final VariableElement element = mImplMembers.get(key); final Name declaredClassName = Utils.getDeclaredClassNameWithoutGenerics(element); if (declaredClassName != null && ClassName.bestGuess(declaredClassName.toString()).equals(listComponent)) { componentsInImpl.add(element.getSimpleName().toString()); } } return componentsInImpl; } /** * Generate a private constructor to enforce singleton-ity. */ public void generateConstructor() { mClassTypeSpec.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build()); } /** * Generates a method to create the initial values for parameters annotated with {@link State}. * This method also validates that the delegate method only tries to assign an initial value to * State annotated parameters. */ public void generateCreateInitialState( ExecutableElement from, ClassName contextClass, ClassName componentClass) { verifyParametersForCreateInitialState(contextClass, from); final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = null; methodDescription.name = "createInitialState"; methodDescription.parameterTypes = new TypeName[] {contextClass}; generateDelegate(methodDescription, from, componentClass); } private void verifyParametersForCreateInitialState( ClassName contextClass, ExecutableElement executableElement) { final List<VariableElement> parameters = (List<VariableElement>) executableElement.getParameters(); if (parameters.size() < ON_CREATE_INITIAL_STATE + 1) { throw new ComponentsProcessingException( executableElement, "The @OnCreateInitialState method should have an " + contextClass + "followed by Output parameters matching state parameters."); } final TypeName firstParamType = ClassName.get(parameters.get(0).asType()); if (!firstParamType.equals(contextClass)) { throw new ComponentsProcessingException( parameters.get(0), "The first argument of the @OnCreateInitialState method should be an " + contextClass + "."); } for (int i = ON_CREATE_INITIAL_STATE, size = parameters.size(); i < size; i++) { final VariableElement element = parameters.get(i); final TypeMirror elementInnerClassType = Utils.getGenericTypeArgument(element.asType(), ClassNames.OUTPUT); if (elementInnerClassType != null) { final String paramName = element.getSimpleName().toString(); VariableElement implParameter = mStateMap.get(paramName); if (implParameter == null || implParameter.getAnnotation(State.class) == null) { throw new ComponentsProcessingException( executableElement, "Only parameters annotated with @State can be initialized in @OnCreateInitialState," + " parameter without annotation is: " + paramName); } } } } /** * Generate a method implementation that delegates to another method that takes annotated props. * * @param from description of method signature to be generated * @param to method to which to delegate * @param propsClass Component / Delegate. The base class of the inner implementation object * @throws java.io.IOException If one of the writer methods throw */ public void generateDelegate( MethodDescription from, ExecutableElement to, ClassName propsClass) { generateDelegate( from, to, Collections.<TypeName>emptyList(), Collections.<String, String>emptyMap(), propsClass); } public void generateDelegate( MethodDescription from, ExecutableElement to, List<TypeName> expectedTypes, ClassName propsClass) { generateDelegate( from, to, expectedTypes, Collections.<String, String>emptyMap(), propsClass); } /** * Generate a method implementation that delegates to another method that takes annotated props. * * @param from description of method signature to be generated * @param to method to which to delegate * @param propsClass Component / Delegate. The base class of the inner implementation object * @throws java.io.IOException If one of the writer methods throw */ public void generateDelegate( MethodDescription from, ExecutableElement to, List<TypeName> expectedTypes, Map<String, String> parameterTranslation, ClassName propsClass) { final Visibility visibility; if (Arrays.asList(from.accessType).contains(Modifier.PRIVATE)) { visibility = Visibility.PRIVATE; } else if (Arrays.asList(from.accessType).contains(Modifier.PROTECTED)) { visibility = Visibility.PROTECTED; } else if (Arrays.asList(from.accessType).contains(Modifier.PUBLIC)) { visibility = Visibility.PUBLIC; } else { visibility = Visibility.PACKAGE; } final List<Parameter> toParams = getParams(to); final List<Parameter> fromParams = new ArrayList<>(); for (int i = 0; i < from.parameterTypes.length; i++) { fromParams.add(new Parameter(from.parameterTypes[i], toParams.get(i).name)); } final List<PrintableException> errors = new ArrayList<>(); for (int i = 0; i < expectedTypes.size(); i++) { if (!toParams.get(i).type.equals(expectedTypes.get(i))) { errors.add(new ComponentsProcessingException( to.getParameters().get(i), "Expected " + expectedTypes.get(i))); } } if (!errors.isEmpty()) { throw new MultiPrintableException(errors); } writeMethodSpec(new DelegateMethodSpecBuilder() .implClassName(getImplClassName()) .abstractImplType(propsClass) .implParameters(mImplParameters) .checkedExceptions( from.exceptions == null ? new ArrayList<TypeName>() : Arrays.asList(from.exceptions)) .overridesSuper( from.annotations != null && Arrays.asList(from.annotations).contains(Override.class)) .parameterTranslation(parameterTranslation) .visibility(visibility) .fromName(from.name) .fromReturnType(from.returnType == null ? TypeName.VOID : from.returnType) .fromParams(fromParams) .target(mSourceDelegateAccessorName) .toName(to.getSimpleName().toString()) .stateParams(mStateMap.keySet()) .toReturnType(ClassName.get(to.getReturnType())) .toParams(toParams) .build()); } /** * Returns {@code true} if the given types match. */ public boolean isSameType(TypeMirror a, TypeMirror b) { return mProcessingEnv.getTypeUtils().isSameType(a, b); } /** * Generate an onEvent implementation that delegates to the @OnEvent-annotated method. */ public void generateOnEventHandlers(ClassName componentClassName, ClassName contextClassName) { for (ExecutableElement element : mOnEventMethods) { generateOnEventHandler(element, contextClassName); } } /** * Generate the static methods of the Component that can be called to update its state. */ public void generateOnStateUpdateMethods( ClassName contextClass, ClassName componentClassName, ClassName stateContainerClassName, ClassName stateUpdateInterface, Stages.StaticFlag staticFlag) { for (ExecutableElement element : mOnUpdateStateMethods) { validateOnStateUpdateMethodDeclaration(element); generateStateUpdateClass( element, componentClassName, stateContainerClassName, stateUpdateInterface, staticFlag); generateOnStateUpdateMethods(element, contextClass, componentClassName); } } /** * Validate that the declaration of a method annotated with {@link OnUpdateState} is correct: * <ul> * <li>1. Method parameters annotated with {@link Param} don't have the same name as parameters * annotated with {@link State} or {@link Prop}.</li> * <li>2. Method parameters not annotated with {@link Param} must be of type * com.facebook.litho.StateValue.</li> * <li>3. Names of method parameters not annotated with {@link Param} must match the name of * a parameter annotated with {@link State}.</li> * <li>4. Type of method parameters not annotated with {@link Param} must match the type of * a parameter with the same name annotated with {@link State}.</li> * </ul> */ private void validateOnStateUpdateMethodDeclaration(ExecutableElement element) { final List<VariableElement> annotatedParams = Utils.getParametersWithAnnotation(element, Param.class); // Check for (VariableElement annotatedParam : annotatedParams) { if (mStateMap.get(annotatedParam.getSimpleName().toString()) != null) { throw new ComponentsProcessingException( annotatedParam, "Parameters annotated with @Param should not have the same name as a parameter " + "annotated with @State or @Prop"); } } final List<VariableElement> params = (List<VariableElement>) element.getParameters(); for (VariableElement param : params) { if (annotatedParams.contains(param)) { continue; } final TypeMirror paramType = param.asType(); // Check if (paramType.getKind() != DECLARED) { throw new ComponentsProcessingException( param, "Parameters not annotated with @Param must be of type " + "com.facebook.litho.StateValue"); } final DeclaredType paramDeclaredType = (DeclaredType) param.asType(); final String paramDeclaredTypeName = paramDeclaredType .asElement() .getSimpleName() .toString(); if (!paramDeclaredTypeName.equals(ClassNames.STATE_VALUE.simpleName())) { throw new ComponentsProcessingException( "All state parameters must be of type com.facebook.litho.StateValue, " + param.getSimpleName() + " is of type " + param.asType()); } VariableElement stateMatchingParam = mStateMap.get(param.getSimpleName().toString()); // Check if (stateMatchingParam == null || stateMatchingParam.getAnnotation(State.class) == null) { throw new ComponentsProcessingException( param, "Names of parameters of type StateValue must match the name of a parameter annotated " + "with @State"); } // Check final List<TypeMirror> typeArguments = (List<TypeMirror>) paramDeclaredType.getTypeArguments(); if (typeArguments.isEmpty()) { throw new ComponentsProcessingException( param, "Type parameter for a parameter of type StateValue should match the type of " + "a parameter with the same name annotated with @State"); } final TypeMirror typeArgument = typeArguments.get(0); final TypeName stateMatchingParamTypeName = ClassName.get(stateMatchingParam.asType()); if (stateMatchingParamTypeName.isPrimitive()) { TypeName stateMatchingParamBoxedType = stateMatchingParamTypeName.box(); if (!stateMatchingParamBoxedType.equals(TypeName.get(typeArgument))) { throw new ComponentsProcessingException( param, "Type parameter for a parameter of type StateValue should match the type of " + "a parameter with the same name annotated with @State"); } } } } /** * Generate an EventHandler factory methods */ public void generateEventHandlerFactories( ClassName contextClassName, ClassName componentClassName) { for (ExecutableElement element : mOnEventMethods) { generateEventHandlerFactory( element, contextClassName, componentClassName); } } // ExecutableElement.hashCode may be different in different runs of the // processor. getElementId() is deterministic and ensures that the output is // the same across multiple runs. private int getElementId(ExecutableElement el) { return (mQualifiedClassName.hashCode() * 31 + el.getSimpleName().hashCode()) * 31 + el.asType().toString().hashCode(); } /** * Generate a dispatchOnEvent() implementation for the component. */ public void generateDispatchOnEvent( ClassName contextClassName) { final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("dispatchOnEvent") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(TypeName.OBJECT) .addParameter( ParameterSpec.builder(ClassNames.EVENT_HANDLER, "eventHandler", Modifier.FINAL).build()) .addParameter( ParameterSpec.builder(ClassNames.OBJECT, "eventState", Modifier.FINAL).build()); methodBuilder.addStatement("int id = eventHandler.id"); methodBuilder.beginControlFlow("switch($L)", "id"); final String implInstanceName = "_" + getImplInstanceName(); for (ExecutableElement element : mOnEventMethods) { methodBuilder.beginControlFlow("case $L:", getElementId(element)); final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final String eventName = eventClass.toString(); methodBuilder.addStatement( "$L $L = ($L) $L", eventName, implInstanceName, eventName, "eventState"); final CodeBlock.Builder eventHandlerParams = CodeBlock.builder(); eventHandlerParams.indent(); int i = 0; eventHandlerParams.add("\n($T) eventHandler.params[$L],", contextClassName, i++); for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) { eventHandlerParams.add( "\n" + implInstanceName + ".$L,", v.getSimpleName().toString()); } for (VariableElement v : Utils.getParametersWithAnnotation(element, Param.class)) { eventHandlerParams.add("\n($T) eventHandler.params[$L],", ClassName.get(v.asType()), i); i++; } eventHandlerParams.add("\n$L", "eventHandler.mHasEventDispatcher"); eventHandlerParams.unindent(); if (element.getReturnType().getKind() != VOID) { methodBuilder.addStatement( "return do$L($L)", capitalize(element.getSimpleName().toString()), eventHandlerParams.build()); } else { methodBuilder.addStatement( "do$L($L)", capitalize(element.getSimpleName().toString()), eventHandlerParams.build()); methodBuilder.addStatement("return null"); } methodBuilder.endControlFlow(); } methodBuilder.addStatement("default: \nreturn null"); methodBuilder.endControlFlow(); writeMethodSpec(methodBuilder.build()); } private void generateEventHandlerFactory( ExecutableElement element, ClassName contextClassName, ClassName componentClassName) { final List<VariableElement> eventParamElements = Utils.getParametersWithAnnotation(element, Param.class); final List<Parameter> eventParams = new ArrayList<>(); final List<String> typeParameters = new ArrayList<>(); for (VariableElement e : eventParamElements) { eventParams.add(new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString())); for (TypeMirror typeParam : getTypeVarArguments(e.asType())) { typeParameters.add(typeParam.toString()); } } final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final TypeName eventClassName = ClassName.bestGuess(((TypeElement) eventClass.asElement()).getQualifiedName().toString()); writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder() .eventId(getElementId(element)) .eventName(element.getSimpleName().toString()) .contextClass(contextClassName) .eventHandlerClassName( ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName)) .eventParams(eventParams) .typeParameters(typeParameters) .build()); writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder() .eventId(getElementId(element)) .eventName(element.getSimpleName().toString()) .contextClass(componentClassName) .eventHandlerClassName( ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName)) .eventParams(eventParams) .typeParameters(typeParameters) .build()); } private void generateOnEventHandler( ExecutableElement element, ClassName contextClassName) { if (element.getParameters().size() == 0 || !ClassName.get(element.getParameters().get(0).asType()).equals(contextClassName)) { throw new ComponentsProcessingException( element, "The first parameter for an onEvent method should be of type " +contextClassName.toString()); } final String evenHandlerName = element.getSimpleName().toString(); final List<Parameter> fromParams = new ArrayList<>(); fromParams.add(new Parameter( contextClassName, element.getParameters().get(0).getSimpleName().toString())); final List<VariableElement> fromParamElements = Utils.getParametersWithAnnotation(element, FromEvent.class); fromParamElements.addAll(Utils.getParametersWithAnnotation(element, Param.class)); for (VariableElement v : fromParamElements) { fromParams.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); } writeMethodSpec(new DelegateMethodSpecBuilder() .implClassName(getImplClassName()) .abstractImplType(ClassNames.HAS_EVENT_DISPATCHER_CLASSNAME) .implParameters(mImplParameters) .visibility(PRIVATE) .fromName("do" + capitalize(evenHandlerName)) .fromParams(fromParams) .target(mSourceDelegateAccessorName) .toName(evenHandlerName) .toParams(getParams(element)) .fromReturnType(ClassName.get(element.getReturnType())) .toReturnType(ClassName.get(element.getReturnType())) .stateParams(mStateMap.keySet()) .build()); } private void generateOnStateUpdateMethods( ExecutableElement element, ClassName contextClass, ClassName componentClass) { final String methodName = element.getSimpleName().toString(); final List<VariableElement> updateMethodParamElements = Utils.getParametersWithAnnotation(element, Param.class); final OnStateUpdateMethodSpecBuilder builder = new OnStateUpdateMethodSpecBuilder() .componentClass(componentClass) .lifecycleImplClass(mSimpleClassName) .stateUpdateClassName(getStateUpdateClassName(element)); for (VariableElement e : updateMethodParamElements) { builder.updateMethodParam( new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString())); List<TypeMirror> genericArgs = getTypeVarArguments(e.asType()); if (genericArgs != null) { for (TypeMirror genericArg : genericArgs) { builder.typeParameter(genericArg.toString()); } } } writeMethodSpec(builder .updateMethodName(methodName) .async(false) .contextClass(contextClass) .build()); writeMethodSpec(builder .updateMethodName(methodName + "Async") .async(true) .contextClass(contextClass) .build()); } static List<TypeMirror> getTypeVarArguments(TypeMirror diffType) { List<TypeMirror> typeVarArguments = new ArrayList<>(); if (diffType.getKind() == DECLARED) { final DeclaredType parameterDeclaredType = (DeclaredType) diffType; final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments(); for (TypeMirror typeArgument : typeArguments) { if (typeArgument.getKind() == TYPEVAR) { typeVarArguments.add(typeArgument); } } } return typeVarArguments; } public static List<TypeMirror> getGenericTypeArguments(TypeMirror diffType) { if (diffType.getKind() == DECLARED) { final DeclaredType parameterDeclaredType = (DeclaredType) diffType; final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments(); return (List<TypeMirror>) typeArguments; } return null; } public static List<Parameter> getParams(ExecutableElement e) { final List<Parameter> params = new ArrayList<>(); for (VariableElement v : e.getParameters()) { params.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); } return params; } /** * Generates a class that implements {@link com.facebook.litho.ComponentLifecycle} given * a method annotated with {@link OnUpdateState}. The class constructor takes as params all the * params annotated with {@link Param} on the method and keeps them in class members. * @param element The method annotated with {@link OnUpdateState} */ private void generateStateUpdateClass( ExecutableElement element, ClassName componentClassName, ClassName stateContainerClassName, ClassName updateStateInterface, StaticFlag staticFlag) { final String stateUpdateClassName = getStateUpdateClassName(element); final TypeName implClassName = ClassName.bestGuess(getImplClassName()); final StateUpdateImplClassBuilder stateUpdateImplClassBuilder = new StateUpdateImplClassBuilder() .withTarget(mSourceDelegateAccessorName) .withSpecOnUpdateStateMethodName(element.getSimpleName().toString()) .withComponentImplClassName(implClassName) .withComponentClassName(componentClassName) .withComponentStateUpdateInterface(updateStateInterface) .withStateContainerClassName(stateContainerClassName) .withStateContainerImplClassName(ClassName.bestGuess(getStateContainerImplClassName())) .withStateUpdateImplClassName(stateUpdateClassName) .withSpecOnUpdateStateMethodParams(getParams(element)) .withStateValueParams(getStateValueParams(element)) .withStaticFlag(staticFlag); final List<VariableElement> parametersVarElements = Utils.getParametersWithAnnotation(element, Param.class); final List<Parameter> parameters = new ArrayList<>(); for (VariableElement v : parametersVarElements) { parameters.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); for (TypeMirror typeVar : getTypeVarArguments(v.asType())) { stateUpdateImplClassBuilder.typeParameter(typeVar.toString()); } } stateUpdateImplClassBuilder.withParamsForStateUpdate(parameters); writeInnerTypeSpec(stateUpdateImplClassBuilder.build()); } /** * Generate an onLoadStyle implementation. */ public void generateOnLoadStyle() { final ExecutableElement delegateMethod = Utils.getAnnotatedMethod( mSourceElement, OnLoadStyle.class); if (delegateMethod == null) { return; } final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onLoadStyle") .addAnnotation( AnnotationSpec .builder(SuppressWarnings.class) .addMember("value", "$S", "unchecked").build()) .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .addParameter(ClassNames.COMPONENT_CONTEXT, "_context") .addParameter( ParameterSpec.builder( ParameterizedTypeName.get( ClassNames.COMPONENT, WildcardTypeName.subtypeOf(Object.class)), "_component") .build()); final List<? extends VariableElement> parameters = delegateMethod.getParameters(); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final TypeName typeName = ClassName.get(v.asType()); methodBuilder.addStatement( "$L $L = ($L) $L", typeName, v.getSimpleName(), typeName, "acquireOutput()"); } final CodeBlock.Builder delegateParameters = CodeBlock.builder().indent(); delegateParameters.add("\n_context"); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { delegateParameters.add(",\n$L", parameters.get(i).getSimpleName()); } delegateParameters.unindent(); methodBuilder.addStatement( "this.$L.$L($L)", mSourceDelegateAccessorName, delegateMethod.getSimpleName(), delegateParameters.build()); final String implClassName = getImplClassName(); final String implInstanceName = "_" + getImplInstanceName();
import java.math.*; public class SlamShuffle { public static final String DATA_FILE = "data.txt"; public static final BigInteger SIZE_OF_DECK = BigInteger.valueOf(119315717514047L);; public static final BigInteger SHUFFLE_TIMES = BigInteger.valueOf(101741582076661L); public static final int CARD = 2020; public static void main (String[] args) { boolean debug = false; boolean verify = false; for (int i = 0; i < args.length; i++) { if ("-help".equals(args[i])) { System.out.println("Usage: [-verify] [-debug] [-help]"); System.exit(0); } if ("-debug".equals(args[i])) debug = true; if ("-verify".equals(args[i])) verify = true; } if (verify) { Verifier theVerifier = new Verifier(debug); if (theVerifier.verify()) System.out.println("\nVerified ok!"); else System.out.println("\nVerify failed!"); System.exit(0); } Dealer theDealer = new Dealer(DATA_FILE, debug); Deck theDeck = theDealer.dealCards(SIZE_OF_DECK); int position = theDeck.positionOfCard(10); System.out.println("Position of card "+10+" is "+position); } }
package com.facebook.litho.processor; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; 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.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.facebook.common.internal.ImmutableList; import com.facebook.litho.annotations.Event; import com.facebook.litho.annotations.FromEvent; import com.facebook.litho.annotations.OnCreateInitialState; import com.facebook.litho.annotations.OnCreateTreeProp; import com.facebook.litho.annotations.OnEvent; import com.facebook.litho.annotations.OnLoadStyle; import com.facebook.litho.annotations.OnUpdateState; import com.facebook.litho.annotations.Param; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.litho.annotations.State; import com.facebook.litho.annotations.TreeProp; import com.facebook.litho.javapoet.JPUtil; import com.facebook.litho.processor.GetTreePropsForChildrenMethodBuilder.CreateTreePropMethodData; import com.facebook.litho.specmodels.model.ClassNames; import com.facebook.litho.specmodels.model.PropDefaultModel; import com.facebook.litho.specmodels.processor.PropDefaultsExtractor; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.squareup.javapoet.WildcardTypeName; import static com.facebook.litho.processor.Utils.capitalize; import static com.facebook.litho.processor.Visibility.PRIVATE; import static com.facebook.litho.specmodels.generator.GeneratorConstants.DELEGATE_FIELD_NAME; import static com.facebook.litho.specmodels.generator.GeneratorConstants.SPEC_INSTANCE_NAME; import static java.util.Arrays.asList; import static javax.lang.model.type.TypeKind.ARRAY; import static javax.lang.model.type.TypeKind.DECLARED; import static javax.lang.model.type.TypeKind.DOUBLE; import static javax.lang.model.type.TypeKind.FLOAT; import static javax.lang.model.type.TypeKind.TYPEVAR; import static javax.lang.model.type.TypeKind.VOID; public class Stages { public static final String IMPL_CLASS_NAME_SUFFIX = "Impl"; private static final String INNER_IMPL_BUILDER_CLASS_NAME = "Builder"; private static final String STATE_UPDATE_IMPL_NAME_SUFFIX = "StateUpdate"; public static final String STATE_CONTAINER_IMPL_NAME_SUFFIX = "StateContainerImpl"; public static final String STATE_CONTAINER_IMPL_MEMBER = "mStateContainerImpl"; private static final String REQUIRED_PROPS_NAMES = "REQUIRED_PROPS_NAMES"; private static final String REQUIRED_PROPS_COUNT = "REQUIRED_PROPS_COUNT"; private static final int ON_STYLE_PROPS = 1; private static final int ON_CREATE_INITIAL_STATE = 1; private final boolean mSupportState; public enum StaticFlag { STATIC, NOT_STATIC } public enum StyleableFlag { STYLEABLE, NOT_STYLEABLE } // Using these names in props might cause conflicts with the method names in the // component's generated layout builder class so we trigger a more user-friendly // error if the component tries to use them. This list should be kept in sync // with BaseLayoutBuilder. private static final String[] RESERVED_PROP_NAMES = new String[] { "withLayout", "key", "loadingEventHandler", }; private static final Class<Annotation>[] TREE_PROP_ANNOTATIONS = new Class[] { TreeProp.class, }; private static final Class<Annotation>[] PROP_ANNOTATIONS = new Class[] { Prop.class, }; private static final Class<Annotation>[] STATE_ANNOTATIONS = new Class[] { State.class, }; private final ProcessingEnvironment mProcessingEnv; private final TypeElement mSourceElement; private final String mQualifiedClassName; private final Class<Annotation>[] mStageAnnotations; private final Class<Annotation>[] mInterStagePropAnnotations; private final Class<Annotation>[] mParameterAnnotations; private final TypeSpec.Builder mClassTypeSpec; private final List<TypeVariableName> mTypeVariables; private final List<TypeElement> mEventDeclarations; private final Map<String, String> mPropJavadocs; private final String mSimpleClassName; private String mSourceDelegateAccessorName = DELEGATE_FIELD_NAME; private List<VariableElement> mProps; private List<VariableElement> mOnCreateInitialStateDefinedProps; private ImmutableList<PropDefaultModel> mPropDefaults; private List<VariableElement> mTreeProps; private final Map<String, VariableElement> mStateMap = new LinkedHashMap<>(); // Map of name to VariableElement, for members of the inner implementation class, in order private LinkedHashMap<String, VariableElement> mImplMembers; private List<Parameter> mImplParameters; private final Map<String, TypeMirror> mExtraStateMembers; // List of methods that have @OnEvent on it. private final List<ExecutableElement> mOnEventMethods; // List of methods annotated with @OnUpdateState. private final List<ExecutableElement> mOnUpdateStateMethods; private final List<ExecutableElement> mOnCreateTreePropsMethods; // List of methods that define stages (e.g. OnCreateLayout) private List<ExecutableElement> mStages; public TypeElement getSourceElement() { return mSourceElement; } public Stages( ProcessingEnvironment processingEnv, TypeElement sourceElement, String qualifiedClassName, Class<Annotation>[] stageAnnotations, Class<Annotation>[] interStagePropAnnotations, TypeSpec.Builder typeSpec, List<TypeVariableName> typeVariables, boolean supportState, Map<String, TypeMirror> extraStateMembers, List<TypeElement> eventDeclarations, Map<String, String> propJavadocs) { mProcessingEnv = processingEnv; mSourceElement = sourceElement; mQualifiedClassName = qualifiedClassName; mStageAnnotations = stageAnnotations; mInterStagePropAnnotations = interStagePropAnnotations; mClassTypeSpec = typeSpec; mTypeVariables = typeVariables; mEventDeclarations = eventDeclarations; mPropJavadocs = propJavadocs; final List<Class<Annotation>> parameterAnnotations = new ArrayList<>(); parameterAnnotations.addAll(asList(PROP_ANNOTATIONS)); parameterAnnotations.addAll(asList(STATE_ANNOTATIONS)); parameterAnnotations.addAll(asList(mInterStagePropAnnotations)); parameterAnnotations.addAll(asList(TREE_PROP_ANNOTATIONS)); mParameterAnnotations = parameterAnnotations.toArray( new Class[parameterAnnotations.size()]); mSupportState = supportState; mSimpleClassName = Utils.getSimpleClassName(mQualifiedClassName); mOnEventMethods = Utils.getAnnotatedMethods(mSourceElement, OnEvent.class); mOnUpdateStateMethods = Utils.getAnnotatedMethods(mSourceElement, OnUpdateState.class); mOnCreateTreePropsMethods = Utils.getAnnotatedMethods(mSourceElement, OnCreateTreeProp.class); mExtraStateMembers = extraStateMembers; validateOnEventMethods(); populatePropDefaults(); populateStages(); validateAnnotatedParameters(); populateOnCreateInitialStateDefinedProps(); populateProps(); populateTreeProps(); if (mSupportState) { populateStateMap(); } validatePropDefaults(); populateImplMembers(); populateImplParameters(); validateStyleOutputs(); } private boolean isInterStagePropAnnotationValidInStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); final int stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } // This logic relies on the fact that there are prop annotations for each stage (except for // some number at the end) return interStagePropIndex < stageIndex; } private boolean doesInterStagePropAnnotationMatchStage( Class<? extends Annotation> interStageProp, Class<? extends Annotation> stage) { final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp); // Null stage is allowed and indicates prop int stageIndex = -1; if (stage != null) { stageIndex = asList(mStageAnnotations).indexOf(stage); if (interStagePropIndex < 0 || stageIndex < 0) { throw new IllegalArgumentException(); // indicates bug in the annotation processor } } return interStagePropIndex == stageIndex; } private void validateOnEventMethods() { final Map<String, Boolean> existsMap = new HashMap<>(); for (ExecutableElement element : mOnEventMethods) { if (existsMap.containsKey(element.getSimpleName().toString())) { throw new ComponentsProcessingException( element, "@OnEvent declared methods must have unique names"); } final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final TypeMirror returnType = Utils.getAnnotationParameter( mProcessingEnv, eventClass.asElement(), Event.class, "returnType"); if (!mProcessingEnv.getTypeUtils().isSameType(element.getReturnType(), returnType)) { throw new ComponentsProcessingException( element, "Method " + element.getSimpleName() + " must return " + returnType + ", since that is what " + eventClass + " expects."); } final List<? extends VariableElement> parameters = Utils.getEnclosedFields((TypeElement) eventClass.asElement()); for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) { boolean hasMatchingParameter = false; for (VariableElement parameter : parameters) { if (parameter.getSimpleName().equals(v.getSimpleName()) && parameter.asType().toString().equals(v.asType().toString())) { hasMatchingParameter = true; break; } } if (!hasMatchingParameter) { throw new ComponentsProcessingException( v, v.getSimpleName() + " of this type is not a member of " + eventClass); } return; } existsMap.put(element.getSimpleName().toString(), true); } } /** * Ensures that the declared events don't clash with the predefined ones. */ private void validateEventDeclarations() { for (TypeElement eventDeclaration : mEventDeclarations) { final Event eventAnnotation = eventDeclaration.getAnnotation(Event.class); if (eventAnnotation == null) { throw new ComponentsProcessingException( eventDeclaration, "Events must be declared with the @Event annotation, event is: " + eventDeclaration); } final List<? extends VariableElement> fields = Utils.getEnclosedFields(eventDeclaration); for (VariableElement field : fields) { if (!field.getModifiers().contains(Modifier.PUBLIC) || field.getModifiers().contains(Modifier.FINAL)) { throw new ComponentsProcessingException( field, "Event fields must be declared as public non-final"); } } } } private void validateStyleOutputs() { final ExecutableElement delegateMethod = Utils.getAnnotatedMethod( mSourceElement, OnLoadStyle.class); if (delegateMethod == null) { return; } final List<? extends VariableElement> parameters = delegateMethod.getParameters(); if (parameters.size() < ON_STYLE_PROPS) { throw new ComponentsProcessingException( delegateMethod, "The @OnLoadStyle method should have an ComponentContext" + "followed by Output parameters matching component create."); } final TypeName firstParamType = ClassName.get(parameters.get(0).asType()); if (!firstParamType.equals(ClassNames.COMPONENT_CONTEXT)) { throw new ComponentsProcessingException( parameters.get(0), "The first argument of the @OnLoadStyle method should be an ComponentContext."); } for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final TypeMirror outputType = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT); if (outputType == null) { throw new ComponentsProcessingException( parameters.get(i), "The @OnLoadStyle method should have only have Output arguments matching " + "component create."); } final Types typeUtils = mProcessingEnv.getTypeUtils(); final String name = v.getSimpleName().toString(); boolean matchesProp = false; for (Element prop : mProps) { if (!prop.getSimpleName().toString().equals(name)) { continue; } matchesProp = true; if (!typeUtils.isAssignable(prop.asType(), outputType)) { throw new ComponentsProcessingException( v, "Searching for prop \"" + name + "\" of type " + ClassName.get(outputType) + " but found prop with the same name of type " + ClassName.get(prop.asType())); } } if (!matchesProp) { throw new ComponentsProcessingException( v, "Output named '" + v.getSimpleName() + "' does not match any prop " + "in the component."); } } } private void validateAnnotatedParameters() { final List<PrintableException> exceptions = new ArrayList<>(); final Map<String, VariableElement> variableNameToElementMap = new HashMap<>(); final Map<String, Class<? extends Annotation>> outputVariableToStage = new HashMap<>(); for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage == null) { continue; } // Enforce #5: getSpecDefinedParameters will verify that parameters don't have duplicate // annotations for (VariableElement v : getSpecDefinedParameters(stage)) { try { final String variableName = v.getSimpleName().toString(); final Annotation interStagePropAnnotation = getInterStagePropAnnotation(v); final boolean isOutput = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT) != null; if (isOutput) { outputVariableToStage.put(variableName, stageAnnotation); } // Enforce if (interStagePropAnnotation != null) { final Class<? extends Annotation> outputStage = outputVariableToStage.get(variableName); if (!doesInterStagePropAnnotationMatchStage( interStagePropAnnotation.annotationType(), outputStage)) { throw new ComponentsProcessingException( v, "Inter-stage prop declaration is incorrect, the same name and type must be " + "used in every method where the inter-stage prop is declared."); } } // Enforce if (interStagePropAnnotation != null && !isInterStagePropAnnotationValidInStage( interStagePropAnnotation.annotationType(), stageAnnotation)) { throw new ComponentsProcessingException( v, "Inter-stage create must refer to previous stages."); } final VariableElement existingType = variableNameToElementMap.get(variableName); if (existingType != null && !isSameType(existingType.asType(), v.asType())) { // We have a type mis-match. This is allowed, provided that the previous type is an // outputand the new type is an prop, and the type argument of the output matches the // prop. In the future, we may want to allow stages to modify outputs from previous // stages, but for now we disallow it. // Enforce #1 and #2 if ((getInterStagePropAnnotation(v) == null || Utils.getGenericTypeArgument(existingType.asType(), ClassNames.OUTPUT) == null) && Utils.getGenericTypeArgument(existingType.asType(), ClassNames.DIFF) == null) { throw new ComponentsProcessingException( v, "Inconsistent type for '" + variableName + "': '" + existingType.asType() + "' and '" + v.asType() + "'"); } } else if (existingType == null) { // We haven't see a parameter with this name yet. Therefore it must be either @Prop, // @State or an output. final boolean isFromProp = getParameterAnnotation(v, PROP_ANNOTATIONS) != null; final boolean isFromState = getParameterAnnotation(v, STATE_ANNOTATIONS) != null; final boolean isFromTreeProp = getParameterAnnotation(v, TREE_PROP_ANNOTATIONS) != null; if (isFromState && !mSupportState) { throw new ComponentsProcessingException( v, "State is not supported in this kind of Spec."); } if (!isFromProp && !isFromState && !isOutput && !isFromTreeProp) { throw new ComponentsProcessingException( v, "Inter-stage prop declared without source."); } } // Enforce final Prop propAnnotation = v.getAnnotation(Prop.class); if (propAnnotation != null) { for (String reservedPropName : RESERVED_PROP_NAMES) { if (reservedPropName.equals(variableName)) { throw new ComponentsProcessingException( v, "'" + reservedPropName + "' is a reserved prop name used by " + "the component's layout builder. Please use another name."); } } // Enforce final boolean hasDefaultValue = hasDefaultValue(v); if (hasDefaultValue && !propAnnotation.optional()) { throw new ComponentsProcessingException( v, "Prop is not optional but has a declared default value."); } // Enforce if (existingType != null) { final Prop existingPropAnnotation = existingType.getAnnotation(Prop.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The prop '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this prop is declared identically."); } } } // Enforce TypeName typeName; try { typeName = ClassName.get(v.asType()); } catch (IllegalArgumentException e) { throw new ComponentsProcessingException( v, "Prop type does not exist"); } // Enforce final List<ClassName> illegalPropTypes = Arrays.asList( ClassNames.COMPONENT_LAYOUT, ClassNames.COMPONENT_LAYOUT_BUILDER, ClassNames.COMPONENT_LAYOUT_CONTAINER_BUILDER, ClassNames.COMPONENT_BUILDER, ClassNames.COMPONENT_BUILDER_WITH_LAYOUT, ClassNames.REFERENCE_BUILDER); if (illegalPropTypes.contains(typeName)) { throw new ComponentsProcessingException( v, "Props may not be declared with the following types:" + illegalPropTypes); } } variableNameToElementMap.put(variableName, v); } catch (PrintableException e) { exceptions.add(e); } } } if (!exceptions.isEmpty()) { throw new MultiPrintableException(exceptions); } } private boolean hasSameAnnotations(VariableElement v1, VariableElement v2) { final List<? extends AnnotationMirror> v1Annotations = v1.getAnnotationMirrors(); final List<? extends AnnotationMirror> v2Annotations = v2.getAnnotationMirrors(); if (v1Annotations.size() != v2Annotations.size()) { return false; } final int count = v1Annotations.size(); for (int i = 0; i < count; i++) { final AnnotationMirror a1 = v1Annotations.get(i); final AnnotationMirror a2 = v2Annotations.get(i); // Some object in this hierarchy don't implement equals correctly. // They do however produce very nice strings representations which we can compare instead. if (!a1.toString().equals(a2.toString())) { return false; } } return true; } public void validateStatic() { validateStaticFields(); validateStaticMethods(); } private void validateStaticFields() { for (Element element : mSourceElement.getEnclosedElements()) { if (element.getKind() == ElementKind.FIELD && !element.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( element, "Field " + element.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } private void validateStaticMethods() { for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null && !stage.getModifiers().contains(Modifier.STATIC)) { throw new ComponentsProcessingException( stage, "Method " + stage.getSimpleName() + " in " + mSourceElement.getQualifiedName() + " must be static"); } } } /** * Gather a list of VariableElement that are the props to this component */ private void populateProps() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getProps(stage)) { // Validation unnecessary - already handled by validateAnnotatedParameters final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mProps = new ArrayList<>(variableNameToElementMap.values()); addCreateInitialStateDefinedProps(mProps); } /** * Gather a list of VariableElement that are the state to this component */ private void populateStateMap() { // We use a linked hash map to guarantee iteration order final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : getState(stage)) { final String variableName = v.getSimpleName().toString(); if (mStateMap.containsKey(variableName)) { VariableElement existingType = mStateMap.get(variableName); final State existingPropAnnotation = existingType.getAnnotation(State.class); if (existingPropAnnotation != null) { if (!hasSameAnnotations(v, existingType)) { throw new ComponentsProcessingException( v, "The state '" + variableName + "' is configured differently for different " + "methods. Ensure each instance of this state is declared identically."); } } } mStateMap.put( variableName, v); } } } private void populateTreeProps() { final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>(); for (ExecutableElement stage : mStages) { for (VariableElement v : Utils.getParametersWithAnnotation(stage, TreeProp.class)) { final String variableName = v.getSimpleName().toString(); variableNameToElementMap.put(variableName, v); } } mTreeProps = new ArrayList<>(variableNameToElementMap.values()); } /** * Get the list of stages (OnInflate, OnMeasure, OnMount) that are defined for this component. */ private void populateStages() { mStages = new ArrayList<>(); for (Class<Annotation> stageAnnotation : mStageAnnotations) { final ExecutableElement stage = Utils.getAnnotatedMethod( mSourceElement, stageAnnotation); if (stage != null) { mStages.add(stage); } } if (mOnEventMethods != null) { mStages.addAll(mOnEventMethods); } mStages.addAll(mOnCreateTreePropsMethods); } /** * @param prop The prop to determine if it has a default or not. * @return Returns true if the prop has a default, false otherwise. */ private boolean hasDefaultValue(VariableElement prop) { final String name = prop.getSimpleName().toString(); final TypeName type = TypeName.get(prop.asType()); for (PropDefaultModel propDefault : mPropDefaults) { if (propDefault.mName.equals(name) && propDefault.mType.equals(type)) { return true; } } return false; } /** * Fail if any elements that exist in mPropDefaults do not exist in mProps. */ private void validatePropDefaults() { for (PropDefaultModel propDefault : mPropDefaults) { final ImmutableList<Modifier> modifiers = propDefault.mModifiers; if (!modifiers.contains(Modifier.STATIC) || !modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.PRIVATE)) { throw new RuntimeException( "Defaults for props (fields annotated with " + PropDefault.class + ") must be " + "non-private, static, and final. This is not the case for " + propDefault.mName); } if (!hasValidNameAndType(propDefault)) { throw new RuntimeException( "Prop defaults (fields annotated with " + PropDefault.class + ") should have the " + "same name and type as the prop that they set the default for. This is not the " + "case for " + propDefault.mName); } } } /** * @return true if the given prop default matches the name and type of a prop, false otherwise. */ private boolean hasValidNameAndType(PropDefaultModel propDefault) { for (VariableElement prop : mProps) { if (prop.getSimpleName().toString().equals(propDefault.mName) && TypeName.get(prop.asType()).equals(propDefault.mType)) { return true; } } return false; } /** * Gather a list of parameters from the given element that are props to this component. */ private static List<VariableElement> getProps(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, Prop.class); } /** * Gather a list of parameters from the given element that are state to this component. */ private static List<VariableElement> getState(ExecutableElement element) { return Utils.getParametersWithAnnotation(element, State.class); } /** * Gather a list of parameters from the given element that are defined by the spec. That is, they * aren't one of the parameters predefined for a given method. For example, OnCreateLayout has a * predefined parameter of type LayoutContext. Spec-defined parameters are annotated with one of * our prop annotations or are of type {@link com.facebook.litho.Output}. */ private List<VariableElement> getSpecDefinedParameters(ExecutableElement element) { return getSpecDefinedParameters(element, true); } private List<VariableElement> getSpecDefinedParameters( ExecutableElement element, boolean shouldIncludeOutputs) { final ArrayList<VariableElement> specDefinedParameters = new ArrayList<>(); for (VariableElement v : element.getParameters()) { final boolean isAnnotatedParameter = getParameterAnnotation(v) != null; final boolean isInterStageOutput = Utils.getGenericTypeArgument( v.asType(), ClassNames.OUTPUT) != null; if (isAnnotatedParameter && isInterStageOutput) { throw new ComponentsProcessingException( v, "Variables that are both prop and output are forbidden."); } else if (isAnnotatedParameter || (shouldIncludeOutputs && isInterStageOutput)) { specDefinedParameters.add(v); } } return specDefinedParameters; } private void populateOnCreateInitialStateDefinedProps() { final ExecutableElement onCreateInitialState = Utils.getAnnotatedMethod( getSourceElement(), OnCreateInitialState.class); if (onCreateInitialState == null) { mOnCreateInitialStateDefinedProps = new ArrayList<>(); } else { mOnCreateInitialStateDefinedProps = getSpecDefinedParameters(onCreateInitialState, false); } } /** * Get the @FromLayout, @FromMeasure, etc annotation on this element (@Prop isn't * considered - use getParameterAnnotation if you want to consider them) */ private Annotation getInterStagePropAnnotation(VariableElement element) { return getParameterAnnotation(element, mInterStagePropAnnotations); } /** * Get the annotation, if any, present on a parameter. Annotations are restricted to our whitelist * of parameter annotations: e.g. {@link Prop}, {@link State} etc) */ private Annotation getParameterAnnotation(VariableElement element) { return getParameterAnnotation(element, mParameterAnnotations); } /** * Get the annotation, if any, present on a parameter. Annotations are restricted to the specified * whitelist. If there is a duplicate we will issue an error. */ private Annotation getParameterAnnotation( VariableElement element, Class<Annotation>[] possibleAnnotations) { final ArrayList<Annotation> annotations = new ArrayList<>(); for (Class<Annotation> annotationClass : possibleAnnotations) { final Annotation annotation = element.getAnnotation(annotationClass); if (annotation != null) { annotations.add(annotation); } } if (annotations.isEmpty()) { return null; } else if (annotations.size() == 1) { return annotations.get(0); } else { throw new ComponentsProcessingException( element, "Duplicate parameter annotation: '" + annotations.get(0) + "' and '" + annotations.get(1) + "'"); } } /** * Generate javadoc block describing component props. */ public void generateJavadoc() { for (VariableElement v : mProps) { final Prop propAnnotation = v.getAnnotation(Prop.class); final String propTag = propAnnotation.optional() ? "@prop-optional" : "@prop-required"; final String javadoc = mPropJavadocs != null ? mPropJavadocs.get(v.getSimpleName().toString()) : ""; final String sanitizedJavadoc = javadoc != null ? javadoc.replace('\n', ' ') : null; // Adds javadoc with following format: // @prop-required name type javadoc. // This can be changed later to use clear demarcation for fields. // This is a block tag and cannot support inline tags like "{@link something}". mClassTypeSpec.addJavadoc( "$L $L $L $L\n", propTag, v.getSimpleName().toString(), Utils.getTypeName(v.asType()), sanitizedJavadoc); } } /** * Generate a method for this component which either lazily instantiates a singleton reference or * return this depending on whether this lifecycle is static or not. */ public void generateGetter(boolean isStatic) { final ClassName className = ClassName.bestGuess(mQualifiedClassName); if (isStatic) { mClassTypeSpec.addField( FieldSpec .builder(className, SPEC_INSTANCE_NAME, Modifier.PRIVATE, Modifier.STATIC) .initializer("null") .build()); mClassTypeSpec.addMethod( MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC) .addModifiers(Modifier.STATIC) .addModifiers(Modifier.SYNCHRONIZED) .returns(className) .beginControlFlow("if ($L == null)", SPEC_INSTANCE_NAME) .addStatement("$L = new $T()", SPEC_INSTANCE_NAME, className) .endControlFlow() .addStatement("return $L", SPEC_INSTANCE_NAME) .build()); } else { mClassTypeSpec.addMethod( MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC) .returns(className) .addStatement("return this") .build()); } } public void generateSourceDelegate(boolean initialized) { final ClassName specClassName = ClassName.get(mSourceElement); generateSourceDelegate(initialized, specClassName); } public void generateSourceDelegate(boolean initialized, TypeName specTypeName) { final FieldSpec.Builder builder = FieldSpec .builder(specTypeName, DELEGATE_FIELD_NAME) .addModifiers(Modifier.PRIVATE); if (initialized) { builder.initializer("new $T()", specTypeName); } mClassTypeSpec.addField(builder.build()); } private MethodSpec generateMakeShallowCopy(ClassName componentClassName, boolean hasDeepCopy) { final List<String> componentsInImpl = findComponentsInImpl(componentClassName); final List<String> interStageComponentVariables = getInterStageVariableNames(); if (componentsInImpl.isEmpty() && interStageComponentVariables.isEmpty() && mOnUpdateStateMethods.isEmpty()) { return null; } final String implClassName = getImplClassName(); return new ShallowCopyMethodSpecBuilder() .componentsInImpl(componentsInImpl) .interStageVariables(interStageComponentVariables) .implClassName(implClassName) .hasDeepCopy(hasDeepCopy) .stateContainerImplClassName(getStateContainerImplClassName()) .build(); } private List<String> findComponentsInImpl(ClassName listComponent) { final List<String> componentsInImpl = new ArrayList<>(); for (String key : mImplMembers.keySet()) { final VariableElement element = mImplMembers.get(key); final Name declaredClassName = Utils.getDeclaredClassNameWithoutGenerics(element); if (declaredClassName != null && ClassName.bestGuess(declaredClassName.toString()).equals(listComponent)) { componentsInImpl.add(element.getSimpleName().toString()); } } return componentsInImpl; } /** * Generate a private constructor to enforce singleton-ity. */ public void generateConstructor() { mClassTypeSpec.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build()); } /** * Generates a method to create the initial values for parameters annotated with {@link State}. * This method also validates that the delegate method only tries to assign an initial value to * State annotated parameters. */ public void generateCreateInitialState( ExecutableElement from, ClassName contextClass, ClassName componentClass) { verifyParametersForCreateInitialState(contextClass, from); final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] { Override.class }; methodDescription.accessType = Modifier.PROTECTED; methodDescription.returnType = null; methodDescription.name = "createInitialState"; methodDescription.parameterTypes = new TypeName[] {contextClass}; generateDelegate(methodDescription, from, componentClass); } private void verifyParametersForCreateInitialState( ClassName contextClass, ExecutableElement executableElement) { final List<VariableElement> parameters = (List<VariableElement>) executableElement.getParameters(); if (parameters.size() < ON_CREATE_INITIAL_STATE + 1) { throw new ComponentsProcessingException( executableElement, "The @OnCreateInitialState method should have an " + contextClass + "followed by Output parameters matching state parameters."); } final TypeName firstParamType = ClassName.get(parameters.get(0).asType()); if (!firstParamType.equals(contextClass)) { throw new ComponentsProcessingException( parameters.get(0), "The first argument of the @OnCreateInitialState method should be an " + contextClass + "."); } for (int i = ON_CREATE_INITIAL_STATE, size = parameters.size(); i < size; i++) { final VariableElement element = parameters.get(i); final TypeMirror elementInnerClassType = Utils.getGenericTypeArgument(element.asType(), ClassNames.OUTPUT); if (elementInnerClassType != null) { final String paramName = element.getSimpleName().toString(); VariableElement implParameter = mStateMap.get(paramName); if (implParameter == null || implParameter.getAnnotation(State.class) == null) { throw new ComponentsProcessingException( executableElement, "Only parameters annotated with @State can be initialized in @OnCreateInitialState," + " parameter without annotation is: " + paramName); } } } } /** * Generate a method implementation that delegates to another method that takes annotated props. * * @param from description of method signature to be generated * @param to method to which to delegate * @param propsClass Component / Delegate. The base class of the inner implementation object * @throws java.io.IOException If one of the writer methods throw */ public void generateDelegate( MethodDescription from, ExecutableElement to, ClassName propsClass) { generateDelegate( from, to, Collections.<TypeName>emptyList(), Collections.<String, String>emptyMap(), propsClass); } public void generateDelegate( MethodDescription from, ExecutableElement to, List<TypeName> expectedTypes, ClassName propsClass) { generateDelegate( from, to, expectedTypes, Collections.<String, String>emptyMap(), propsClass); } /** * Generate a method implementation that delegates to another method that takes annotated props. * * @param from description of method signature to be generated * @param to method to which to delegate * @param propsClass Component / Delegate. The base class of the inner implementation object * @throws java.io.IOException If one of the writer methods throw */ public void generateDelegate( MethodDescription from, ExecutableElement to, List<TypeName> expectedTypes, Map<String, String> parameterTranslation, ClassName propsClass) { final Visibility visibility; if (Arrays.asList(from.accessType).contains(Modifier.PRIVATE)) { visibility = Visibility.PRIVATE; } else if (Arrays.asList(from.accessType).contains(Modifier.PROTECTED)) { visibility = Visibility.PROTECTED; } else if (Arrays.asList(from.accessType).contains(Modifier.PUBLIC)) { visibility = Visibility.PUBLIC; } else { visibility = Visibility.PACKAGE; } final List<Parameter> toParams = getParams(to); final List<Parameter> fromParams = new ArrayList<>(); for (int i = 0; i < from.parameterTypes.length; i++) { fromParams.add(new Parameter(from.parameterTypes[i], toParams.get(i).name)); } final List<PrintableException> errors = new ArrayList<>(); for (int i = 0; i < expectedTypes.size(); i++) { if (!toParams.get(i).type.equals(expectedTypes.get(i))) { errors.add(new ComponentsProcessingException( to.getParameters().get(i), "Expected " + expectedTypes.get(i))); } } if (!errors.isEmpty()) { throw new MultiPrintableException(errors); } writeMethodSpec(new DelegateMethodSpecBuilder() .implClassName(getImplClassName()) .abstractImplType(propsClass) .implParameters(mImplParameters) .checkedExceptions( from.exceptions == null ? new ArrayList<TypeName>() : Arrays.asList(from.exceptions)) .overridesSuper( from.annotations != null && Arrays.asList(from.annotations).contains(Override.class)) .parameterTranslation(parameterTranslation) .visibility(visibility) .fromName(from.name) .fromReturnType(from.returnType == null ? TypeName.VOID : from.returnType) .fromParams(fromParams) .target(mSourceDelegateAccessorName) .toName(to.getSimpleName().toString()) .stateParams(mStateMap.keySet()) .toReturnType(ClassName.get(to.getReturnType())) .toParams(toParams) .build()); } /** * Returns {@code true} if the given types match. */ public boolean isSameType(TypeMirror a, TypeMirror b) { return mProcessingEnv.getTypeUtils().isSameType(a, b); } /** * Generate an onEvent implementation that delegates to the @OnEvent-annotated method. */ public void generateOnEventHandlers(ClassName componentClassName, ClassName contextClassName) { for (ExecutableElement element : mOnEventMethods) { generateOnEventHandler(element, contextClassName); } } /** * Generate the static methods of the Component that can be called to update its state. */ public void generateOnStateUpdateMethods( ClassName contextClass, ClassName componentClassName, ClassName stateContainerClassName, ClassName stateUpdateInterface, Stages.StaticFlag staticFlag) { for (ExecutableElement element : mOnUpdateStateMethods) { validateOnStateUpdateMethodDeclaration(element); generateStateUpdateClass( element, componentClassName, stateContainerClassName, stateUpdateInterface, staticFlag); generateOnStateUpdateMethods(element, contextClass, componentClassName); } } /** * Validate that the declaration of a method annotated with {@link OnUpdateState} is correct: * <ul> * <li>1. Method parameters annotated with {@link Param} don't have the same name as parameters * annotated with {@link State} or {@link Prop}.</li> * <li>2. Method parameters not annotated with {@link Param} must be of type * com.facebook.litho.StateValue.</li> * <li>3. Names of method parameters not annotated with {@link Param} must match the name of * a parameter annotated with {@link State}.</li> * <li>4. Type of method parameters not annotated with {@link Param} must match the type of * a parameter with the same name annotated with {@link State}.</li> * </ul> */ private void validateOnStateUpdateMethodDeclaration(ExecutableElement element) { final List<VariableElement> annotatedParams = Utils.getParametersWithAnnotation(element, Param.class); // Check for (VariableElement annotatedParam : annotatedParams) { if (mStateMap.get(annotatedParam.getSimpleName().toString()) != null) { throw new ComponentsProcessingException( annotatedParam, "Parameters annotated with @Param should not have the same name as a parameter " + "annotated with @State or @Prop"); } } final List<VariableElement> params = (List<VariableElement>) element.getParameters(); for (VariableElement param : params) { if (annotatedParams.contains(param)) { continue; } final TypeMirror paramType = param.asType(); // Check if (paramType.getKind() != DECLARED) { throw new ComponentsProcessingException( param, "Parameters not annotated with @Param must be of type " + "com.facebook.litho.StateValue"); } final DeclaredType paramDeclaredType = (DeclaredType) param.asType(); final String paramDeclaredTypeName = paramDeclaredType .asElement() .getSimpleName() .toString(); if (!paramDeclaredTypeName.equals(ClassNames.STATE_VALUE.simpleName())) { throw new ComponentsProcessingException( "All state parameters must be of type com.facebook.litho.StateValue, " + param.getSimpleName() + " is of type " + param.asType()); } VariableElement stateMatchingParam = mStateMap.get(param.getSimpleName().toString()); // Check if (stateMatchingParam == null || stateMatchingParam.getAnnotation(State.class) == null) { throw new ComponentsProcessingException( param, "Names of parameters of type StateValue must match the name of a parameter annotated " + "with @State"); } // Check final List<TypeMirror> typeArguments = (List<TypeMirror>) paramDeclaredType.getTypeArguments(); if (typeArguments.isEmpty()) { throw new ComponentsProcessingException( param, "Type parameter for a parameter of type StateValue should match the type of " + "a parameter with the same name annotated with @State"); } final TypeMirror typeArgument = typeArguments.get(0); final TypeName stateMatchingParamTypeName = ClassName.get(stateMatchingParam.asType()); if (stateMatchingParamTypeName.isPrimitive()) { TypeName stateMatchingParamBoxedType = stateMatchingParamTypeName.box(); if (!stateMatchingParamBoxedType.equals(TypeName.get(typeArgument))) { throw new ComponentsProcessingException( param, "Type parameter for a parameter of type StateValue should match the type of " + "a parameter with the same name annotated with @State"); } } } } /** * Generate an EventHandler factory methods */ public void generateEventHandlerFactories( ClassName contextClassName, ClassName componentClassName) { for (ExecutableElement element : mOnEventMethods) { generateEventHandlerFactory( element, contextClassName, componentClassName); } } // ExecutableElement.hashCode may be different in different runs of the // processor. getElementId() is deterministic and ensures that the output is // the same across multiple runs. private int getElementId(ExecutableElement el) { return (mQualifiedClassName.hashCode() * 31 + el.getSimpleName().hashCode()) * 31 + el.asType().toString().hashCode(); } /** * Generate a dispatchOnEvent() implementation for the component. */ public void generateDispatchOnEvent( ClassName contextClassName) { final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("dispatchOnEvent") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(TypeName.OBJECT) .addParameter( ParameterSpec.builder(ClassNames.EVENT_HANDLER, "eventHandler", Modifier.FINAL).build()) .addParameter( ParameterSpec.builder(ClassNames.OBJECT, "eventState", Modifier.FINAL).build()); methodBuilder.addStatement("int id = eventHandler.id"); methodBuilder.beginControlFlow("switch($L)", "id"); final String implInstanceName = "_" + getImplInstanceName(); for (ExecutableElement element : mOnEventMethods) { methodBuilder.beginControlFlow("case $L:", getElementId(element)); final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final String eventName = eventClass.toString(); methodBuilder.addStatement( "$L $L = ($L) $L", eventName, implInstanceName, eventName, "eventState"); final CodeBlock.Builder eventHandlerParams = CodeBlock.builder(); eventHandlerParams.indent(); int i = 0; eventHandlerParams.add("\n($T) eventHandler.params[$L],", contextClassName, i++); for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) { eventHandlerParams.add( "\n" + implInstanceName + ".$L,", v.getSimpleName().toString()); } for (VariableElement v : Utils.getParametersWithAnnotation(element, Param.class)) { eventHandlerParams.add("\n($T) eventHandler.params[$L],", ClassName.get(v.asType()), i); i++; } eventHandlerParams.add("\n$L", "eventHandler.mHasEventDispatcher"); eventHandlerParams.unindent(); if (element.getReturnType().getKind() != VOID) { methodBuilder.addStatement( "return do$L($L)", capitalize(element.getSimpleName().toString()), eventHandlerParams.build()); } else { methodBuilder.addStatement( "do$L($L)", capitalize(element.getSimpleName().toString()), eventHandlerParams.build()); methodBuilder.addStatement("return null"); } methodBuilder.endControlFlow(); } methodBuilder.addStatement("default: \nreturn null"); methodBuilder.endControlFlow(); writeMethodSpec(methodBuilder.build()); } private void generateEventHandlerFactory( ExecutableElement element, ClassName contextClassName, ClassName componentClassName) { final List<VariableElement> eventParamElements = Utils.getParametersWithAnnotation(element, Param.class); final List<Parameter> eventParams = new ArrayList<>(); final List<String> typeParameters = new ArrayList<>(); for (VariableElement e : eventParamElements) { eventParams.add(new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString())); for (TypeMirror typeParam : getTypeVarArguments(e.asType())) { typeParameters.add(typeParam.toString()); } } final DeclaredType eventClass = Utils.getAnnotationParameter( mProcessingEnv, element, OnEvent.class, "value"); final TypeName eventClassName = ClassName.bestGuess(((TypeElement) eventClass.asElement()).getQualifiedName().toString()); writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder() .eventId(getElementId(element)) .eventName(element.getSimpleName().toString()) .contextClass(contextClassName) .eventHandlerClassName( ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName)) .eventParams(eventParams) .typeParameters(typeParameters) .build()); writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder() .eventId(getElementId(element)) .eventName(element.getSimpleName().toString()) .contextClass(componentClassName) .eventHandlerClassName( ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName)) .eventParams(eventParams) .typeParameters(typeParameters) .build()); } private void generateOnEventHandler( ExecutableElement element, ClassName contextClassName) { if (element.getParameters().size() == 0 || !ClassName.get(element.getParameters().get(0).asType()).equals(contextClassName)) { throw new ComponentsProcessingException( element, "The first parameter for an onEvent method should be of type " +contextClassName.toString()); } final String evenHandlerName = element.getSimpleName().toString(); final List<Parameter> fromParams = new ArrayList<>(); fromParams.add(new Parameter( contextClassName, element.getParameters().get(0).getSimpleName().toString())); final List<VariableElement> fromParamElements = Utils.getParametersWithAnnotation(element, FromEvent.class); fromParamElements.addAll(Utils.getParametersWithAnnotation(element, Param.class)); for (VariableElement v : fromParamElements) { fromParams.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); } writeMethodSpec(new DelegateMethodSpecBuilder() .implClassName(getImplClassName()) .abstractImplType(ClassNames.HAS_EVENT_DISPATCHER_CLASSNAME) .implParameters(mImplParameters) .visibility(PRIVATE) .fromName("do" + capitalize(evenHandlerName)) .fromParams(fromParams) .target(mSourceDelegateAccessorName) .toName(evenHandlerName) .toParams(getParams(element)) .fromReturnType(ClassName.get(element.getReturnType())) .toReturnType(ClassName.get(element.getReturnType())) .stateParams(mStateMap.keySet()) .build()); } private void generateOnStateUpdateMethods( ExecutableElement element, ClassName contextClass, ClassName componentClass) { final String methodName = element.getSimpleName().toString(); final List<VariableElement> updateMethodParamElements = Utils.getParametersWithAnnotation(element, Param.class); final OnStateUpdateMethodSpecBuilder builder = new OnStateUpdateMethodSpecBuilder() .componentClass(componentClass) .lifecycleImplClass(mSimpleClassName) .stateUpdateClassName(getStateUpdateClassName(element)); for (VariableElement e : updateMethodParamElements) { builder.updateMethodParam( new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString())); List<TypeMirror> genericArgs = getTypeVarArguments(e.asType()); if (genericArgs != null) { for (TypeMirror genericArg : genericArgs) { builder.typeParameter(genericArg.toString()); } } } writeMethodSpec(builder .updateMethodName(methodName) .async(false) .contextClass(contextClass) .build()); writeMethodSpec(builder .updateMethodName(methodName + "Async") .async(true) .contextClass(contextClass) .build()); } static List<TypeMirror> getTypeVarArguments(TypeMirror diffType) { List<TypeMirror> typeVarArguments = new ArrayList<>(); if (diffType.getKind() == DECLARED) { final DeclaredType parameterDeclaredType = (DeclaredType) diffType; final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments(); for (TypeMirror typeArgument : typeArguments) { if (typeArgument.getKind() == TYPEVAR) { typeVarArguments.add(typeArgument); } } } return typeVarArguments; } public static List<TypeMirror> getGenericTypeArguments(TypeMirror diffType) { if (diffType.getKind() == DECLARED) { final DeclaredType parameterDeclaredType = (DeclaredType) diffType; final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments(); return (List<TypeMirror>) typeArguments; } return null; } public static List<Parameter> getParams(ExecutableElement e) { final List<Parameter> params = new ArrayList<>(); for (VariableElement v : e.getParameters()) { params.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); } return params; } /** * Generates a class that implements {@link com.facebook.litho.ComponentLifecycle} given * a method annotated with {@link OnUpdateState}. The class constructor takes as params all the * params annotated with {@link Param} on the method and keeps them in class members. * @param element The method annotated with {@link OnUpdateState} */ private void generateStateUpdateClass( ExecutableElement element, ClassName componentClassName, ClassName stateContainerClassName, ClassName updateStateInterface, StaticFlag staticFlag) { final String stateUpdateClassName = getStateUpdateClassName(element); final TypeName implClassName = ClassName.bestGuess(getImplClassName()); final StateUpdateImplClassBuilder stateUpdateImplClassBuilder = new StateUpdateImplClassBuilder() .withTarget(mSourceDelegateAccessorName) .withSpecOnUpdateStateMethodName(element.getSimpleName().toString()) .withComponentImplClassName(implClassName) .withComponentClassName(componentClassName) .withComponentStateUpdateInterface(updateStateInterface) .withStateContainerClassName(stateContainerClassName) .withStateContainerImplClassName(ClassName.bestGuess(getStateContainerImplClassName())) .withStateUpdateImplClassName(stateUpdateClassName) .withSpecOnUpdateStateMethodParams(getParams(element)) .withStateValueParams(getStateValueParams(element)) .withStaticFlag(staticFlag); final List<VariableElement> parametersVarElements = Utils.getParametersWithAnnotation(element, Param.class); final List<Parameter> parameters = new ArrayList<>(); for (VariableElement v : parametersVarElements) { parameters.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString())); for (TypeMirror typeVar : getTypeVarArguments(v.asType())) { stateUpdateImplClassBuilder.typeParameter(typeVar.toString()); } } stateUpdateImplClassBuilder.withParamsForStateUpdate(parameters); writeInnerTypeSpec(stateUpdateImplClassBuilder.build()); } /** * Generate an onLoadStyle implementation. */ public void generateOnLoadStyle() { final ExecutableElement delegateMethod = Utils.getAnnotatedMethod( mSourceElement, OnLoadStyle.class); if (delegateMethod == null) { return; } final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onLoadStyle") .addAnnotation( AnnotationSpec .builder(SuppressWarnings.class) .addMember("value", "$S", "unchecked").build()) .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .addParameter(ClassNames.COMPONENT_CONTEXT, "_context") .addParameter( ParameterSpec.builder( ParameterizedTypeName.get( ClassNames.COMPONENT, WildcardTypeName.subtypeOf(Object.class)), "_component") .build()); final List<? extends VariableElement> parameters = delegateMethod.getParameters(); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final TypeName typeName = ClassName.get(v.asType()); methodBuilder.addStatement( "$L $L = ($L) $L", typeName, v.getSimpleName(), typeName, "acquireOutput()"); } final CodeBlock.Builder delegateParameters = CodeBlock.builder().indent(); delegateParameters.add("\n_context"); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { delegateParameters.add(",\n$L", parameters.get(i).getSimpleName()); } delegateParameters.unindent(); methodBuilder.addStatement( "this.$L.$L($L)", mSourceDelegateAccessorName, delegateMethod.getSimpleName(), delegateParameters.build()); final String implClassName = getImplClassName(); final String implInstanceName = "_" + getImplInstanceName(); methodBuilder.addStatement( "$L " + implInstanceName + "= ($L) _component", implClassName, implClassName); for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) { final VariableElement v = parameters.get(i); final String name = v.getSimpleName().toString(); methodBuilder.beginControlFlow("if ($L.get() != null)", name); methodBuilder.addStatement( "$L.$L = $L.get()", implInstanceName, name, name); methodBuilder.endControlFlow(); methodBuilder.addStatement("releaseOutput($L)", name); } writeMethodSpec(methodBuilder.build()); } /** * Find variables annotated with {@link PropDefault} */ private void populatePropDefaults() { mPropDefaults = PropDefaultsExtractor.getPropDefaults(mSourceElement); } public void generateComponentImplClass(Stages.StaticFlag isStatic) { generateStateContainerImplClass(isStatic, ClassNames.STATE_CONTAINER_COMPONENT); final String implClassName = getImplClassName(); final ClassName stateContainerImplClass = ClassName.bestGuess(getSimpleClassName() + STATE_CONTAINER_IMPL_NAME_SUFFIX); final TypeSpec.Builder implClassBuilder = TypeSpec.classBuilder(implClassName) .addModifiers(Modifier.PRIVATE) .superclass( ParameterizedTypeName.get( ClassNames.COMPONENT, ClassName.bestGuess(getSimpleClassName()))) .addSuperinterface(Cloneable.class); if (isStatic.equals(Stages.StaticFlag.STATIC)) { implClassBuilder.addModifiers(Modifier.STATIC); implClassBuilder.addTypeVariables(mTypeVariables); } implClassBuilder.addField(stateContainerImplClass, STATE_CONTAINER_IMPL_MEMBER); implClassBuilder.addMethod(generateStateContainerGetter(ClassNames.STATE_CONTAINER_COMPONENT)); generateComponentClassProps(implClassBuilder, ClassNames.EVENT_HANDLER); MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addStatement("super(get())") .addStatement(STATE_CONTAINER_IMPL_MEMBER + " = new $T()", stateContainerImplClass); implClassBuilder.addMethod(constructorBuilder.build()); implClassBuilder.addMethod( MethodSpec.methodBuilder("getSimpleName") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(ClassNames.STRING) .addStatement("return \"" + getSimpleClassName() + "\"") .build()); final MethodSpec equalsBuilder = generateEqualsMethodDefinition(true); implClassBuilder.addMethod(equalsBuilder); final MethodSpec copyInterStage = generateCopyInterStageImpl(implClassName); if (copyInterStage != null) { implClassBuilder.addMethod(copyInterStage); } for (ExecutableElement element : mOnUpdateStateMethods) { final String stateUpdateClassName = getStateUpdateClassName(element); final List<Parameter> parameters = getParamsWithAnnotation(element, Param.class); implClassBuilder.addMethod( new CreateStateUpdateInstanceMethodSpecBuilder() .parameters(parameters) .stateUpdateClass(stateUpdateClassName) .build()); } final MethodSpec makeShallowCopy = generateMakeShallowCopy(ClassNames.COMPONENT, /* hasDeepCopy */ false); if (makeShallowCopy != null) { implClassBuilder.addMethod(makeShallowCopy); } writeInnerTypeSpec(implClassBuilder.build()); } public void generateLazyStateUpdateMethods( ClassName context, ClassName componentClass, TypeName stateUpdateType, TypeName stateContainerComponent) { for (VariableElement state : mStateMap.values()) { if (state.getAnnotation(State.class).canUpdateLazily()) { writeMethodSpec(new OnLazyStateUpdateMethodSpecBuilder() .contextClass(context) .componentClass(componentClass) .stateUpdateType(stateUpdateType) .stateName(state.getSimpleName().toString()) .stateType(ClassName.get(state.asType())) .withStateContainerClassName(stateContainerComponent) .implClass(getImplClassName()) .lifecycleImplClass(mSimpleClassName) .build()); } } } private void generateStateContainerImplClass( Stages.StaticFlag isStatic, ClassName stateContainerClassName) { final TypeSpec.Builder stateContainerImplClassBuilder = TypeSpec .classBuilder(getStateContainerImplClassName()) .addSuperinterface(stateContainerClassName); if (isStatic.equals(Stages.StaticFlag.STATIC)) { stateContainerImplClassBuilder.addModifiers(Modifier.STATIC, Modifier.PRIVATE); stateContainerImplClassBuilder.addTypeVariables(mTypeVariables); } for (String stateName : mStateMap.keySet()) { VariableElement v = mStateMap.get(stateName); stateContainerImplClassBuilder.addField(getPropFieldSpec(v, true)); } writeInnerTypeSpec(stateContainerImplClassBuilder.build()); } private static MethodSpec generateStateContainerGetter(ClassName stateContainerClassName) { return MethodSpec.methodBuilder("getStateContainer") .addModifiers(Modifier.PROTECTED) .addAnnotation(Override.class) .returns(stateContainerClassName) .addStatement("return " + STATE_CONTAINER_IMPL_MEMBER) .build(); } public void generateReferenceImplClass( Stages.StaticFlag isStatic, TypeMirror referenceType) { final TypeSpec.Builder implClassBuilder = TypeSpec.classBuilder(getImplClassName()) .addModifiers(Modifier.PRIVATE) .superclass( ParameterizedTypeName.get( ClassNames.REFERENCE, ClassName.get(referenceType))); if (isStatic.equals(Stages.StaticFlag.STATIC)) { implClassBuilder.addModifiers(Modifier.STATIC); } generateComponentClassProps(implClassBuilder, null); implClassBuilder.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addStatement("super(get())") .build()); implClassBuilder.addMethod( MethodSpec.methodBuilder("getSimpleName") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(ClassNames.STRING) .addStatement("return \"" + getSimpleClassName() + "\"") .build()); final MethodSpec equalsBuilder = generateEqualsMethodDefinition(false); implClassBuilder.addMethod(equalsBuilder); writeInnerTypeSpec(implClassBuilder.build()); } public void generateTransferState( ClassName contextClassName, ClassName componentClassName, ClassName stateContainerClassName) { if (!mStateMap.isEmpty()) { MethodSpec methodSpec = new TransferStateSpecBuilder() .contextClassName(contextClassName) .componentClassName(componentClassName) .componentImplClassName(getImplClassName()) .stateContainerClassName(stateContainerClassName) .stateContainerImplClassName(getStateContainerImplClassName()) .stateParameters(mStateMap.keySet()) .build(); mClassTypeSpec.addMethod(methodSpec); } } public void generateHasState() { if (mStateMap.isEmpty()) { return; } MethodSpec hasStateMethod = MethodSpec.methodBuilder("hasState") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(TypeName.BOOLEAN) .addStatement("return true") .build(); mClassTypeSpec.addMethod(hasStateMethod); } public void generateListComponentImplClass(Stages.StaticFlag isStatic) { generateStateContainerImplClass(isStatic, SectionClassNames.STATE_CONTAINER_SECTION); final ClassName stateContainerImplClass = ClassName.bestGuess(getSimpleClassName() + STATE_CONTAINER_IMPL_NAME_SUFFIX); final TypeSpec.Builder stateClassBuilder = TypeSpec.classBuilder(getImplClassName()) .addModifiers(Modifier.PRIVATE) .superclass( ParameterizedTypeName.get( SectionClassNames.SECTION, ClassName.bestGuess(getSimpleClassName()))) .addSuperinterface(Cloneable.class); if (isStatic.equals(Stages.StaticFlag.STATIC)) { stateClassBuilder.addModifiers(Modifier.STATIC); } stateClassBuilder.addField(stateContainerImplClass, STATE_CONTAINER_IMPL_MEMBER); stateClassBuilder.addMethod(generateStateContainerGetter(SectionClassNames.STATE_CONTAINER_SECTION)); generateComponentClassProps(stateClassBuilder, ClassNames.EVENT_HANDLER); stateClassBuilder.addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addStatement("super(get())") .addStatement(STATE_CONTAINER_IMPL_MEMBER + " = new $T()", stateContainerImplClass) .build()); final MethodSpec equalsBuilder = generateEqualsMethodDefinition(false); stateClassBuilder.addMethod(equalsBuilder); for (ExecutableElement element : mOnUpdateStateMethods) { final String stateUpdateClassName = getStateUpdateClassName(element); final List<Parameter> parameters = getParamsWithAnnotation(element, Param.class); stateClassBuilder.addMethod( new CreateStateUpdateInstanceMethodSpecBuilder() .parameters(parameters) .stateUpdateClass(stateUpdateClassName) .build()); } final MethodSpec makeShallowCopy = generateMakeShallowCopy(SectionClassNames.SECTION, /* hasDeepCopy */ true); if (makeShallowCopy != null) { stateClassBuilder.addMethod(makeShallowCopy); } writeInnerTypeSpec(stateClassBuilder.build()); } private MethodSpec generateEqualsMethodDefinition(boolean shouldCheckId) { final String implClassName = getImplClassName(); final String implInstanceName = getImplInstanceName(); MethodSpec.Builder equalsBuilder = MethodSpec.methodBuilder("equals") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addParameter(TypeName.OBJECT, "other") .beginControlFlow("if (this == other)") .addStatement("return true") .endControlFlow() .beginControlFlow("if (other == null || getClass() != other.getClass())") .addStatement("return false") .endControlFlow() .addStatement(implClassName + " " + implInstanceName + " = (" + implClassName + ") other"); if (shouldCheckId) { equalsBuilder .beginControlFlow( "if (this.getId() == " + implInstanceName + ".getId())") .addStatement("return true") .endControlFlow(); } for (VariableElement v : mImplMembers.values()) { if (!isState(v)) { addCompareStatement(implInstanceName, v, equalsBuilder, false); } } for (VariableElement v : mStateMap.values()) { addCompareStatement(implInstanceName, v, equalsBuilder, true); } equalsBuilder.addStatement("return true"); return equalsBuilder.build(); } private static void addCompareStatement( String implInstanceName, VariableElement v, MethodSpec.Builder equalsBuilder, boolean isState) { final TypeMirror variableType = v.asType(); final TypeMirror outputTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.OUTPUT); final TypeMirror diffTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.DIFF); final TypeKind variableKind = diffTypeMirror != null ? diffTypeMirror.getKind() : variableType.getKind(); String qualifiedName = ""; if (variableType instanceof DeclaredType) { final DeclaredType declaredType = (DeclaredType) variableType; qualifiedName = ((TypeElement) declaredType.asElement()).getQualifiedName().toString(); } final String stateContainerMember = isState ? "." + STATE_CONTAINER_IMPL_MEMBER : ""; final CharSequence thisVarName = isState ? STATE_CONTAINER_IMPL_MEMBER + "." + v.getSimpleName() : v.getSimpleName(); if (outputTypeMirror == null) { if (variableKind == FLOAT) { equalsBuilder .beginControlFlow( "if (Float.compare($L, " + implInstanceName + stateContainerMember + ".$L) != 0)", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (variableKind == DOUBLE) { equalsBuilder .beginControlFlow( "if (Double.compare($L, " + implInstanceName + stateContainerMember + ".$L) != 0)", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (variableType.getKind() == ARRAY) { equalsBuilder .beginControlFlow( "if (!Arrays.equals($L, " + implInstanceName + stateContainerMember + ".$L))", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (variableType.getKind().isPrimitive()) { equalsBuilder .beginControlFlow( "if ($L != " + implInstanceName + stateContainerMember + ".$L)", thisVarName, v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else if (qualifiedName.equals(ClassNames.REFERENCE)) { equalsBuilder .beginControlFlow( "if (Reference.shouldUpdate($L, " + implInstanceName + stateContainerMember + ".$L))", thisVarName, v.getSimpleName(), v.getSimpleName(), v.getSimpleName(), v.getSimpleName()) .addStatement("return false") .endControlFlow(); } else { equalsBuilder .beginControlFlow( "if ($L != null ? !$L.equals(" + implInstanceName + stateContainerMember + ".$L) : " + implInstanceName + stateContainerMember + ".$L != null)", thisVarName, thisVarName, v.getSimpleName(), v.getSimpleName()) .addStatement("return false") .endControlFlow(); } } } private boolean isState(VariableElement v) { for (VariableElement find : mStateMap.values()) { if (find.getSimpleName().equals(v.getSimpleName())) { return true; } } return false; } private void generateComponentClassProps( TypeSpec.Builder implClassBuilder, ClassName eventHandlerClassName) { for (VariableElement v : mImplMembers.values()) { implClassBuilder.addField(getPropFieldSpec(v, false)); } if (mExtraStateMembers != null) { for (String key : mExtraStateMembers.keySet()) { final TypeMirror variableType = mExtraStateMembers.get(key); final FieldSpec.Builder fieldBuilder = FieldSpec.builder(TypeName.get(variableType), key); implClassBuilder.addField(fieldBuilder.build()); } } for (TypeElement event : mEventDeclarations) { implClassBuilder.addField(FieldSpec.builder( eventHandlerClassName, getEventHandlerInstanceName(event.getSimpleName().toString())) .build()); } } private FieldSpec getPropFieldSpec(VariableElement v, boolean isStateProp) { final TypeMirror variableType = v.asType(); TypeMirror wrappingTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.OUTPUT); if (wrappingTypeMirror == null) { wrappingTypeMirror = Utils.getGenericTypeArgument(variableType, ClassNames.DIFF); } final TypeName variableClassName = JPUtil.getTypeFromMirror( wrappingTypeMirror != null ? wrappingTypeMirror : variableType); final FieldSpec.Builder fieldBuilder = FieldSpec.builder( variableClassName, v.getSimpleName().toString()); if (!isInterStageComponentVariable(v)) { if (isStateProp) { fieldBuilder.addAnnotation(State.class); } else { fieldBuilder.addAnnotation(Prop.class); } } final boolean hasDefaultValue = hasDefaultValue(v); if (hasDefaultValue) { fieldBuilder.initializer( "$L.$L", mSourceElement.getSimpleName().toString(), v.getSimpleName().toString()); } return fieldBuilder.build(); } public void generateIsPureRender() { final MethodSpec.Builder shouldUpdateComponent = MethodSpec.methodBuilder("isPureRender") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addStatement("return true"); mClassTypeSpec.addMethod(shouldUpdateComponent.build()); } public void generateCallsShouldUpdateOnMount() { final MethodSpec.Builder isFast = MethodSpec.methodBuilder("callsShouldUpdateOnMount") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addStatement("return true"); mClassTypeSpec.addMethod(isFast.build()); } public void generateShouldUpdateMethod( ExecutableElement shouldUpdateElement, ClassName comparedInstancesClassName) { final ClassName implClass = ClassName.bestGuess(getImplClassName()); final MethodSpec.Builder shouldUpdateComponent = MethodSpec.methodBuilder("shouldUpdate") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(TypeName.BOOLEAN) .addParameter(comparedInstancesClassName, "previous") .addParameter(comparedInstancesClassName, "next"); final List<? extends VariableElement> shouldUpdateParams = shouldUpdateElement.getParameters(); final int shouldUpdateParamSize = shouldUpdateParams.size(); if (shouldUpdateParamSize > 0) { shouldUpdateComponent .addStatement( "$L previousImpl = ($L) previous", implClass, implClass) .addStatement( "$L nextImpl = ($L) next", implClass, implClass); } final CodeBlock.Builder delegateParameters = CodeBlock.builder(); delegateParameters.indent(); int i = 0; final CodeBlock.Builder releaseDiffs = CodeBlock.builder(); for (VariableElement variableElement : shouldUpdateParams) { final Name variableElementName = variableElement.getSimpleName(); final TypeMirror variableElementType = variableElement.asType(); final VariableElement componentMember = findPropVariableForName(variableElementName); if (componentMember == null) { throw new ComponentsProcessingException( variableElement, "Arguments for ShouldUpdate should match declared Props"); } final TypeMirror innerType = Utils.getGenericTypeArgument( variableElementType, ClassNames.DIFF); if (innerType == null) { throw new ComponentsProcessingException( variableElement, "Arguments for ShouldUpdate should be of type Diff " + componentMember.asType()); } final TypeName typeName; final TypeName innerTypeName = JPUtil.getTypeFromMirror(innerType); if (componentMember.asType().getKind().isPrimitive()) { typeName = JPUtil.getTypeFromMirror(componentMember.asType()).box(); } else { typeName = JPUtil.getTypeFromMirror(componentMember.asType()); } if (!typeName.equals(innerTypeName)) { throw new ComponentsProcessingException( variableElement, "Diff Type parameter does not match Prop " + componentMember); } shouldUpdateComponent .addStatement( "$L $L = acquireDiff(previousImpl.$L, nextImpl.$L)", variableElementType, variableElementName, variableElementName, variableElementName); if (i != 0) { delegateParameters.add(",\n"); } delegateParameters.add(variableElementName.toString()); i++; releaseDiffs.addStatement( "releaseDiff($L)", variableElementName); } delegateParameters.unindent(); shouldUpdateComponent.addStatement( "boolean shouldUpdate = $L.$L(\n$L)", mSourceDelegateAccessorName, shouldUpdateElement.getSimpleName(), delegateParameters.build()); shouldUpdateComponent.addCode(releaseDiffs.build()); shouldUpdateComponent.addStatement( "return shouldUpdate"); mClassTypeSpec.addMethod(shouldUpdateComponent.build()); } public void generateTreePropsMethods(ClassName contextClassName, ClassName componentClassName) { verifyOnCreateTreePropsForChildren(contextClassName); if (!mTreeProps.isEmpty()) { final PopulateTreePropsMethodBuilder builder = new PopulateTreePropsMethodBuilder(); builder.componentClassName = componentClassName; builder.lifecycleImplClass = getImplClassName(); for (VariableElement treeProp : mTreeProps) { builder.treeProps.add( new Parameter(ClassName.get(treeProp.asType()), treeProp.getSimpleName().toString())); } mClassTypeSpec.addMethod(builder.build()); } if (mOnCreateTreePropsMethods.isEmpty()) { return; } final GetTreePropsForChildrenMethodBuilder builder = new GetTreePropsForChildrenMethodBuilder(); builder.lifecycleImplClass = getImplClassName(); builder.delegateName = getSourceDelegateAccessorName(); builder.contextClassName = contextClassName; builder.componentClassName = componentClassName; for (ExecutableElement executable : mOnCreateTreePropsMethods) { final CreateTreePropMethodData method = new CreateTreePropMethodData(); method.parameters = getParams(executable); method.returnType = ClassName.get(executable.getReturnType()); method.name = executable.getSimpleName().toString(); builder.createTreePropMethods.add(method); } mClassTypeSpec.addMethod(builder.build()); } private void verifyOnCreateTreePropsForChildren(ClassName contextClassName) { for (ExecutableElement method : mOnCreateTreePropsMethods) { if (method.getReturnType().getKind().equals(TypeKind.VOID)) { throw new ComponentsProcessingException( method, "@OnCreateTreeProp annotated method" + method.getSimpleName() + "cannot have a void return type"); } final List<? extends VariableElement> params = method.getParameters(); if (params.isEmpty() || !ClassName.get(params.get(0).asType()).equals(contextClassName)) { throw new ComponentsProcessingException( method, "The first argument of an @OnCreateTreeProp method should be the " + contextClassName.simpleName()); } } } private VariableElement findPropVariableForName(Name variableElementName) { for (VariableElement prop : mProps) { if (prop.getSimpleName().equals(variableElementName)) { return prop; } } return null; } private MethodSpec generateCopyInterStageImpl(String implClassName) { final List<String> elementList = getInterStageVariableNames(); if (elementList.isEmpty()) { return null; } final String implInstanceName = getImplInstanceName(); final MethodSpec.Builder copyInterStageComponentBuilder = MethodSpec .methodBuilder("copyInterStageImpl") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .returns(TypeName.VOID) .addParameter( ParameterizedTypeName.get( ClassNames.COMPONENT, ClassName.bestGuess(getSimpleClassName())), "impl") .addStatement( "$L " + implInstanceName + " = ($L) impl", implClassName, implClassName); for (String s : elementList) { copyInterStageComponentBuilder .addStatement( "$L = " + implInstanceName + ".$L", s, s); } return copyInterStageComponentBuilder.build(); } private List<String> getInterStageVariableNames() { final List<String> elementList = new ArrayList<>(); for (VariableElement v : mImplMembers.values()) { if (isInterStageComponentVariable(v)) { elementList.add(v.getSimpleName().toString()); } } return elementList; } private static boolean isInterStageComponentVariable(VariableElement variableElement) { final TypeMirror variableType = variableElement.asType(); final TypeMirror outputTypeMirror = Utils.getGenericTypeArgument( variableType, ClassNames.OUTPUT); return outputTypeMirror != null; } private static boolean isStateProp(VariableElement variableElement) { return variableElement.getAnnotation(State.class) != null; } public void generateListEvents() { for (TypeElement event : mEventDeclarations) { generateEvent( event, ClassNames.EVENT_HANDLER, SectionClassNames.SECTION_LIFECYCLE, SectionClassNames.SECTION_CONTEXT, "getSectionScope"); } } private static String getEventHandlerInstanceName(String eventHandlerClassName) { return Character.toLowerCase(eventHandlerClassName.charAt(0)) + eventHandlerClassName.substring(1) + "Handler"; } private void generateEvent( TypeElement eventDeclaration, ClassName eventHandlerClassName, ClassName lifecycleClassName, ClassName contextClassName, String scopeMethodName) { final String eventName = eventDeclaration.getSimpleName().toString(); writeMethodSpec(MethodSpec.methodBuilder("get" + eventName + "Handler") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(eventHandlerClassName) .addParameter(contextClassName, "context") .addCode( CodeBlock.builder() .beginControlFlow("if (context.$L() == null)", scopeMethodName) .addStatement("return null") .endControlFlow() .build()) .addStatement( "return (($L.$T) context.$L()).$L", getSimpleClassName(), ClassName.bestGuess(getImplClassName()), scopeMethodName, getEventHandlerInstanceName(eventName)) .build()); // Override the method that the component will call to fire the event. final MethodDescription methodDescription = new MethodDescription(); methodDescription.annotations = new Class[] {}; methodDescription.accessType = Modifier.STATIC; methodDescription.name = "dispatch" + eventName; methodDescription.parameterTypes = new TypeName[] { ClassName.bestGuess(mQualifiedClassName) };
import java.util.*; public class MathsParser { public MathsParser (boolean debug) { _debug = debug; } /** * All numbers within expressions are single digit so we can continue to use them as * characters. * * Handle different precedence to part 1. */ public long parse (Vector<String> data) { long finalResult = 0L; for (int i = 0; i < data.size(); i++) { String currentLine = data.elementAt(i); char[] lineArray = currentLine.trim().replaceAll("\\s", "").toCharArray(); // remove all spaces } return finalResult; } private boolean _debug; }
package com.facebook.litho.widget; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.text.Editable; import android.text.InputFilter; import android.text.Layout; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.Gravity; import android.widget.EditText; import com.facebook.R; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentLayout; import com.facebook.litho.EventHandler; import com.facebook.litho.Output; import com.facebook.litho.Size; import com.facebook.litho.annotations.MountSpec; import com.facebook.litho.annotations.OnBind; import com.facebook.litho.annotations.OnCreateMountContent; import com.facebook.litho.annotations.OnLoadStyle; import com.facebook.litho.annotations.OnMeasure; import com.facebook.litho.annotations.OnMount; import com.facebook.litho.annotations.OnUnbind; import com.facebook.litho.annotations.OnUnmount; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.litho.utils.MeasureUtils; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.text.Layout.Alignment.ALIGN_NORMAL; import static android.view.View.TEXT_ALIGNMENT_CENTER; import static android.view.View.TEXT_ALIGNMENT_TEXT_END; import static android.view.View.TEXT_ALIGNMENT_TEXT_START; @MountSpec(isPureRender = true, events = {TextChangedEvent.class}) class EditTextSpec { private static final Layout.Alignment[] ALIGNMENT = Layout.Alignment.values(); private static final TextUtils.TruncateAt[] TRUNCATE_AT = TextUtils.TruncateAt.values(); private static final Typeface DEFAULT_TYPEFACE = Typeface.DEFAULT; private static final int DEFAULT_COLOR = 0; private static final int[][] DEFAULT_TEXT_COLOR_STATE_LIST_STATES = {{0}}; private static final int[] DEFAULT_TEXT_COLOR_STATE_LIST_COLORS = {Color.BLACK}; private static final int DEFAULT_HINT_COLOR = 0; private static final int[][] DEFAULT_HINT_COLOR_STATE_LIST_STATES = {{0}}; private static final int[] DEFAULT_HINT_COLOR_STATE_LIST_COLORS = {Color.LTGRAY}; private static final int DEFAULT_GRAVITY = Gravity.CENTER_VERTICAL | Gravity.START; @PropDefault protected static final int minLines = Integer.MIN_VALUE; @PropDefault protected static final int maxLines = Integer.MAX_VALUE; @PropDefault protected static final int maxLength = Integer.MAX_VALUE; @PropDefault protected static final int shadowColor = Color.GRAY; @PropDefault protected static final int textColor = DEFAULT_COLOR; @PropDefault protected static final ColorStateList textColorStateList = new ColorStateList(DEFAULT_TEXT_COLOR_STATE_LIST_STATES,DEFAULT_TEXT_COLOR_STATE_LIST_COLORS); @PropDefault protected static final int hintColor = DEFAULT_HINT_COLOR; @PropDefault protected static final ColorStateList hintColorStateList = new ColorStateList(DEFAULT_HINT_COLOR_STATE_LIST_STATES,DEFAULT_HINT_COLOR_STATE_LIST_COLORS); @PropDefault protected static final int linkColor = DEFAULT_COLOR; @PropDefault protected static final int textSize = 13; @PropDefault protected static final int textStyle = DEFAULT_TYPEFACE.getStyle(); @PropDefault protected static final Typeface typeface = DEFAULT_TYPEFACE; @PropDefault protected static final float spacingMultiplier = 1.0f; @PropDefault protected static final Layout.Alignment textAlignment = ALIGN_NORMAL; @PropDefault protected static final int gravity = DEFAULT_GRAVITY; @PropDefault protected static final boolean editable = true; @PropDefault protected static final int selection = -1; @OnLoadStyle static void onLoadStyle( ComponentContext c, Output<TextUtils.TruncateAt> ellipsize, Output<Float> spacingMultiplier, Output<Integer> minLines, Output<Integer> maxLines, Output<Boolean> isSingleLine, Output<CharSequence> text, Output<ColorStateList> textColorStateList, Output<Integer> linkColor, Output<Integer> highlightColor, Output<Integer> textSize, Output<Layout.Alignment> textAlignment, Output<Integer> textStyle, Output<Float> shadowRadius, Output<Float> shadowDx, Output<Float> shadowDy, Output<Integer> shadowColor, Output<Integer> gravity) { final TypedArray a = c.obtainStyledAttributes(R.styleable.Text, 0); for (int i = 0, size = a.getIndexCount(); i < size; i++) { final int attr = a.getIndex(i); if (attr == R.styleable.Text_android_text) { text.set(a.getString(attr)); } else if (attr == R.styleable.Text_android_textColor) { textColorStateList.set(a.getColorStateList(attr)); } else if (attr == R.styleable.Text_android_textSize) { textSize.set(a.getDimensionPixelSize(attr, 0)); } else if (attr == R.styleable.Text_android_ellipsize) { final int index = a.getInteger(attr, 0); if (index > 0) { ellipsize.set(TRUNCATE_AT[index - 1]); } } else if (SDK_INT >= JELLY_BEAN_MR1 && attr == R.styleable.Text_android_textAlignment) { textAlignment.set(ALIGNMENT[a.getInteger(attr, 0)]); } else if (attr == R.styleable.Text_android_minLines) { minLines.set(a.getInteger(attr, -1)); } else if (attr == R.styleable.Text_android_maxLines) { maxLines.set(a.getInteger(attr, -1)); } else if (attr == R.styleable.Text_android_singleLine) { isSingleLine.set(a.getBoolean(attr, false)); } else if (attr == R.styleable.Text_android_textColorLink) { linkColor.set(a.getColor(attr, 0)); } else if (attr == R.styleable.Text_android_textColorHighlight) { highlightColor.set(a.getColor(attr, 0)); } else if (attr == R.styleable.Text_android_textStyle) { textStyle.set(a.getInteger(attr, 0)); } else if (attr == R.styleable.Text_android_lineSpacingMultiplier) { spacingMultiplier.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowDx) { shadowDx.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowDy) { shadowDy.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowRadius) { shadowRadius.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowColor) { shadowColor.set(a.getColor(attr, 0)); } else if (attr == R.styleable.Text_android_gravity) { gravity.set(a.getInteger(attr, 0)); } } a.recycle(); } @OnMeasure static void onMeasure( ComponentContext c, ComponentLayout layout, int widthSpec, int heightSpec, Size size, @Prop(optional = true, resType = ResType.STRING) CharSequence text, @Prop(optional = true, resType = ResType.STRING) CharSequence hint, @Prop(optional = true) TextUtils.TruncateAt ellipsize, @Prop(optional = true, resType = ResType.INT) int minLines, @Prop(optional = true, resType = ResType.INT) int maxLines, @Prop(optional = true, resType = ResType.INT) int maxLength, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowRadius, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDx, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDy, @Prop(optional = true, resType = ResType.COLOR) int shadowColor, @Prop(optional = true, resType = ResType.BOOL) boolean isSingleLine, @Prop(optional = true, resType = ResType.COLOR) int textColor, @Prop(optional = true) ColorStateList textColorStateList, @Prop(optional = true, resType = ResType.COLOR) int hintColor, @Prop(optional = true) ColorStateList hintColorStateList, @Prop(optional = true, resType = ResType.COLOR) int linkColor, @Prop(optional = true, resType = ResType.COLOR) int highlightColor, @Prop(optional = true, resType = ResType.DIMEN_TEXT) int textSize, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float extraSpacing, @Prop(optional = true, resType = ResType.FLOAT) float spacingMultiplier, @Prop(optional = true) int textStyle, @Prop(optional = true) Typeface typeface, @Prop(optional = true) Layout.Alignment textAlignment, @Prop(optional = true) int gravity, @Prop(optional = true) boolean editable, @Prop(optional = true) int selection) { // TODO(11759579) - don't allocate a new EditText in every measure. final EditText editText = new EditText(c); initEditText( editText, text, hint, ellipsize, minLines, maxLines, maxLength, shadowRadius, shadowDx, shadowDy, shadowColor, isSingleLine, textColor, textColorStateList, hintColor, hintColorStateList, linkColor, highlightColor, textSize, extraSpacing, spacingMultiplier, textStyle, typeface, textAlignment, gravity, editable, selection); editText.measure( MeasureUtils.getViewMeasureSpec(widthSpec), MeasureUtils.getViewMeasureSpec(heightSpec)); size.width = editText.getMeasuredWidth(); size.height = editText.getMeasuredHeight(); } @OnCreateMountContent protected static EditTextTextTextChangedEventHandler onCreateMountContent( ComponentContext c) { return new EditTextTextTextChangedEventHandler(c); } @OnMount static void onMount( final ComponentContext c, EditTextTextTextChangedEventHandler editTextView, @Prop(optional = true, resType = ResType.STRING) CharSequence text, @Prop(optional = true, resType = ResType.STRING) CharSequence hint, @Prop(optional = true) TextUtils.TruncateAt ellipsize, @Prop(optional = true, resType = ResType.INT) int minLines, @Prop(optional = true, resType = ResType.INT) int maxLines, @Prop(optional = true, resType = ResType.INT) int maxLength, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowRadius, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDx, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDy, @Prop(optional = true, resType = ResType.COLOR) int shadowColor, @Prop(optional = true, resType = ResType.BOOL) boolean isSingleLine, @Prop(optional = true, resType = ResType.COLOR) int textColor, @Prop(optional = true) ColorStateList textColorStateList, @Prop(optional = true, resType = ResType.COLOR) int hintColor, @Prop(optional = true) ColorStateList hintColorStateList, @Prop(optional = true, resType = ResType.COLOR) int linkColor, @Prop(optional = true, resType = ResType.COLOR) int highlightColor, @Prop(optional = true, resType = ResType.DIMEN_TEXT) int textSize, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float extraSpacing, @Prop(optional = true, resType = ResType.FLOAT) float spacingMultiplier, @Prop(optional = true) int textStyle, @Prop(optional = true) Typeface typeface, @Prop(optional = true) Layout.Alignment textAlignment, @Prop(optional = true) int gravity, @Prop(optional = true) boolean editable, @Prop(optional = true) int selection) { editTextView.setEventHandler( com.facebook.litho.widget.EditText.getTextChangedEventHandler(c)); initEditText( editTextView, text, hint, ellipsize, minLines, maxLines, maxLength, shadowRadius, shadowDx, shadowDy, shadowColor, isSingleLine, textColor, textColorStateList, hintColor, hintColorStateList, linkColor, highlightColor, textSize, extraSpacing, spacingMultiplier, textStyle, typeface, textAlignment, gravity, editable, selection); } @OnBind static void onBind( ComponentContext c, EditTextTextTextChangedEventHandler editText) { editText.attachWatcher(); } @OnUnbind static void onUnbind( ComponentContext c, EditTextTextTextChangedEventHandler editText) { editText.detachWatcher(); } @OnUnmount static void onUnmount( ComponentContext c, EditTextTextTextChangedEventHandler editText) { editText.setEventHandler(null); } private static void initEditText( EditText editText, CharSequence text, CharSequence hint, TextUtils.TruncateAt ellipsize, int minLines, int maxLines, int maxLength, float shadowRadius, float shadowDx, float shadowDy, int shadowColor, boolean isSingleLine, int textColor, ColorStateList textColorStateList,
package org.fseek.thedeath.os.util; import java.util.Locale; /** * Util class to detect the running operating system * @author Simon */ @SuppressWarnings("unused") public class OSDetector { private static final int EMULATE_NONE = -1; private static final int EMULATE_LINUX = 1; private static final int EMULATE_WINDOWS = 2; private static final int EMULATE_MAC = 3; private static final int EMULATE = EMULATE_NONE; public static final byte OS_LINUX_OTHER = 6; public static final byte OS_MAC_OTHER = 5; public static final byte OS_WINDOWS_OTHER = 4; public static final byte OS_WINDOWS_NT = 3; public static final byte OS_WINDOWS_2000 = 2; public static final byte OS_WINDOWS_XP = 0; public static final byte OS_WINDOWS_2003 = 7; public static final byte OS_WINDOWS_VISTA = 1; public static final byte OS_WINDOWS_7 = 8; public static final byte OS_WINDOWS_8 = 9; private static final byte OS_ID; static { if (EMULATE > 0) { switch (EMULATE) { case EMULATE_WINDOWS: OS_ID = OS_WINDOWS_7; break; case EMULATE_MAC: OS_ID = OS_MAC_OTHER; break; default: OS_ID = OS_LINUX_OTHER; break; } } else { String OS = System.getProperty("os.name").toLowerCase(Locale.getDefault()); if (OS.indexOf("windows 8") > -1) { OS_ID = OS_WINDOWS_8; } else if (OS.indexOf("windows 7") > -1) { OS_ID = OS_WINDOWS_7; } else if (OS.indexOf("windows xp") > -1) { OS_ID = OS_WINDOWS_XP; } else if (OS.indexOf("windows vista") > -1) { OS_ID = OS_WINDOWS_VISTA; } else if (OS.indexOf("windows 2000") > -1) { OS_ID = OS_WINDOWS_2000; } else if (OS.indexOf("windows 2003") > -1) { OS_ID = OS_WINDOWS_2003; } else if (OS.indexOf("nt") > -1) { OS_ID = OS_WINDOWS_NT; } else if (OS.indexOf("windows") > -1) { OS_ID = OS_WINDOWS_OTHER; } else if (OS.indexOf("mac") > -1) { OS_ID = OS_MAC_OTHER; } else { OS_ID = OS_LINUX_OTHER; } } } public static boolean isLinux() { return OS_ID == OS_LINUX_OTHER; } public static boolean isMac() { return OS_ID == OS_MAC_OTHER; } public static boolean isUnix() { return isLinux() || isMac(); } public static boolean isWindows() { switch (OS_ID) { case OS_WINDOWS_XP: case OS_WINDOWS_VISTA: case OS_WINDOWS_2000: case OS_WINDOWS_2003: case OS_WINDOWS_NT: case OS_WINDOWS_8: case OS_WINDOWS_7: case OS_WINDOWS_OTHER: return true; } return false; } }
package org.bouncycastle.mail.smime.test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.KeyPair; import java.security.Security; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import junit.framework.TestCase; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute; import org.bouncycastle.asn1.smime.SMIMECapability; import org.bouncycastle.asn1.smime.SMIMECapabilityVector; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.RecipientInformation; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.SignerInformationStore; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; import org.bouncycastle.cms.jcajce.JcaX509CertSelectorConverter; import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; import org.bouncycastle.cms.jcajce.ZlibCompressor; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.mail.smime.SMIMECompressedGenerator; import org.bouncycastle.mail.smime.SMIMEEnveloped; import org.bouncycastle.mail.smime.SMIMEEnvelopedGenerator; import org.bouncycastle.mail.smime.SMIMESigned; import org.bouncycastle.mail.smime.SMIMESignedGenerator; import org.bouncycastle.mail.smime.SMIMESignedParser; import org.bouncycastle.mail.smime.SMIMEUtil; import org.bouncycastle.mail.smime.util.FileBackedMimeBodyPart; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.Store; public class SMIMEMiscTest extends TestCase { static MimeBodyPart msg; static String signDN; static KeyPair signKP; static X509Certificate signCert; static String origDN; static KeyPair origKP; static X509Certificate origCert; static String reciDN; static KeyPair reciKP; static X509Certificate reciCert; private static final JcaX509CertSelectorConverter selectorConverter = new JcaX509CertSelectorConverter(); KeyPair dsaSignKP; X509Certificate dsaSignCert; KeyPair dsaOrigKP; X509Certificate dsaOrigCert; static { try { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); } msg = SMIMETestUtil.makeMimeBodyPart("Hello world!\n"); signDN = "O=Bouncy Castle, C=AU"; signKP = CMSTestUtil.makeKeyPair(); signCert = CMSTestUtil.makeCertificate(signKP, signDN, signKP, signDN); origDN = "CN=Eric H. Echidna, E=eric@bouncycastle.org, O=Bouncy Castle, C=AU"; origKP = CMSTestUtil.makeKeyPair(); origCert = CMSTestUtil.makeCertificate(origKP, origDN, signKP, signDN); } catch (Exception e) { throw new RuntimeException("problem setting up signed test class: " + e); } } /* * * INFRASTRUCTURE * */ public SMIMEMiscTest(String name) { super(name); } public static void main(String args[]) { Security.addProvider(new BouncyCastleProvider()); junit.textui.TestRunner.run(SMIMEMiscTest.class); } public void testSHA256WithRSAParserEncryptedWithAES() throws Exception { List certList = new ArrayList(); certList.add(origCert); certList.add(signCert); Store certs = new JcaCertStore(certList); SMIMEEnvelopedGenerator encGen = new SMIMEEnvelopedGenerator(); encGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(origCert).setProvider("BC")); MimeBodyPart mp = encGen.generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build()); ASN1EncodableVector signedAttrs = generateSignedAttributes(); SMIMESignedGenerator gen = new SMIMESignedGenerator(); gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(signedAttrs)).build("SHA256withRSA", origKP.getPrivate(), origCert)); gen.addCertificates(certs); MimeMultipart smm = gen.generate(mp); File tmpFile = File.createTempFile("bcTest", ".mime"); MimeMessage msg = createMimeMessage(tmpFile, smm); SMIMESignedParser s = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), (MimeMultipart)msg.getContent()); certs = s.getCertificates(); verifyMessageBytes(mp, s.getContent()); verifySigners(certs, s.getSignerInfos()); tmpFile.delete(); } public void testSHA256WithRSACompressed() throws Exception { List certList = new ArrayList(); certList.add(origCert); certList.add(signCert); Store certs = new JcaCertStore(certList); SMIMECompressedGenerator cGen = new SMIMECompressedGenerator(); MimeBodyPart mp = cGen.generate(msg, new ZlibCompressor()); ASN1EncodableVector signedAttrs = generateSignedAttributes(); SMIMESignedGenerator gen = new SMIMESignedGenerator(); gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(signedAttrs)).build("SHA256withRSA", origKP.getPrivate(), origCert)); gen.addCertificates(certs); MimeMultipart smm = gen.generate(mp); File tmpFile = File.createTempFile("bcTest", ".mime"); MimeMessage msg = createMimeMessage(tmpFile, smm); SMIMESigned s = new SMIMESigned((MimeMultipart)msg.getContent()); certs = s.getCertificates(); verifyMessageBytes(mp, s.getContent()); verifySigners(certs, s.getSignerInfos()); tmpFile.delete(); } public void testQuotePrintableSigPreservation() throws Exception { MimeMessage msg = new MimeMessage((Session)null, getClass().getResourceAsStream("qp-soft-break.eml")); SMIMEEnvelopedGenerator encGen = new SMIMEEnvelopedGenerator(); encGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(origCert).setProvider("BC")); MimeBodyPart mp = encGen.generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build()); SMIMEEnveloped env = new SMIMEEnveloped(mp); RecipientInformation ri = (RecipientInformation)env.getRecipientInfos().getRecipients().iterator().next(); MimeBodyPart mm = SMIMEUtil.toMimeBodyPart(ri.getContentStream(new JceKeyTransEnvelopedRecipient(origKP.getPrivate()).setProvider("BC"))); SMIMESigned s = new SMIMESigned((MimeMultipart)mm.getContent()); Collection c = s.getSignerInfos().getSigners(); Iterator it = c.iterator(); Store certs = s.getCertificates(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))); } ((FileBackedMimeBodyPart)mm).dispose(); } public void testSHA256WithRSAParserCompressed() throws Exception { List certList = new ArrayList(); certList.add(origCert); certList.add(signCert); Store certs = new JcaCertStore(certList); SMIMECompressedGenerator cGen = new SMIMECompressedGenerator(); MimeBodyPart mp = cGen.generate(msg, new ZlibCompressor()); ASN1EncodableVector signedAttrs = generateSignedAttributes(); SMIMESignedGenerator gen = new SMIMESignedGenerator(); gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(signedAttrs)).build("SHA256withRSA", origKP.getPrivate(), origCert)); gen.addCertificates(certs); MimeMultipart smm = gen.generate(mp); File tmpFile = File.createTempFile("bcTest", ".mime"); MimeMessage msg = createMimeMessage(tmpFile, smm); SMIMESignedParser s = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), (MimeMultipart)msg.getContent()); certs = s.getCertificates(); verifyMessageBytes(mp, s.getContent()); verifySigners(certs, s.getSignerInfos()); tmpFile.delete(); } public void testBrokenEnvelope() throws Exception { Session session = Session.getDefaultInstance(System.getProperties(), null); MimeMessage msg = new MimeMessage(session, getClass().getResourceAsStream("brokenEnv.message")); try { new SMIMEEnveloped(msg); } catch (CMSException e) { if (!e.getMessage().equals("Malformed content.")) { fail("wrong exception on bogus envelope"); } } } private void verifySigners(Store certs, SignerInformationStore signers) throws Exception { Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation)it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))); } } private void verifyMessageBytes(MimeBodyPart a, MimeBodyPart b) throws Exception { ByteArrayOutputStream bOut1 = new ByteArrayOutputStream(); a.writeTo(bOut1); bOut1.close(); ByteArrayOutputStream bOut2 = new ByteArrayOutputStream(); b.writeTo(bOut2); bOut2.close(); assertEquals(true, Arrays.equals(bOut1.toByteArray(), bOut2.toByteArray())); } /** * Create a mime message representing the multipart. We need to do * this as otherwise no raw content stream for the message will exist. */ private MimeMessage createMimeMessage(File tmpFile, MimeMultipart smm) throws Exception { FileOutputStream fOut = new FileOutputStream(tmpFile); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); Address fromUser = new InternetAddress("\"Eric H. Echidna\"<eric@bouncycastle.org>"); Address toUser = new InternetAddress("example@bouncycastle.org"); MimeMessage body = new MimeMessage(session); body.setFrom(fromUser); body.setRecipient(Message.RecipientType.TO, toUser); body.setSubject("example signed message"); body.setContent(smm, smm.getContentType()); body.saveChanges(); body.writeTo(fOut); fOut.close(); return new MimeMessage(session, new FileInputStream(tmpFile)); } private ASN1EncodableVector generateSignedAttributes() { ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); caps.addCapability(SMIMECapability.dES_CBC); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); return signedAttrs; } }
// This file is part of Elveos.org. // Elveos.org is free software: you can redistribute it and/or modify it // option) any later version. // Elveos.org is distributed in the hope that it will be useful, but WITHOUT // more details. package com.bloatit.web.linkable.team; import com.bloatit.data.DaoTeam.Right; import com.bloatit.framework.webprocessor.annotations.MaxConstraint; import com.bloatit.framework.webprocessor.annotations.MinConstraint; import com.bloatit.framework.webprocessor.annotations.NonOptional; import com.bloatit.framework.webprocessor.annotations.Optional; import com.bloatit.framework.webprocessor.annotations.ParamContainer; import com.bloatit.framework.webprocessor.annotations.RequestParam; import com.bloatit.framework.webprocessor.annotations.RequestParam.Role; import com.bloatit.framework.webprocessor.annotations.tr; import com.bloatit.framework.webprocessor.context.Context; import com.bloatit.framework.webprocessor.url.Url; import com.bloatit.model.ElveosUserToken; import com.bloatit.model.Member; import com.bloatit.model.Team; import com.bloatit.model.managers.TeamManager; import com.bloatit.web.actions.LoggedAction; import com.bloatit.web.url.CreateTeamActionUrl; import com.bloatit.web.url.CreateTeamPageUrl; import com.bloatit.web.url.TeamPageUrl; /** * <p> * An action used to create a new team * </p> */ @ParamContainer("team/docreate") public final class CreateTeamAction extends LoggedAction { @RequestParam(role = Role.POST) @NonOptional(@tr("You forgot to write a team name")) @MinConstraint(min = 2, message = @tr("The team unique name size has to be superior to %constraint% but your text is %valueLength% characters long.")) @MaxConstraint(max = 50, message = @tr("The team unique name size has to be inferior to %constraint% your text is %valueLength% characters long.")) private final String login; @RequestParam(role = Role.POST) @MinConstraint(min = 4, message = @tr("The contact size has to be superior to %constraint% but your text is %valueLength% characters long.")) @MaxConstraint(max = 300, message = @tr("The contact size has to be inferior to %constraint%.")) @Optional private final String contact; @RequestParam(role = Role.POST) @NonOptional(@tr("You forgot to write a description")) @MinConstraint(min = 4, message = @tr("The description size has to be superior to %constraint% but your text is %valueLength% characters long.")) @MaxConstraint(max = 5000, message = @tr("The description size has to be inferior to %constraint% but your text is %valueLength% characters long.")) private final String description; @RequestParam(role = Role.POST) private final Right right; private final CreateTeamActionUrl url; public CreateTeamAction(final CreateTeamActionUrl url) { super(url); this.url = url; this.contact = url.getContact(); this.description = url.getDescription(); this.login = url.getLogin(); this.right = url.getRight(); } @Override protected Url checkRightsAndEverything(final Member me) { if (TeamManager.exist(login)) { session.notifyError(Context.tr("The team name ''{0}''already used. Find another name.", login)); url.getLoginParameter().addErrorMessage(Context.tr("Team name already used.")); return doProcessErrors(); } return NO_ERROR; } @Override public Url doProcessRestricted(final Member me) { final Team newTeam = new Team(login.trim(), contact, description, right, me); return new TeamPageUrl(newTeam); } @Override protected Url doProcessErrors(final ElveosUserToken userToken) { return new CreateTeamPageUrl(); } @Override protected String getRefusalReason() { return Context.tr("You must be logged to create a new team"); } @Override protected void transmitParameters() { session.addParameter(url.getContactParameter()); session.addParameter(url.getDescriptionParameter()); session.addParameter(url.getLoginParameter()); session.addParameter(url.getRightParameter()); } }
package mockit; import java.util.*; import org.junit.*; import static java.util.Arrays.*; import static org.junit.Assert.*; public final class ExpectationsWithSomeArgumentMatchersRecordedTest { @SuppressWarnings({"UnusedDeclaration"}) static class Collaborator { void setValue(int value) {} void setValue(double value) {} void setValue(float value) {} String setValue(String value) { return ""; } void setValues(long value1, byte value2, double value3, short value4) {} boolean booleanValues(long value1, byte value2, double value3, short value4) { return true; } static void staticSetValues(long value1, byte value2, double value3, short value4) {} static long staticLongValues(long value1, byte value2, double value3, short value4) { return -2; } List<?> complexOperation(Object input1, Object... otherInputs) { return input1 == null ? Collections.emptyList() : asList(otherInputs); } final void simpleOperation(int a, String b, Date c) {} long anotherOperation(byte b, long l) { return -1; } static void staticVoidMethod(long l, char c, double d) {} static boolean staticBooleanMethod(boolean b, String s, int[] array) { return false; } } @Mocked Collaborator mock; @Test public void useMatcherOnlyForOneArgument() { new Expectations() { { mock.simpleOperation(withEqual(1), "", null); mock.simpleOperation(withNotEqual(1), null, (Date) withNull()); mock.simpleOperation(1, withNotEqual("arg"), null); minTimes = 1; maxTimes = 2; mock.simpleOperation(12, "arg", (Date) withNotNull()); mock.anotherOperation((byte) 0, anyLong); result = 123L; mock.anotherOperation(anyByte, 5); result = -123L; Collaborator.staticVoidMethod(34L, anyChar, 5.0); Collaborator.staticBooleanMethod(true, withSuffix("end"), null); result = true; } }; mock.simpleOperation(1, "", null); mock.simpleOperation(2, "str", null); mock.simpleOperation(1, "", null); mock.simpleOperation(12, "arg", new Date()); assertEquals(123L, mock.anotherOperation((byte) 0, 5)); assertEquals(-123L, mock.anotherOperation((byte) 3, 5)); Collaborator.staticVoidMethod(34L, '8', 5.0); assertTrue(Collaborator.staticBooleanMethod(true, "start-end", null)); } @Test(expected = AssertionError.class) public void useMatcherOnlyForFirstArgumentWithUnexpectedReplayValue() { new Expectations() { { mock.simpleOperation(withEqual(1), "", null); } }; mock.simpleOperation(2, "", null); } @Test(expected = AssertionError.class) public void useMatcherOnlyForSecondArgumentWithUnexpectedReplayValue() { new Expectations() { { mock.simpleOperation(1, withPrefix("arg"), null); } }; mock.simpleOperation(1, "Xyz", null); } @Test(expected = AssertionError.class) public void useMatcherOnlyForLastArgumentWithUnexpectedReplayValue() { new Expectations() { { mock.simpleOperation(12, "arg", (Date) withNotNull()); } }; mock.simpleOperation(12, "arg", null); } @Test public void useMatchersForParametersOfAllSizes() { new NonStrictExpectations() { { mock.setValues(123L, withEqual((byte) 5), 6.4, withNotEqual((short) 14)); mock.booleanValues(12L, (byte) 4, withEqual(6.0, 0.1), withEqual((short) 14)); Collaborator.staticSetValues(withNotEqual(1L), (byte) 4, 6.1, withEqual((short) 3)); Collaborator.staticLongValues(12L, anyByte, withEqual(6.1), (short) 4); } }; mock.setValues(123L, (byte) 5, 6.4, (short) 41); assertFalse(mock.booleanValues(12L, (byte) 4, 6.1, (short) 14)); Collaborator.staticSetValues(2L, (byte) 4, 6.1, (short) 3); assertEquals(0L, Collaborator.staticLongValues(12L, (byte) -7, 6.1, (short) 4)); } @Test public void useAnyIntField() { new Expectations() { { mock.setValue(anyInt); } }; mock.setValue(1); } @Test public void useAnyStringField() { new NonStrictExpectations() { { mock.setValue(anyString); returns("one", "two"); } }; assertEquals("one", mock.setValue("test")); assertEquals("two", mock.setValue("")); } @Test public void useSeveralAnyFields() { final Date now = new Date(); new Expectations() { { mock.simpleOperation(anyInt, null, null); mock.simpleOperation(anyInt, "test", null); mock.simpleOperation(3, "test2", null); mock.simpleOperation(-1, null, (Date) any); mock.simpleOperation(1, anyString, now); Collaborator.staticSetValues(2L, anyByte, 0.0, anyShort); } }; mock.simpleOperation(2, "abc", now); mock.simpleOperation(5, "test", null); mock.simpleOperation(3, "test2", null); mock.simpleOperation(-1, "Xyz", now); mock.simpleOperation(1, "", now); Collaborator.staticSetValues(2, (byte) 1, 0, (short) 2); } @Test public void useWithMethodsMixedWithAnyFields() { new Expectations() { { mock.simpleOperation(anyInt, null, (Date) any); mock.simpleOperation(anyInt, withEqual("test"), null); mock.simpleOperation(3, withPrefix("test"), (Date) any); mock.simpleOperation(-1, anyString, (Date) any); mock.simpleOperation(1, anyString, (Date) withNotNull()); } }; mock.simpleOperation(2, "abc", new Date()); mock.simpleOperation(5, "test", null); mock.simpleOperation(3, "test2", null); mock.simpleOperation(-1, "Xyz", new Date()); mock.simpleOperation(1, "", new Date()); } interface Scheduler { List<String> getAlerts(Object o, int i, boolean b); } @Test public void useMatchersInInvocationsToInterfaceMethods(final Scheduler mock) { new NonStrictExpectations() { { mock.getAlerts(any, 1, anyBoolean); result = asList("A", "b"); } }; assertEquals(2, mock.getAlerts("123", 1, true).size()); } }
package manage.control; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import io.restassured.common.mapper.TypeRef; import io.restassured.http.ContentType; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; import manage.AbstractIntegrationTest; import manage.model.*; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.data.mongodb.core.query.Query; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.net.URLEncoder; import java.util.*; import java.util.regex.Pattern; import static io.restassured.RestAssured.given; import static io.restassured.config.RestAssuredConfig.newConfig; import static io.restassured.config.XmlConfig.xmlConfig; import static java.util.Collections.singletonMap; import static manage.mongo.MongoChangelog.CHANGE_REQUEST_POSTFIX; import static manage.service.MetaDataService.*; import static org.apache.http.HttpStatus.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @SuppressWarnings("unchecked") public class MetaDataControllerTest extends AbstractIntegrationTest { @Test public void get() { given() .when() .get("manage/api/client/metadata/saml20_sp/1") .then() .statusCode(SC_OK) .body("id", equalTo("1")) .body("revision.number", equalTo(0)) .body("data.metaDataFields.'name:pt'", equalTo("OpenConext PT")) .body("data.entityid", equalTo("Duis ad do")); } @Test public void getNotFound() { given() .when() .get("manage/api/client/metadata/saml20_sp/x") .then() .statusCode(SC_NOT_FOUND); } @Test public void templateSp() { given() .when() .get("manage/api/client/template/saml20_sp") .then() .statusCode(SC_OK) .body("type", equalTo("saml20_sp")) .body("data.arp.enabled", equalTo(false)) .body("data.arp.attributes", notNullValue()) .body("data.metaDataFields", notNullValue()) .body("data.entityid", emptyOrNullString()) .body("data.state", equalTo("testaccepted")) .body("data.allowedEntities.size()", is(0)) .body("data.disableConsent", emptyOrNullString()); } @Test public void templateIdp() { given() .when() .get("manage/api/client/template/saml20_idp") .then() .statusCode(SC_OK) .body("type", equalTo("saml20_idp")) .body("data.allowedall", equalTo(true)) .body("data.metaDataFields", notNullValue()) .body("data.entityid", emptyOrNullString()) .body("data.state", equalTo("testaccepted")) .body("data.allowedEntities.size()", is(0)) .body("data.disableConsent.size()", is(0)); } @Test public void remove() { MetaData metaData = metaDataRepository.findById("1", "saml20_sp"); assertNotNull(metaData); String reasonForDeletion = "Reason for deletion"; given() .when() .header("Content-type", "application/json") .body(Collections.singletonMap("revisionNote", reasonForDeletion)) .put("manage/api/client/metadata/saml20_sp/1") .then() .statusCode(SC_OK); metaData = metaDataRepository.findById("1", "saml20_sp"); assertNull(metaData); List<MetaData> revisions = metaDataRepository.findRaw("saml20_sp_revision", "{\"revision.parentId\": \"1\"}"); assertEquals(2, revisions.size()); MetaData revision = revisions.get(1); assertEquals(revision.getData().get("revisionnote"), reasonForDeletion); assertEquals("saml2_user.com", revision.getRevision().getUpdatedBy()); } @Test public void removeNonExistent() { given() .when() .header("Content-type", "application/json") .put("manage/api/client/metadata/saml20_sp/99999") .then() .statusCode(SC_NOT_FOUND); } @Test public void configuration() { given() .when() .get("manage/api/client/metadata/configuration") .then() .statusCode(SC_OK) .body("size()", is(5)) .body("title", hasItems("saml20_sp", "saml20_idp", "single_tenant_template", "oidc10_rp", "oauth20_rs")); } @Test public void post() throws IOException { doPost(true, "saml2_user.com"); } @Test public void postInternal() throws IOException { doPost(false, "sp-portal"); } private void doPost(boolean client, String expectedUpdatedBy) throws java.io.IOException { String id = createServiceProviderMetaData(client); MetaData savedMetaData = metaDataRepository.findById(id, EntityType.SP.getType()); Revision revision = savedMetaData.getRevision(); assertEquals(expectedUpdatedBy, revision.getUpdatedBy()); assertEquals(0, revision.getNumber()); assertNotNull(revision.getCreated()); } private String createServiceProviderMetaData(boolean client) throws java.io.IOException { Map<String, Object> data = readValueFromFile("/json/valid_service_provider.json"); MetaData metaData = new MetaData(EntityType.SP.getType(), data); RequestSpecification given = given(); if (!client) { given .auth() .preemptive() .basic("sp-portal", "secret"); } return given .when() .body(metaData) .header("Content-type", "application/json") .post("manage/api/" + (client ? "client" : "internal") + "/metadata") .then() .statusCode(SC_OK) .extract().path("id"); } @Test public void update() throws IOException { String id = createServiceProviderMetaData(true); Map<String, Object> pathUpdates = new HashMap<>(); pathUpdates.put("metaDataFields.description:en", "New description"); pathUpdates.put("allowedall", false); pathUpdates.put("allowedEntities", Arrays.asList(singletonMap("name", "https://allow-me"), singletonMap("name", "http://mock-idp"))); MetaDataUpdate metaDataUpdate = new MetaDataUpdate(id, EntityType.SP.getType(), pathUpdates, Collections.emptyMap()); given() .auth() .preemptive() .basic("sp-portal", "secret") .body(metaDataUpdate) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_OK) .body("id", equalTo(id)) .body("revision.number", equalTo(1)) .body("revision.updatedBy", equalTo("sp-portal")) .body("data.allowedall", equalTo(false)) .body("data.metaDataFields.'description:en'", equalTo("New description")) .body("data.allowedEntities[0].name", equalTo("http://mock-idp")) .body("data.allowedEntities", hasSize(1)); } @Test public void updateArp() throws IOException { Map<String, Object> pathUpdates = new HashMap<>(); pathUpdates.put("arp", Map.of("enabled", true, "attributes", singletonMap("urn:mace:dir:attribute-def:eduPersonAffiliation", Collections.singletonList(Map.of("value", "student", "source", "idp"))))); MetaDataUpdate metaDataUpdate = new MetaDataUpdate("1", EntityType.SP.getType(), pathUpdates, Collections.emptyMap()); given() .auth() .preemptive() .basic("sp-portal", "secret") .body(metaDataUpdate) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_OK); MetaData metaData = metaDataRepository.findById("1", EntityType.SP.getType()); Map<String, Object> arp = (Map<String, Object>) metaData.getData().get("arp"); Map<String, Object> attributes = (Map<String, Object>) arp.get("attributes"); assertEquals(1, attributes.size()); } @Test public void updateAllowedEntities() { Map<String, Object> pathUpdates = new HashMap<>(); pathUpdates.put("allowedEntities", List.of(Map.of("name", "http://mock-idp"))); MetaDataUpdate metaDataUpdate = new MetaDataUpdate("3", EntityType.SP.getType(), pathUpdates, Collections.emptyMap()); given() .auth() .preemptive() .basic("sp-portal", "secret") .body(metaDataUpdate) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_OK); MetaData metaData = metaDataRepository.findById("3", EntityType.SP.getType()); List<Map<String, String>> allowedEntities = (List<Map<String, String>>) metaData.getData().get("allowedEntities"); assertEquals(1, allowedEntities.size()); } @Test public void removeMetadataField() { Map<String, Object> pathUpdates = new HashMap<>(); pathUpdates.put("metaDataFields.description:en", null); MetaDataUpdate metaDataUpdate = new MetaDataUpdate("4", EntityType.SP.getType(), pathUpdates, Collections.emptyMap()); given() .auth() .preemptive() .basic("sp-portal", "secret") .body(metaDataUpdate) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_OK); MetaData metaData = metaDataRepository.findById("4", EntityType.SP.getType()); Map<String, Object> metaDataFields = metaData.metaDataFields(); assertFalse(metaDataFields.containsKey("description:en")); } @Test public void updateNonExistent() { MetaDataUpdate metaDataUpdate = new MetaDataUpdate("99999", EntityType.SP.getType(), Collections.emptyMap(), Collections.emptyMap()); given() .auth() .preemptive() .basic("sp-portal", "secret") .body(metaDataUpdate) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_NOT_FOUND); } @Test public void updateWithValidationErrors() throws IOException { String id = createServiceProviderMetaData(true); Map<String, Object> pathUpdates = new HashMap<>(); pathUpdates.put("metaDataFields.NameIDFormats:0", "bogus"); MetaDataUpdate metaDataUpdate = new MetaDataUpdate(id, EntityType.SP.getType(), pathUpdates, Collections.emptyMap()); given() .auth() .preemptive() .basic("sp-portal", "secret") .body(metaDataUpdate) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_BAD_REQUEST) .body("validations", notNullValue()); } @Test public void updateWithoutCorrectScope() { given() .auth() .preemptive() .basic("pdp", "secret") .body(new MetaDataUpdate("id", EntityType.SP.getType(), new HashMap<>(), Collections.emptyMap())) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_FORBIDDEN); } @Test public void updateWithoutCorrectUser() { given() .auth() .preemptive() .basic("bogus", "nope") .body(new HashMap<>()) .header("Content-type", "application/json") .when() .put("/manage/api/internal/merge") .then() .statusCode(SC_FORBIDDEN); } @Test public void putClient() { doPut(true, "saml2_user.com"); } @Test public void putInternal() { doPut(false, "sp-portal"); } @SuppressWarnings("unchecked") private void doPut(boolean client, String expectedUpdatedBy) { MetaData metaData = metaDataRepository.findById("1", EntityType.SP.getType()); Map.class.cast(metaData.getData()).put("entityid", "changed"); RequestSpecification given = given(); if (!client) { given .auth() .preemptive() .basic("sp-portal", "secret"); } given .when() .body(metaData) .header("Content-type", "application/json") .put("/manage/api/" + (client ? "client" : "internal") + "/metadata") .then() .statusCode(SC_OK) .body("revision.number", equalTo(1)) .body("revision.created", notNullValue()) .body("revision.updatedBy", equalTo(expectedUpdatedBy)) .body("data.entityid", equalTo("changed")); List<MetaData> revisions = metaDataRepository.getMongoTemplate().findAll(MetaData.class, "saml20_sp_revision"); assertEquals(1, revisions.size()); Revision revision = revisions.get(0).getRevision(); assertEquals("some.user", revision.getUpdatedBy()); assertEquals(0, revision.getNumber()); assertEquals("1", revision.getParentId()); given() .when() .get("manage/api/client/revisions/saml20_sp/1") .then() .statusCode(SC_OK) .body("size()", is(1)) .body("[0].id", notNullValue()) .body("[0].revision.number", equalTo(0)) .body("[0].data.entityid", equalTo("Duis ad do")); } @Test public void autoComplete() { given() .when() .queryParam("query", "mock") .get("manage/api/client/autocomplete/saml20_sp") .then() .statusCode(SC_OK) .body("suggestions.size()", is(2)) .body("suggestions.'_id'", hasItems("3", "5")) .body("suggestions.data.entityid", hasItems( "http://mock-sp", "https://serviceregistry.test2.surfconext.nl/simplesaml/module.php/saml/sp/metadata.php/default-sp-2")); } @Test public void autoCompleteEscaping() { given() .when() .queryParam("query", "(test)") .get("manage/api/client/autocomplete/saml20_idp") .then() .statusCode(SC_OK) .body("suggestions.size()", is(1)) .body("suggestions.data.entityid", hasItems( "https://idp.test2.surfconext.nl")); } @Test public void autoAlternativesWildcards() { given() .when() .queryParam("query", "Duis do") .get("manage/api/client/autocomplete/saml20_sp") .then() .statusCode(SC_OK) .body("suggestions.size()", is(1)); } @Test public void uniqueEntityId() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("entityid", "https@//oidc.rp"); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/uniqueEntityId/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(1)); } @Test public void uniqueEntityIdCaseInsensitive() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("entityid", "https@//OIDC.RP"); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/uniqueEntityId/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(1)); } @Test public void search() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("metaDataFields.coin:do_not_add_attribute_aliases", true); searchOptions.put("metaDataFields.contacts:3:contactType", "technical"); searchOptions.put("metaDataFields.NameIDFormat", "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"); searchOptions.put(REQUESTED_ATTRIBUTES, Arrays.asList( "allowedall", "metaDataFields.AssertionConsumerService:0:Location" )); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(2)) .body("'_id'", hasItems("2", "3")) .body("data.entityid", hasItems( "http://mock-sp", "https://profile.test2.surfconext.nl/authentication/metadata")) .body("data.metaDataFields.'name:en'", hasItems( "OpenConext Profile", "OpenConext Mujina SP")) .body("data.metaDataFields.'AssertionConsumerService:0:Location'", hasItems( "https://profile.test2.surfconext.nl/authentication/consume-assertion", "https://mujina-sp.test2.surfconext.nl/saml/SSO")); } /** * This is an outstanding bug where Manage cast numeric strings to int. Won't be fixed to * maintain backward compatibility for scrips that assume all metadata values are strings. */ @Test public void searchBug() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("metaDataFields.coin:institution_id", "123"); searchOptions.put(REQUESTED_ATTRIBUTES, Arrays.asList( "allowedall", "metaDataFields.AssertionConsumerService:0:Location" )); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_idp") .then() .statusCode(SC_OK) .body("size()", is(0)); } @Test public void searchWithLogicalAnd() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("entityid", "Duis ad do"); searchOptions.put("metaDataFields.AssertionConsumerService:0:Location", "https://profile.test2.surfconext.nl/authentication/consume-assertion"); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(0)); } @Test public void searchWithLogicalOr() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("entityid", "Duis ad do"); searchOptions.put("metaDataFields.AssertionConsumerService:0:Location", "https://profile.test2.surfconext.nl/authentication/consume-assertion"); searchOptions.put(LOGICAL_OPERATOR_IS_AND, false); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(2)) .body("data.entityid", hasItems( "Duis ad do", "https://profile.test2.surfconext.nl/authentication/metadata")); } @Test public void searchWithListIn() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("entityid", Arrays.asList( "Duis ad do", "https://profile.test2.surfconext.nl/authentication/metadata", "http://mock-sp")); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(3)); } @Test public void searchOidcRp() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put("entityid", "https@//oidc.rp"); searchOptions.put(ALL_ATTRIBUTES, true); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/oidc10_rp") .then() .statusCode(SC_OK) .body("size()", is(1)); } @Test public void rawSearch() { String query = "{$and: [{$or:[{\"data.allowedEntities.name\": {$in: [\"http://mock-idp\"]}}, {\"data" + ".allowedall\": true}]}, {\"data.state\":\"prodaccepted\"}]}"; given() .auth() .preemptive() .basic("sp-portal", "secret") .when() .header("Content-type", "application/json") .queryParam("query", query) .get("manage/api/internal/rawSearch/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(5)); } @Test public void rawSearchEncoded() throws UnsupportedEncodingException { String query = URLEncoder.encode("{$and: [{$or:[{\"data.allowedEntities.name\": {$in: " + "[\"http://mock-idp\"]}}, {\"data" + ".allowedall\": true}]}, {\"data.state\":\"prodaccepted\"}]}", "UTF-8"); given() .auth() .preemptive() .basic("sp-portal", "secret") .when() .header("Content-type", "application/json") .get("manage/api/internal/rawSearch/saml20_sp?query=" + query) .then() .statusCode(SC_OK) .body("size()", is(5)); } private void doUpdate(EntityType type, String id, String revisionNote) { MetaData metaData = given() .when() .get("manage/api/client/metadata/" + type.getType() + "/" + id) .as(MetaData.class); metaData.getData().put("revisionnote", revisionNote); metaData.getData().put("notes", UUID.randomUUID().toString()); given().when() .body(metaData) .header("Content-type", "application/json") .put("/manage/api/client/metadata") .then() .statusCode(SC_OK); } @Test public void recentActivity() { doDelete(EntityType.SP, "2", "Delete revision SP 2"); doDelete(EntityType.RS, "10", "Delete revision RS 10"); doUpdate(EntityType.SP, "1", "First revision SP"); doUpdate(EntityType.RP, "9", "First revision RP"); doUpdate(EntityType.IDP, "6", "First revision IDP"); doUpdate(EntityType.SP, "1", "Second revision SP"); doUpdate(EntityType.SP, "1", "Third revision SP"); Map<String, Object> body = new HashMap<>(); body.put("types", Arrays.asList(EntityType.RP.getType(), EntityType.IDP.getType(), EntityType.SP.getType(), EntityType.RS.getType())); body.put("limit", 6); List<Map<String, Object>> results = given() .when() .header("Content-type", "application/json") .body(body) .post("manage/api/client/recent-activity") .as(mapListTypeRef); assertEquals(6, results.size()); Map<String, Object> sp1 = results.get(0); assertEquals("1", sp1.get("id")); assertEquals("Third revision SP", ((Map) sp1.get("data")).get("revisionnote")); assertNull(((Map) sp1.get("revision")).get("terminated")); Map<String, Object> idp6 = results.get(1); assertEquals("6", idp6.get("id")); assertEquals("First revision IDP", ((Map) idp6.get("data")).get("revisionnote")); assertNull(((Map) idp6.get("revision")).get("terminated")); Map<String, Object> rp9 = results.get(2); assertEquals("9", rp9.get("id")); assertEquals("First revision RP", ((Map) rp9.get("data")).get("revisionnote")); assertNull(((Map) rp9.get("revision")).get("terminated")); Map<String, Object> rs10 = results.get(3); assertEquals("Delete revision RS 10", ((Map) rs10.get("data")).get("revisionnote")); assertNotNull(((Map) rs10.get("revision")).get("terminated")); Map<String, Object> sp2 = results.get(4); assertEquals("Delete revision SP 2", ((Map) sp2.get("data")).get("revisionnote")); assertNotNull(((Map) sp2.get("revision")).get("terminated")); } private void doDelete(EntityType entityType, String id, String revisionNote) { given().when() .header("Content-type", "application/json") .body(Collections.singletonMap("revisionNote", revisionNote)) .put("manage/api/client/metadata/" + entityType.getType() + "/" + id) .then() .statusCode(SC_OK); } @Test public void searchWithAllAttributes() { Map<String, Object> searchOptions = new HashMap<>(); searchOptions.put(ALL_ATTRIBUTES, true); given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(7)) .body("data.metaDataFields.'SingleLogoutService_Location'", hasItems( "https://sls", null, null, null, null, null)); } @Test public void whiteListingProdAccepted() { given() .when() .queryParam("state", "prodaccepted") .get("manage/api/client/whiteListing/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(6)) .body("data.allowedall", hasItems(true, false)); } @Test public void whiteListingTestAccepted() { given() .when() .queryParam("state", "testaccepted") .get("manage/api/client/whiteListing/saml20_sp") .then() .statusCode(SC_OK) .body("size()", is(2)) .body("data.allowedall", hasItems(true, false)); } @Test public void validate() throws java.io.IOException { Map<String, Object> data = readValueFromFile("/json/valid_service_provider.json"); MetaData metaData = new MetaData(EntityType.SP.getType(), data); given() .auth() .preemptive() .basic("sp-portal", "secret") .when() .body(metaData) .header("Content-type", "application/json") .post("manage/api/internal/validate/metadata") .then() .statusCode(SC_OK) .body(emptyOrNullString()); } @Test public void validateWithErrors() throws java.io.IOException { Map<String, Object> data = readValueFromFile("/json/valid_service_provider.json"); Map.class.cast(data.get("metaDataFields")).put("AssertionConsumerService:0:Binding", "bogus"); MetaData metaData = new MetaData(EntityType.SP.getType(), data); given() .auth() .preemptive() .basic("sp-portal", "secret") .when() .body(metaData) .header("Content-type", "application/json") .post("manage/api/internal/validate/metadata") .then() .statusCode(SC_BAD_REQUEST) .body("validations", equalTo("#/metaDataFields/AssertionConsumerService:0:Binding: bogus is not a valid " + "enum value")); } @Test public void newSp() { String xml = readFile("sp_portal/sp_xml.xml"); Map<String, String> body = singletonMap("xml", xml); doNewSp(body) .statusCode(SC_OK) .body("data.entityid", equalTo("https://engine.test2.surfconext.nl/authentication/sp/metadata")); } @Test public void newSpWithDuplicateEntityId() { String xml = readFile("sp_portal/sp_xml.xml"); String entityId = "https://profile.test2.surfconext.nl/authentication/metadata"; xml = xml.replaceAll(Pattern.quote("https://engine.test2.surfconext.nl/authentication/sp/metadata"), entityId); Map<String, String> body = new HashMap<>(); body.put("xml", xml); doNewSp(body) .statusCode(SC_BAD_REQUEST) .body("message", equalTo(String.format("There already exists a MetaData entry with entityId: %s", entityId))); } @Test public void newSpWithMissingRequiredFields() { String xml = readFile("sp_portal/sp_xml_missing_required_fields.xml"); Map<String, String> body = new HashMap<>(); body.put("xml", xml); doNewSp(body) .statusCode(SC_BAD_REQUEST) .body("validations", equalTo( "#/metaDataFields: required key [AssertionConsumerService:0:Binding] not found, " + "#/metaDataFields: required key [AssertionConsumerService:0:Location] not found")); } private ValidatableResponse doNewSp(Map<String, String> body) { return given() .auth() .preemptive() .basic("sp-portal", "secret") .body(body) .header("Content-type", "application/json") .when() .post("/manage/api/internal/new-sp") .then(); } @Test public void updateSp() { MetaData metaData = metaDataRepository.findById("1", EntityType.SP.getType()); String xml = readFile("sp_portal/sp_xml.xml"); Map<String, String> body = singletonMap("xml", xml); doUpdateSp(body, metaData) .statusCode(SC_OK); MetaData updated = metaDataRepository.findById("1", EntityType.SP.getType()); assertEquals(1L, updated.getVersion().longValue()); assertEquals(updated.getData().get("entityid"), "https://engine.test2.surfconext.nl/authentication/sp/metadata"); } @Test public void exportToXml() { String xml = given() .auth() .preemptive() .basic("sp-portal", "secret") .get("/manage/api/internal/sp-metadata/1") .asString(); assertTrue(xml.contains("entityID=\"Duis ad do\"")); } @Test public void putReconcileEntityIdIdP() { MetaData metaData = metaDataRepository.findById("7", EntityType.IDP.getType()); Map.class.cast(metaData.getData()).put("entityid", "new-entityid"); given() .when() .body(metaData) .header("Content-type", "application/json") .put("/manage/api/client/metadata") .then() .statusCode(SC_OK); List<MetaData> sps = metaDataRepository.findRaw("saml20_sp", "{\"data.allowedEntities.name\" : " + "\"new-entityid\"}"); assertEquals(2, sps.size()); } @Test public void deleteReconcileEntityIdSP() { MetaData idp = metaDataRepository.findById("6", "saml20_idp"); assertEquals(3, List.class.cast(idp.getData().get("allowedEntities")).size()); assertEquals(2, List.class.cast(idp.getData().get("disableConsent")).size()); given() .when() .header("Content-type", "application/json") .put("manage/api/client/metadata/saml20_sp/3") .then() .statusCode(SC_OK); idp = metaDataRepository.findById("6", "saml20_idp"); assertEquals(2, List.class.cast(idp.getData().get("allowedEntities")).size()); assertEquals(1, List.class.cast(idp.getData().get("disableConsent")).size()); } @Test public void restoreRevision() { String type = EntityType.SP.getType(); MetaData metaData = metaDataRepository.findById("1", type); Map.class.cast(metaData.getData()).put("entityid", "something changed"); given() .when() .body(metaData) .header("Content-type", "application/json") .put("/manage/api/client/metadata") .then() .statusCode(SC_OK); List<MetaData> revisions = metaDataRepository.getMongoTemplate().findAll(MetaData.class, "saml20_sp_revision"); assertEquals(1, revisions.size()); RevisionRestore revisionRestore = new RevisionRestore(revisions.get(0).getId(), type.concat("_revision"), type); given() .when() .body(revisionRestore) .header("Content-type", "application/json") .put("manage/api/client/restoreRevision") .then() .statusCode(SC_OK); revisions = metaDataRepository.getMongoTemplate().findAll(MetaData.class, "saml20_sp_revision"); assertEquals(2, revisions.size()); revisions.forEach(rev -> assertEquals(rev.getRevision().getParentId(), "1")); } @Test public void importFeed() throws IOException { String urlS = new ClassPathResource("xml/edugain_feed.xml").getURL().toString(); Import importRequest = new Import(urlS, null); Map result = given() .body(importRequest) .header("Content-type", "application/json") .post("manage/api/client/import/feed") .getBody() .as(Map.class); assertEquals(3, result.size()); assertEquals(2, List.class.cast(result.get("imported")).size()); result = given() .body(importRequest) .header("Content-type", "application/json") .post("manage/api/client/import/feed") .getBody() .as(Map.class); assertEquals(3, result.size()); assertEquals(2, List.class.cast(result.get("no_changes")).size()); urlS = new ClassPathResource("xml/edugain_feed_changed.xml").getURL().toString(); importRequest = new Import(urlS, null); result = given() .body(importRequest) .header("Content-type", "application/json") .post("manage/api/client/import/feed") .getBody() .as(Map.class); assertEquals(3, result.size()); assertEquals(2, List.class.cast(result.get("merged")).size()); } @Test public void importFeedIdemPotency() throws IOException { String urlS = new ClassPathResource("import_xml/edugain_sniplet.xml").getURL().toString(); Import importRequest = new Import(urlS, null); Map result = given() .body(importRequest) .header("Content-type", "application/json") .post("manage/api/client/import/feed") .getBody() .as(Map.class); assertEquals(1, ((List) result.get("total")).get(0)); Map imported = (Map) ((List) result.get("imported")).get(0); assertEquals("https://impacter.eu/sso/metadata", imported.get("entityId")); String id = (String) imported.get("id"); MetaData metaData = given() .body(importRequest) .header("Content-type", "application/json") .get("manage/api/client/metadata/saml20_sp/" + id) .getBody() .as(MetaData.class); importRequest = new Import(urlS, "https://impacter.eu/sso/metadata"); result = given() .body(importRequest) .header("Content-type", "application/json") .post("manage/api/client/import/endpoint/xml/saml20_sp") .getBody() .as(Map.class); Set<String> keysFromMetaData = metaData.metaDataFields().keySet(); Set<String> metaDataFields = ((Map) result.get("metaDataFields")).keySet(); keysFromMetaData.removeAll(metaDataFields); assertEquals(Arrays.asList("coin:imported_from_edugain", "coin:interfed_source"), new ArrayList(keysFromMetaData)); } @Test public void restoreDeletedRevision() { String type = EntityType.SP.getType(); given() .when() .header("Content-type", "application/json") .put("manage/api/client/metadata/saml20_sp/1") .then() .statusCode(SC_OK); MetaData metaData = metaDataRepository.findById("1", "saml20_sp"); assertNull(metaData); List<MetaData> revisions = metaDataRepository.getMongoTemplate().findAll(MetaData.class, "saml20_sp_revision"); assertEquals(2, revisions.size()); RevisionRestore revisionRestore = new RevisionRestore(revisions.get(0).getId(), type.concat("_revision"), type); given() .when() .body(revisionRestore) .header("Content-type", "application/json") .put("manage/api/client/restoreDeleted") .then() .statusCode(SC_OK); metaData = metaDataRepository.findById("1", "saml20_sp"); assertNotNull(metaData); revisions = metaDataRepository.getMongoTemplate().findAll(MetaData.class, "saml20_sp_revision"); assertEquals(2, revisions.size()); revisions.forEach(rev -> assertEquals(rev.getRevision().getParentId(), "1")); } private ValidatableResponse doUpdateSp(Map<String, String> body, MetaData metaData) { return given() .auth() .preemptive() .basic("sp-portal", "secret") .body(body) .header("Content-type", "application/json") .when() .post("/manage/api/internal/update-sp/" + metaData.getId() + "/" + metaData.getVersion()) .then(); } @Test public void updateWithValidationError() throws IOException { Map<String, Object> data = readValueFromFile("/metadata_templates/oidc10_rp.template.json"); data.put("entityid", "https://unique_entity_id"); List.class.cast(Map.class.cast(data.get("metaDataFields")).get("redirectUrls")).add("javascript:alert(document.domain)"); MetaData metaData = new MetaData(EntityType.RP.getType(), data); given() .auth() .preemptive() .basic("sp-portal", "secret") .when() .body(metaData) .header("Content-type", "application/json") .post("manage/api/client/metadata") .then() .statusCode(SC_BAD_REQUEST); } @Test public void deleteMetaDataKey() { String keyToDelete = "displayName:en"; List result = given() .auth() .preemptive() .basic("sp-portal", "secret") .when() .body(new MetaDataKeyDelete("saml20_sp", keyToDelete)) .header("Content-type", "application/json") .put("manage/api/internal/delete-metadata-key") .getBody() .as(List.class); assertEquals(5, result.size()); result.forEach(entityId -> { MetaData metaData = metaDataRepository.findRaw("saml20_sp", String.format("{\"data.entityid\":\"%s\"}", entityId)).get(0); assertEquals(false, metaData.metaDataFields().containsKey(keyToDelete)); }); } @Test public void connectValidSpWithoutInteraction() { String idpEntityId = "https://idp.test2.surfconext.nl"; String idUId = "6"; String spId = "Duis ad do"; String spType = "saml20_sp"; Map<String, String> connectionData = new HashMap<>(); connectionData.put("idpId", idpEntityId); connectionData.put("spId", spId); connectionData.put("spType", spType); connectionData.put("user", "John Doe"); connectionData.put("loaLevel", "http://test.surfconext.nl/assurance/loa2"); given() .auth() .preemptive() .basic("sp-portal", "secret") .header("Content-type", "application/json") .body(connectionData) .put("manage/api/internal/connectWithoutInteraction/") .then() .statusCode(SC_OK); MetaData idp = metaDataRepository.findById(idUId, EntityType.IDP.getType()); Map<String, Object> data = idp.getData(); List<Map> allowedEntities = (List<Map>) data.get("allowedEntities"); assertTrue(listOfMapsContainsValue(allowedEntities, spId)); List<Map<String, String>> stepUpEntities = (List<Map<String, String>>) data.get("stepupEntities"); String level = stepUpEntities.stream().filter(map -> map.get("name").equals(spId)).map(map -> map.get("level")).findFirst().get(); assertEquals("http://test.surfconext.nl/assurance/loa2", level); } @Test public void connectSpWithSameInstitutionIdAsIdp() { String idpEntityId = "https://idp.test2.surfconext.nl"; String idUId = "6"; String rpId = "https@//oidc.rp"; String rpType = "oidc10_rp"; Map<String, String> connectionData = new HashMap<>(); connectionData.put("idpId", idpEntityId); connectionData.put("spId", rpId); connectionData.put("spType", rpType); connectionData.put("user", "John Doe"); connectionData.put("userUrn", "urn:collab:person:example.com:jdoe"); given() .auth() .preemptive() .basic("sp-portal", "secret") .header("Content-type", "application/json") .body(connectionData) .put("manage/api/internal/connectWithoutInteraction/") .then() .statusCode(SC_OK); MetaData idp = metaDataRepository.findById(idUId, EntityType.IDP.getType()); Map<String, Object> data = idp.getData(); assertEquals(data.get("revisionnote"), "Connected https@//oidc.rp on request of John Doe - urn:collab:person:example.com:jdoe via Dashboard."); List<Map> allowedEntities = (List<Map>) data.get("allowedEntities"); assert listOfMapsContainsValue(allowedEntities, rpId); } @Test public void connectSpWithIdPNotAllowed() { String idpEntityId = "https://idp.test2.surfconext.nl"; String spId = "https://serviceregistry.test2.surfconext.nl/simplesaml/module.php/saml/sp/metadata.php/default-sp-2"; String spType = "saml20_sp"; Map<String, String> connectionData = new HashMap<>(); connectionData.put("idpId", idpEntityId); connectionData.put("spId", spId); connectionData.put("spType", spType); connectionData.put("user", "John Doe"); given() .auth() .preemptive() .basic("sp-portal", "secret") .header("Content-type", "application/json") .body(connectionData) .put("manage/api/internal/connectWithoutInteraction/") .then() .statusCode(SC_FORBIDDEN); } @Test public void connectSpAllowsNoneWithoutInteraction() { Map<String, String> connectionData = new HashMap<>(); String idpEntityId = "https://idp.test2.surfconext.nl"; connectionData.put("idpId", idpEntityId); connectionData.put("spId", "https://profile.test2.surfconext.nl/authentication/metadata"); connectionData.put("spType", "saml20_sp"); connectionData.put("user", "John Doe"); given() .auth() .preemptive() .basic("sp-portal", "secret") .header("Content-type", "application/json") .body(connectionData) .put("manage/api/internal/connectWithoutInteraction/") .then() .statusCode(SC_OK); MetaData sp = metaDataRepository.findById("2", EntityType.SP.getType()); Map<String, Object> data = sp.getData(); List<Map> allowedEntities = (List<Map>) data.get("allowedEntities"); assert listOfMapsContainsValue(allowedEntities, idpEntityId); } @Test public void connectInvalidSpWithoutInteraction() { Map<String, String> connectionData = new HashMap<>(); connectionData.put("idpId", "Duis ad do"); connectionData.put("spId", null); connectionData.put("spType", "saml20_sp"); connectionData.put("user", "John Doe"); given() .auth() .preemptive() .basic("sp-portal", "secret") .header("Content-type", "application/json") .body(connectionData) .put("manage/api/internal/connectWithoutInteraction/") .then() .statusCode(SC_NOT_FOUND); } @Test public void connectValidSpWithoutInteractionInvalidApiUser() { String idpEntityId = "https://idp.test2.surfconext.nl"; String spId = "Duis ad do"; String spType = "saml20_sp"; Map<String, String> connectionData = new HashMap<>(); connectionData.put("idpId", idpEntityId); connectionData.put("spId", spId); connectionData.put("spType", spType); connectionData.put("user", "John Doe"); connectionData.put("loaLevel", "http://test.surfconext.nl/assurance/loa2"); given() .auth() .preemptive() .basic("stats", "secret") .header("Content-type", "application/json") .body(connectionData) .put("manage/api/internal/connectWithoutInteraction/") .then() .statusCode(SC_FORBIDDEN); } @Test public void exportMetadataXml() throws IOException { given() .config(newConfig().xmlConfig(xmlConfig() .declareNamespace("md", "urn:oasis:names:tc:SAML:2.0:metadata"))) .auth() .preemptive() .basic("sp-portal", "secret") .contentType(ContentType.XML) .when() .get("/manage/api/internal/xml/metadata/saml20_sp/1") .then() .body("md:EntityDescriptor.@entityID", equalTo("Duis ad do")); } @Test public void emptyArpArray() throws java.io.IOException { Map<String, Object> data = readValueFromFile("/json/sp_dashboard_arp_array.json"); MetaData metaData = new MetaData(EntityType.SP.getType(), data); given().auth() .preemptive() .basic("sp-portal", "secret") .when() .body(metaData) .header("Content-type", "application/json") .post("manage/api/internal/metadata") .then() .statusCode(SC_BAD_REQUEST) .body("validations", equalTo("#/arp/attributes: expected type: JSONObject, found: JSONArray")); } @Test public void createChangeRequest() throws JsonProcessingException { doCreateChangeRequest(); List<MetaDataChangeRequest> requests = given() .when() .get("manage/api/client/change-requests/saml20_sp/1") .as(new TypeRef<>() { }); assertEquals(1, requests.size()); MetaDataChangeRequest request = requests.get(0); assertEquals(4, request.getMetaDataSummary().size()); assertEquals(3, request.getAuditData().size()); assertEquals(3, request.getPathUpdates().size()); } @Test public void arpAdditionChangeRequest() throws IOException { String changeRequestJson = readFile("json/incremental_arp_change_request.json"); given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequestJson) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .then() .statusCode(SC_OK); MetaDataChangeRequest metaDataChangeRequest = mongoTemplate() .find(new Query(), MetaDataChangeRequest.class, EntityType.SP.getType().concat(CHANGE_REQUEST_POSTFIX)).get(0); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest(metaDataChangeRequest.getId(), EntityType.SP.getType(), metaDataChangeRequest.getMetaDataId(), "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("1", EntityType.SP.getType()); Map attributes = (Map) ((Map) metaData.getData().get("arp")).get("attributes"); assertTrue(attributes.containsKey("urn:mace:dir:attribute-def:eduPersonOrcid")); assertEquals(6, attributes.size()); } @Test public void arpRemovalChangeRequest() throws IOException { String changeRequestJson = readFile("json/incremental_arp_removal_change_request.json"); given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequestJson) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .then() .statusCode(SC_OK); MetaDataChangeRequest metaDataChangeRequest = mongoTemplate() .find(new Query(), MetaDataChangeRequest.class, EntityType.SP.getType().concat(CHANGE_REQUEST_POSTFIX)).get(0); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest(metaDataChangeRequest.getId(), EntityType.SP.getType(), metaDataChangeRequest.getMetaDataId(), "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("1", EntityType.SP.getType()); Map attributes = (Map) ((Map) metaData.getData().get("arp")).get("attributes"); assertFalse(attributes.containsKey("urn:mace:dir:attribute-def:mail")); assertEquals(4, attributes.size()); } @Test public void acceptChangeRequest() { doCreateChangeRequest(); MetaDataChangeRequest metaDataChangeRequest = mongoTemplate() .find(new Query(), MetaDataChangeRequest.class, EntityType.SP.getType().concat(CHANGE_REQUEST_POSTFIX)).get(0); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest(metaDataChangeRequest.getId(), EntityType.SP.getType(), metaDataChangeRequest.getMetaDataId(), "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("1", EntityType.SP.getType()); assertEquals("New description", metaData.metaDataFields().get("description:en")); List<MetaDataChangeRequest> requests = given() .when() .get("manage/api/client/change-requests/saml20_sp/1") .as(new TypeRef<>() { }); assertEquals(0, requests.size()); } @Test public void changeRequestDisableConsent() { Map<String, Object> pathUpdates = new HashMap<>(); List<Map<String, String>> disableConsent = List.of( Map.of("name", "http://disableConsent1", "type", "default_consent", "explanation:nl", "NL", "explanation:en", "EN"), Map.of("name", "http://mock-sp", "type", "no_consent"), Map.of("name", "Duis ad do", "type", "minimal_consent", "explanation:nl", "NL", "explanation:en", "EN") ); pathUpdates.put("disableConsent", disableConsent); Map<String, Object> auditData = new HashMap<>(); auditData.put("user", "jdoe"); MetaDataChangeRequest changeRequest = new MetaDataChangeRequest( "6", EntityType.IDP.getType(), "Because....", pathUpdates, auditData ); Map results = given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequest) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .as(Map.class); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest((String) results.get("id"), EntityType.IDP.getType(), "6", "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("6", EntityType.IDP.getType()); List<Map<String, String>> newDisableConsent = (List<Map<String, String>>) metaData.getData().get("disableConsent"); Map<String, String> duisAdDo = newDisableConsent.stream().filter(map -> map.get("name").equals("Duis ad do")).findFirst().get(); assertEquals("minimal_consent", duisAdDo.get("type")); } @Test public void changeRequestRemoveMetadataField() { Map<String, Object> pathUpdates = new HashMap<>(); pathUpdates.put("metaDataFields.contacts:3:contactType", null); Map<String, Object> auditData = new HashMap<>(); auditData.put("user", "jdoe"); MetaDataChangeRequest changeRequest = new MetaDataChangeRequest( "6", EntityType.IDP.getType(), "Because....", pathUpdates, auditData ); Map results = given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequest) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .as(Map.class); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest((String) results.get("id"), EntityType.IDP.getType(), "6", "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("6", EntityType.IDP.getType()); assertFalse(metaData.metaDataFields().containsKey("contacts:3:contactType")); } @Test public void rejectChangeRequest() { doCreateChangeRequest(); MetaDataChangeRequest metaDataChangeRequest = mongoTemplate() .find(new Query(), MetaDataChangeRequest.class, EntityType.SP.getType().concat(CHANGE_REQUEST_POSTFIX)).get(0); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest(metaDataChangeRequest.getId(), EntityType.SP.getType(), metaDataChangeRequest.getMetaDataId(), "Rev notes")) .put("/manage/api/client/change-requests/reject") .then() .statusCode(200); List<MetaDataChangeRequest> requests = given() .when() .get("manage/api/client/change-requests/saml20_sp/1") .as(new TypeRef<>() { }); assertEquals(0, requests.size()); } @Test public void changeRequestAddition() { Map<String, Object> pathUpdates = Map.of("allowedEntities", Map.of("name", "https://idp.test2.surfconext.nl")); Map<String, Object> auditData = Map.of("user", "jdoe"); MetaDataChangeRequest changeRequest = new MetaDataChangeRequest( "2", EntityType.SP.getType(), "Because....", pathUpdates, auditData ); changeRequest.setIncrementalChange(true); changeRequest.setPathUpdateType(PathUpdateType.ADDITION); Map results = given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequest) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .as(Map.class); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest((String) results.get("id"), EntityType.SP.getType(), "2", "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("2", EntityType.SP.getType()); List<Map<String, String>> allowedEntities = (List<Map<String, String>>) metaData.getData().get("allowedEntities"); assertEquals(2, allowedEntities.size()); } @Test public void changeRequestRemoval() { Map<String, Object> pathUpdates = Map.of("allowedEntities", Map.of("name", "http://mock-idp")); Map<String, Object> auditData = Map.of("user", "jdoe"); MetaDataChangeRequest changeRequest = new MetaDataChangeRequest( "2", EntityType.SP.getType(), "Because....", pathUpdates, auditData ); changeRequest.setIncrementalChange(true); changeRequest.setPathUpdateType(PathUpdateType.REMOVAL); Map results = given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequest) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .as(Map.class); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest((String) results.get("id"), EntityType.SP.getType(), "2", "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("2", EntityType.SP.getType()); List<Map<String, String>> allowedEntities = (List<Map<String, String>>) metaData.getData().get("allowedEntities"); assertEquals(0, allowedEntities.size()); } @Test public void changeRequestRemovalMultiple() { MetaData currentMetaData = metaDataRepository.findById("6", EntityType.IDP.getType()); List<Map<String, String>> currentAllowedEntities = (List<Map<String, String>>) currentMetaData.getData().get("allowedEntities"); assertEquals(3, currentAllowedEntities.size()); Map<String, Object> pathUpdates = Map.of("allowedEntities", List.of(Map.of("name", "https: Map<String, Object> auditData = Map.of("user", "jdoe"); MetaDataChangeRequest changeRequest = new MetaDataChangeRequest( "6", EntityType.IDP.getType(), "Because....", pathUpdates, auditData ); changeRequest.setIncrementalChange(true); changeRequest.setPathUpdateType(PathUpdateType.REMOVAL); Map results = given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequest) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .as(Map.class); given() .when() .contentType(ContentType.JSON) .body(new ChangeRequest((String) results.get("id"), EntityType.IDP.getType(), "6", "Rev notes")) .put("/manage/api/client/change-requests/accept") .then() .statusCode(200); MetaData metaData = metaDataRepository.findById("6", EntityType.IDP.getType()); List<Map<String, String>> allowedEntities = (List<Map<String, String>>) metaData.getData().get("allowedEntities"); assertEquals(0, allowedEntities.size()); } @Test public void searchWithEntityCategoriesMultpleKeys() throws JsonProcessingException { Map<String, Object> searchOptions = readValueFromFile("/api/search_multiple_equal_keys.json"); List<Map<String, Object>> results = given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_sp") .as(new TypeRef<>() { }); assertEquals(1, results.size()); } @Test public void searchWithEntityCategoriesList() throws JsonProcessingException { Map<String, Object> searchOptions = readValueFromFile("/api/search_multiple_list_values.json"); List<Map<String, Object>> results = given() .when() .body(searchOptions) .header("Content-type", "application/json") .post("manage/api/client/search/saml20_sp") .as(new TypeRef<>() { }); assertEquals(3, results.size()); } private Map<String, Object> readValueFromFile(String path) throws JsonProcessingException { return objectMapper.readValue(readFile(path), new TypeReference<>() { }); } private void doCreateChangeRequest() { Map<String, Object> pathUpdates = new HashMap<>(); pathUpdates.put("metaDataFields.description:en", "New description"); pathUpdates.put("allowedall", false); pathUpdates.put("allowedEntities", Arrays.asList(singletonMap("name", "https://allow-me"), singletonMap("name", "http://mock-idp"))); Map<String, Object> auditData = new HashMap<>(); auditData.put("user", "jdoe"); MetaDataChangeRequest changeRequest = new MetaDataChangeRequest( "1", EntityType.SP.getType(), "Because....", pathUpdates, auditData ); given().auth().preemptive().basic("sp-portal", "secret") .when() .body(changeRequest) .header("Content-type", "application/json") .post("manage/api/internal/change-requests") .then() .statusCode(SC_OK); } }
package com.example.tetris; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; import com.example.ccweibo.R; /** * Tetris will be represented by a 18 * 10 color * * @author flamearrow * */ public class TetrisView extends SurfaceView implements Callback { private Random rand = new Random(); private static final int MATRIX_HEIGHT = 24; private static final int MATRIX_WIDTH = 12; private static final int PREVIEW_EDGE = 4; private static final int SQUARE_EDGE_WIDTH = 2; private static final int SQUARE_EDGE_COLOR = Color.YELLOW; private static final int SEPARATOR_COLOR = Color.DKGRAY; private static final double GOLDEN_RATIO = 0.618; private static final int INITIAL_BLOCK_COLOR = Color.GRAY; private TetrisThread _thread; // Android Color are all int! private int[][] _gameMatrix; private int[][] _previewMatrix; private int _screenWidth; private int _screenHeight; // Paint object si used to draw stuff private Paint _backgroundPaint; private Paint _gameMatrixPaint; private Paint _previewMatrixPaint; private Paint _separatorPaint; private Paint _staticPaint; private int _level; private int _score; private int _currentHeight; private boolean _justStart; private Block _currentBlock; private Block _nextBlock; private Set<Point> _currentBlockPoints; private List<Point> _backList; private int getRandomColor() { switch (rand.nextInt(7)) { case 0: return Color.BLACK; case 1: return Color.RED; case 2: return Color.GREEN; case 3: return Color.BLUE; case 4: return Color.YELLOW; case 5: return Color.CYAN; case 6: return Color.MAGENTA; default: return Color.WHITE; } } public Block.Direction getRandomDirection() { switch (rand.nextInt(4)) { case 0: return Block.Direction.Down; case 1: return Block.Direction.Up; case 2: return Block.Direction.Left; case 3: return Block.Direction.Right; default: return null; } } /** * @return a block with random value and color */ private Block getRandomBlock() { switch (rand.nextInt(7)) { case 0: return new Block(Block.Value.I, getRandomColor(), getRandomDirection()); case 1: return new Block(Block.Value.L, getRandomColor(), getRandomDirection()); case 2: return new Block(Block.Value.O, getRandomColor(), getRandomDirection()); case 3: return new Block(Block.Value.rL, getRandomColor(), getRandomDirection()); case 4: return new Block(Block.Value.rS, getRandomColor(), getRandomDirection()); case 5: return new Block(Block.Value.S, getRandomColor(), getRandomDirection()); case 6: return new Block(Block.Value.T, getRandomColor(), getRandomDirection()); default: return null; } } // Note: customized View needs to implement this two param constructor public TetrisView(Context context, AttributeSet attrs) { super(context, attrs); // this call is ensuring surfaceCreated() method will be called getHolder().addCallback(this); _gameMatrix = new int[MATRIX_HEIGHT][MATRIX_WIDTH]; _previewMatrix = new int[PREVIEW_EDGE][PREVIEW_EDGE]; _backgroundPaint = new Paint(); _gameMatrixPaint = new Paint(); _previewMatrixPaint = new Paint(); _separatorPaint = new Paint(); _staticPaint = new Paint(); _currentBlockPoints = new HashSet<Point>(); _backList = new LinkedList<Point>(); } // pause the game, we want to save game state after returning to game public void pause() { surfaceDestroyed(null); } public void releaseResources() { } // rotate the current active block public void rotate() { } private void updateComponents() { // if it's just started, we don't want to update matrixs as they are // already updated if (_justStart) { _justStart = false; return; } boolean addAnotherBlock = updateGameMatrix(); if (addAnotherBlock) { boolean gameOver = addBlockToMatrix(_gameMatrix, MATRIX_HEIGHT - 1, 4, _nextBlock); if (gameOver) { stopGame(); } _currentBlock = _nextBlock; updatePreviewMatrix(); } updateTimer(); updateScoreBoard(); } /** * stop game, prompt for new game or not */ private void stopGame() { // TODO implement this } /** * First dropping the floating block one line if applicable * * then remove all full lines * * @return whether we need to add another block to the game */ private boolean updateGameMatrix() { // first move the floating block one line down boolean canDropOneLine = true; Point tmpPoint = new Point(); for (Point p : _currentBlockPoints) { tmpPoint.set(p.x - 1, p.y); if (_currentBlockPoints.contains(tmpPoint)) { continue; } // if we hit bottom or the lower block is already set then we can't // continue dropping if ((tmpPoint.x < 0) || (_gameMatrix[tmpPoint.x][tmpPoint.y] != INITIAL_BLOCK_COLOR)) { canDropOneLine = false; break; } } if (canDropOneLine) { _backList.clear(); for (Point p : _currentBlockPoints) { _gameMatrix[p.x][p.y] = INITIAL_BLOCK_COLOR; p.offset(-1, 0); } for (Point p : _currentBlockPoints) { _gameMatrix[p.x][p.y] = _currentBlock.color; _backList.add(p); } // important: we need to update Points index in the hashset _currentBlockPoints.clear(); _currentBlockPoints.addAll(_backList); // TODO: update _currentHeight } // then check if we need to remove lines from bottom to _currentHeight int currentRow = 0; int currentBottom = Integer.MAX_VALUE; while (currentRow < _currentHeight) { for (int i = 0; i < MATRIX_WIDTH; i++) { if (_gameMatrix[currentRow][i] == INITIAL_BLOCK_COLOR) { // if this line can't be removed, we either skip it or drop // it to currentBottom // currentBottom is not empty, need to drop if (currentBottom != Integer.MAX_VALUE) { moveRow(_gameMatrix, currentRow, currentBottom); currentBottom = currentRow; } currentRow++; break; } } // if we can reach here then currentRow needs to be removed if (currentBottom > currentRow) currentBottom = currentRow; // clear the row clearRow(_gameMatrix, currentRow); currentRow++; } return !canDropOneLine; } // move the currentRow to the currentBottom row of the matrix, clear // currentRow private void moveRow(int[][] matrix, int currentRow, int currentBottom) { for (int i = 0; i < MATRIX_WIDTH; i++) { matrix[currentBottom][i] = matrix[currentRow][i]; matrix[currentRow][i] = INITIAL_BLOCK_COLOR; } } private void clearRow(int[][] matrix, int rowToClear) { for (int i = 0; i < MATRIX_WIDTH; i++) { matrix[rowToClear][i] = INITIAL_BLOCK_COLOR; } } private void updatePreviewMatrix() { for (int i = 0; i < PREVIEW_EDGE; i++) for (int j = 0; j < PREVIEW_EDGE; j++) _previewMatrix[i][j] = INITIAL_BLOCK_COLOR; _nextBlock = getRandomBlock(); addBlockToMatrix(_previewMatrix, PREVIEW_EDGE - 1, 0, _nextBlock); } /** * add a new block to specified color matrix, if there's no space for the * given block, return false * * @param colorMatrix * @param x * @param y * @param newBlock * @return whether game is over */ private boolean addBlockToMatrix(int[][] colorMatrix, int x, int y, Block newBlock) { // with hex value defined, just apply it to a 4*4 matrix int count = 0; int value = newBlock.value.gethexV(); int color = newBlock.color; int[][] tmpMatrix = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (((value >> (count++)) & 1) > 0) { tmpMatrix[i][j] = color; } } } // rotate to the correct direction switch (newBlock.direction) { case Right: rotateMatrix(tmpMatrix, 1); break; case Down: rotateMatrix(tmpMatrix, 2); break; case Left: rotateMatrix(tmpMatrix, 3); break; case Up: default: break; } // apply the tmp matrix to colorMatrix for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { // we find a collision, game over if (colorMatrix[x - i][y + j] != INITIAL_BLOCK_COLOR) { return true; } else if (tmpMatrix[i][j] != 0) { colorMatrix[x - i][y + j] = tmpMatrix[i][j]; } } } updateCurrentBlockPoints(); return false; } /** * Rotate a 4x4 matrix Rotate sequence clockwisely for n times * * @param matrix * @param times */ private void rotateMatrix(int[][] matrix, int times) { for (int loop = 0; loop <= times; loop++) { int tmp = -1; for (int i = 0; i < 4; i++) { for (int j = i; j < 4; j++) { tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } for (int i = 0; i < 2; i++) { for (int j = 0; j < 4; j++) { tmp = matrix[i][j]; matrix[i][j] = matrix[3 - i][j]; matrix[3 - i][j] = tmp; } } } } private void updateTimer() { } private void updateScoreBoard() { } private void drawComponents(Canvas canvas) { _backgroundPaint.setColor(Color.WHITE); canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), _backgroundPaint); // a squre's edge length, should accommodate with width // the total width is shared by gameSection width, previewSection with // and a separator int blockEdge = _screenWidth / (MATRIX_WIDTH + PREVIEW_EDGE + 1); // first draw the game secion // starting from bottom left, draw a MATRIX_HEIGHT x MATRIX_WIDTH matrix // each block has a black frame and filled with color at // _colorMatrix[i][j] Point currentPoint = new Point(0, _screenHeight); // for (int i = MATRIX_HEIGHT - 1; i >= 0; i--) { for (int i = 0; i < MATRIX_HEIGHT - 1; i++) { for (int j = 0; j < MATRIX_WIDTH; j++) { // draw edge _gameMatrixPaint.setColor(SQUARE_EDGE_COLOR); canvas.drawRect(currentPoint.x, currentPoint.y - blockEdge, currentPoint.x + blockEdge, currentPoint.y, _gameMatrixPaint); // draw squre _gameMatrixPaint.setColor(_gameMatrix[i][j]); canvas.drawRect(currentPoint.x + SQUARE_EDGE_WIDTH, currentPoint.y - blockEdge + SQUARE_EDGE_WIDTH, currentPoint.x + blockEdge - SQUARE_EDGE_WIDTH, currentPoint.y - SQUARE_EDGE_WIDTH, _gameMatrixPaint); currentPoint.offset(blockEdge, 0); } // move to the start of next line currentPoint.offset(-MATRIX_WIDTH * blockEdge, -blockEdge); } // then draw the left-right separator currentPoint.set(MATRIX_WIDTH * blockEdge + blockEdge / 2, 0); _separatorPaint.setColor(SEPARATOR_COLOR); _separatorPaint.setStrokeWidth(blockEdge / 2); canvas.drawLine(currentPoint.x, 0, currentPoint.x, _screenHeight, _separatorPaint); // then draw the top-bottom separator, should separate it in golden // ratio currentPoint.offset(0, (int) (_screenHeight * (1 - GOLDEN_RATIO))); canvas.drawLine(currentPoint.x, currentPoint.y, _screenWidth, currentPoint.y, _separatorPaint); // then draw the preview section, should be in center of top part currentPoint.set(currentPoint.x + blockEdge / 2, currentPoint.y / 2); currentPoint.offset(0, -PREVIEW_EDGE / 2 * blockEdge); for (int i = 0; i < PREVIEW_EDGE; i++) { for (int j = 0; j < PREVIEW_EDGE; j++) { // draw edge _previewMatrixPaint.setColor(SQUARE_EDGE_COLOR); canvas.drawRect(currentPoint.x, currentPoint.y - blockEdge, currentPoint.x + blockEdge, currentPoint.y, _previewMatrixPaint); // draw squre _previewMatrixPaint.setColor(_previewMatrix[i][j]); canvas.drawRect(currentPoint.x + SQUARE_EDGE_WIDTH, currentPoint.y - blockEdge + SQUARE_EDGE_WIDTH, currentPoint.x + blockEdge - SQUARE_EDGE_WIDTH, currentPoint.y - SQUARE_EDGE_WIDTH, _previewMatrixPaint); currentPoint.offset(blockEdge, 0); } // move to the start of next line currentPoint.offset(-PREVIEW_EDGE * blockEdge, blockEdge); } // then draw Level and score // this needs to be exposed to update separately currentPoint.set(currentPoint.x, (int) (_screenHeight * (1 - GOLDEN_RATIO / 2))); currentPoint.offset(blockEdge, -2 * blockEdge); canvas.drawText(getResources().getString(R.string.level) + _level, currentPoint.x, currentPoint.y, _staticPaint); currentPoint.offset(0, 4 * blockEdge); canvas.drawText(getResources().getString(R.string.score) + _score, currentPoint.x, currentPoint.y, _staticPaint); } // called when first added to the View, used to record screen width and // height @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); _screenHeight = h; _screenWidth = w; } // move the current active block to left/right if according whether this tap // happens at left/right half of the screen public void moveLR(MotionEvent e) { } @Override public void surfaceCreated(SurfaceHolder holder) { newGame(holder); } private void newGame(SurfaceHolder holder) { initializeParams(); initializeMatrix(); _thread = new TetrisThread(holder); _thread.setRunning(true); _thread.start(); } private void initializeParams() { _level = 10; _score = 0; _currentHeight = 0; _justStart = true; } // this is called when a new game is started, add a random block in // _gameMatrix and a random block in _previewMatrix private void initializeMatrix() { for (int i = 0; i < MATRIX_HEIGHT; i++) for (int j = 0; j < MATRIX_WIDTH; j++) _gameMatrix[i][j] = INITIAL_BLOCK_COLOR; for (int i = 0; i < PREVIEW_EDGE; i++) for (int j = 0; j < PREVIEW_EDGE; j++) _previewMatrix[i][j] = INITIAL_BLOCK_COLOR; _currentBlock = getRandomBlock(); addBlockToMatrix(_gameMatrix, MATRIX_HEIGHT - 1, 4, _currentBlock); updateCurrentBlockPoints(); _nextBlock = getRandomBlock(); addBlockToMatrix(_previewMatrix, PREVIEW_EDGE - 1, 0, _nextBlock); } /** * add four points to the current Blocks */ private void updateCurrentBlockPoints() { _currentBlockPoints.clear(); for (int i = MATRIX_HEIGHT - 1; i > MATRIX_HEIGHT - 5; i for (int j = 0; j < MATRIX_WIDTH; j++) { if (_gameMatrix[i][j] != INITIAL_BLOCK_COLOR) { _currentBlockPoints.add(new Point(i, j)); } } } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } // This is called when you exit the game, should stop the thread. Otherwise // it will continue trying to draw on a Null canvas and cause NPE @Override public void surfaceDestroyed(SurfaceHolder holder) { _thread.setRunning(false); boolean retry = true; while (retry) { try { _thread.join(); retry = false; } catch (InterruptedException e) { e.printStackTrace(); } } } private class TetrisThread extends Thread { // _holder is used to retrieve Canvas object of the current SurfaceView private SurfaceHolder _holder; private boolean _running; public TetrisThread(SurfaceHolder holder) { _holder = holder; } public void setRunning(boolean running) { _running = running; } @Override public void run() { Canvas canvas = null; long previousFrameTime = System.currentTimeMillis(); while (_running) { long currentFrameTime = System.currentTimeMillis(); long elapsed = currentFrameTime - previousFrameTime; // we want to update the canvas every 100 milis // just a simple speed controller // to implement 'falling immediately' we need a fancier one if (elapsed < 1000 - _level * 50) { continue; } try { canvas = _holder.lockCanvas(null); synchronized (_holder) { previousFrameTime = currentFrameTime; updateComponents(); drawComponents(canvas); } } finally { if (canvas != null) { _holder.unlockCanvasAndPost(canvas); } } } } } }
package com.cs1635.classme; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.shared.Event; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class tab_events extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tab_events, container, false); Button createEvent = (Button) rootView.findViewById(R.id.cal_view_submit); createEvent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getActivity(),CreateEventActivity.class)); } }); populateListView(rootView); ListView lv = (ListView) rootView.findViewById(R.id.cal_view_existing); lv.setAdapter(new ExistingEventsAdapter(getActivity(), 42, new ArrayList<Event>() ) ); return rootView; } private void populateListView(View rootView){ final ListView listView = (ListView) rootView.findViewById(R.id.cal_view_existing); new AsyncTask<Void,Void,ArrayList<Event>>() { @Override protected ArrayList<Event> doInBackground(Void... voidsss) { List<NameValuePair> params = new ArrayList<NameValuePair>(1); params.add(new BasicNameValuePair("classID", BuckCourse.classId)); HttpResponse response; try { response = AppEngineClient.makeRequest("/listEvents", params); //parse Gson gson = new Gson(); Type listOfEvents = new TypeToken<ArrayList<Event>>(){}.getType(); String entityString = EntityUtils.toString(response.getEntity()); return gson.fromJson(entityString, listOfEvents); //Return listy! :) "Youre doing great, buck. keep it up" --Robert //"You forgot an apostrophe" --Robert } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<Event> listy) { if (listy != null) { ExistingEventsAdapter adapt = (ExistingEventsAdapter) listView.getAdapter(); adapt.addAll(listy); adapt.notifyDataSetChanged(); } } }.execute(); } }
package org.ovirt.mobile.movirt.model; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.text.format.DateUtils; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import org.ovirt.mobile.movirt.provider.OVirtContract; import org.ovirt.mobile.movirt.util.CursorHelper; @DatabaseTable(tableName = ConnectionInfo.TABLE) public class ConnectionInfo extends BaseEntity<Integer> implements OVirtContract.ConnectionInfo { private static final String STRING_UNKNOWN_TIME = "unknown"; private static final long LONG_UNKNOWN_TIME = -1; private static final int FORMAT_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_YEAR; @DatabaseField(columnName = ID, id = true) private int id; @DatabaseField(columnName = ConnectionInfo.STATE) private State state; @DatabaseField(columnName = ConnectionInfo.ATTEMPT) private long lastAttempt; @DatabaseField(columnName = ConnectionInfo.SUCCESSFUL) private long lastSuccessful; public ConnectionInfo() { this.id = 1; this.state = State.UNKNOWN; this.lastAttempt = LONG_UNKNOWN_TIME; this.lastSuccessful = LONG_UNKNOWN_TIME; } public void updateWithCurrentTime(State state) { this.state = state; long time = System.currentTimeMillis(); this.lastAttempt = time; if (state == State.OK) { this.lastSuccessful = time; } } @Override public Uri getBaseUri() { return CONTENT_URI; } @Override public ContentValues toValues() { ContentValues values = new ContentValues(); values.put(ID, id); values.put(STATE, state.toString()); values.put(ATTEMPT, lastAttempt); values.put(SUCCESSFUL, lastSuccessful); return values; } @Override protected void initFromCursorHelper(CursorHelper cursorHelper) { setId(cursorHelper.getInt(ID)); try { setState(State.valueOf(cursorHelper.getString(STATE))); } catch (Exception e) { setState(State.UNKNOWN); } try { setLastAttempt(cursorHelper.getLong(ATTEMPT)); } catch (Exception e) { setLastAttempt(LONG_UNKNOWN_TIME); } try { setLastSuccessful(cursorHelper.getLong(SUCCESSFUL)); } catch (Exception e) { setLastSuccessful(LONG_UNKNOWN_TIME); } } public State getState() { return state; } public void setState(State state) { this.state = state; } public long getLastAttempt() { return lastAttempt; } public void setLastAttempt(long lastAttempt) { this.lastAttempt = lastAttempt; } public long getLastSuccessful() { return lastSuccessful; } public void setLastSuccessful(long lastSuccessful) { this.lastSuccessful = lastSuccessful; } @Override public Integer getId() { return id; } @Override public void setId(Integer id) { this.id = id; } public String getMessage(Context context) { return "Connection: " + state + ".\nLast Attempt: " + getLastAttemptWithTimeZone(context) + ".\nLast Successful: " + getLastSuccessfulWithTimeZone(context) + '.'; } public String getLastAttemptWithTimeZone(Context context) { return convertDateToString(context, lastAttempt); } public String getLastSuccessfulWithTimeZone(Context context) { return convertDateToString(context, lastSuccessful); } private String convertDateToString(Context context, long date) { if (date == LONG_UNKNOWN_TIME) { return STRING_UNKNOWN_TIME; } return DateUtils.formatDateTime(context, date, FORMAT_FLAGS); } public enum State { OK, FAILED, UNKNOWN } }
package com.theisleoffavalon.mcmanager.chatterbox; import java.util.ArrayList; import java.util.List; import net.minecraft.network.packet.NetHandler; import net.minecraft.network.packet.Packet3Chat; import cpw.mods.fml.common.network.*; /** * This class grabs all the chat code from Minecraft and hands it off to who * ever wants it. * * @author SgtHotshot09 * */ public class ChatInterceptor implements IChatListener { /** * Holds a List of ChatRelays */ private List<IChatRelay> chatRelays = new ArrayList<IChatRelay>(); /** * Constructs a ChatInterceptor which is an IChatListener. It then registers * the ChatInterceptor with the NetworkRegistry */ public ChatInterceptor() { NetworkRegistry.instance().registerChatListener(this); } @Override public Packet3Chat serverChat(NetHandler handler, Packet3Chat message) { // TODO: use the chat message chatHasArrived("<" + handler.getPlayer().username + ">" + message.message); return message; } @Override public Packet3Chat clientChat(NetHandler handler, Packet3Chat message) { // TODO: use the chat message chatHasArrived("<" + handler.getPlayer().username + ">" + message.message); return message; } /** * Register a ChatRelay with the system * * @param cr ChatRelay * */ public void registerChatRelay(IChatRelay cr) { chatRelays.add(cr); } /** * UnRegisters a ChatRelay with the system * @param cr ChatRelay */ public void unregisterChatRelay(IChatRelay cr) { chatRelays.remove(cr); } /** * Is called when a chat Has arrived to be distributed * * @param message A message to send * */ public void chatHasArrived(String message) { for(IChatRelay cr : chatRelays) { cr.chatHasArrived(message); } } }
package com.haulmont.cuba.report.formatters; import com.haulmont.cuba.core.app.ServerConfig; import com.haulmont.cuba.core.entity.FileDescriptor; import com.haulmont.cuba.core.global.ConfigProvider; import com.haulmont.cuba.report.Band; import com.haulmont.cuba.report.ReportOutputType; import com.haulmont.cuba.report.exception.ReportFormatterException; import com.haulmont.cuba.report.formatters.tools.*; import static com.haulmont.cuba.report.formatters.tools.ODTHelper.*; import static com.haulmont.cuba.report.formatters.tools.ODTTableHelper.*; import static com.haulmont.cuba.report.formatters.tools.ODTUnoConverter.*; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XEnumeration; import com.sun.star.container.XIndexAccess; import com.sun.star.frame.XDispatchHelper; import com.sun.star.io.IOException; import com.sun.star.io.XInputStream; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XComponent; import com.sun.star.table.XCell; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextTable; import com.sun.star.uno.UnoRuntime; import com.sun.star.util.XReplaceable; import com.sun.star.util.XSearchDescriptor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.ArrayList; public class DocFormatter extends AbstractFormatter { private OOOConnection connection; private Band rootBand; private FileDescriptor templateFileDescriptor; private ReportOutputType reportOutputType; private XComponent xComponent; private Log log = LogFactory.getLog(DocFormatter.class); public DocFormatter(FileDescriptor templateFileDescriptor, ReportOutputType reportOutputType) { String openOfficePath = ConfigProvider.getConfig(ServerConfig.class).getOpenOfficePath(); try { connection = OOOConnector.createConnection(openOfficePath); } catch (Exception ex) { throw new RuntimeException("Please check OpenOffice path: " + openOfficePath); } this.templateFileDescriptor = templateFileDescriptor; this.reportOutputType = reportOutputType; } public byte[] createDocument(Band rootBand) { this.rootBand = rootBand; try { XInputStream xis = getXInputStream(templateFileDescriptor); xComponent = loadXComponent(connection.createXComponentLoader(), xis); // Handling tables fillTables(); // Handling text replaceAllAliasesInDocument(); // Saving document to output stream and closing return saveAndClose(xComponent); } catch (java.lang.Exception ex) { throw new java.lang.RuntimeException(ex); } } private byte[] saveAndClose(XComponent xComponent) throws IOException { OOOutputStream ooos = new OOOutputStream(); String filterName; if (ReportOutputType.PDF.equals(reportOutputType)) { filterName = "writer_pdf_Export"; } else { filterName = "writer8"; } saveXComponent(xComponent, ooos, filterName); closeXComponent(xComponent); return ooos.toByteArray(); } private void fillTables() throws com.sun.star.uno.Exception { List<String> tablesNames = new ArrayList<String>(Arrays.asList(getTablesNames(xComponent))); tablesNames.retainAll(rootBand.getBandDefinitionNames()); XDispatchHelper xDispatchHelper = connection.createXDispatchHelper(); for (String tableName : tablesNames) { Band band = findBand(rootBand, tableName); XTextTable xTextTable = getTableByName(xComponent, tableName); if (band != null) { // todo remove this hack! // try to select one cell without it workaround int columnCount = xTextTable.getColumns().getCount(); if (columnCount < 2) xTextTable.getColumns().insertByIndex(columnCount, 1); fillTable(tableName, band.getParentBand(), xTextTable, xDispatchHelper); // end of workaround -> if (columnCount < 2) xTextTable.getColumns().removeByIndex(columnCount, 1); } else { if (haveValueExpressions(xTextTable)) deleteLastRow(xTextTable); } } } public boolean haveValueExpressions(XTextTable xTextTable) { int lastrow = xTextTable.getRows().getCount() - 1; try { for (int i = 0; i < xTextTable.getColumns().getCount(); i++) { String templateText = asXText(ODTTableHelper.getXCell(xTextTable, i, lastrow)).getString(); if (templateText.matches(UNIVERSAL_ALIAS_PATTERN)) { return true; } } } catch (Exception e) { throw new ReportFormatterException(e); } return false; } private void fillTable(String name, Band parentBand, XTextTable xTextTable, XDispatchHelper xDispatchHelper) throws com.sun.star.uno.Exception { ClipBoardHelper.clear(); for (int i = 0; i < parentBand.getChildren().size(); i++) { if (name.equals(parentBand.getChildren().get(i).getName())) { duplicateLastRow(xDispatchHelper, asXTextDocument(xComponent).getCurrentController(), xTextTable); } } int i = 0; for (Band child : parentBand.getChildren()) { if (name.equals(child.getName())) { fillRow(child, xTextTable, i); i++; } } deleteLastRow(xTextTable); } private void fillRow(Band band, XTextTable xTextTable, int row) throws com.sun.star.lang.IndexOutOfBoundsException, NoSuchElementException, WrappedTargetException { int colCount = xTextTable.getColumns().getCount(); for (int col = 0; col < colCount; col++) { fillCell(band, getXCell(xTextTable, col, row)); } } private void fillCell(Band band, XCell xCell) throws NoSuchElementException, WrappedTargetException { XEnumeration paragraphs = asXEnumerationAccess(xCell).createEnumeration(); while (paragraphs.hasMoreElements()) { Object paragraph = paragraphs.nextElement(); // todo: check here that paragraph is not table XEnumeration textPortions = asXEnumerationAccess(paragraph).createEnumeration(); while (textPortions.hasMoreElements()) { XTextRange textPortion = asXTextRange(textPortions.nextElement()); String portionText = textPortion.getString(); textPortion.setString(insertBandDataToString(band, portionText)); } } } /** * Replaces all aliases (${bandname.paramname} in document text). * If there is not appropriate band or alias is bad - throws RuntimeException */ private void replaceAllAliasesInDocument() { XTextDocument xTextDocument = asXTextDocument(xComponent); XReplaceable xReplaceable = (XReplaceable) UnoRuntime.queryInterface(XReplaceable.class, xTextDocument); XSearchDescriptor searchDescriptor = xReplaceable.createSearchDescriptor(); searchDescriptor.setSearchString(ALIAS_WITH_BAND_NAME_PATTERN); try { searchDescriptor.setPropertyValue("SearchRegularExpression", true); XIndexAccess indexAccess = xReplaceable.findAll(searchDescriptor); for (int i = 0; i < indexAccess.getCount(); i++) { XTextRange o = asXTextRange(indexAccess.getByIndex(i)); String alias = unwrapParameterName(o.getString()); String[] parts = alias.split("\\."); if (parts == null || parts.length < 2) throw new ReportFormatterException("Bad alias : " + o.getString()); String bandName = parts[0]; Band band = bandName.equals("Root") ? rootBand : rootBand.getChildByName(bandName); if (band == null) throw new ReportFormatterException("No band for alias : " + alias); StringBuffer paramName = new StringBuffer(); for (int j = 1; j < parts.length; j++) { paramName.append(parts[j]); if (j != parts.length - 1) paramName.append("."); } Object parameter = band.getParameter(paramName.toString()); o.setString(parameter != null ? parameter.toString() : ""); } } catch (Exception ex) { throw new ReportFormatterException(ex); } } private Band findBand(Band band, String name) { if (band.getName().equals(name)) { return band; } for (Band child : band.getChildren()) { Band fromChild = findBand(child, name); if (fromChild != null) { return fromChild; } } return null; } }
package com.wizzardo.tools.misc; import java.util.ArrayList; import java.util.List; public class CharTree<V> { private CharTreeNode<V> root; protected int size; public CharTree() { } public CharTreeNode<V> getRoot() { return root; } public CharTree<V> append(String s, V value) { return append(s.toCharArray(), value); } public CharTree<V> appendReverse(String s, V value) { return append(reverse(s.toCharArray()), value); } public synchronized CharTree<V> append(char[] chars, V value) { if (root == null) root = new SingleCharTreeNode<V>(); try { char b = chars[0]; root = root.append(b); CharTreeNode<V> temp = root.next(b); CharTreeNode<V> prev = root; char p = b; for (int i = 1; i < chars.length; i++) { b = chars[i]; CharTreeNode<V> next = temp.append(b); prev.set(p, next); prev = next; temp = next.next(b); p = b; } if (temp.value == null) size++; temp.value = value; } catch (Exception e) { throw new IllegalStateException("Cannot append '" + new String(chars) + "'", e); } return this; } public int size() { return size; } public boolean contains(String name) { return get(name) != null; } public boolean contains(char[] chars) { return contains(chars, 0, chars.length); } public boolean contains(char[] chars, int offset, int length) { return get(chars, offset, length) != null; } public V get(char[] chars) { return get(chars, 0, chars.length); } public V get(char[] chars, int offset, int length) { CharTreeNode<V> node = root; for (int i = offset; i < offset + length && node != null; i++) { node = node.next(chars[i]); } return node == null ? null : node.value; } public V get(String s) { CharTreeNode<V> node = root; int length = s.length(); for (int i = 0; i < length && node != null; i++) { node = node.next(s.charAt(i)); } return node == null ? null : node.value; } public V findStarts(char[] chars) { return findStarts(chars, 0, chars.length); } public V findStarts(char[] chars, int offset, int length) { CharTreeNode<V> node = root; for (int i = offset; i < offset + length && node != null && node.value == null; i++) { node = node.next(chars[i]); } return node == null ? null : node.value; } public V findStarts(String s) { CharTreeNode<V> node = root; int length = s.length(); for (int i = 0; i < length && node != null && node.value == null; i++) { node = node.next(s.charAt(i)); } return node == null ? null : node.value; } public List<V> findAllStarts(char[] chars) { return findAllStarts(chars, 0, chars.length); } public List<V> findAllStarts(char[] chars, int offset, int length) { CharTreeNode<V> node = root; List<V> list = new ArrayList<V>(); for (int i = offset; i < offset + length && node != null; i++) { node = node.next(chars[i]); addIfNotNull(list, node); } return list; } public List<V> findAllStarts(String s) { CharTreeNode<V> node = root; List<V> list = new ArrayList<V>(); int length = s.length(); for (int i = 0; i < length && node != null; i++) { node = node.next(s.charAt(i)); addIfNotNull(list, node); } return list; } public V findEnds(char[] chars) { return findEnds(chars, 0, chars.length); } public V findEnds(char[] chars, int offset, int length) { CharTreeNode<V> node = root; int l = chars.length - 1; for (int i = offset; i < offset + length && node != null && node.value == null; i++) { node = node.next(chars[l - i]); } return node == null ? null : node.value; } public V findEnds(String s) { CharTreeNode<V> node = root; int length = s.length(); for (int i = 0; i < length && node != null && node.value == null; i++) { node = node.next(s.charAt(length - i - 1)); } return node == null ? null : node.value; } public List<V> findAllEnds(char[] chars) { return findAllEnds(chars, 0, chars.length); } public List<V> findAllEnds(char[] chars, int offset, int length) { CharTreeNode<V> node = root; int l = chars.length - 1; List<V> list = new ArrayList<V>(); for (int i = offset; i < offset + length && node != null; i++) { node = node.next(chars[l - i]); addIfNotNull(list, node); } return list; } public List<V> findAllEnds(String s) { CharTreeNode<V> node = root; int length = s.length(); List<V> list = new ArrayList<V>(); for (int i = 0; i < length && node != null; i++) { node = node.next(s.charAt(length - i - 1)); addIfNotNull(list, node); } return list; } private void addIfNotNull(List<V> list, CharTreeNode<V> node) { if (node != null && node.value != null) list.add(node.value); } public static abstract class CharTreeNode<V> { protected V value; public abstract CharTreeNode<V> next(char b); public abstract CharTreeNode<V> append(char b); public abstract CharTreeNode<V> set(char b, CharTreeNode<V> node); public V getValue() { return value; } public void setValue(V value) { this.value = value; } } public static class ArrayCharTreeNode<V> extends CharTreeNode<V> { private CharTreeNode<V>[] nodes; public ArrayCharTreeNode(int size) { increase(size); } @Override public CharTreeNode<V> next(char b) { if (b >= nodes.length) return null; return nodes[b]; } @Override public CharTreeNode<V> append(char b) { increase(b + 1); if (nodes[b] == null) nodes[b] = new SingleCharTreeNode<V>(); return this; } @Override public CharTreeNode<V> set(char b, CharTreeNode<V> node) { increase(b + 1); nodes[b] = node; return this; } private void increase(int size) { if (nodes == null) nodes = new CharTreeNode[size]; else if (nodes.length < size) { CharTreeNode<V>[] temp = new CharTreeNode[size]; System.arraycopy(nodes, 0, temp, 0, nodes.length); nodes = temp; } } } static class SingleCharTreeNode<V> extends CharTreeNode<V> { private char b; private CharTreeNode<V> next; @Override public CharTreeNode<V> next(char b) { if (b == this.b) return next; return null; } @Override public CharTreeNode<V> append(char b) { if (next != null && this.b != b) { ArrayCharTreeNode<V> node = new ArrayCharTreeNode<V>(Math.max(this.b, b)); node.set(this.b, next); node.append(b); return node; } else if (this.b == b) return this; else { this.b = b; next = new SingleCharTreeNode<V>(); return this; } } @Override public CharTreeNode<V> set(char b, CharTreeNode<V> n) { if (next != null && this.b != b) { ArrayCharTreeNode<V> node = new ArrayCharTreeNode<V>(Math.max(this.b, b)); node.set(this.b, next); node.set(b, n); return node; } else if (this.b == b) { next = n; return this; } else { this.b = b; next = n; return this; } } @Override public String toString() { return "single " + b; } } public static char[] reverse(char[] chars) { char c; for (int i = 0, j = chars.length - 1; i < j; i++, j c = chars[i]; chars[i] = chars[j]; chars[j] = c; } return chars; } }
package com.haulmont.cuba.web.toolkit.ui; import com.haulmont.cuba.toolkit.gwt.client.ui.VTwinColumnSelect; import com.vaadin.terminal.PaintException; import com.vaadin.terminal.PaintTarget; import com.vaadin.terminal.Resource; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.ClientWidget; import com.vaadin.ui.TwinColSelect; import org.apache.commons.lang.StringUtils; @SuppressWarnings("serial") @ClientWidget(VTwinColumnSelect.class) public class TwinColumnSelect extends TwinColSelect { private OptionStyleGenerator styleGenerator; private boolean nativeSelect; @Override protected int paintOptions(PaintTarget target, String[] selectedKeys, int keyIndex, Object id, String key, String caption, Resource icon) throws PaintException { target.startTag("so"); if (icon != null) { target.addAttribute("icon", icon); } target.addAttribute("caption", caption); if (id != null && id.equals(getNullSelectionItemId())) { target.addAttribute("nullselection", true); } target.addAttribute("key", key); final boolean selected = isSelected(id) && keyIndex < selectedKeys.length; if (selected) { target.addAttribute("selected", true); selectedKeys[keyIndex++] = key; } if (styleGenerator != null) { String style = styleGenerator.generateStyle(this, id, selected); if (!StringUtils.isEmpty(style)) { target.addAttribute("style", style); } } target.endTag("so"); return keyIndex; } @Override protected String getComponentType() { return nativeSelect ? "nativetwincolumn" : "twincoluumn"; } public OptionStyleGenerator getStyleGenerator() { return styleGenerator; } public void setStyleGenerator(OptionStyleGenerator styleGenerator) { this.styleGenerator = styleGenerator; requestRepaint(); } public boolean isNativeSelect() { return nativeSelect; } public void setNativeSelect(boolean nativeSelect) { this.nativeSelect = nativeSelect; requestRepaint(); } public interface OptionStyleGenerator { String generateStyle(AbstractSelect source, Object itemId, boolean selected); } }
package org.wildfly.swarm.naming; import org.junit.Ignore; import org.junit.Test; import org.wildfly.swarm.container.Container; /** * @author Bob McWhirter */ public class NamingInVmTest { @Ignore @Test public void testSimple() throws Exception { Container container = new Container(); container.fraction( new NamingFraction() ); container.start().stop(); } }
package uk.dangrew.nuts.apis.tesco.api.parsing; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import uk.dangrew.kode.launch.TestApplication; import uk.dangrew.nuts.apis.tesco.model.api.ProductDetail; public class ModelUpdaterTest { private ProductDetail updateFrom; private ProductDetail updateTo; private ModelUpdater< ProductDetail > systemUnderTest; @Before public void initialiseSystemUnderTest() { TestApplication.startPlatform(); MockitoAnnotations.initMocks( this ); updateFrom = new ProductDetail(); updateTo = new ProductDetail(); systemUnderTest = new ModelUpdater<>( updateFrom ); }//End Method @Test public void shouldAddFromOnePropertyToAnother() { assertThat( updateTo.characteristics().isFood().get(), is( nullValue() ) ); updateFrom.characteristics().isFood().set( true ); systemUnderTest.set( p -> p.characteristics().isFood(), updateTo ); assertThat( updateTo.characteristics().isFood().get(), is( true ) ); }//End Method }//End Class
//FILE: TileCreatorDlg.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //This file is distributed in the hope that it will be useful, //of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. //CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.DecimalFormat; import java.util.prefs.Preferences; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JComboBox; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.MMCoreJ; import mmcorej.StrVector; import org.micromanager.navigation.MultiStagePosition; import org.micromanager.navigation.StagePosition; import org.micromanager.utils.MMDialog; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.ReportingUtils; public class TileCreatorDlg extends MMDialog { private static final long serialVersionUID = 1L; private CMMCore core_; private MultiStagePosition[] endPosition_; private boolean[] endPositionSet_; private PositionListDlg positionListDlg_; private JTextField overlapField_; private JComboBox overlapUnitsCombo_; private enum OverlapUnitEnum {UM, PX, PERCENT}; private OverlapUnitEnum overlapUnit_ = OverlapUnitEnum.UM; private JTextField pixelSizeField_; private final JLabel labelLeft_ = new JLabel(); private final JLabel labelTop_ = new JLabel(); private final JLabel labelRight_ = new JLabel(); private final JLabel labelBottom_ = new JLabel(); private int prefix_ = 0; private static final DecimalFormat FMT_POS = new DecimalFormat("000"); /** * Create the dialog */ public TileCreatorDlg(CMMCore core, MMOptions opts, PositionListDlg positionListDlg) { super(); setResizable(false); setName("tileDialog"); getContentPane().setLayout(null); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { savePosition(); } }); core_ = core; positionListDlg_ = positionListDlg; endPosition_ = new MultiStagePosition[4]; endPositionSet_ = new boolean[4]; setTitle("Tile Creator"); setBounds(300, 300, 344, 280); Preferences root = Preferences.userNodeForPackage(this.getClass()); setPrefsNode(root.node(root.absolutePath() + "/TileCreatorDlg")); Rectangle r = getBounds(); //loadPosition(r.x, r.y, r.width, r.height); loadPosition(r.x, r.y); final JButton goToLeftButton = new JButton(); goToLeftButton.setFont(new Font("", Font.PLAIN, 10)); goToLeftButton.setText("Go To"); goToLeftButton.setBounds(20, 89, 93, 23); getContentPane().add(goToLeftButton); goToLeftButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (endPositionSet_[3]) goToPosition(endPosition_[3]); } }); labelLeft_.setFont(new Font("", Font.PLAIN, 8)); labelLeft_.setHorizontalAlignment(JLabel.CENTER); labelLeft_.setText(""); labelLeft_.setBounds(0, 112, 130, 14); getContentPane().add(labelLeft_); final JButton setLeftButton = new JButton(); setLeftButton.setBounds(20, 66, 93, 23); setLeftButton.setFont(new Font("", Font.PLAIN, 10)); setLeftButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { markPosition(3); labelLeft_.setText(thisPosition()); } }); setLeftButton.setText("Set"); getContentPane().add(setLeftButton); labelTop_.setFont(new Font("", Font.PLAIN, 8)); labelTop_.setHorizontalAlignment(JLabel.CENTER); labelTop_.setText(""); labelTop_.setBounds(115, 51, 130, 14); getContentPane().add(labelTop_); final JButton goToTopButton = new JButton(); goToTopButton.setFont(new Font("", Font.PLAIN, 10)); goToTopButton.setText("Go To"); goToTopButton.setBounds(133, 28, 93, 23); getContentPane().add(goToTopButton); goToTopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (endPositionSet_[0]) goToPosition(endPosition_[0]); } }); final JButton setTopButton = new JButton(); setTopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { markPosition(0); labelTop_.setText(thisPosition()); } }); setTopButton.setBounds(133, 5, 93, 23); setTopButton.setFont(new Font("", Font.PLAIN, 10)); setTopButton.setText("Set"); getContentPane().add(setTopButton); labelRight_.setFont(new Font("", Font.PLAIN, 8)); labelRight_.setHorizontalAlignment(JLabel.CENTER); labelRight_.setText(""); labelRight_.setBounds(214, 112, 130, 14); getContentPane().add(labelRight_); final JButton setRightButton = new JButton(); setRightButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { markPosition(1); labelRight_.setText(thisPosition()); } }); setRightButton.setBounds(234, 66, 93, 23); setRightButton.setFont(new Font("", Font.PLAIN, 10)); setRightButton.setText("Set"); getContentPane().add(setRightButton); labelBottom_.setFont(new Font("", Font.PLAIN, 8)); labelBottom_.setHorizontalAlignment(JLabel.CENTER); labelBottom_.setText(""); labelBottom_.setBounds(115, 172, 130, 14); getContentPane().add(labelBottom_); final JButton setBottomButton = new JButton(); setBottomButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { markPosition(2); labelBottom_.setText(thisPosition()); } }); setBottomButton.setFont(new Font("", Font.PLAIN, 10)); setBottomButton.setText("Set"); setBottomButton.setBounds(133, 126, 93, 23); getContentPane().add(setBottomButton); final JButton goToRightButton = new JButton(); goToRightButton.setFont(new Font("", Font.PLAIN, 10)); goToRightButton.setText("Go To"); goToRightButton.setBounds(234, 89, 93, 23); getContentPane().add(goToRightButton); goToRightButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (endPositionSet_[1]) goToPosition(endPosition_[1]); } }); final JButton goToBottomButton = new JButton(); goToBottomButton.setFont(new Font("", Font.PLAIN, 10)); goToBottomButton.setText("Go To"); goToBottomButton.setBounds(133, 149, 93, 23); getContentPane().add(goToBottomButton); goToBottomButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (endPositionSet_[2]) goToPosition(endPosition_[2]); } }); final JLabel overlapLabel = new JLabel(); overlapLabel.setFont(new Font("", Font.PLAIN, 10)); overlapLabel.setText("Overlap"); overlapLabel.setBounds(20, 189, 80, 14); getContentPane().add(overlapLabel); overlapField_ = new JTextField(); overlapField_.setBounds(70, 186, 50, 20); overlapField_.setFont(new Font("", Font.PLAIN, 10)); overlapField_.setText("0"); getContentPane().add(overlapField_); String[] unitStrings = { "um", "px", "%" }; overlapUnitsCombo_ = new JComboBox(unitStrings); overlapUnitsCombo_.setSelectedIndex(0); overlapUnitsCombo_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JComboBox cb = (JComboBox)arg0.getSource(); overlapUnit_ = OverlapUnitEnum.values()[cb.getSelectedIndex()]; } }); overlapUnitsCombo_.setBounds(125, 186, 80, 20); getContentPane().add(overlapUnitsCombo_); final JLabel pixelSizeLabel = new JLabel(); pixelSizeLabel.setFont(new Font("", Font.PLAIN, 10)); pixelSizeLabel.setText("Pixel Size [um]"); pixelSizeLabel.setBounds(205, 189, 80, 14); getContentPane().add(pixelSizeLabel); pixelSizeField_ = new JTextField(); pixelSizeField_.setFont(new Font("", Font.PLAIN, 10)); pixelSizeField_.setBounds(280, 186, 50, 20); pixelSizeField_.setText(NumberUtils.doubleToDisplayString(core_.getPixelSizeUm())); getContentPane().add(pixelSizeField_); final JButton okButton = new JButton(); okButton.setFont(new Font("", Font.PLAIN, 10)); okButton.setText("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { savePosition(); addToPositionList(); } }); okButton.setBounds(20, 216, 93, 23); getContentPane().add(okButton); final JButton cancelButton = new JButton(); cancelButton.setBounds(133, 216, 93, 23); cancelButton.setFont(new Font("", Font.PLAIN, 10)); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { savePosition(); dispose(); } }); cancelButton.setText("Cancel"); getContentPane().add(cancelButton); final JButton resetButton = new JButton(); resetButton.setBounds(234, 216, 93, 23); resetButton.setFont(new Font("", Font.PLAIN, 10)); resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { reset(); } }); resetButton.setText("Reset"); getContentPane().add(resetButton); } /** * Store current xyPosition. */ private void markPosition(int location) { MultiStagePosition msp = new MultiStagePosition(); msp.setDefaultXYStage(core_.getXYStageDevice()); msp.setDefaultZStage(core_.getFocusDevice()); // read 1-axis stages try { StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice); for (int i=0; i<stages.size(); i++) { StagePosition sp = new StagePosition(); sp.stageName = stages.get(i); sp.numAxes = 1; sp.x = core_.getPosition(stages.get(i)); msp.add(sp); } // read 2-axis stages StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice); for (int i=0; i<stages2D.size(); i++) { StagePosition sp = new StagePosition(); sp.stageName = stages2D.get(i); sp.numAxes = 2; sp.x = core_.getXPosition(stages2D.get(i)); sp.y = core_.getYPosition(stages2D.get(i)); msp.add(sp); } } catch (Exception e) { ReportingUtils.showError(e); } endPosition_[location] = msp; endPositionSet_[location] = true; } /** * Update display of the current xy position. */ private String thisPosition() { StringBuffer sb = new StringBuffer(); // read 1-axis stages try { StrVector stages = core_.getLoadedDevicesOfType(DeviceType.StageDevice); for (int i=0; i<stages.size(); i++) { StagePosition sp = new StagePosition(); sp.stageName = stages.get(i); sp.numAxes = 1; sp.x = core_.getPosition(stages.get(i)); sb.append(sp.getVerbose() + "\n"); } // read 2-axis stages StrVector stages2D = core_.getLoadedDevicesOfType(DeviceType.XYStageDevice); for (int i=0; i<stages2D.size(); i++) { StagePosition sp = new StagePosition(); sp.stageName = stages2D.get(i); sp.numAxes = 2; sp.x = core_.getXPosition(stages2D.get(i)); sp.y = core_.getYPosition(stages2D.get(i)); sb.append(sp.getVerbose() + "\n"); } } catch (Exception e) { ReportingUtils.showError(e); } return sb.toString(); } /* * Create the tile list based on user input, pixelsize, and imagesize */ private void addToPositionList() { // check if we are calibrated, TODO: allow input of image size double pixSizeUm = 0.0; try { pixSizeUm = NumberUtils.displayStringToDouble(pixelSizeField_.getText()); } catch (Exception e) { ReportingUtils.logError(e); } if (pixSizeUm <= 0.0) { JOptionPane.showMessageDialog(this, "Pixel Size should be a value > 0 (usually 0.1 -1 um). It should be experimentally determined. "); return; } double overlap = 0.0; try { overlap = NumberUtils.displayStringToDouble(overlapField_.getText()); } catch (Exception e) { //handleError(e.getMessage()); } boolean correction, transposeXY, mirrorX, mirrorY; String camera = core_.getCameraDevice(); if (camera == null) { JOptionPane.showMessageDialog(null, "This function does not work without a camera"); return; } try{ String tmp = core_.getProperty(camera, "TransposeCorrection"); if (tmp.equals("0")) correction = false; else correction = true; tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_MirrorX()); if (tmp.equals("0")) mirrorX = false; else mirrorX = true; tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_MirrorY()); if (tmp.equals("0")) mirrorY = false; else mirrorY = true; tmp = core_.getProperty(camera, MMCoreJ.getG_Keyword_Transpose_SwapXY()); if (tmp.equals("0")) transposeXY = false; else transposeXY = true; } catch(Exception exc) { ReportingUtils.showError(exc); return; } double overlapUmX; double overlapUmY; if(overlapUnit_ == OverlapUnitEnum.UM) overlapUmX = overlapUmY = overlap; else if(overlapUnit_ == OverlapUnitEnum.PERCENT) { overlapUmX = pixSizeUm * (overlap / 100) * core_.getImageWidth(); overlapUmY = pixSizeUm * (overlap / 100) * core_.getImageHeight(); } else { // overlapUnit_ == OverlapUnit.PX overlapUmX = overlap * pixSizeUm; overlapUmY = overlap * pixSizeUm; } double tmpXUm = pixSizeUm * core_.getImageWidth() - overlapUmX; double tmpYUm = pixSizeUm * core_.getImageHeight() - overlapUmY; double tileSizeXUm = tmpXUm; double tileSizeYUm = tmpYUm ; // if camera does not correct image orientation, we'll correct for it here: if (!correction) { // Order: swapxy, then mirror axis if (transposeXY) {tileSizeXUm = tmpYUm; tileSizeYUm = tmpXUm;} } // Make sure at least two corners were set int nrSet = 0; for (int i=0; i<4; i++) { if (endPositionSet_[i]) nrSet++; } if (nrSet < 2) { JOptionPane.showMessageDialog(this, "At least two corners should be set"); return; } // Calculate a bounding rectangle around the defaultXYStage positions // TODO: develop method to deal with multiple axis double minX = 0.0, minY = 0.0, maxX = 0.0, maxY = 0.0, meanZ = 0.0; boolean firstSet = false; StagePosition sp = new StagePosition(); for (int i=0; i<4; i++) { if (endPositionSet_[i]) { if (!firstSet) { sp = endPosition_[i].get(endPosition_[i].getDefaultXYStage()); minX = maxX = sp.x; minY = maxY = sp.y; sp = endPosition_[i].get(endPosition_[i].getDefaultZStage()); meanZ = sp.x; firstSet = true; } else { sp = endPosition_[i].get(endPosition_[i].getDefaultXYStage()); if (sp.x < minX) minX = sp.x; if (sp.x > maxX) maxX = sp.x; if (sp.y < minY) minY = sp.y; if (sp.y > maxY) maxY = sp.y; sp = endPosition_[i].get(endPosition_[i].getDefaultZStage()); meanZ += sp.x; } } } meanZ = meanZ/nrSet; // if there are at least three set points, use them to define a // focus plane: a, b, c such that z = f(x, y) = a*x + b*y + c. double zPlaneA = 0.0, zPlaneB = 0.0, zPlaneC = 0.0; boolean hasZPlane = false; if (nrSet >= 3) { hasZPlane = true; double x1 = 0.0, y1 = 0.0, z1 = 0.0; double x2 = 0.0, y2 = 0.0, z2 = 0.0; double x3 = 0.0, y3 = 0.0, z3 = 0.0; boolean sp1Set = false; boolean sp2Set = false; boolean sp3Set = false; // if there are four points set, we should either (a) choose the // three that are least co-linear, or (b) use a linear regression to // fit a focus plane that minimizes the errors at the four selected // positions. this code does neither - it just uses the first three // positions it finds. for (int i=0; i<4; i++) { if (endPositionSet_[i] && !sp1Set) { x1 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x; y1 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y; z1 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x; sp1Set = true; } else if (endPositionSet_[i] && !sp2Set) { x2 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x; y2 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y; z2 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x; sp2Set = true; } else if (endPositionSet_[i] && !sp3Set) { x3 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).x; y3 = endPosition_[i].get(endPosition_[i].getDefaultXYStage()).y; z3 = endPosition_[i].get(endPosition_[i].getDefaultZStage()).x; sp3Set = true; } } // define vectors 1-->2, 1-->3 double x12 = x2 - x1; double y12 = y2 - y1; double z12 = z2 - z1; double x13 = x3 - x1; double y13 = y3 - y1; double z13 = z3 - z1; // first, make sure the points aren't co-linear: the angle between // vectors 1-->2 and 1-->3 must be "sufficiently" large double dot_prod = x12 * x13 + y12 * y13 + z12 * z13; double magnitude12 = x12 * x12 + y12 * y12 + z12 * z12; magnitude12 = Math.sqrt(magnitude12); double magnitude13 = x13 * x13 + y13 * y13 + z13 * z13; magnitude13 = Math.sqrt(magnitude13); double cosTheta = dot_prod / (magnitude12 * magnitude13); double theta = Math.acos(cosTheta); // in RADIANS // "sufficiently" large here is 0.5 radians, or about 30 degrees if(theta < 0.5 || theta > (2 * Math.PI - 0.5) || (theta > (Math.PI - 0.5) && theta < (Math.PI + 0.5))) hasZPlane = false; // intermediates: ax + by + cz + d = 0 double a = y12 * z13 - y13 * z12; double b = z12 * x13 - z13 * x12; double c = x12 * y13 - x13 * y12; double d = -1 * (a * x1 + b * y1 + c * z1); // shuffle to z = f(x, y) = zPlaneA * x + zPlaneB * y + zPlaneC zPlaneA = a / (-1 * c); zPlaneB = b / (-1 * c); zPlaneC = d / (-1 * c); } // make sure the user wants to continue if they've asked for Z positions // but haven't defined enough (non-colinear!) points for a Z plane if(positionListDlg_.useDrive(core_.getFocusDevice()) && !hasZPlane) { int choice = JOptionPane.showConfirmDialog(this, "You are creating a position list that includes\n" + "a Z (focus) position, but the grid locations\n" + "you've chosen are co-linear! If you continue,\n" + "the focus for the new positions will be\n" + "the average focus for the grid locations you set.\n\n" + "If you want to calculate the focus for the new\n" + "positions, you must select at least three grid corners\n" + "that aren't co-linear!\n\nContinue?", "Continue with co-linear focus?", JOptionPane.YES_NO_OPTION); if(choice == JOptionPane.NO_OPTION || choice == JOptionPane.CLOSED_OPTION) return; } // calculate number of images in X and Y int nrImagesX = (int) Math.floor ( (maxX - minX) / tileSizeXUm ) + 2; int nrImagesY = (int) Math.floor ( (maxY - minY) / tileSizeYUm ) + 2; // Increment prefix for these positions prefix_ += 1; // todo handle mirrorX mirrorY for (int y=0; y< nrImagesY; y++) { for (int x=0; x<nrImagesX; x++) { // on even rows go left to right, on odd rows right to left int tmpX = x; if ( (y & 1) == 1) tmpX = nrImagesX - x - 1; MultiStagePosition msp = new MultiStagePosition(); // Add XY position msp.setDefaultXYStage(core_.getXYStageDevice()); msp.setDefaultZStage(core_.getFocusDevice()); StagePosition spXY = new StagePosition(); spXY.stageName = core_.getXYStageDevice(); spXY.numAxes = 2; spXY.x = minX + (tmpX * tileSizeXUm); spXY.y = minY + (y * tileSizeYUm); msp.add(spXY); // Add Z position StagePosition spZ = new StagePosition(); spZ.stageName = core_.getFocusDevice(); spZ.numAxes = 1; if(hasZPlane) { double z = zPlaneA * spXY.x + zPlaneB * spXY.y + zPlaneC; spZ.x = z; } else spZ.x = meanZ; if (positionListDlg_.useDrive(spZ.stageName)) msp.add(spZ); // Add 'metadata' msp.setGridCoordinates(y, tmpX); if(overlapUnit_ == OverlapUnitEnum.UM || overlapUnit_ == OverlapUnitEnum.PX) { msp.setProperty("OverlapUm", NumberUtils.doubleToCoreString(overlapUmX)); int overlapPix = (int) Math.floor(overlapUmX/pixSizeUm); msp.setProperty("OverlapPixels", NumberUtils.intToCoreString(overlapPix)); } else { // overlapUnit_ == OverlapUnit.PERCENT // overlapUmX != overlapUmY; store both msp.setProperty("OverlapUmX", NumberUtils.doubleToCoreString(overlapUmX)); msp.setProperty("OverlapUmY", NumberUtils.doubleToCoreString(overlapUmY)); int overlapPixX = (int) Math.floor(overlapUmX/pixSizeUm); int overlapPixY = (int) Math.floor(overlapUmY/pixSizeUm); msp.setProperty("OverlapPixelsX", NumberUtils.intToCoreString(overlapPixX)); msp.setProperty("OverlapPixelsY", NumberUtils.intToCoreString(overlapPixX)); } // Add to position list positionListDlg_.addPosition(msp, generatePosLabel(prefix_ + "-Pos", tmpX, y)); } } dispose(); } /* * Delete all positions from the dialog and update labels. Re-read pixel calibration - when available - from the core */ private void reset() { for (int i=0; i<4; i++) endPositionSet_[i] = false; labelTop_.setText(""); labelRight_.setText(""); labelBottom_.setText(""); labelLeft_.setText(""); double pxsz = core_.getPixelSizeUm(); pixelSizeField_.setText(NumberUtils.doubleToDisplayString(pxsz)); } /* * Move stage to position */ private void goToPosition(MultiStagePosition position) { try { MultiStagePosition.goToPosition(position, core_); } catch (Exception e) { ReportingUtils.logError(e); } } private void handleError(String txt) { JOptionPane.showMessageDialog(this, txt); } public static String generatePosLabel(String prefix, int x, int y) { String name = prefix + "_" + FMT_POS.format(x) + "_" + FMT_POS.format(y); return name; } }
package org.formular.core; import android.content.res.XmlResourceParser; public class XmlDecoder { public static IOperation fromXML(XmlResourceParser xml){ return null; }; }
/*code written by Douglas King * edited by Mathew Boland */ package gonqbox.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import gonqbox.Pages; import gonqbox.dao.DAO; import gonqbox.models.User; /** Purpose: Servlet to login user. Redirects to homepage * on success. Reloads index.jsp on failure. * @author Mathew Boland * @version 0.1 */ @WebServlet(name = "login", urlPatterns = { "/loginServlet" }) public class LoginServlet extends HttpServlet{ private static final long serialVersionUID = 1L; //DAO Instance to access database private DAO dao = DAO.getInstance(); /** * Purpose: To check the given username and password * @param request and response * @return void */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("userpass"); User user = dao.loginUser(username, password); //check if user found if(user != null){ request.getSession().setAttribute("user", user); request.setAttribute("login_messenger","Login Successful, welcome " + user.getUsername()); } else { request.setAttribute("login_messenger_err","Invalid Username or Password"); } request.getRequestDispatcher(Pages.INDEX.toString()).forward(request,response); } }
package com.isawabird; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class AboutActivity extends Activity { TextView appNameTextView; TextView versionTextView; TextView developedTextView; TextView namesTextView; TextView contactTextView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); getActionBar().hide(); appNameTextView = (TextView) findViewById(R.id.aboutTextView_title); appNameTextView.setTypeface(Utils.getTangerineTypeface(this)); versionTextView = (TextView) findViewById(R.id.aboutTextView_version); versionTextView.setTypeface(Utils.getOpenSansLightTypeface(this)); developedTextView = (TextView) findViewById(R.id.aboutTextView_developed); developedTextView.setTypeface(Utils.getOpenSansLightTypeface(this)); namesTextView = (TextView) findViewById(R.id.aboutTextView_names); namesTextView.setTypeface(Utils.getOpenSansLightTypeface(this)); contactTextView = (TextView) findViewById(R.id.aboutTextView_contact); contactTextView.setTypeface(Utils.getOpenSansLightTypeface(this)); namesTextView.setText("Srihari Kulkarni\nJerry Mannel\nPradeep S Bhat\nChethan Kumar SN"); contactTextView.setText("Contact us at birdr@dhatu.com"); } }
package plugin.google.maps; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import java.util.List; import java.util.ArrayList; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaResourceApi; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Point; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; import android.text.style.StyleSpan; import android.util.Log; import android.util.DisplayMetrics; import android.view.WindowManager; import android.view.animation.BounceInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.TextView; import plugin.google.maps.FakedR; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.maps.android.ui.IconGenerator; import com.squareup.picasso.Picasso; import com.squareup.picasso.RequestCreator; public class PluginMarker extends MyPlugin { private PicassoMarker picassoMarker; private AsyncLoadImageInterface asyncLoadImageInterface; private enum Animation { DROP, BOUNCE } private CustomInfoWindowAdapter customInfoWindowAdapter; @SuppressWarnings("unused") private PluginAsyncInterface noOpAsyncInterface() { return new PluginAsyncInterface() { @Override public void onPostExecute(Object object){ Log.d("client", "noOpAsyncInterface onPostExecute"); } @Override public void onError(String errorMsg){ Log.d("client", "noOpAsyncInterface onError: " + errorMsg); } }; } @SuppressWarnings("unused") private MarkerOptions getMarkerOptions(final JSONObject opts) throws JSONException { // Create an instance of Marker class final MarkerOptions markerOptions = new MarkerOptions(); if (opts.has("position")) { JSONObject position = opts.getJSONObject("position"); markerOptions.position(new LatLng(position.getDouble("lat"), position.getDouble("lng"))); } if (opts.has("title")) { markerOptions.title(opts.getString("title")); } if (opts.has("snippet")) { markerOptions.snippet(opts.getString("snippet")); } if (opts.has("visible")) { if (opts.has("icon") && "".equals(opts.getString("icon")) == false) { markerOptions.visible(false); } else { markerOptions.visible(opts.getBoolean("visible")); } } if (opts.has("draggable")) { markerOptions.draggable(opts.getBoolean("draggable")); } if (opts.has("rotation")) { markerOptions.rotation((float)opts.getDouble("rotation")); } if (opts.has("flat")) { markerOptions.flat(opts.getBoolean("flat")); } if (opts.has("opacity")) { markerOptions.alpha((float) opts.getDouble("opacity")); } if (opts.has("zIndex")) { // do nothing, API v2 has no zIndex :( } return markerOptions; } private Bundle getIconBundle(final JSONObject opts) throws JSONException{ Bundle bundle = null; Object value = opts.get("icon"); if (JSONObject.class.isInstance(value)) { JSONObject iconProperty = (JSONObject)value; bundle = PluginUtil.Json2Bundle(iconProperty); // The `anchor` of the `icon` property if (iconProperty.has("anchor")) { value = iconProperty.get("anchor"); if (JSONArray.class.isInstance(value)) { JSONArray points = (JSONArray)value; double[] anchorPoints = new double[points.length()]; for (int i = 0; i < points.length(); i++) { anchorPoints[i] = points.getDouble(i); } bundle.putDoubleArray("anchor", anchorPoints); } } // The `infoWindowAnchor` property for infowindow if (opts.has("infoWindowAnchor")) { value = opts.get("infoWindowAnchor"); if (JSONArray.class.isInstance(value)) { JSONArray points = (JSONArray)value; double[] anchorPoints = new double[points.length()]; for (int i = 0; i < points.length(); i++) { anchorPoints[i] = points.getDouble(i); } bundle.putDoubleArray("infoWindowAnchor", anchorPoints); } } } else if (JSONArray.class.isInstance(value)) { float[] hsv = new float[3]; JSONArray arrayRGBA = (JSONArray)value; Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv); bundle = new Bundle(); bundle.putFloat("iconHue", hsv[0]); } else { bundle = new Bundle(); bundle.putString("url", (String)value); } if (opts.has("animation")) { bundle.putString("animation", opts.getString("animation")); } if (opts.has("markerType")) { bundle.putString("markerType", opts.getString("markerType")); } if (opts.has("customMarkerFirstString")) { bundle.putString("customMarkerFirstString", opts.getString("customMarkerFirstString")); } if (opts.has("customMarkerSecondString")) { bundle.putString("customMarkerSecondString", opts.getString("customMarkerSecondString")); } if (opts.has("mapOrientation")) { bundle.putString("mapOrientation", opts.getString("mapOrientation")); } return bundle; } private void setAnimationForJustCreatedMarker(Marker marker, String markerAnimation, final CallbackContext callbackContext) throws JSONException{ PluginAsyncInterface asyncInterface; if (callbackContext != null){ asyncInterface = new PluginAsyncInterface() { @Override public void onPostExecute(Object object){ Marker marker = (Marker)object; try { callbackContext.success(getMarkerResultJSON(marker)); } catch (JSONException e){ callbackContext.error("Error generating result JSON"); } } @Override public void onError(String errorMsg){ callbackContext.error(errorMsg); } }; } else { asyncInterface = noOpAsyncInterface(); } if (markerAnimation != null) { PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, asyncInterface); } else { if (callbackContext != null) { callbackContext.success(getMarkerResultJSON(marker)); } } } private void setIconforJustCreatedMarker(Marker marker, final JSONObject opts, Bundle bundle, final CallbackContext callbackContext) throws JSONException{ Log.d("client", "-- setting icon for just created marker"); PluginAsyncInterface asyncInterface; asyncInterface = new PluginAsyncInterface() { @Override public void onPostExecute(Object object) { Marker marker = (Marker)object; if (opts.has("visible")) { try { marker.setVisible(opts.getBoolean("visible")); } catch (JSONException e) {} } else { marker.setVisible(true); } // Animation if (opts.has("animation")) { try { setAnimationForJustCreatedMarker(marker, opts.getString("animation"), callbackContext); } catch (JSONException e) { e.printStackTrace(); } } else { if (callbackContext != null){ try { callbackContext.success(getMarkerResultJSON(marker)); } catch (JSONException e){ callbackContext.error("Error generating result JSON"); } } else { Log.d("client", "-- setIconforJustCreatedMarker: callbackContext is null"); } } } @Override public void onError(String errorMsg) { callbackContext.error(errorMsg); } }; this.setIcon_(marker, bundle, asyncInterface); } private void storeMarker(Marker marker, final JSONObject opts) throws JSONException { // Store the marker String id = "marker_" + marker.getId(); this.objects.put(id, marker); JSONObject properties = new JSONObject(); if (opts.has("styles")) { properties.put("styles", opts.getJSONObject("styles")); } if (opts.has("disableAutoPan")) { properties.put("disableAutoPan", opts.getBoolean("disableAutoPan")); } else { properties.put("disableAutoPan", false); } this.objects.put("marker_property_" + marker.getId(), properties); } private JSONObject getMarkerResultJSON(final Marker marker) throws JSONException{ final JSONObject result = new JSONObject(); result.put("hashCode", marker.hashCode()); result.put("id", "marker_" + marker.getId()); return result; } private void setIconAndAnimationForMarker(Marker marker, JSONObject opts, CallbackContext callbackContext) throws JSONException { // Load icon if (opts.has("icon")) { Bundle bundle = getIconBundle(opts); setIconforJustCreatedMarker(marker, opts, bundle, callbackContext); } else { // Animation if (opts.has("animation")) { try { setAnimationForJustCreatedMarker(marker, opts.getString("animation"), callbackContext); } catch (JSONException e) { e.printStackTrace(); } } else { if (callbackContext != null){ callbackContext.success(getMarkerResultJSON(marker)); } } } } @SuppressWarnings("unused") private Marker addMarkerToMap(MarkerOptions markerOptions, final JSONObject opts, final CallbackContext callbackContext) throws JSONException { Log.d("client", "-- adding marker to map"); Marker marker = map.addMarker(markerOptions); storeMarker(marker, opts); setIconAndAnimationForMarker(marker, opts, callbackContext); return marker; } /** * Create a marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void createMarker(final JSONArray args, final CallbackContext callbackContext) throws JSONException { JSONObject opts = args.getJSONObject(1); addMarkerToMap(getMarkerOptions(opts), opts, callbackContext); } /** * Create multiple markers * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void createMultipleMarkers(final JSONArray args, final CallbackContext callbackContext) throws JSONException { final JSONArray markersJSONArray = args.getJSONArray(1); JSONObject opts; MarkerOptions markerOptions; Marker marker; Log.d("client", "creating multiple markers"); List<JSONObject> optsList = new ArrayList<JSONObject>(); List<MarkerOptions> markerOptionsList = new ArrayList<MarkerOptions>(); JSONArray resultsJSONArray = new JSONArray(); for(int i=0; i < markersJSONArray.length(); i++){ opts = markersJSONArray.getJSONObject(i); optsList.add(opts); markerOptionsList.add(getMarkerOptions(opts)); } for(int i=0; i < markersJSONArray.length(); i++){ marker = addMarkerToMap(markerOptionsList.get(i), optsList.get(i), null); resultsJSONArray.put(getMarkerResultJSON(marker)); } Log.d("client", "-- added markers to map"); callbackContext.success(resultsJSONArray); } private void setDropAnimation_(final Marker marker, final PluginAsyncInterface callback) { final Handler handler = new Handler(); final long startTime = SystemClock.uptimeMillis(); final long duration = 100; final Projection proj = this.map.getProjection(); final LatLng markerLatLng = marker.getPosition(); final Point markerPoint = proj.toScreenLocation(markerLatLng); final Point startPoint = new Point(markerPoint.x, 0); final Interpolator interpolator = new LinearInterpolator(); handler.post(new Runnable() { @Override public void run() { LatLng startLatLng = proj.fromScreenLocation(startPoint); long elapsed = SystemClock.uptimeMillis() - startTime; float t = interpolator.getInterpolation((float) elapsed / duration); double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude; double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude; marker.setPosition(new LatLng(lat, lng)); if (t < 1.0) { // Post again 16ms later. handler.postDelayed(this, 16); } else { marker.setPosition(markerLatLng); callback.onPostExecute(marker); } } }); } private void setBounceAnimation_(final Marker marker, final PluginAsyncInterface callback) { final Handler handler = new Handler(); final long startTime = SystemClock.uptimeMillis(); final long duration = 2000; final Projection proj = this.map.getProjection(); final LatLng markerLatLng = marker.getPosition(); final Point startPoint = proj.toScreenLocation(markerLatLng); startPoint.offset(0, -200); final Interpolator interpolator = new BounceInterpolator(); handler.post(new Runnable() { @Override public void run() { LatLng startLatLng = proj.fromScreenLocation(startPoint); long elapsed = SystemClock.uptimeMillis() - startTime; float t = interpolator.getInterpolation((float) elapsed / duration); double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude; double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude; marker.setPosition(new LatLng(lat, lng)); if (t < 1.0) { // Post again 16ms later. handler.postDelayed(this, 16); } else { marker.setPosition(markerLatLng); callback.onPostExecute(marker); } } }); } private void setMarkerAnimation_(Marker marker, String animationType, PluginAsyncInterface callback) { Animation animation = null; try { animation = Animation.valueOf(animationType.toUpperCase(Locale.US)); } catch (Exception e) { e.printStackTrace(); } if (animation == null) { callback.onPostExecute(marker); return; } switch(animation) { case DROP: this.setDropAnimation_(marker, callback); break; case BOUNCE: this.setBounceAnimation_(marker, callback); break; default: break; } } @SuppressWarnings("unused") private void setAnimation(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); String animation = args.getString(2); final Marker marker = this.getMarker(id); this.setMarkerAnimation_(marker, animation, new PluginAsyncInterface() { @Override public void onPostExecute(Object object) { callbackContext.success(); } @Override public void onError(String errorMsg) { callbackContext.error(errorMsg); } }); } /** * Show the InfoWindow binded with the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void showInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); Marker marker = this.getMarker(id); marker.showInfoWindow(); this.sendNoResult(callbackContext); } /** * Set rotation for the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setRotation(final JSONArray args, final CallbackContext callbackContext) throws JSONException { float rotation = (float)args.getDouble(2); String id = args.getString(1); this.setFloat("setRotation", id, rotation, callbackContext); } /** * Set opacity for the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException { float alpha = (float)args.getDouble(2); String id = args.getString(1); this.setFloat("setAlpha", id, alpha, callbackContext); } /** * Set zIndex for the marker (dummy code, not available on Android V2) * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setZIndex(final JSONArray args, final CallbackContext callbackContext) throws JSONException { // nothing to do :( // it's a shame google... } /** * set position * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); LatLng position = new LatLng(args.getDouble(2), args.getDouble(3)); Marker marker = this.getMarker(id); marker.setPosition(position); this.sendNoResult(callbackContext); } /** * Set flat for the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setFlat(final JSONArray args, final CallbackContext callbackContext) throws JSONException { boolean isFlat = args.getBoolean(2); String id = args.getString(1); this.setBoolean("setFlat", id, isFlat, callbackContext); } /** * Set visibility for the object * @param args * @param callbackContext * @throws JSONException */ protected void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean visible = args.getBoolean(2); String id = args.getString(1); this.setBoolean("setVisible", id, visible, callbackContext); } /** * @param args * @param callbackContext * @throws JSONException */ protected void setDisableAutoPan(JSONArray args, CallbackContext callbackContext) throws JSONException { boolean disableAutoPan = args.getBoolean(2); String id = args.getString(1); Marker marker = this.getMarker(id); String propertyId = "marker_property_" + marker.getId(); JSONObject properties = null; if (this.objects.containsKey(propertyId)) { properties = (JSONObject)this.objects.get(propertyId); } else { properties = new JSONObject(); } properties.put("disableAutoPan", disableAutoPan); this.objects.put(propertyId, properties); this.sendNoResult(callbackContext); } /** * Set title for the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setTitle(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String title = args.getString(2); String id = args.getString(1); this.setString("setTitle", id, title, callbackContext); } /** * Set the snippet for the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setSnippet(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String snippet = args.getString(2); String id = args.getString(1); this.setString("setSnippet", id, snippet, callbackContext); } /** * Hide the InfoWindow binded with the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void hideInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); Marker marker = this.getMarker(id); marker.hideInfoWindow(); this.sendNoResult(callbackContext); } /** * Return the position of the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void getPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); Marker marker = this.getMarker(id); LatLng position = marker.getPosition(); JSONObject result = new JSONObject(); result.put("lat", position.latitude); result.put("lng", position.longitude); callbackContext.success(result); } /** * Return 1 if the InfoWindow of the marker is shown * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void isInfoWindowShown(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); Marker marker = this.getMarker(id); Boolean isInfoWndShown = marker.isInfoWindowShown(); callbackContext.success(isInfoWndShown ? 1 : 0); } /** * Remove the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void remove(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); Marker marker = this.getMarker(id); if (marker == null) { callbackContext.success(); return; } marker.remove(); this.objects.remove(id); String propertyId = "marker_property_" + id; this.objects.remove(propertyId); this.sendNoResult(callbackContext); } /** * Remove the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void removeMultipleMarkers(final JSONArray args, final CallbackContext callbackContext) throws JSONException { JSONArray markersToRemove = args.getJSONArray(1); String id; for(int i=0; i < markersToRemove.length(); i++){ id = markersToRemove.getString(i); Marker marker = this.getMarker(id); if (marker != null) { marker.remove(); this.objects.remove(id); String propertyId = "marker_property_" + id; this.objects.remove(propertyId); } } callbackContext.success(); } /** * Set anchor for the icon of the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setIconAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException { float anchorX = (float)args.getDouble(2); float anchorY = (float)args.getDouble(3); String id = args.getString(1); Marker marker = this.getMarker(id); Bundle imageSize = (Bundle) this.objects.get("imageSize"); if (imageSize != null) { this._setIconAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height")); } this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void updateEstimationMarker(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); String firstString = args.getString(2); String secondString = args.getString(3); String mapOrientation = args.getString(4); Marker marker = this.getMarker(id); boolean markerOrientation = mapOrientation.equals("e2w"); buildDestinationMarker(marker, markerOrientation, firstString, secondString); this.sendNoResult(callbackContext); } @SuppressWarnings("unused") private void showCustomInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); String firstString = args.getString(2); String secondString = args.getString(3); String markerType = args.getString(4); Marker marker = this.getMarker(id); if (markerType.equals("infowindow")) { if (map != null && customInfoWindowAdapter == null) { customInfoWindowAdapter = new CustomInfoWindowAdapter(getContext()); } map.setInfoWindowAdapter(customInfoWindowAdapter); customInfoWindowAdapter.updateInfoWindowText(marker, firstString, secondString); } this.sendNoResult(callbackContext); } /** * Set anchor for the InfoWindow of the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setInfoWindowAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException { float anchorX = (float)args.getDouble(2); float anchorY = (float)args.getDouble(3); String id = args.getString(1); Marker marker = this.getMarker(id); Bundle imageSize = (Bundle) this.objects.get("imageSize"); if (imageSize != null) { this._setInfoWindowAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height")); } this.sendNoResult(callbackContext); } /** * Set draggable for the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setDraggable(final JSONArray args, final CallbackContext callbackContext) throws JSONException { Boolean draggable = args.getBoolean(2); String id = args.getString(1); this.setBoolean("setDraggable", id, draggable, callbackContext); } /** * Set icon of the marker * @param args * @param callbackContext * @throws JSONException */ @SuppressWarnings("unused") private void setIcon(final JSONArray args, final CallbackContext callbackContext) throws JSONException { String id = args.getString(1); Marker marker = this.getMarker(id); Object value = args.get(2); Bundle bundle = null; if (JSONObject.class.isInstance(value)) { JSONObject iconProperty = (JSONObject)value; bundle = PluginUtil.Json2Bundle(iconProperty); // The `anchor` for icon if (iconProperty.has("anchor")) { value = iconProperty.get("anchor"); if (JSONArray.class.isInstance(value)) { JSONArray points = (JSONArray)value; double[] anchorPoints = new double[points.length()]; for (int i = 0; i < points.length(); i++) { anchorPoints[i] = points.getDouble(i); } bundle.putDoubleArray("anchor", anchorPoints); } } } else if (JSONArray.class.isInstance(value)) { float[] hsv = new float[3]; JSONArray arrayRGBA = (JSONArray)value; Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv); bundle = new Bundle(); bundle.putFloat("iconHue", hsv[0]); } else if (String.class.isInstance(value)) { bundle = new Bundle(); bundle.putString("url", (String)value); } if (bundle != null) { this.setIcon_(marker, bundle, new PluginAsyncInterface() { @Override public void onPostExecute(Object object) { PluginMarker.this.sendNoResult(callbackContext); } @Override public void onError(String errorMsg) { callbackContext.error(errorMsg); } }); } else { this.sendNoResult(callbackContext); } } private void setIcon_(final Marker marker, final Bundle iconProperty, final PluginAsyncInterface callback) { if (iconProperty.containsKey("iconHue")) { float hue = iconProperty.getFloat("iconHue"); marker.setIcon(BitmapDescriptorFactory.defaultMarker(hue)); callback.onPostExecute(marker); return; } String iconUrl = iconProperty.getString("url"); if (iconUrl.indexOf(": iconUrl.startsWith("/") == false && iconUrl.startsWith("www/") == false) { iconUrl = "./" + iconUrl; } if (iconUrl.indexOf("./") == 0) { String currentPage = this.webView.getUrl(); currentPage = currentPage.replaceAll("[^\\/]*$", ""); iconUrl = iconUrl.replace("./", currentPage); } if (iconUrl == null) { callback.onPostExecute(marker); return; } // Insert here our estimation marker if (iconProperty.containsKey("markerType") && iconProperty.getString("markerType") != null && iconProperty.getString("markerType").equals("estimation")) { // Custom Cabify Marker if (iconProperty.containsKey("customMarkerFirstString") && iconProperty.containsKey("customMarkerSecondString")) { String firstString = iconProperty.getString("customMarkerFirstString"); String secondString = iconProperty.getString("customMarkerSecondString"); boolean markerOrientation = iconProperty.containsKey("mapOrientation") && iconProperty.getString("mapOrientation").equals("e2w"); buildDestinationMarker(marker, markerOrientation, firstString, secondString); callback.onPostExecute(marker); return; } } if (iconUrl.indexOf("http") != 0) { AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() { @Override protected Bitmap doInBackground(Void... params) { String iconUrl = iconProperty.getString("url"); Bitmap image = null; if (iconUrl.indexOf("cdvfile: CordovaResourceApi resourceApi = webView.getResourceApi(); iconUrl = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, iconUrl); } if (iconUrl.indexOf("data:image/") == 0 && iconUrl.indexOf(";base64,") > -1) { String[] tmp = iconUrl.split(","); image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]); } else if (iconUrl.indexOf("file: iconUrl.indexOf("file:///android_asset/") == -1) { iconUrl = iconUrl.replace("file: File tmp = new File(iconUrl); if (tmp.exists()) { image = BitmapFactory.decodeFile(iconUrl); } else { if (PluginMarker.this.mapCtrl.isDebug) { Log.w("GoogleMaps", "icon is not found (" + iconUrl + ")"); } } } else if (iconUrl.indexOf("file:///android_asset/") == 0) { iconUrl = iconUrl.replace("file:///android_asset/", ""); if (iconUrl.indexOf("./") == 0) { iconUrl = iconUrl.replace("./", "www/"); } AssetManager assetManager = PluginMarker.this.cordova.getActivity().getAssets(); InputStream inputStream; try { inputStream = assetManager.open(iconUrl); image = BitmapFactory.decodeStream(inputStream); } catch (IOException e) { e.printStackTrace(); callback.onPostExecute(marker); return null; } } else { if (iconUrl.indexOf("cabify:///marker/") == 0) { iconUrl = iconUrl.replace("cabify:///marker/", ""); } int targetResourceId = FakedR.getId(getContext(),"drawable",iconUrl); if(targetResourceId != 0){ image = BitmapFactory.decodeResource(PluginMarker.this.cordova.getActivity().getResources(), targetResourceId); } } if (image == null) { callback.onPostExecute(marker); return null; } Boolean isResized = false; if (iconProperty.containsKey("size") == true) { Object size = iconProperty.get("size"); if (Bundle.class.isInstance(size)) { Bundle sizeInfo = (Bundle)size; int width = sizeInfo.getInt("width", 0); int height = sizeInfo.getInt("height", 0); if (width > 0 && height > 0) { isResized = true; width = (int)Math.round(width * PluginMarker.this.density); height = (int)Math.round(height * PluginMarker.this.density); image = PluginUtil.resizeBitmap(image, width, height); } } } return image; } @Override protected void onPostExecute(Bitmap image) { if (image == null) { callback.onPostExecute(marker); return; } try { //TODO: check image is valid? BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image); marker.setIcon(bitmapDescriptor); // Save the information for the anchor property Bundle imageSize = new Bundle(); imageSize.putInt("width", image.getWidth()); imageSize.putInt("height", image.getHeight()); PluginMarker.this.objects.put("imageSize", imageSize); // The `anchor` of the `icon` property if (iconProperty.containsKey("anchor") == true) { double[] anchor = iconProperty.getDoubleArray("anchor"); if (anchor.length == 2) { _setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height")); } } // The `anchor` property for the infoWindow if (iconProperty.containsKey("infoWindowAnchor") == true) { double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor"); if (anchor.length == 2) { _setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height")); } } // Check if we have a fucking info window to paint // Insert here our estimation marker if (iconProperty.containsKey("markerType") && iconProperty.getString("markerType") != null && iconProperty.getString("markerType").equals("infowindow")) { // Custom Cabify Marker if (iconProperty.containsKey("firstString") && iconProperty.containsKey("secondString")) { String firstString = iconProperty.getString("firstString"); String secondString = iconProperty.getString("secondString"); if(map != null){ customInfoWindowAdapter = new CustomInfoWindowAdapter(getContext()); map.setInfoWindowAdapter(customInfoWindowAdapter); customInfoWindowAdapter.updateInfoWindowText(marker, firstString, secondString); } } } callback.onPostExecute(marker); } catch (java.lang.IllegalArgumentException e) { Log.e("GoogleMapsPlugin","PluginMarker: Warning - marker method called when marker has been disposed, wait for addMarker callback before calling more methods on the marker (setIcon etc)."); //e.printStackTrace(); } } }; task.execute(); return; } if (iconUrl.indexOf("http") == 0) { int width = -1; int height = -1; if (iconProperty.containsKey("size") == true) { Bundle sizeInfo = (Bundle) iconProperty.get("size"); width = sizeInfo.getInt("width", width); height = sizeInfo.getInt("height", height); } asyncLoadImageInterface = new AsyncLoadImageInterface() { @Override public void onPostExecute(Bitmap image) { if (image == null) { callback.onPostExecute(marker); return; } BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image); marker.setIcon(bitmapDescriptor); // Save the information for the anchor property Bundle imageSize = new Bundle(); imageSize.putInt("width", image.getWidth()); imageSize.putInt("height", image.getHeight()); PluginMarker.this.objects.put("imageSize", imageSize); // The `anchor` of the `icon` property if (iconProperty.containsKey("anchor") == true) { double[] anchor = iconProperty.getDoubleArray("anchor"); if (anchor.length == 2) { _setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height")); } } // Insert here our estimation marker if (iconProperty.containsKey("markerType") && iconProperty.getString("markerType") != null && iconProperty.getString("markerType").equals("infowindow")) { // Custom Cabify Marker if (iconProperty.containsKey("firstString") && iconProperty.containsKey("secondString")) { String firstString = iconProperty.getString("firstString"); String secondString = iconProperty.getString("secondString"); if (map != null) { customInfoWindowAdapter = new CustomInfoWindowAdapter(getContext()); map.setInfoWindowAdapter(customInfoWindowAdapter); customInfoWindowAdapter.updateInfoWindowText(marker, firstString, secondString); } } } // The `anchor` property for the infoWindow if (iconProperty.containsKey("infoWindowAnchor") == true) { double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor"); if (anchor.length == 2) { _setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height")); } } callback.onPostExecute(marker); } }; picassoMarker = new PicassoMarker(callback, asyncLoadImageInterface); RequestCreator requestCreator = Picasso.with(this.cordova.getActivity()) .load(iconUrl); if(width != -1 || height != -1){ requestCreator = requestCreator.resize(width,height); } requestCreator.into(picassoMarker); } } private void _setIconAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) { // The `anchor` of the `icon` property anchorX = anchorX * this.density; anchorY = anchorY * this.density; marker.setAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight)); } private void _setInfoWindowAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) { // The `anchor` of the `icon` property anchorX = anchorX * this.density; anchorY = anchorY * this.density; marker.setInfoWindowAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight)); } private void buildDestinationMarker(Marker marker, boolean leftIndicator, String first, String second) { IconGenerator iconFactory = new IconGenerator(getContext()); TextView t = new TextView(getContext()); t.setBackgroundResource(leftIndicator ? FakedR.getId(getContext(),"drawable","ic_marker_destination_left") : FakedR.getId(getContext(),"drawable","ic_marker_destination_right")); t.setTextSize(11); t.setTextColor(Color.parseColor("#CCCCCC")); t.setIncludeFontPadding(false); iconFactory.setBackground(null); iconFactory.setContentView(t); Bitmap sampleBitmap = iconFactory.makeIcon(); if (first != null && !first.equals("null")) { // Tweak the incoming text to show it in two lines first = first.concat("\n"); } else { first = ""; } Spannable wordtoSpan = new SpannableString(first + second); wordtoSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#FFFFFF")), first.length(), first.length() + second.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); wordtoSpan.setSpan(new RelativeSizeSpan(1.2f), first.length(), first.length() + second.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); wordtoSpan.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), first.length(), first.length() + second.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); t.setText(wordtoSpan); Bitmap bitmap = iconFactory.makeIcon(); marker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap)); marker.setAnchor(computeMarkerHorizontalAnchor(leftIndicator, sampleBitmap.getWidth(), bitmap.getWidth()), 1.0f); } private float computeMarkerHorizontalAnchor(boolean leftIndicator, int originalWidth, int computedWidth) { int supposedAnchorPos = (int) (leftIndicator ? originalWidth * 0.3f : originalWidth * 0.7f); if (leftIndicator) { return (float) supposedAnchorPos / computedWidth; } else { return (float) (computedWidth - (originalWidth - supposedAnchorPos)) / computedWidth; } } private Context getContext(){ return this.cordova.getActivity().getApplicationContext(); } }
package heufybot.modules; import heufybot.core.Logger; import heufybot.utils.FileUtils; import heufybot.utils.StringUtils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class Event extends Module { private String eventsPath = "data/events.json"; private List<MyEvent> events; public Event() { this.authType = AuthType.Anyone; this.apiVersion = "0.5.0"; this.triggerTypes = new TriggerType[] { TriggerType.Message }; this.trigger = "^" + commandPrefix + "(event|timetill|timesince|r(emove)?event)($| .*)"; this.events = new ArrayList<MyEvent>(); } public void processEvent(String source, String message, String triggerUser, List<String> params) { if(message.toLowerCase().matches("^" + commandPrefix + "event.*")) { if(params.size() < 3) { bot.getIRC().cmdPRIVMSG(source, "You didn't specify an event."); return; } params.remove(0); Date eventDate; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { eventDate = dateFormat.parse(params.get(0) + " " + params.get(1)); if(params.size() < 3) { bot.getIRC().cmdPRIVMSG(source, "You didn't specify an event."); return; } params.remove(0); params.remove(0); } catch (java.text.ParseException e) { dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { eventDate = dateFormat.parse(params.get(0)); params.remove(0); } catch (java.text.ParseException e1) { bot.getIRC().cmdPRIVMSG(source, "The date you specified is invalid. Use \"yyyy-MM-dd\" or \"yyyy-MM-dd HH:mm\" as the format."); return; } } MyEvent event = new MyEvent(triggerUser, eventDate, StringUtils.join(params, " ")); int latestDateIndex = 0; for(int i = 0; i < events.size(); i++) { if(eventDate.after(events.get(i).getDate())) { latestDateIndex = i + 1; } } events.add(latestDateIndex, event); writeEvents(); bot.getIRC().cmdPRIVMSG(source, "Event \"" + event.getEventString() + "\" on the date " + event.getFormattedDate() + " (UTC) was added to the events database!"); } else if(message.toLowerCase().matches("^" + commandPrefix + "r(emove)?event.*")) { } else if(message.toLowerCase().matches("^" + commandPrefix + "timetill.*")) { if(params.size() == 1) { bot.getIRC().cmdPRIVMSG(source, "You didn't specify an event."); return; } params.remove(0); String search = StringUtils.join(params, " "); for(MyEvent event : events) { Date now = new Date(); if(event.getEventString().toLowerCase().matches(".*" + search.toLowerCase() + ".*") && event.getDate().after(now)) { String timeDifference = getTimeDifferenceString(now, event.getDate()); bot.getIRC().cmdPRIVMSG(source, event.getUser() + "'s event \"" + event.getEventString() + "\" will occur in " + timeDifference + "."); return; } } bot.getIRC().cmdPRIVMSG(source, "No event matching \"" + search + "\" was found in the events database."); } else if(message.toLowerCase().matches("^" + commandPrefix + "timesince.*")) { if(params.size() == 1) { bot.getIRC().cmdPRIVMSG(source, "You didn't specify an event."); return; } params.remove(0); String search = StringUtils.join(params, " "); for(MyEvent event : events) { Date now = new Date(); if(event.getEventString().toLowerCase().matches(".*" + search.toLowerCase() + ".*") && event.getDate().before(now)) { String timeDifference = getTimeDifferenceString(event.getDate(), now); bot.getIRC().cmdPRIVMSG(source, event.getUser() + "'s event \"" + event.getEventString() + "\" occurred " + timeDifference + " ago."); return; } } bot.getIRC().cmdPRIVMSG(source, "No event matching \"" + search + "\" was found in the events database."); } } @Override public String getHelp(String message) { return "Commands: " + commandPrefix + "uptime | Shows how long the bot has been running."; } @Override public void onLoad() { if(FileUtils.touchFile(eventsPath)) { FileUtils.writeFile(eventsPath, "[]"); } readEvents(); } @Override public void onUnload() { writeEvents(); } private int elapsed(Calendar before, Calendar after, int field) { Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected. int elapsed = -1; while (!clone.after(after)) { clone.add(field, 1); elapsed++; } return elapsed; } private String getTimeDifferenceString(Date date1, Date date2) { Calendar start = Calendar.getInstance(); start.setTime(date1); Calendar end = Calendar.getInstance(); end.setTime(date2); Integer[] elapsed = new Integer[3]; Calendar clone = (Calendar) start.clone(); // Otherwise changes are been reflected. elapsed[0] = elapsed(clone, end, Calendar.DATE); clone.add(Calendar.DATE, elapsed[0]); elapsed[1] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000; clone.add(Calendar.HOUR, elapsed[1]); elapsed[2] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000; clone.add(Calendar.MINUTE, elapsed[2]); return elapsed[0] + " day(s), " + elapsed[1] + " hour(s) and " + elapsed[2] + " minute(s)"; } private void readEvents() { try { JSONArray eventsArray = (JSONArray) new JSONParser().parse(FileUtils.readFile(eventsPath)); for(int i = 0; i < eventsArray.size(); i++) { JSONObject eventObject = (JSONObject) eventsArray.get(i); String user = eventObject.get("user").toString(); Date date = MyEvent.formatDate(eventObject.get("date").toString()); String eventString = eventObject.get("event").toString(); MyEvent event = new MyEvent(user, date, eventString); events.add(event); } } catch (ParseException e) { Logger.error("Module: Event", "The events database could not be read."); } } @SuppressWarnings("unchecked") private void writeEvents() { JSONArray eventsArray = new JSONArray(); for(MyEvent event : events) { JSONObject eventObject = new JSONObject(); eventObject.put("user", event.getUser()); eventObject.put("date", event.getFormattedDate()); eventObject.put("event", event.getEventString()); eventsArray.add(eventObject); } FileUtils.writeFile(eventsPath, eventsArray.toJSONString()); } }
package org.biojava.nbio.structure.test; import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.PDBFileParser; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.ChemCompProvider; import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import static org.junit.Assume.assumeNoException; import static org.junit.Assert.*; public class StructureToolsTest { Structure structure, structure2, structure3, structure4; @Before public void setUp() throws IOException { InputStream inStream = this.getClass().getResourceAsStream("/5pti.pdb"); assertNotNull(inStream); PDBFileParser pdbpars = new PDBFileParser(); structure = pdbpars.parsePDBFile(inStream) ; assertNotNull(structure); assertEquals("structure does not contain one chain ", 1 ,structure.size()); // since biojava 5, chains contain either only polymers or only nonpolymers: here we get the first protein chain with 58 residues Chain chain = structure.getChainByIndex(0); assertEquals("Wrong number of residues.",58,chain.getAtomLength()); inStream.close(); // Load structure2 inStream = this.getClass().getResourceAsStream("/1lnl.pdb"); assertNotNull(inStream); structure2 = pdbpars.parsePDBFile(inStream) ; assertNotNull(structure2); assertEquals("structure does not contain 3 chains ", 3 ,structure2.size()); inStream.close(); // Load structure3 inStream = this.getClass().getResourceAsStream("/1a4w.pdb"); assertNotNull(inStream); structure3 = pdbpars.parsePDBFile(inStream) ; assertNotNull(structure3); assertEquals("structure does not contain 3 chains ", 3 ,structure3.size()); inStream.close(); } @Test public void testGetCAAtoms(){ Atom[] cas = StructureTools.getRepresentativeAtomArray(structure); assertEquals("did not find the expected number of Atoms (58), but got " + cas.length,58,cas.length); } @Test public void testGetAtomsConsistency() throws IOException, StructureException{ //Save the existing ChemCompProvider ChemCompProvider provider = ChemCompGroupFactory.getChemCompProvider(); ChemCompGroupFactory.setChemCompProvider(new DownloadChemCompProvider()); AtomCache cache = new AtomCache(); FileParsingParameters params = new FileParsingParameters(); cache.setFileParsingParams(params); Structure hivA = cache.getStructure("1hiv.A"); Atom[] caSa = StructureTools.getRepresentativeAtomArray(hivA); Atom[] caCa = StructureTools.getRepresentativeAtomArray(hivA.getChainByIndex(0)); assertEquals("did not find the same number of Atoms from structure and from chain..", caSa.length,caCa.length); Structure hivB = cache.getStructure("1hiv.B"); Atom[] caSb = StructureTools.getRepresentativeAtomArray(hivB); Atom[] caCb = StructureTools.getRepresentativeAtomArray(hivB.getChainByIndex(0)); assertEquals("did not find the same number of Atoms from structure and from chain..", caSb.length,caCb.length); //Both chains have to be the same size (A and B) assertEquals(99,caSa.length); assertEquals("did not find the same number of Atoms in both chains...", caSa.length,caCb.length); assertEquals(99,caSa.length); ChemCompGroupFactory.setChemCompProvider(provider); } @Test public void testGetNrAtoms(){ int length = StructureTools.getNrAtoms(structure); assertEquals("did not find the expected number of Atoms (1087), but got " + length,1087,length); } @Test @SuppressWarnings("deprecation") public void testGetSubRanges() throws StructureException { String range; Structure substr; Chain chain; // normal substructures range = "A:3-7"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 5, chain.getAtomLength() ); // full chains range = "A"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); // since biojava 5, chains contain either only polymers or only nonpolymers: here we get the first protein chain with 408 residues assertEquals("Did not find the expected number of residues in "+range, 408, chain.getAtomLength() ); //assertEquals("subrange doesn't equal original chain A.", structure2.getChainByPDB("A"), chain); // full chains range = "A:"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); // since biojava 5, chains contain either only polymers or only nonpolymers: here we get the first protein chain with 408 residues assertEquals("Did not find the expected number of residues in "+range, 408, chain.getAtomLength() ); //assertEquals("subrange doesn't equal original chain A.", structure2.getChainByPDB("A"), chain); // combined ranges range = "A:3-7,B:8-12"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 2, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in first chain of "+range, 5, chain.getAtomLength() ); chain = substr.getChainByIndex(1); assertEquals("Did not find the expected number of residues in second chain of "+range, 5, chain.getAtomLength() ); // combined ranges range = "A,B:8-12"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 2, substr.size()); // since biojava 5, chains contain either only polymers or only nonpolymers: here we get the first protein chain with 408 residues chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in first chain of "+range, 408, chain.getAtomLength() ); chain = substr.getChainByIndex(1); assertEquals("Did not find the expected number of residues in second chain of "+range, 5, chain.getAtomLength() ); // parentheses range = "(A:3-7)"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 5, chain.getAtomLength() ); // single residue range = "A:3"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 1, chain.getAtomLength() ); // negative residues range = "A:-3"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 1, chain.getAtomLength() ); range = "A:-3--1"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 3, chain.getAtomLength() ); range = "A:-3-1"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 4, chain.getAtomLength() ); // Special '-' case range = "-"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Should have gotten whole structure",structure2, substr); // Test single-chain syntax range = "_:"; substr = StructureTools.getSubRanges(structure, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); // since biojava 5, chains contain either only polymers or only nonpolymers: here we get the first protein chain with 58 residues chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in first chain of "+range, 58, chain.getAtomLength() ); // Test single-chain syntax in a multi-chain structure. Should give chain A. range = "_:"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); // since biojava 5, chains contain either only polymers or only nonpolymers: here we get the first protein chain with 408 residues chain = substr.getChainByIndex(0); assertEquals("Chain _ not converted to chain A.","A",chain.getChainID()); assertEquals("Did not find the expected number of residues in first chain of "+range, 408, chain.getAtomLength() ); try { range = "X:"; substr = StructureTools.getSubRanges(structure2, range); fail("Illegal chain name in '"+range+"'. Should throw StructureException"); } catch(StructureException ex) {} //expected // some negative tests try { range = "7-10"; substr = StructureTools.getSubRanges(structure2, range); fail("Illegal range '"+range+"'. Should throw IllegalArgumentException"); } catch(IllegalArgumentException ex) {} //expected try { range = "A7-10"; substr = StructureTools.getSubRanges(structure2, range); fail("Illegal range '"+range+"'. Should throw IllegalArgumentException"); } catch(IllegalArgumentException ex) {} //expected } @Test public void testRevisedConvention() throws IOException, StructureException{ AtomCache cache = new AtomCache(); String name11 = "4hhb.A"; Structure s = cache.getStructure(name11); assertEquals(1,s.getPolyChains().size()); assertEquals(3,s.getChains().size()); // protein, HEM, water String name12 = "4hhb.A:"; s = cache.getStructure(name12); assertEquals(1,s.getPolyChains().size()); assertEquals(3,s.getChains().size()); String name13 = "4hhb.A_"; s = cache.getStructure(name13); assertEquals(1,s.getPolyChains().size()); assertEquals(3,s.getChains().size()); String name9 = "4hhb.C_1-83"; String chainId = "C"; s = cache.getStructure(name9); assertEquals(1,s.getPolyChains().size()); assertEquals(2,s.getChains().size()); // drops waters Chain c = s.getPolyChainByPDB(chainId); assertEquals(c.getName(),chainId); Atom[] ca = StructureTools.getRepresentativeAtomArray(s); assertEquals(83,ca.length); String name10 = "4hhb.C_1-83,A_1-10"; s = cache.getStructure(name10); assertEquals(2,s.getPolyChains().size()); assertEquals(3,s.getChains().size()); // Includes C heme ca = StructureTools.getRepresentativeAtomArray(s); assertEquals(93, ca.length); } // this will get replaced by // public void testStructureToolsRegexp(){ // Pattern p = ResidueRange.RANGE_REGEX; // String t2 = "A_10-20"; // Matcher m2 = p.matcher(t2); // assertNotNull(m2); // assertTrue(m2.find()); // assertTrue(m2.matches()); // // for (int i=0;i< m2.groupCount();i++){ // // String s = m2.group(i); // // System.out.println(s); // assertEquals(3,m2.groupCount()); // String t1 = "A:10-20"; // Matcher m1 = p.matcher(t1); // assertNotNull(m1); // assertTrue(m1.find()); // assertTrue(m1.matches()); // assertEquals(3,m1.groupCount()); // String t3 = "A"; // Matcher m3 = p.matcher(t3); // assertNotNull(m3); // assertTrue(m3.find()); // assertTrue(m3.matches()); // assertEquals(3,m3.groupCount()); /** * Test some subranges that we used to have problems with * @throws StructureException */ @Test @SuppressWarnings("deprecation") public void testGetSubRangesExtended() throws StructureException { String range; Structure substr; Chain chain; // negative indices range = "A:-3-7"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); // Note residue 0 is missing from 1lnl assertEquals("Did not find the expected number of residues in "+range, 10, chain.getAtomLength() ); // double negative indices range = "A:-3--1"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 3, chain.getAtomLength() ); // mixed indices range = "A:-3-+1"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 4, chain.getAtomLength() ); // positive indices range = "A:+1-6"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 6, chain.getAtomLength() ); // partial ranges range = "A:-+1"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 4, chain.getAtomLength() ); range = "A:--1"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 3, chain.getAtomLength() ); range = "A:^-+1"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 4, chain.getAtomLength() ); range = "A:^-$"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.getPolyChains().size()); chain = substr.getPolyChains().get(0); range = "A:400-"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 6, chain.getAtomLength() ); range = "A:400-$"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 6, chain.getAtomLength() ); // whitespace range = "A:3-7, B:8-12"; substr = StructureTools.getSubRanges(structure2, range); assertEquals("Wrong number of chains in "+range, 2, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in first chain of "+range, 5, chain.getAtomLength() ); chain = substr.getChainByIndex(1); assertEquals("Did not find the expected number of residues in second chain of "+range, 5, chain.getAtomLength() ); } /** * Test insertion codes * @throws StructureException */ @Test @SuppressWarnings("deprecation") public void testGetSubRangesInsertionCodes() throws StructureException { String range; Structure substr; Chain chain; // range including insertion range = "H:35-37"; //includes 36A substr = StructureTools.getSubRanges(structure3, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 4, chain.getAtomLength() ); // end with insertion range = "H:35-36A"; substr = StructureTools.getSubRanges(structure3, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 3, chain.getAtomLength() ); // begin with insertion range = "H:36A-38"; //includes 36A substr = StructureTools.getSubRanges(structure3, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 3, chain.getAtomLength() ); // within insertion range = "L:14-14K"; substr = StructureTools.getSubRanges(structure3, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 12, chain.getAtomLength() ); // within insertion range = "L:14C-14J"; substr = StructureTools.getSubRanges(structure3, range); assertEquals("Wrong number of chains in "+range, 1, substr.size()); chain = substr.getChainByIndex(0); assertEquals("Did not find the expected number of residues in "+range, 8, chain.getAtomLength() ); } public void testGroupsWithinShell() { //TODO } @Test public void testCAmmCIF() throws StructureException { //Save the existing ChemCompProvider ChemCompProvider provider = ChemCompGroupFactory.getChemCompProvider(); ChemCompGroupFactory.setChemCompProvider(new DownloadChemCompProvider()); //mmCIF files left justify their atom names (eg "CA "), so can have different behavior AtomCache pdbCache = new AtomCache(); pdbCache.setUseMmCif(false); FileParsingParameters params = new FileParsingParameters(); pdbCache.setFileParsingParams(params); AtomCache mmcifCache = new AtomCache(); mmcifCache.setUseMmCif(true); FileParsingParameters params2 = new FileParsingParameters(); mmcifCache.setFileParsingParams(params2); Structure pdb=null, mmcif=null; String name = "3PIU"; try { pdb = pdbCache.getStructure(name); mmcif = mmcifCache.getStructure(name); } catch (IOException e) { assumeNoException(e); } Atom[] pdbCA = StructureTools.getRepresentativeAtomArray(pdb); Atom[] mmcifCA = StructureTools.getRepresentativeAtomArray(mmcif); assertEquals("PDB has wrong length",409,pdbCA.length); assertEquals("PDB has wrong length",409,mmcifCA.length); ChemCompGroupFactory.setChemCompProvider(provider); } @Test public void testGetRepresentativeAtomsProtein() throws StructureException, IOException { Structure s = StructureIO.getStructure("1smt"); Chain c = s.getChain(0); Atom[] atoms = StructureTools.getRepresentativeAtomArray(c); assertEquals(98,atoms.length); Chain clonedChain = (Chain)c.clone(); atoms = StructureTools.getRepresentativeAtomArray(clonedChain); assertEquals(98,atoms.length); } @Test public void testGetRepresentativeAtomsDna() throws StructureException, IOException { Structure s = StructureIO.getStructure("2pvi"); Chain c = s.getChainByPDB("C"); Atom[] atoms = StructureTools.getRepresentativeAtomArray(c); // chain C (1st nucleotide chain) // actually it should be 13, but at the moment one of the nucleotides is not caught correctly because it's non-standard assertEquals(12,atoms.length); Chain clonedChain = (Chain)c.clone(); atoms = StructureTools.getRepresentativeAtomArray(clonedChain); // chain C (1st nucleotide chain) assertEquals(12,atoms.length); } }
package org.biojava.bio.structure.io; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.StructureException; import org.biojava.bio.structure.StructureTools; import org.biojava.bio.structure.align.model.AFP; import org.biojava.bio.structure.align.model.AFPChain; import org.biojava.bio.structure.align.util.AtomCache; import org.biojava.bio.structure.align.xml.AFPChainXMLConverter; import org.biojava3.core.sequence.ProteinSequence; import org.custommonkey.xmlunit.DetailedDiff; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.Difference; import org.custommonkey.xmlunit.XMLUnit; import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; /** * A test for {@link FastaAFPChainConverter}. * @author dmyersturnbull * */ public class FastaAFPChainConverterTest { static { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreComments(true); XMLUnit.setIgnoreAttributeOrder(true); } public static void printDetailedDiff(Diff diff, PrintStream ps) { DetailedDiff detDiff = new DetailedDiff(diff); for (Object object : detDiff.getAllDifferences()) { Difference difference = (Difference) object; ps.println(difference); } } /** * Compares two XML files without regard to the order of elements or attributes, and ignoring any element named \"releaseDate\". * @return Whether the files are \"similar\" */ public static boolean compareXml(File expectedFile, File actualFile) { try { FileReader expectedFr = new FileReader(expectedFile); FileReader actualFr = new FileReader(actualFile); Diff diff = new Diff(expectedFr, actualFr); // ignore order // look at element, id, and weight (weight is a nested element) diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); final boolean isSimilar = diff.similar(); if (!isSimilar) printDetailedDiff(diff, System.err); expectedFr.close(); actualFr.close(); return isSimilar; } catch (IOException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } } private AtomCache cache; @Before public void setUp() { cache = new AtomCache(); } @Test public void testCpAsymmetric() throws IOException, StructureException { Structure structure = cache.getStructure("1w0p"); String first = ("alfdynatgdtefdspakqgwmqdntnngsgvltnadgmpawlvqgiggraqwtyslstnqhaqassfgwrmttemkvlsggmitnyyangtqrvlpiisldssgnlvvefegqtgrtvlatgtaateyhkfelvflpgsnpsasfyfdgklirdniqptaskQNMIVWGNGSSntdgvaayrdikfei String second = (" AFPChain afpChain = FastaAFPChainConverter.cpFastaToAfpChain(first, second, structure, -393); // TODO } @Test public void testCpSymmetric2() throws IOException,StructureException { String a = "--vRSLNCTLRDSQQ-KSLVMSG String b = "esnDKIPVALGLKEKnLYLSSVLkddKPTLQLESVDpknypkkkmekRFVFNKIEINN Structure structure = StructureTools.getStructure("31BI"); AFPChain afpChain = FastaAFPChainConverter.cpFastaToAfpChain(a, b, structure, 104); assertEquals("Wrong TM-score", 0.6284, afpChain.getTMScore(), 0.001); // TODO } @Test public void testCpSymmetric1() throws IOException,StructureException { //cat 2GG6-best.fasta |tr -d \\n|pbcopy String a = "-SSRPATAR-KSSGLSGTVRIPGDKSISHRSFMFGGLA-SGETRITGLLEG-EDvINTGKAMQAMGARIRKEGd String b = "dGVRTIRLEgRGKLTGQVIDVPGDPSSTAFPLVAALLVpGSDVTILNVLMNpTR-TGLILTLQEMGADIEVINprlaggedvaDLRVRSS Structure structure = StructureTools.getStructure("2GG6"); AFPChain afpChain = FastaAFPChainConverter.cpFastaToAfpChain(a, b, structure, 215); // TODO } // TODO I probably broke this test // @Test public void testIncomplete() throws IOException, StructureException { Structure s1 = cache.getStructure("1w0p"); Structure s2 = cache.getStructure("1qdm"); ProteinSequence seq1 = new ProteinSequence("GWGG ProteinSequence seq2 = new ProteinSequence("WMQNQLAQNKT--QDLILDYVNQLCNRL AFPChain afpChain = FastaAFPChainConverter.fastaToAfpChain(seq1, seq2, s1, s2); assertEquals("Wrong number of EQRs", 33, afpChain.getNrEQR()); String xml = AFPChainXMLConverter.toXML(afpChain); System.out.println(xml); File expected = new File("src/test/resources/1w0p_1qdm.xml"); File x = File.createTempFile("1w0p_1qdm_output", "xml.tmp"); x.deleteOnExit(); BufferedWriter bw = new BufferedWriter(new FileWriter(x)); bw.write(xml); bw.close(); assertTrue("AFPChain is wrong", compareXml(expected, x)); } }
package io.jenkins.blueocean.service.embedded.rest; import hudson.console.AnnotatedLargeText; import io.jenkins.blueocean.commons.ServiceException; import org.kohsuke.stapler.AcceptHeader; import org.kohsuke.stapler.Header; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.framework.io.CharSpool; import org.kohsuke.stapler.framework.io.LineEndNormalizingWriter; import javax.annotation.Nonnull; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * @author Vivek Pandey */ public class LogResource{ public static final long DEFAULT_LOG_THREASHOLD = 150; private final AnnotatedLargeText logText; private final Reader appenderLogReader; public LogResource(AnnotatedLargeText log) { this(log, LogAppender.DEFAULT); } public LogResource(@Nonnull AnnotatedLargeText log, @Nonnull LogAppender logAppender) { this.logText = log; this.appenderLogReader = logAppender.getLog(); } public void doIndex(StaplerRequest req, StaplerResponse rsp, @Header("Accept") AcceptHeader accept){ writeLog(req,rsp,accept); } private void writeLog(StaplerRequest req, StaplerResponse rsp, AcceptHeader accept) { try { String download = req.getParameter("download"); if("true".equalsIgnoreCase(download)) { rsp.setHeader("Content-Disposition", "attachment; filename=log.txt"); } rsp.setContentType("text/plain;charset=UTF-8"); rsp.setStatus(HttpServletResponse.SC_OK); writeLogs(req, rsp); } catch (IOException e) { throw new ServiceException.UnexpectedErrorException("Failed to get logText: " + e.getMessage(), e); } } private void writeLogs(StaplerRequest req, StaplerResponse rsp) throws IOException { long threshold = DEFAULT_LOG_THREASHOLD * 1024; String s = req.getParameter("thresholdInKB"); if(s!=null) { threshold = Long.parseLong(s) * 1024; } long offset; if(req.getParameter("start") != null){ offset = Long.parseLong(req.getParameter("start")); }else if(logText.length() > threshold){ offset = logText.length()-threshold; } else{ offset = 0; } CharSpool spool = new CharSpool(); long r = logText.writeLogTo(offset,spool); Writer w = createWriter(req, rsp, r - offset); spool.writeTo(new LineEndNormalizingWriter(w)); if(!logText.isComplete()) { rsp.addHeader("X-More-Data", "true"); }else{ int text = appenderLogReader.read(); while(text != -1){ w.write(text); r++; text = appenderLogReader.read(); } } rsp.addHeader("X-Text-Size", String.valueOf(r)); rsp.addHeader("X-Text-Delivered", String.valueOf(r - offset)); w.close(); } private Writer createWriter(StaplerRequest req, StaplerResponse rsp, long size) throws IOException { // when sending big text, try compression. don't bother if it's small if(size >4096) return rsp.getCompressedWriter(req); else return rsp.getWriter(); } }
package com.tinkerpop.blueprints.impls.neo4j; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.EdgeTestSuite; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.GraphTestSuite; import com.tinkerpop.blueprints.Index; import com.tinkerpop.blueprints.IndexTestSuite; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.IndexableGraphTestSuite; import com.tinkerpop.blueprints.KeyIndexableGraphTestSuite; import com.tinkerpop.blueprints.Parameter; import com.tinkerpop.blueprints.QueryTestSuite; import com.tinkerpop.blueprints.TestSuite; import com.tinkerpop.blueprints.TransactionalGraphTestSuite; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.VertexTestSuite; import com.tinkerpop.blueprints.impls.GraphTest; import com.tinkerpop.blueprints.util.io.gml.GMLReaderTestSuite; import com.tinkerpop.blueprints.util.io.graphml.GraphMLReaderTestSuite; import com.tinkerpop.blueprints.util.io.graphson.GraphSONReaderTestSuite; import org.neo4j.index.impl.lucene.LowerCaseKeywordAnalyzer; import org.neo4j.kernel.EmbeddedReadOnlyGraphDatabase; import java.io.File; import java.lang.reflect.Method; import java.util.Iterator; public class Neo4jGraphTest extends GraphTest { /*public void testNeo4jBenchmarkTestSuite() throws Exception { this.stopWatch(); doTestSuite(new Neo4jBenchmarkTestSuite(this)); printTestPerformance("Neo4jBenchmarkTestSuite", this.stopWatch()); }*/ public void testVertexTestSuite() throws Exception { this.stopWatch(); doTestSuite(new VertexTestSuite(this)); printTestPerformance("VertexTestSuite", this.stopWatch()); } public void testEdgeTestSuite() throws Exception { this.stopWatch(); doTestSuite(new EdgeTestSuite(this)); printTestPerformance("EdgeTestSuite", this.stopWatch()); } public void testGraphTestSuite() throws Exception { this.stopWatch(); doTestSuite(new GraphTestSuite(this)); printTestPerformance("GraphTestSuite", this.stopWatch()); } public void testQueryTestSuite() throws Exception { this.stopWatch(); doTestSuite(new QueryTestSuite(this)); printTestPerformance("QueryTestSuite", this.stopWatch()); } public void testKeyIndexableGraphTestSuite() throws Exception { this.stopWatch(); doTestSuite(new KeyIndexableGraphTestSuite(this)); printTestPerformance("KeyIndexableGraphTestSuite", this.stopWatch()); } public void testIndexableGraphTestSuite() throws Exception { this.stopWatch(); doTestSuite(new IndexableGraphTestSuite(this)); printTestPerformance("IndexableGraphTestSuite", this.stopWatch()); } public void testIndexTestSuite() throws Exception { this.stopWatch(); doTestSuite(new IndexTestSuite(this)); printTestPerformance("IndexTestSuite", this.stopWatch()); } public void testTransactionalGraphTestSuite() throws Exception { this.stopWatch(); doTestSuite(new TransactionalGraphTestSuite(this)); printTestPerformance("TransactionalGraphTestSuite", this.stopWatch()); } public void testGraphMLReaderTestSuite() throws Exception { this.stopWatch(); doTestSuite(new GraphMLReaderTestSuite(this)); printTestPerformance("GraphMLReaderTestSuite", this.stopWatch()); } public void testGraphSONReaderTestSuite() throws Exception { this.stopWatch(); doTestSuite(new GraphSONReaderTestSuite(this)); printTestPerformance("GraphSONReaderTestSuite", this.stopWatch()); } public void testGMLReaderTestSuite() throws Exception { this.stopWatch(); doTestSuite(new GMLReaderTestSuite(this)); printTestPerformance("GMLReaderTestSuite", this.stopWatch()); } public Graph generateGraph() { String directory = this.getWorkingDirectory(); Neo4jGraph graph = new Neo4jGraph(directory); graph.setCheckElementsInTransaction(true); return graph; } public void doTestSuite(final TestSuite testSuite) throws Exception { String directory = this.getWorkingDirectory(); deleteDirectory(new File(directory)); for (Method method : testSuite.getClass().getDeclaredMethods()) { if (method.getName().startsWith("test")) { System.out.println("Testing " + method.getName() + "..."); method.invoke(testSuite); deleteDirectory(new File(directory)); } } } private String getWorkingDirectory() { return this.computeTestDataRoot().getAbsolutePath(); } public void testLongIdConversions() { String id1 = "100"; // good 100 String id2 = "100.0"; // good 100 String id3 = "100.1"; // good 100 String id4 = "one"; // bad try { Double.valueOf(id1).longValue(); assertTrue(true); } catch (NumberFormatException e) { assertFalse(true); } try { Double.valueOf(id2).longValue(); assertTrue(true); } catch (NumberFormatException e) { assertFalse(true); } try { Double.valueOf(id3).longValue(); assertTrue(true); } catch (NumberFormatException e) { assertFalse(true); } try { Double.valueOf(id4).longValue(); assertTrue(false); } catch (NumberFormatException e) { assertFalse(false); } } public void testQueryIndex() throws Exception { String directory = this.getWorkingDirectory(); deleteDirectory(new File(directory)); Neo4jGraph graph = new Neo4jGraph(directory); Index<Vertex> vertexIndex = graph.createIndex("vertices", Vertex.class); Index<Edge> edgeIndex = graph.createIndex("edges", Edge.class); Vertex a = graph.addVertex(null); a.setProperty("name", "marko"); vertexIndex.put("name", "marko", a); Iterator itty = graph.getIndex("vertices", Vertex.class).query("name", "*rko").iterator(); int counter = 0; while (itty.hasNext()) { counter++; assertEquals(itty.next(), a); } assertEquals(counter, 1); Vertex b = graph.addVertex(null); Edge edge = graph.addEdge(null, a, b, "knows"); edge.setProperty("weight", 0.75); edgeIndex.put("weight", 0.75, edge); itty = graph.getIndex("edges", Edge.class).query("label", "k?ows").iterator(); counter = 0; while (itty.hasNext()) { counter++; assertEquals(itty.next(), edge); } assertEquals(counter, 0); itty = graph.getIndex("edges", Edge.class).query("weight", "[0.5 TO 1.0]").iterator(); counter = 0; while (itty.hasNext()) { counter++; assertEquals(itty.next(), edge); } assertEquals(counter, 1); assertEquals(count(graph.getIndex("edges", Edge.class).query("weight", "[0.1 TO 0.5]")), 0); graph.shutdown(); deleteDirectory(new File(directory)); } public void testIndexParameters() throws Exception { String directory = this.getWorkingDirectory(); deleteDirectory(new File(directory)); IndexableGraph graph = new Neo4jGraph(directory); Index<Vertex> index = graph.createIndex("luceneIdx", Vertex.class, new Parameter<String, String>("analyzer", LowerCaseKeywordAnalyzer.class.getName())); Vertex a = graph.addVertex(null); a.setProperty("name", "marko"); index.put("name", "marko", a); Iterator itty = index.query("name", "*rko").iterator(); int counter = 0; while (itty.hasNext()) { counter++; assertEquals(itty.next(), a); } assertEquals(counter, 1); itty = index.query("name", "MaRkO").iterator(); counter = 0; while (itty.hasNext()) { counter++; assertEquals(itty.next(), a); } assertEquals(counter, 1); graph.shutdown(); deleteDirectory(new File(this.getWorkingDirectory())); } public void testReadOnlyGraph() throws Exception { String directory = this.getWorkingDirectory(); deleteDirectory(new File(directory)); Neo4jGraph graph = new Neo4jGraph(directory); assertEquals(graph.getIndexedKeys(Vertex.class).size(), 0); assertFalse(graph.getIndexedKeys(Vertex.class).contains("name")); graph.createKeyIndex("name", Vertex.class); graph.addVertex(null).setProperty("name", "marko"); graph.addVertex(null).setProperty("name", "matthias"); assertEquals(graph.getIndexedKeys(Vertex.class).size(), 1); assertTrue(graph.getIndexedKeys(Vertex.class).contains("name")); graph.shutdown(); graph = new Neo4jGraph(new EmbeddedReadOnlyGraphDatabase(directory)); assertEquals(count(graph.getVertices()), 2); assertEquals(count(graph.getVertices("name", "marko")), 1); assertEquals(count(graph.getVertices("name", "matthias")), 1); assertEquals(graph.getIndexedKeys(Vertex.class).size(), 1); assertTrue(graph.getIndexedKeys(Vertex.class).contains("name")); graph.shutdown(); deleteDirectory(new File(directory)); } }
package gov.nih.nci.cagrid.cadsr.service; import gov.nih.nci.cadsr.domain.DataElement; import gov.nih.nci.cadsr.umlproject.domain.Project; import gov.nih.nci.cadsr.umlproject.domain.SemanticMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLAssociationMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLAttributeMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLClassMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLPackageMetadata; import gov.nih.nci.cagrid.cadsr.common.CaDSRUtils; import gov.nih.nci.cagrid.cadsr.domain.UMLAssociation; import gov.nih.nci.cagrid.metadata.common.UMLClass; import gov.nih.nci.cagrid.metadata.dataservice.DomainModel; import gov.nih.nci.cagrid.metadata.dataservice.DomainModelExposedUMLAssociationCollection; import gov.nih.nci.cagrid.metadata.dataservice.DomainModelExposedUMLClassCollection; import gov.nih.nci.cagrid.metadata.dataservice.UMLAssociationEdge; import gov.nih.nci.cagrid.metadata.dataservice.UMLAssociationSourceUMLAssociationEdge; import gov.nih.nci.cagrid.metadata.dataservice.UMLAssociationTargetUMLAssociationEdge; import gov.nih.nci.cagrid.metadata.dataservice.UMLClassReference; import gov.nih.nci.system.applicationservice.ApplicationException; import gov.nih.nci.system.applicationservice.ApplicationService; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * DomainModelBuilder Builds a DomainModel * * @author <A HREF="MAILTO:ervin@bmi.osu.edu">David W. Ervin</A> * * @created Jun 1, 2006 * @version $Id$ */ public class DomainModelBuilder { protected static Log LOG = LogFactory.getLog(DomainModelBuilder.class.getName()); // Project -> (packageName, UMLPackageMetadata) private static Map projectUmlPackages = null; // UMLPackageMetadata -> Set(UMLClassMetadata) private static Map packageClasses = null; // UMLClassMetadata -> Set(UMLAssociationMetadata) private static Map classAssociations = null; private ApplicationService cadsr = null; private Project mostRecentCompleteProject = null; public DomainModelBuilder(ApplicationService cadsr) { this.cadsr = cadsr; } /** * Gets a DomainModel that represents the entire project * * @param proj * @return */ public DomainModel getDomainModel(Project proj) throws RemoteException { // find all packages in the project and hand off to // getDomainModel(Package, String[]); Project completeProject = findCompleteProject(proj); Map umlPackages = getPackagesFromProject(completeProject); String[] packageNames = new String[umlPackages.keySet().size()]; umlPackages.keySet().toArray(packageNames); return getDomainModel(completeProject, packageNames); } /** * Gets a DomainModel that represents the project and packages * * @param proj * The project to build a domain model for * @param packageNames * The names of packages to include in the domain model * @return * @throws RemoteException */ public DomainModel getDomainModel(Project proj, String[] packageNames) throws RemoteException { // find the complete project Project completeProject = findCompleteProject(proj); // grab the classes out of the packages List classes = new ArrayList(); if (packageNames != null) { for (int i = 0; i < packageNames.length; i++) { UMLPackageMetadata pack = getPackageMetadata(completeProject, packageNames[i]); UMLClassMetadata[] mdArray = getClasses(completeProject, pack); Collections.addAll(classes, mdArray); } } UMLClassMetadata[] classArray = new UMLClassMetadata[classes.size()]; classes.toArray(classArray); // grab associations for each class List associationMetadataList = new ArrayList(); for (int i = 0; i < classArray.length; i++) { UMLClassMetadata clazz = classArray[i]; UMLAssociationMetadata[] mdArray = getAssociations(completeProject, clazz); Collections.addAll(associationMetadataList, mdArray); } UMLAssociation[] associationArray = new UMLAssociation[associationMetadataList.size()]; for (int i = 0; i < associationMetadataList.size(); i++) { UMLAssociationMetadata assocMd = (UMLAssociationMetadata) associationMetadataList.get(i); associationArray[i] = CaDSRUtils.convertAssociation(assocMd); } // hand off return getDomainModel(completeProject, classArray, associationArray); } /** * Generates a DomainModel that represents the project and the given subset * of classes and associations * * @param proj * The project to build a domain model for * @param classes * The classes to include in the domain model * @param associations * The asociations to include in the domain model * @return * @throws RemoteException */ public DomainModel getDomainModel(Project proj, UMLClassMetadata[] classes, UMLAssociation[] associations) throws RemoteException { // find the proper project from the caDSR first Project completeProject = findCompleteProject(proj); DomainModel model = new DomainModel(); // project model.setProjectDescription(completeProject.getDescription()); model.setProjectLongName(completeProject.getLongName()); model.setProjectShortName(completeProject.getShortName()); model.setProjectVersion(completeProject.getVersion()); // classes DomainModelExposedUMLClassCollection exposedClasses = new DomainModelExposedUMLClassCollection(); if (classes != null) { UMLClass[] umlClasses = new UMLClass[classes.length]; for (int i = 0; i < classes.length; i++) { umlClasses[i] = CaDSRUtils.convertClass(classes[i]); } exposedClasses.setUMLClass(umlClasses); } model.setExposedUMLClassCollection(exposedClasses); // associations DomainModelExposedUMLAssociationCollection exposedAssociations = new DomainModelExposedUMLAssociationCollection(); if (associations != null) { gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation[] umlAssociations = new gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation[associations.length]; for (int i = 0; i < associations.length; i++) { umlAssociations[i] = convertAssociation(associations[i]); } exposedAssociations.setUMLAssociation(umlAssociations); } model.setExposedUMLAssociationCollection(exposedAssociations); return model; } private gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation convertAssociation(UMLAssociation cadsrAssociation) { gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation converted = new gov.nih.nci.cagrid.metadata.dataservice.UMLAssociation(); converted.setBidirectional(cadsrAssociation.isIsBidirectional()); UMLAssociationSourceUMLAssociationEdge convertedSourceEdge = new UMLAssociationSourceUMLAssociationEdge(); UMLAssociationEdge sourceEdge = new UMLAssociationEdge(); sourceEdge.setMaxCardinality(cadsrAssociation.getSourceMaxCardinality()); sourceEdge.setMinCardinality(cadsrAssociation.getSourceMinCardinality()); sourceEdge.setRoleName(cadsrAssociation.getSourceRoleName()); if (sourceEdge.getRoleName() == null) { sourceEdge.setRoleName(""); } sourceEdge.setUMLClassReference(new UMLClassReference(cadsrAssociation.getSourceUMLClassMetadata() .getUMLClassMetadata().getId())); convertedSourceEdge.setUMLAssociationEdge(sourceEdge); converted.setSourceUMLAssociationEdge(convertedSourceEdge); UMLAssociationTargetUMLAssociationEdge convertedTargetEdge = new UMLAssociationTargetUMLAssociationEdge(); UMLAssociationEdge targetEdge = new UMLAssociationEdge(); targetEdge.setMaxCardinality(cadsrAssociation.getTargetMaxCardinality()); targetEdge.setMinCardinality(cadsrAssociation.getTargetMinCardinality()); targetEdge.setRoleName(cadsrAssociation.getTargetRoleName()); if (targetEdge.getRoleName() == null) { targetEdge.setRoleName(""); } targetEdge.setUMLClassReference(new UMLClassReference(cadsrAssociation.getTargetUMLClassMetadata() .getUMLClassMetadata().getId())); convertedTargetEdge.setUMLAssociationEdge(targetEdge); converted.setTargetUMLAssociationEdge(convertedTargetEdge); return converted; } private UMLPackageMetadata getPackageMetadata(Project proj, String packageName) throws RemoteException { Map umlPackages = getPackagesFromProject(proj); UMLPackageMetadata pack = (UMLPackageMetadata) umlPackages.get(packageName); return pack; } private Map getPackagesFromProject(Project proj) throws RemoteException { if (projectUmlPackages == null) { projectUmlPackages = new HashMap(); } Map umlPackages = (Map) projectUmlPackages.get(proj); if (umlPackages == null) { LOG.debug("Project " + proj.getLongName() + " not yet cached"); // project not yet in the cache umlPackages = new HashMap(); // get packages for project from cadsr application service UMLPackageMetadata packagePrototype = new UMLPackageMetadata(); packagePrototype.setProject(proj); try { List packs = cadsr.search(UMLPackageMetadata.class, packagePrototype); Iterator packIter = packs.iterator(); while (packIter.hasNext()) { UMLPackageMetadata pack = (UMLPackageMetadata) packIter.next(); umlPackages.put(pack.getName(), pack); } // put the packages in the project -> package mapping cache projectUmlPackages.put(proj, umlPackages); LOG.debug("Added " + umlPackages.size() + " packages to cache for project " + proj.getLongName()); } catch (ApplicationException ex) { LOG.error("Error searching for packages: " + ex.getMessage()); throw new RemoteException("Error searching for packages: " + ex.getMessage(), ex); } } return umlPackages; } private UMLClassMetadata[] getClasses(Project proj, UMLPackageMetadata pack) throws RemoteException { if (packageClasses == null) { packageClasses = new HashMap(); } UMLClassMetadata[] classes = (UMLClassMetadata[]) packageClasses.get(pack); if (classes == null) { LOG.debug("Classes for package " + pack.getName() + " not yet cached"); UMLClassMetadata classPrototype = new UMLClassMetadata(); classPrototype.setUMLPackageMetadata(pack); classPrototype.setProject(proj); try { Iterator classListIter = cadsr.search(UMLClassMetadata.class, classPrototype).iterator(); List classList = new ArrayList(); while (classListIter.hasNext()) { UMLClassMetadata metadata = (UMLClassMetadata) classListIter.next(); // ensure the attributes and semantic metadata are brought back Iterator attribIter = metadata.getUMLAttributeMetadataCollection().iterator(); while (attribIter.hasNext()) { UMLAttributeMetadata att = (UMLAttributeMetadata) attribIter.next(); DataElement de = att.getDataElement(); de.getContext(); de.getDataElementConcept().getObjectClass(); String typeName = de.getValueDomain().getDatatypeName(); LOG.debug(typeName); if (att.getDescription() == null) { att.setDescription(""); } } Iterator smIter = metadata.getSemanticMetadataCollection().iterator(); while (smIter.hasNext()) { SemanticMetadata sm = (SemanticMetadata) smIter.next(); LOG.debug(sm.getConceptCode()); LOG.debug(sm.getConcept().getLongName()); } classList.add(metadata); } classes = new UMLClassMetadata[classList.size()]; classList.toArray(classes); // cache the classes array packageClasses.put(pack, classes); LOG.debug("Added " + classes.length + " classes to cache for package " + pack.getName()); } catch (ApplicationException ex) { LOG.error("Error searching for classes in package: " + pack.getName() + ": " + ex.getMessage()); throw new RemoteException("Error searching for classes in package: " + pack.getName() + ": " + ex.getMessage(), ex); } } return classes; } private UMLAssociationMetadata[] getAssociations(Project proj, UMLClassMetadata clazz) throws RemoteException { if (classAssociations == null) { classAssociations = new HashMap(); } UMLAssociationMetadata[] associations = (UMLAssociationMetadata[]) classAssociations.get(clazz); if (associations == null) { LOG.debug("Associations for class " + clazz.getFullyQualifiedName() + " not yet cached"); UMLAssociationMetadata associationPrototype = new UMLAssociationMetadata(); associationPrototype.setSourceUMLClassMetadata(clazz); associationPrototype.setProject(proj); try { Iterator associationListIter = cadsr.search( UMLAssociationMetadata.class, associationPrototype).iterator(); List associationList = new ArrayList(); while (associationListIter.hasNext()) { UMLAssociationMetadata metadata = (UMLAssociationMetadata) associationListIter.next(); // force population of these fields metadata.getSourceUMLClassMetadata(); metadata.getTargetUMLClassMetadata(); associationList.add(metadata); } associations = new UMLAssociationMetadata[associationList.size()]; associationList.toArray(associations); // cache the associations classAssociations.put(clazz, associations); LOG.debug("Added " + associations.length + " associations to cache for class " + clazz.getFullyQualifiedName()); } catch (ApplicationException ex) { LOG.error("Error searching for associations on class " + clazz.getFullyQualifiedName() + ": " + ex.getMessage()); throw new RemoteException("Error searching for associations on class " + clazz.getFullyQualifiedName() + ": " + ex.getMessage(), ex); } } return associations; } private Project findCompleteProject(Project prototype) throws RemoteException { if (prototype != mostRecentCompleteProject) { List completeProjects = new ArrayList(); Iterator projectIter = null; try { projectIter = cadsr.search(Project.class, prototype).iterator(); } catch (ApplicationException ex) { throw new RemoteException("Error retrieving complete project: " + ex.getMessage(), ex); } // should be ONLY ONE project from the caDSR while (projectIter.hasNext()) { completeProjects.add(projectIter.next()); } if (completeProjects.size() == 1) { mostRecentCompleteProject = (Project) completeProjects.get(0); } else if (completeProjects.size() == 0) { throw new RemoteException("No project found in caDSR"); } else { throw new RemoteException("More than one project (" + completeProjects.size() + ") found. Prototype project is ambiguous"); } } return mostRecentCompleteProject; } }
package org.csstudio.utility.pv.epics; import gov.aps.jca.Channel; import gov.aps.jca.Channel.ConnectionState; import gov.aps.jca.Monitor; import gov.aps.jca.dbr.DBR; import gov.aps.jca.dbr.DBRType; import gov.aps.jca.event.ConnectionEvent; import gov.aps.jca.event.ConnectionListener; import gov.aps.jca.event.GetEvent; import gov.aps.jca.event.GetListener; import gov.aps.jca.event.MonitorEvent; import gov.aps.jca.event.MonitorListener; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.csstudio.data.values.IMetaData; import org.csstudio.data.values.IValue; import org.csstudio.platform.libs.epics.EpicsPlugin.MonitorMask; import org.csstudio.utility.pv.PV; import org.csstudio.utility.pv.PVListener; import org.eclipse.core.runtime.PlatformObject; /** EPICS ChannelAccess implementation of the PV interface. * * @see PV * @author Kay Kasemir */ @SuppressWarnings("nls") public class EPICS_V3_PV extends PlatformObject implements PV, ConnectionListener, MonitorListener { /** Use plain mode? * @see #EPICS_V3_PV(String, boolean) */ final private boolean plain; /** Channel name. */ final private String name; private enum State { /** Nothing happened, yet */ Idle, /** Trying to connect */ Connecting, /** Got basic connection */ Connected, /** Requested MetaData */ GettingMetadata, /** Received MetaData */ GotMetaData, /** Subscribing to receive value updates */ Subscribing, /** Received Value Updates * <p> * This is the ultimate state! */ GotMonitor, /** Got disconnected */ Disconnected } private State state = State.Idle; /** PVListeners of this PV */ final private CopyOnWriteArrayList<PVListener> listeners = new CopyOnWriteArrayList<PVListener>(); /** JCA channel. LOCK <code>this</code> on change. */ private RefCountedChannel channel_ref = null; /** Either <code>null</code>, or the subscription identifier. * LOCK <code>this</code> on change */ private Monitor subscription = null; /** isConnected? * <code>true</code> if we are currently connected * (based on the most recent connection callback). * <p> * EPICS_V3_PV also runs notifyAll() on <code>this</code> * whenever the connected flag changes to <code>true</code>. */ private volatile boolean connected = false; /** Meta data obtained during connection cycle. */ private IMetaData meta = null; /** Most recent 'live' value. */ private IValue value = null; /** isRunning? * <code>true</code> if we want to receive value updates. */ private volatile boolean running = false; /** Listener to the get... for meta data */ private final GetListener meta_get_listener = new GetListener() { @Override public void getCompleted(final GetEvent event) { // This runs in a CA thread if (event.getStatus().isSuccessful()) { state = State.GotMetaData; final DBR dbr = event.getDBR(); meta = DBR_Helper.decodeMetaData(dbr); Activator.getLogger().log(Level.FINEST, "{0} meta: {1}", new Object[] { name, meta }); } else { Activator.getLogger().log(Level.WARNING, "{0} meta data get error: {1}", new Object[] { name, event.getStatus().getMessage() }); } // Subscribe, but outside of callback (JCA deadlocks) PVContext.scheduleCommand(new Runnable() { @Override public void run() { subscribe(); } }); } }; /** Listener to a get-callback for data. */ private class GetCallbackListener implements GetListener { /** The received meta data/ */ IMetaData meta = null; /** The received value. */ IValue value = null; /** After updating <code>meta</code> and <code>value</code>, * this flag is set, and then <code>notify</code> is invoked * on <code>this</code>. */ boolean got_response = false; public void reset() { got_response = false; } @Override public void getCompleted(final GetEvent event) { // This runs in a CA thread if (event.getStatus().isSuccessful()) { final DBR dbr = event.getDBR(); meta = DBR_Helper.decodeMetaData(dbr); try { value = DBR_Helper.decodeValue(plain, meta, dbr); } catch (final Exception ex) { Activator.getLogger().log(Level.WARNING, "PV " + name, ex); value = null; } Activator.getLogger().log(Level.FINEST, "{0} meta: {1}, value {2}", new Object[] { name, meta, value }); } else { meta = null; value = null; } synchronized (this) { got_response = true; this.notifyAll(); } } } private final GetCallbackListener get_callback = new GetCallbackListener(); /** Generate an EPICS PV. * @param name The PV name. */ public EPICS_V3_PV(final String name) { this(name, false); } /** Generate an EPICS PV. * @param name The PV name. * @param plain When <code>true</code>, only the plain value is requested. * No time etc. * Some PVs only work in plain mode, example: "record.RTYP". */ public EPICS_V3_PV(final String name, final boolean plain) { this.name = name; this.plain = plain; Activator.getLogger().finer(name + " created as EPICS_V3_PV"); } /** Use finalize as last resort for cleanup, but give warnings. */ @Override protected void finalize() throws Throwable { super.finalize(); if (channel_ref != null) { Activator.getLogger().warning("EPICS_V3_PV " + name + " not properly stopped"); try { stop(); } catch (final Throwable ex) { Activator.getLogger().log(Level.WARNING, name + " finalize error", ex); } } Activator.getLogger().finer(name + " finalized."); } /** @return Returns the name. */ @Override public String getName() { return EPICSPVFactory.PREFIX + "://" + name; } /** {@inheritDoc} */ @Override public IValue getValue(final double timeout_seconds) throws Exception { final long end_time = System.currentTimeMillis() + (long)(timeout_seconds * 1000); // Try to connect (NOP if already connected) connect(); // Wait for connection while (! connected) { // Wait... final long remain = end_time - System.currentTimeMillis(); if (remain <= 0) throw new Exception("PV " + name + " connection timeout"); synchronized (this) { this.wait(remain); } } // Reset the callback data get_callback.reset(); // Issue the 'get' final DBRType type = DBR_Helper.getCtrlType(plain, channel_ref.getChannel().getFieldType()); Activator.getLogger().log(Level.FINEST, "{0} get-callback as {1}", new Object[] { name, type.getName() }); channel_ref.getChannel().get( type, channel_ref.getChannel().getElementCount(), get_callback); // Wait for value callback synchronized (get_callback) { while (! get_callback.got_response) { // Wait... final long remain = end_time - System.currentTimeMillis(); if (remain <= 0) throw new Exception("PV " + name + " value timeout"); get_callback.wait(remain); } } value = get_callback.value; return get_callback.value; } /** {@inheritDoc} */ @Override public IValue getValue() { return value; } /** {@inheritDoc} */ @Override public void addListener(final PVListener listener) { listeners.add(listener); if (running && isConnected()) listener.pvValueUpdate(this); } /** {@inheritDoc} */ @Override public void removeListener(final PVListener listener) { listeners.remove(listener); } /** Try to connect to the PV. * OK to call more than once. */ private void connect() throws Exception { state = State.Connecting; // Already attempted a connection? synchronized (this) { if (channel_ref == null) { channel_ref = PVContext.getChannel(name, EPICS_V3_PV.this); } } if (channel_ref.getChannel().getConnectionState() == ConnectionState.CONNECTED) { Activator.getLogger().log(Level.FINEST, "{0} is immediately connected", name); handleConnected(channel_ref.getChannel()); } } /** Disconnect from the PV. * OK to call more than once. */ private void disconnect() { // Releasing the _last_ channel will close the context, // which waits for the JCA Command thread to exit. // If a connection or update for the channel happens at that time, // the JCA command thread will send notifications to this PV, // which had resulted in dead lock: // This code locked the PV, then tried to join the JCA Command thread. // JCA Command thread tried to lock the PV, so it could not exit. // --> Don't lock while calling into the PVContext. RefCountedChannel channel_ref_copy; synchronized (this) { // Never attempted a connection? if (channel_ref == null) return; channel_ref_copy = channel_ref; channel_ref = null; connected = false; } try { PVContext.releaseChannel(channel_ref_copy, this); } catch (final Throwable e) { e.printStackTrace(); } fireDisconnected(); } /** Subscribe for value updates. */ private void subscribe() { synchronized (this) { // Prevent multiple subscriptions. if (subscription != null) { return; } // Late callback, channel already closed? final RefCountedChannel ch_ref = channel_ref; if (ch_ref == null) { return; } final Channel channel = ch_ref.getChannel(); final Logger logger = Activator.getLogger(); try { // TODO Instead of another channel.addMonitor(), // the RefCountedChannel should maintain a single // subscription to the underlying CAJ/JCA channel. // So even with N PVs for the same channel, it's // only one subscription on the network instead of // N subscriptions. final DBRType type = DBR_Helper.getTimeType(plain, channel.getFieldType()); final MonitorMask mask = PVContext.monitor_mask; logger.log(Level.FINER, "{0} subscribed as {1} ({2})", new Object[] { name, type.getName(), mask } ); state = State.Subscribing; subscription = channel.addMonitor(type, channel.getElementCount(), mask.getMask(), this); } catch (final Exception ex) { logger.log(Level.SEVERE, name + " subscribe error", ex); } } } /** Unsubscribe from value updates. */ private void unsubscribe() { Monitor sub_copy; // Atomic access synchronized (this) { sub_copy = subscription; subscription = null; } if (sub_copy == null) { return; } try { sub_copy.clear(); } catch (final Exception ex) { Activator.getLogger().log(Level.SEVERE, name + " unsubscribe error", ex); } } /** {@inheritDoc} */ @Override public void start() throws Exception { if (running) { return; } running = true; connect(); } /** {@inheritDoc} */ @Override public boolean isRunning() { return running; } /** {@inheritDoc} */ @Override public boolean isConnected() { return connected; } /** {@inheritDoc} */ @Override public boolean isWriteAllowed() { return connected && channel_ref.getChannel().getWriteAccess(); } /** {@inheritDoc} */ @Override public String getStateInfo() { return state.toString(); } /** {@inheritDoc} */ @Override public void stop() { running = false; unsubscribe(); disconnect(); } /** {@inheritDoc} */ @Override public void setValue(final Object new_value) throws Exception { if (!isConnected()) { throw new Exception(name + " is not connected"); } // Send strings as strings.. if (new_value instanceof String) { channel_ref.getChannel().put((String)new_value); } else { // other types as double. if (new_value instanceof Double) { final double val = ((Double)new_value).doubleValue(); channel_ref.getChannel().put(val); } else if (new_value instanceof Double []) { final Double dbl[] = (Double [])new_value; final double val[] = new double[dbl.length]; for (int i=0; i<val.length; ++i) { val[i] = dbl[i].doubleValue(); } channel_ref.getChannel().put(val); } else if (new_value instanceof Integer) { final int val = ((Integer)new_value).intValue(); channel_ref.getChannel().put(val); } else if (new_value instanceof Integer []) { final Integer ival[] = (Integer [])new_value; final int val[] = new int[ival.length]; for (int i=0; i<val.length; ++i) { val[i] = ival[i].intValue(); } channel_ref.getChannel().put(val); } else { throw new Exception("Cannot handle type " + new_value.getClass().getName()); } } } /** ConnectionListener interface. */ @Override public void connectionChanged(final ConnectionEvent ev) { // This runs in a CA thread if (ev.isConnected()) { // Transfer to JCACommandThread to avoid deadlocks // The connect event can actually happen 'right away' // when the channel is created, before we even get to assign // the channel_ref. So use the channel from the event, not // the channel_ref which might still be null. PVContext.scheduleCommand(new Runnable() { @Override public void run() { handleConnected((Channel) ev.getSource()); } }); } else { Activator.getLogger().log(Level.FINEST, "{0} disconnected", name); state = State.Disconnected; connected = false; PVContext.scheduleCommand(new Runnable() { @Override public void run() { unsubscribe(); fireDisconnected(); } }); } } /** PV is connected. * Get meta info, or subscribe right away. */ private void handleConnected(final Channel channel) { Activator.getLogger().log(Level.FINEST, "{0} connected ({1})", new Object[] { name, state.name() }); if (state == State.Connected) return; state = State.Connected; // If we're "running", we need to get the meta data and // then subscribe. // Otherwise, we're done. if (!running) { connected = true; meta = null; synchronized (this) { this.notifyAll(); } return; } // else: running, get meta data, then subscribe try { DBRType type = channel.getFieldType(); if (! (plain || type.isSTRING())) { state = State.GettingMetadata; Activator.getLogger().fine("Getting meta info for type " + type.getName()); if (type.isDOUBLE() || type.isFLOAT()) type = DBRType.CTRL_DOUBLE; else if (type.isENUM()) type = DBRType.LABELS_ENUM; else if (type.isINT()) type = DBRType.CTRL_INT; else type = DBRType.CTRL_SHORT; channel.get(type, 1, meta_get_listener); return; } } catch (final Exception ex) { Activator.getLogger().log(Level.SEVERE, name + " connection handling error", ex); return; } // Meta info is not requested, not available for this type, // or there was an error in the get call. // So reset it, then just move on to the subscription. meta = null; subscribe(); } /** MonitorListener interface. */ @Override public void monitorChanged(final MonitorEvent ev) { final Logger log = Activator.getLogger(); // This runs in a CA thread. // Ignore values that arrive after stop() if (!running) { log.finer(name + " monitor while not running (" + state.name() + ")"); return; } if (subscription == null) { log.finer(name + " monitor while not subscribed (" + state.name() + ")"); return; } if (! ev.getStatus().isSuccessful()) { log.warning(name + " monitor error :" + ev.getStatus().getMessage()); return; } state = State.GotMonitor; try { final DBR dbr = ev.getDBR(); if (dbr == null) { log.warning(name + " monitor with null dbr"); return; } value = DBR_Helper.decodeValue(plain, meta, dbr); if (!connected) connected = true; // Logging every received value is expensive and chatty. log.log(Level.FINEST, "{0} monitor: {1} ({2})", new Object[] { name, value, value.getClass().getName() }); fireValueUpdate(); } catch (final Exception ex) { log.log(Level.WARNING, name + " monitor value error", ex); } } /** Notify all listeners. */ private void fireValueUpdate() { for (final PVListener listener : listeners) { listener.pvValueUpdate(this); } } /** Notify all listeners. */ private void fireDisconnected() { for (final PVListener listener : listeners) { listener.pvDisconnected(this); } } @Override public String toString() { return "EPICS_V3_PV '" + name + "'"; } }
package io.particle.android.sdk.devicesetup; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.annotation.NonNull; import android.support.v4.content.LocalBroadcastManager; import com.google.common.base.Preconditions; import io.particle.android.sdk.cloud.ParticleCloudSDK; import io.particle.android.sdk.devicesetup.ui.GetReadyActivity; public class ParticleDeviceSetupLibrary { /** * The contract for the broadcast sent upon device setup completion. * <p/> * <em>NOTE: this broadcast will be sent via the LocalBroadcastManager</em> * <p/> * The DeviceSetupCompleteReceiver class, which wraps up this logic, has been provided as a * convenience. */ public interface DeviceSetupCompleteContract { /** The BroadcastIntent action sent when the device setup process is complete. */ String ACTION_DEVICE_SETUP_COMPLETE = "ACTION_DEVICE_SETUP_COMPLETE"; /** A boolean extra indicating if the setup was successful */ String EXTRA_DEVICE_SETUP_WAS_SUCCESSFUL = "EXTRA_DEVICE_SETUP_WAS_SUCCESSFUL"; /** * A long extra indicating the device ID of the configured device. * <p/> * Value is undefined if EXTRA_DEVICE_SETUP_WAS_SUCCESSFUL is false. */ String EXTRA_CONFIGURED_DEVICE_ID = "EXTRA_CONFIGURED_DEVICE_ID"; } /** * A convenience class which wraps DeviceSetupCompleteContract. * <p/> * Just extend this and override onSetupSuccess() and onSetupFailure() to receive * the success/failure status. */ public static abstract class DeviceSetupCompleteReceiver extends BroadcastReceiver { public abstract void onSetupSuccess(@NonNull String configuredDeviceId); // FIXME: add some extra error information in onSetupFailed() public abstract void onSetupFailure(); /** Optional convenience method for registering this receiver. */ public void register(Context ctx) { LocalBroadcastManager.getInstance(ctx).registerReceiver(this, buildIntentFilter()); } /** Optional convenience method for registering this receiver. */ public void unregister(Context ctx) { LocalBroadcastManager.getInstance(ctx).unregisterReceiver(this); } @Override public void onReceive(Context context, Intent intent) { boolean success = intent.getBooleanExtra( DeviceSetupCompleteContract.EXTRA_DEVICE_SETUP_WAS_SUCCESSFUL, false); String deviceId = intent.getStringExtra(DeviceSetupCompleteContract.EXTRA_CONFIGURED_DEVICE_ID); if (success && deviceId != null) { onSetupSuccess(deviceId); } else { onSetupFailure(); } } public IntentFilter buildIntentFilter() { return new IntentFilter(DeviceSetupCompleteContract.ACTION_DEVICE_SETUP_COMPLETE); } } /** * Start the device setup process. * * @deprecated Use {@link ParticleDeviceSetupLibrary#startDeviceSetup(Context, Class)} * or {@link ParticleDeviceSetupLibrary#startDeviceSetup(Context, SetupCompleteIntentBuilder)} instead. */ @Deprecated public static void startDeviceSetup(Context ctx) { Preconditions.checkNotNull(instance.setupCompleteIntentBuilder, "SetupCompleteIntentBuilder instance is null"); ctx.startActivity(new Intent(ctx, GetReadyActivity.class)); } public static void startDeviceSetup(Context ctx, SetupCompleteIntentBuilder setupCompleteIntentBuilder) { instance.setupCompleteIntentBuilder = setupCompleteIntentBuilder; startDeviceSetup(ctx); } public static void startDeviceSetup(Context ctx, final Class<? extends Activity> mainActivity) { startDeviceSetup(ctx, new SetupCompleteIntentBuilder() { @Override public Intent buildIntent(Context ctx, SetupResult result) { return new Intent(ctx, mainActivity); } }); } // FIXME: allow the SDK consumer to optionally pass in some kind of dynamic intent builder here // instead of a static class // FIXME: or, stop requiring an activity at all and just use a single activity for setup which // uses Fragments internally... /** * Initialize the device setup SDK * * @param ctx any Context (the application context will be accessed from whatever is * passed in here, so leaks are not a concern even if you pass in an * Activity here) * @param mainActivity the class for your 'main" activity, i.e.: the class you want to * return to when the setup process is complete. * @deprecated Use {@link ParticleDeviceSetupLibrary#init(Context)} with * {@link ParticleDeviceSetupLibrary#startDeviceSetup(Context, Class)} * or {@link ParticleDeviceSetupLibrary#startDeviceSetup(Context, SetupCompleteIntentBuilder)} instead. */ @Deprecated public static void init(Context ctx, final Class<? extends Activity> mainActivity) { init(ctx); instance.setupCompleteIntentBuilder = new SetupCompleteIntentBuilder() { @Override public Intent buildIntent(Context ctx, SetupResult result) { return new Intent(ctx, mainActivity); } }; } /** * Initialize the device setup SDK * * @param ctx any Context (the application context will be accessed from whatever is * passed in here, so leaks are not a concern even if you pass in an * Activity here) */ public static void init(Context ctx) { if (instance == null) { // ensure the cloud SDK is initialized ParticleCloudSDK.init(ctx); instance = new ParticleDeviceSetupLibrary(); } } public static ParticleDeviceSetupLibrary getInstance() { Preconditions.checkNotNull(instance, "Library instance is null: did you call ParticleDeviceSetupLibrary.init()?"); return instance; } private static ParticleDeviceSetupLibrary instance; private SetupCompleteIntentBuilder setupCompleteIntentBuilder; /** * @deprecated This exists only because {@link io.particle.android.sdk.ui.NextActivitySelector} * is in a different package, and the plan is to remove that class soon. * As soon as {@link io.particle.android.sdk.ui.NextActivitySelector} is removed, this will be removed. */ @Deprecated public SetupCompleteIntentBuilder getSetupCompleteIntentBuilder() { return setupCompleteIntentBuilder; } private ParticleDeviceSetupLibrary() { } }
package org.hisp.dhis.webapi.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.hisp.dhis.appmanager.App; import org.hisp.dhis.appmanager.AppManager; import org.hisp.dhis.appmanager.AppStatus; import org.hisp.dhis.dxf2.webmessage.WebMessageException; import org.hisp.dhis.dxf2.webmessage.WebMessageUtils; import org.hisp.dhis.hibernate.exception.ReadAccessDeniedException; import org.hisp.dhis.i18n.I18nManager; import org.hisp.dhis.render.DefaultRenderService; import org.hisp.dhis.render.RenderService; import org.hisp.dhis.setting.SettingKey; import org.hisp.dhis.system.util.DateUtils; import org.hisp.dhis.webapi.mvc.annotation.ApiVersion; import org.hisp.dhis.webapi.service.ContextService; import org.hisp.dhis.webapi.utils.ContextUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * @author Lars Helge Overland */ @Controller @RequestMapping( AppController.RESOURCE_PATH ) @ApiVersion( { ApiVersion.Version.DEFAULT, ApiVersion.Version.ALL } ) public class AppController { public static final String RESOURCE_PATH = "/apps"; @Autowired private AppManager appManager; @Autowired private RenderService renderService; @Autowired private I18nManager i18nManager; private final ResourceLoader resourceLoader = new DefaultResourceLoader(); @Autowired protected ContextService contextService; // Resources @RequestMapping( method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_JSON ) public void getApps( @RequestParam( required = false ) String key, HttpServletRequest request, HttpServletResponse response ) throws IOException { List<String> filters = Lists.newArrayList( contextService.getParameterValues( "filter" ) ); String contextPath = ContextUtils.getContextPath( request ); List<App> apps = new ArrayList<>(); if ( key != null ) { App app = appManager.getApp( key, contextPath ); if ( app == null ) { response.sendError( HttpServletResponse.SC_NOT_FOUND ); return; } apps.add( app ); } else if ( !filters.isEmpty() ) { apps = appManager.filterApps( filters, contextPath ); } else { apps = appManager.getApps( contextPath ); } renderService.toJson( response.getOutputStream(), apps ); } @RequestMapping( method = RequestMethod.POST ) @PreAuthorize( "hasRole('ALL') or hasRole('M_dhis-web-app-management')" ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void installApp( @RequestParam( "file" ) MultipartFile file ) throws IOException, WebMessageException { File tempFile = File.createTempFile( "IMPORT_", "_ZIP" ); file.transferTo( tempFile ); AppStatus status = appManager.installApp( tempFile, file.getOriginalFilename() ); if ( !status.ok() ) { String message = i18nManager.getI18n().getString( status.getMessage() ); throw new WebMessageException( WebMessageUtils.conflict( message ) ); } } @RequestMapping( method = RequestMethod.PUT ) @PreAuthorize( "hasRole('ALL') or hasRole('M_dhis-web-app-management')" ) @ResponseStatus( HttpStatus.NO_CONTENT ) public void reloadApps() { appManager.reloadApps(); }
package org.folio.rest.tools; import org.apache.commons.io.FileUtils; import org.folio.util.IoUtil; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; public class GenerateRunnerTest { private static String userDir = System.getProperty("user.dir"); private static File jaxrs = new File(userDir + "/src/main/java/org/folio/rest/jaxrs"); private static File jaxrsBak = new File(userDir + "/src/main/java/org/folio/rest/jaxrs.bak"); private String resourcesDir = userDir + "/src/test/resources/schemas"; private String baseDir = userDir + "/target/GenerateRunnerTest"; @BeforeClass public static void saveJaxrs() { jaxrs.renameTo(jaxrsBak); // ignore any error } @AfterClass public static void restoreJaxrs() throws IOException { FileUtils.deleteDirectory(jaxrs); jaxrsBak.renameTo(jaxrs); // ignore any error } @Before public void cleanDir() throws IOException { ClientGenerator.makeCleanDir(baseDir); System.clearProperty("raml_files"); System.clearProperty("project.basedir"); } private String jobJava() throws IOException { return IoUtil.toStringUtf8(System.getProperty("project.basedir", userDir) + "/src/main/java/org/folio/rest/jaxrs/model/Job.java"); } private String testJava() throws IOException { return IoUtil.toStringUtf8(System.getProperty("project.basedir", userDir) + "/src/main/java/org/folio/rest/jaxrs/model/TestSchema.java"); } private String msgsSchema() throws IOException { return IoUtil.toStringUtf8(System.getProperty("project.basedir", userDir) + "/target/classes/ramls/x/y/msgs.schema"); } private String testSchema() throws IOException { return IoUtil.toStringUtf8(System.getProperty("project.basedir", userDir) + "/target/classes/ramls/test.schema"); } private void assertTest() throws IOException { assertThat(testSchema(), containsString("\"name\"")); assertThat(testJava(), allOf( containsString("String getName("), containsString("setName(String"), containsString("withName(String"))); } @Test public void canRunMainDefaultDirs() throws Exception { GenerateRunner.main(null); assertTest(); } private void assertJobMsgs() throws IOException { assertThat(jobJava(), allOf( containsString("String getModule("), containsString("setModule(String"), containsString("withModule(String"))); assertThat(msgsSchema(), containsString("\"value\"")); } @Test public void canRunMain() throws Exception { System.setProperty("raml_files", resourcesDir); System.setProperty("project.basedir", baseDir); FileUtils.copyDirectory(new File(resourcesDir), new File(baseDir + "/ramls/")); GenerateRunner.main(null); assertJobMsgs(); } @Test public void canRunMainParentDir() throws Exception { System.setProperty("raml_files", resourcesDir); System.setProperty("project.basedir", baseDir + "/submodule"); FileUtils.copyDirectory(new File(resourcesDir), new File(baseDir + "/ramls/")); GenerateRunner.main(null); assertJobMsgs(); } @Test(expected=IOException.class) public void invalidInputDirectory() throws Exception { new GenerateRunner(baseDir).generate(resourcesDir + "/job.schema"); } @Test public void defaultRamlFilesDir() throws Exception { // create ramls dir at default location FileUtils.copyDirectory(new File(userDir + "/ramls/"), new File(baseDir + "/ramls/")); System.setProperty("project.basedir", baseDir); GenerateRunner.main(null); assertTest(); } }
package com.bob.generator.extens.plugins; import org.mybatis.generator.api.CommentGenerator; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.dom.java.*; import org.mybatis.generator.config.Context; import org.mybatis.generator.logging.JdkLoggingImpl; import org.mybatis.generator.logging.Log; import java.util.List; public abstract class PluginAdapterEnhancement extends PluginAdapter { protected Log logger = new JdkLoggingImpl(this.getClass()); protected CommentGenerator commentGenerator; /** * * * @param list * @return */ @Override public boolean validate(List<String> list) { return true; } @Override public void setContext(Context context) { super.setContext(context); commentGenerator = context.getCommentGenerator(); } /** * * * @return */ protected String getSeparator() { return System.getProperty("line.separator"); } protected static String generateGetMethodName(String fieldName) { return "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); } protected static String generateSetMethodName(String fieldName) { return "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); } /** * get,set * * @param topLevelClass * @param introspectedTable * @param field */ protected void addField(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, Field field) { CommentGenerator commentGenerator = context.getCommentGenerator(); // Java commentGenerator.addFieldComment(field, introspectedTable); topLevelClass.addField(field); String fieldName = field.getName(); // Set Method method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); method.setName(generateSetMethodName(fieldName)); method.addParameter(new Parameter(field.getType(), fieldName)); method.addBodyLine("this." + fieldName + "=" + fieldName + ";"); commentGenerator.addGeneralMethodComment(method, introspectedTable); topLevelClass.addMethod(method); // Get method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); method.setReturnType(field.getType()); method.setName(generateGetMethodName(fieldName)); method.addBodyLine("return " + fieldName + ";"); commentGenerator.addGeneralMethodComment(method, introspectedTable); topLevelClass.addMethod(method); } }
package com.hazelcast.ringbuffer.impl; import com.hazelcast.config.Config; import com.hazelcast.config.InMemoryFormat; import com.hazelcast.config.RingbufferConfig; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.ringbuffer.ReadResultSet; import com.hazelcast.ringbuffer.Ringbuffer; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.TestThread; import com.hazelcast.test.annotation.NightlyTest; import org.apache.log4j.Level; import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.LinkedList; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.hazelcast.ringbuffer.OverflowPolicy.FAIL; import static java.lang.Math.max; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; @RunWith(HazelcastSerialClassRunner.class) @Category(NightlyTest.class) public class RingbufferAddAllReadManyStressTest extends HazelcastTestSupport { public static final int MAX_BATCH = 100; private final AtomicBoolean stop = new AtomicBoolean(); private Ringbuffer<Long> ringbuffer; @After public void tearDown() { if (ringbuffer != null) { ringbuffer.destroy(); } } @Test public void whenNoTTL() throws Exception { RingbufferConfig ringbufferConfig = new RingbufferConfig("rb") .setCapacity(20 * 1000 * 1000) .setInMemoryFormat(InMemoryFormat.OBJECT) .setTimeToLiveSeconds(0); test(ringbufferConfig); } @Test public void whenTTLEnabled() throws Exception { RingbufferConfig ringbufferConfig = new RingbufferConfig("rb") .setCapacity(200 * 1000) .setTimeToLiveSeconds(2); test(ringbufferConfig); } @Test public void whenLongTTLAndSmallBuffer() throws Exception { RingbufferConfig ringbufferConfig = new RingbufferConfig("rb") .setCapacity(1000) .setTimeToLiveSeconds(30); test(ringbufferConfig); } @Test public void whenShortTTLAndBigBuffer() throws Exception { RingbufferConfig ringbufferConfig = new RingbufferConfig("rb") .setInMemoryFormat(InMemoryFormat.OBJECT) .setCapacity(20 * 1000 * 1000) .setTimeToLiveSeconds(2); test(ringbufferConfig); } public void test(RingbufferConfig ringbufferConfig) throws Exception { Config config = new Config(); config.addRingBufferConfig(ringbufferConfig); HazelcastInstance[] instances = createHazelcastInstanceFactory(2).newInstances(config); ringbuffer = instances[0].getRingbuffer(ringbufferConfig.getName()); ConsumeThread consumer1 = new ConsumeThread(1); consumer1.start(); ConsumeThread consumer2 = new ConsumeThread(2); consumer2.start(); sleepSeconds(2); ProduceThread producer = new ProduceThread(); producer.start(); sleepAndStop(stop, 60); System.out.println("Waiting fo completion"); producer.assertSucceedsEventually(); consumer1.assertSucceedsEventually(); consumer2.assertSucceedsEventually(); System.out.println("producer.produced:" + producer.produced); assertEquals(producer.produced, consumer1.seq); assertEquals(producer.produced, consumer2.seq); } class ProduceThread extends TestThread { private final ILogger logger = Logger.getLogger(ProduceThread.class); private volatile long produced; long lastLogMs = 0; public ProduceThread() { super("ProduceThread"); } @Override public void onError(Throwable t) { stop.set(true); } @Override public void doRun() throws Throwable { Random random = new Random(); while (!stop.get()) { LinkedList<Long> items = makeBatch(random); addAll(items); } ringbuffer.add(Long.MIN_VALUE); } private LinkedList<Long> makeBatch(Random random) { int count = max(1, random.nextInt(MAX_BATCH)); LinkedList<Long> items = new LinkedList<Long>(); for (int k = 0; k < count; k++) { items.add(produced); produced++; long currentTimeMs = currentTimeMillis(); if (lastLogMs + SECONDS.toMillis(5) < currentTimeMs) { lastLogMs = currentTimeMs; logger.info(getName() + " at " + produced); } } return items; } private void addAll(LinkedList<Long> items) throws InterruptedException, ExecutionException { long sleepMs = 100; for (; ; ) { long result = ringbuffer.addAllAsync(items, FAIL).get(); if (result != -1) { break; } logger.info("Backoff"); MILLISECONDS.sleep(sleepMs); sleepMs = sleepMs * 2; if (sleepMs > 1000) { sleepMs = 1000; } } } } class ConsumeThread extends TestThread { private final ILogger logger = Logger.getLogger(ConsumeThread.class); volatile long seq; long lastLogMs = 0; public ConsumeThread(int id) { super("ConsumeThread-" + id); } @Override public void onError(Throwable t) { stop.set(true); } @Override public void doRun() throws Throwable { seq = ringbuffer.headSequence(); Random random = new Random(); for (; ; ) { int max = max(1, random.nextInt(MAX_BATCH)); ReadResultSet<Long> result = ringbuffer.readManyAsync(seq, 1, max, null).get(); for (Long item : result) { if (item.equals(Long.MIN_VALUE)) { return; } assertEquals(new Long(seq), item); long currentTimeMs = currentTimeMillis(); if (lastLogMs + SECONDS.toMillis(5) < currentTimeMs) { lastLogMs = currentTimeMs; logger.info(getName() + " at " + seq); } seq++; } } } } }
package org.jboss.as.quickstarts.datagrid.helloworld; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.findby.FindByJQuery; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.net.MalformedURLException; import java.net.URL; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.jboss.arquillian.graphene.Graphene.waitModel; /** * Test for Helloworld-jdg quickstart using Drone Arquillian extension and Graphenebrowser framework for testing app UI. * * There are 2 tests, one for the put.jsf/get.jsf pages, where a user can add arbitrary entries, and one for * TestServletPut (adds entry <hello, world>) and TestServletGet (retrieves key <hello>) pages. * * @author jmarkos@redhat.com * @author jholusa@redhat.com */ @RunWith(Arquillian.class) @RunAsClient public class HelloworldTest { // Result is at the same position for both put/get pages - in the 2nd <table> (numbering from 0) in the 2nd <td> @FindByJQuery("table:eq(1) td:eq(1)") private WebElement result; // put page @FindBy(id = "putForm") private WebElement put_putForm; @FindBy(id = "putForm:key") private WebElement put_keyInput; @FindBy(id = "putForm:value") private WebElement put_valueInput; @FindBy(id = "putForm:Put") private WebElement put_putButton; @FindByJQuery("a:contains('Get Some')") private WebElement put_getSomeLink; // get page @FindBy(id = "getForm:key") private WebElement get_getInput; @FindBy(id = "getForm:Get") private WebElement get_getButton; @FindBy(id = "getForm:GetAll") private WebElement get_getAllButton; @FindByJQuery("a:contains('Put Some More')") private WebElement get_putSomeMoreLink; // TestServletPut and TestServletGet pages @FindByJQuery("h1") private WebElement servlets_mainText; @Drone WebDriver browser; @ArquillianResource @OperateOnDeployment("container1") private URL contextPath1; @ArquillianResource @OperateOnDeployment("container2") private URL contextPath2; @Deployment(name = "container1", testable = false) @TargetsContainer("container1") public static WebArchive createTestDeploymentRemote1() { return Deployments.createDeployment(); } @Deployment(name = "container2", testable = false) @TargetsContainer("container2") public static WebArchive createTestDeploymentRemote2() { return Deployments.createDeployment(); } // Test that pages are OK, cache empty at the beginning, proper replication and expiration after 60 seconds @Test public void testbasicOperations() { System.out.println("contextPath: " + contextPath1); System.out.println("contextPath2: " + contextPath2); testEmptyCache(contextPath1); testEmptyCache(contextPath2); putEntry(contextPath1, "key1", "value1"); testEntryPresent(contextPath1, "key1", "value1"); testEntryPresent(contextPath2, "key1", "value1"); putEntry(contextPath2, "key2", "value2"); testEntryPresent(contextPath1, "key2", "value2"); // entries should expire after 60 seconds try { Thread.sleep(61000); } catch (InterruptedException e) { e.printStackTrace(); } testEmptyCache(contextPath1); testEmptyCache(contextPath2); } @Test public void testPredefinedServlets() { URL getURL = null; URL putURL = null; try { putURL = new URL(contextPath1 + "TestServletPut"); getURL = new URL(contextPath2 + "TestServletGet"); } catch (MalformedURLException e) { e.printStackTrace(); fail("Are URLs '" + contextPath1 + "TestServletPut' and '" + contextPath2 + "TestServletGet' correct?"); } browser.get(getURL.toExternalForm()); waitModel().until().element(servlets_mainText).is().present(); assertTrue("Put button is not present.", servlets_mainText.isDisplayed()); String mainText = servlets_mainText.getText(); assertTrue("TestServletGet page (container2) doesn't contain text 'Get Infinispan: null'", mainText.contains("Get Infinispan: null")); browser.get(putURL.toExternalForm()); waitModel().until().element(servlets_mainText).is().present(); assertTrue("Put button is not present.", servlets_mainText.isDisplayed()); mainText = servlets_mainText.getText(); assertTrue("TestServletPut page (container1) doesn't contain text 'Put Infinispan: world'", mainText.contains("Put Infinispan: world")); browser.get(getURL.toExternalForm()); waitModel().until().element(servlets_mainText).is().present(); assertTrue("Put button is not present.", servlets_mainText.isDisplayed()); mainText = servlets_mainText.getText(); assertTrue("TestServletGet page (container2) doesn't contain text 'Get Infinispan: world'", mainText.contains("Get Infinispan: world")); } private void putEntry(URL path, String key, String value) { browser.get(path.toExternalForm()); waitModel().until().element(put_keyInput).is().present(); waitModel().until().element(put_valueInput).is().present(); waitModel().until().element(put_putButton).is().present(); assertTrue("Input for key is not present.", put_keyInput.isDisplayed()); assertTrue("Input for value is not present.", put_valueInput.isDisplayed()); assertTrue("Put button is not present.", put_putButton.isDisplayed()); put_keyInput.sendKeys(key); put_valueInput.sendKeys(value); put_putButton.click(); waitModel().until().element(result).is().present(); String cacheEntries = result.getText(); System.out.println("cacheEntries = " + cacheEntries); assertTrue("Cache does not contain entry key1=value1", cacheEntries.contains(key + "=" + value + " added")); } // tests both get and getAll buttons // Note: It's possible to directly go to URL /Get.jsf, but that adds a dependency on the URL format, so we // navigate there using the Get Some link private void testEntryPresent(URL path, String key, String value) { browser.get(path.toExternalForm()); waitModel().until().element(put_getSomeLink).is().present(); assertTrue("Get Some link is not present.", put_getSomeLink.isDisplayed()); put_getSomeLink.click(); waitModel().until().element(get_getButton).is().present(); waitModel().until().element(get_getAllButton).is().present(); assertTrue("Input for get key is not present.", get_getInput.isDisplayed()); assertTrue("Get button is not present.", get_getButton.isDisplayed()); waitModel().until().element(get_getInput).is().present(); get_getInput.sendKeys(key); waitModel().until().element(get_getButton).is().present(); get_getButton.click(); waitModel().until().element(result).is().present(); String cacheEntries = result.getText(); assertTrue("Cache does not contain key: " + key, cacheEntries.contains(value)); waitModel().until().element(get_getAllButton).is().present(); assertTrue("Get all button is not present.", get_getAllButton.isDisplayed()); get_getAllButton.click(); waitModel().until().element(result).is().present(); cacheEntries = result.getText(); assertTrue("Cache does not contain entry: " + key + "=" + value, cacheEntries.contains(key + "=" + value)); } private void testEmptyCache(URL path) { browser.get(path.toExternalForm()); waitModel().until().element(put_getSomeLink).is().present(); assertTrue("Get Some link is not present.", put_getSomeLink.isDisplayed()); put_getSomeLink.click(); waitModel().until().element(get_getAllButton).is().present(); assertTrue("Get all button is not present.", get_getAllButton.isDisplayed()); get_getAllButton.click(); waitModel().until().element(result).is().present(); String cacheEntries = result.getText(); assertTrue("Cache is not empty!", cacheEntries.contains("Nothing in the Cache")); } }
package com.autonomy.abc.endtoend; import com.autonomy.abc.config.HostedTestBase; import com.autonomy.abc.config.TestConfig; import com.autonomy.abc.selenium.actions.PromotionActionFactory; import com.autonomy.abc.selenium.config.ApplicationType; import com.autonomy.abc.selenium.connections.ConnectionService; import com.autonomy.abc.selenium.connections.WebConnector; import com.autonomy.abc.selenium.element.Checkbox; import com.autonomy.abc.selenium.menu.NavBarTabId; import com.autonomy.abc.selenium.page.indexes.IndexesPage; import com.autonomy.abc.selenium.page.keywords.KeywordsPage; import com.autonomy.abc.selenium.page.search.SearchPage; import com.autonomy.abc.selenium.search.IndexFilter; import com.autonomy.abc.selenium.search.Search; import com.autonomy.abc.selenium.search.SearchActionFactory; import org.apache.commons.lang3.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.Platform; import java.util.Arrays; import java.util.List; import static com.autonomy.abc.framework.ABCAssert.assertThat; import static com.autonomy.abc.framework.ABCAssert.verifyThat; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.core.Is.is; //CSA-1565 public class ConnectionsToFindITCase extends HostedTestBase { private ConnectionService connectionService; private SearchActionFactory searchActionFactory; private PromotionActionFactory promotionActionFactory; private final WebConnector connector = new WebConnector("http: private final String indexName = "fifa"; private final String searchTerm = "football"; private final String trigger = "corruption"; private List<String> synonyms = Arrays.asList(searchTerm,"evil","malfoy","slytherin","greed"); private SearchPage searchPage; private List<String> promotedTitles; public ConnectionsToFindITCase(TestConfig config, String browser, ApplicationType type, Platform platform) { super(config, browser, type, platform); } @Before public void setUp(){ connectionService = new ConnectionService(getApplication(), getElementFactory()); searchActionFactory = new SearchActionFactory(getApplication(), getElementFactory()); promotionActionFactory = new PromotionActionFactory(getApplication(),getElementFactory()); } @Test public void testConnectionsToFind() throws InterruptedException { connectionService.setUpConnection(connector); Search search = searchActionFactory.makeSearch(searchTerm); search.applyFilter(new IndexFilter(indexName)); search.apply(); searchPage = getElementFactory().getSearchPage(); verifyThat("index shows up on search page", searchPage.getSelectedDatabases(), hasItem(indexName)); verifyThat("index has search results", searchPage.countSearchResults(), greaterThan(0)); promotedTitles = searchPage.createAMultiDocumentPromotion(3); getElementFactory().getCreateNewPromotionsPage().addSpotlightPromotion("", trigger); assertThat(searchPage.getPromotedDocumentTitles(), containsInAnyOrder(promotedTitles.toArray())); body.getSideNavBar().switchPage(NavBarTabId.KEYWORDS); KeywordsPage keywordsPage = getElementFactory().getKeywordsPage(); keywordsPage.createNewKeywordsButton().click(); getElementFactory().getCreateNewKeywordsPage().createSynonymGroup(StringUtils.join(synonyms, " "), "English"); searchPage = getElementFactory().getSearchPage(); assertThat(searchPage.getPromotedDocumentTitles(), containsInAnyOrder(promotedTitles.toArray())); assertPromotedItemsForEverySynonym(); connectionService.deleteConnection(connector, true); assertPromotedItemsForEverySynonym(); promotionActionFactory.makeDelete(trigger).apply(); for(String synonym : synonyms){ searchActionFactory.makeSearch(synonym).apply(); assertThat(searchPage.getPromotedResults().size(),is(0)); } body.getSideNavBar().switchPage(NavBarTabId.INDEXES); IndexesPage indexesPage = getElementFactory().getIndexesPage(); indexesPage.findIndex(indexName).findElement(By.className("fa-trash-o")).click(); indexesPage.loadOrFadeWait(); getDriver().findElement(By.className("btn-alert")).click(); searchActionFactory.makeSearch(searchTerm).apply(); for(Checkbox checkbox : searchPage.indexList()){ assertThat(checkbox.getName(),not(indexName)); } } private void assertPromotedItemsForEverySynonym() { for(String synonym : synonyms){ searchActionFactory.makeSearch(synonym).apply(); assertThat(searchPage.getPromotedDocumentTitles(), containsInAnyOrder(promotedTitles.toArray())); } } @After public void tearDown(){ connectionService.deleteConnection(connector, true); } }
package io.hawt.sample; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import org.apache.aries.blueprint.container.BlueprintContainerImpl; import org.apache.camel.CamelException; import org.apache.camel.util.CamelContextHelper; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Slf4jLog; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebInfConfiguration; import org.eclipse.jetty.webapp.WebXmlConfiguration; import org.mortbay.jetty.plugin.JettyWebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.management.MBeanServer; import java.io.File; import java.lang.management.ManagementFactory; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.nio.file.FileSystems; import net_alchim31_livereload.LRServer; /** * A simple bootstrap class */ public class Main { private static final transient Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { try { System.setProperty("org.eclipse.jetty.util.log.class", Slf4jLog.class.getName()); Log.setLog(new Slf4jLog("jetty")); int port = Integer.parseInt(System.getProperty("jettyPort", "8080")); String contextPath = System.getProperty("context", "/hawtio"); if (!contextPath.startsWith("/")) { contextPath = "/" + contextPath; } String sourcePath = "src/main/webapp"; String webXml = sourcePath + "/WEB-INF/web.xml"; require(fileExists(webXml), "No web.xml could be found for $webXml"); String pathSeparator = File.pathSeparator; String classpath = System.getProperty("java.class.path", ""); ImmutableList<String> classpaths = ImmutableList.copyOf(Arrays.asList(classpath.split(pathSeparator))); Iterable<String> jarNames = Iterables.filter(classpaths, new Predicate<String>() { public boolean apply(String path) { return isScannedWebInfLib(path); } }); Iterable<File> allFiles = Iterables.transform(jarNames, new Function<String, File>() { public File apply(String path) { return new File(path); } }); Iterable<File> files = Iterables.filter(allFiles, new Predicate<File>() { public boolean apply(File file) { return file != null && file.exists(); } }); Iterable<File> jars = Iterables.filter(files, new Predicate<File>() { public boolean apply(File file) { return file.isFile(); } }); Iterable<File> extraClassDirs = Iterables.filter(files, new Predicate<File>() { public boolean apply(File file) { return file.isDirectory(); } }); JettyWebAppContext context = new JettyWebAppContext(); context.setWebInfLib(ImmutableList.copyOf(jars)); Configuration[] contextConfigs = {new WebXmlConfiguration(), new WebInfConfiguration()}; context.setConfigurations(contextConfigs); context.setDescriptor(webXml); context.setResourceBases(new String[] {sourcePath}); context.setContextPath(contextPath); context.setParentLoaderPriority(true); // lets try disable the memory mapped file which causes issues // on Windows when using mvn -Pwatch if (System.getProperty("jettyUseFileLock", "").toLowerCase().equals("false")) { //LOG.info("Disabling the use of the Jetty file lock for static content to try fix incremental grunt compilation on Windows"); //context.setCopyWebDir(true); //context.setInitParameter("useFileMappedBuffer", "false"); LOG.info("Setting maxCachedFiles to 0"); context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCachedFiles", "0"); } Server server = new Server(port); server.setHandler(context); // enable JMX MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); MBeanContainer mbeanContainer = new MBeanContainer(mbeanServer); if (server.getContainer() != null) { server.getContainer().addEventListener(mbeanContainer); } server.addBean(mbeanContainer); List<URL> resourcePaths = new ArrayList<URL>(); if (Boolean.valueOf(System.getProperty("loadApps", "true"))) { // lets initialise blueprint ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resources = classLoader.getResources("OSGI-INF/blueprint/blueprint.xml"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); String text = url.toString(); if (text.contains("karaf")) { LOG.info("Ignoring karaf based blueprint file " + text); } else if (text.contains("hawtio-system")) { LOG.info("Ignoring hawtio-system"); } else { resourcePaths.add(url); } } LOG.info("Loading Blueprint contexts " + resourcePaths); Map<String, String> properties = new HashMap<String, String>(); BlueprintContainerImpl container = new BlueprintContainerImpl(classLoader, resourcePaths, properties, true); if (args.length == 0 || !args[0].equals("nospring")) { // now lets startup a spring application context LOG.info("starting spring application context"); ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Object activemq = appContext.getBean("activemq"); LOG.info("created activemq: " + activemq); appContext.start(); LOG.warn("Don't run with scissors!"); LOG.error("Someone somewhere is not using Fuse! :)", new CamelException("My exception message")); // now lets force an exception with a stack trace from camel... try { CamelContextHelper.getMandatoryEndpoint(null, null); } catch (Throwable e) { LOG.error("Expected exception for testing: " + e, e); } } } println(""); println(""); println("OPEN: http://localhost:" + port + contextPath + " using web app source path: " + resourcePaths); println(""); println(""); LOG.info("Starting LiveReload server"); LRServer lrServer = null; int lrPort = 35729; Path docroot = FileSystems.getDefault().getPath("src/main/webapp"); lrServer = new LRServer(lrPort, docroot); lrServer.setExclusions(new String[]{".*\\.ts$"}); LOG.info("starting jetty"); server.start(); LOG.info("Joining the jetty server thread..."); // this guy does a start() and a join()... lrServer.run(); //server.join(); } catch (Throwable e) { LOG.error(e.getMessage(), e); } } /** * Returns true if the file exists */ public static boolean fileExists(String path) { File file = new File(path); return file.exists() && file.isFile(); } /** * Returns true if the directory exists */ public static boolean directoryExists(String path) { File file = new File(path); return file.exists() && file.isDirectory(); } public static void require(boolean flag, String message) { if (!flag) { throw new IllegalStateException(message); } } /** * Returns true if we should scan this lib for annotations */ public static boolean isScannedWebInfLib(String path) { return path.endsWith("kool/website/target/classes"); //return path.contains("kool") //return true } public static void println(Object message) { System.out.println(message); } }
package org.junit.vintage.engine.discovery; import static java.util.stream.Stream.concat; import static org.junit.platform.commons.util.FunctionUtils.where; import java.util.LinkedHashMap; 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 java.util.stream.Stream; /** * @since 4.12 */ class TestClassCollector { private final Set<Class<?>> completeTestClasses = new LinkedHashSet<>(); private final Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> filteredTestClasses = new LinkedHashMap<>(); void addCompletely(Class<?> testClass) { completeTestClasses.add(testClass); } void addFiltered(Class<?> testClass, RunnerTestDescriptorAwareFilter filter) { filteredTestClasses.computeIfAbsent(testClass, key -> new LinkedList<>()).add(filter); } Stream<TestClassRequest> toRequests() { return concat(completeRequests(), filteredRequests()); } private Stream<TestClassRequest> completeRequests() { return completeTestClasses.stream().map(TestClassRequest::new); } private Stream<TestClassRequest> filteredRequests() { // @formatter:off return filteredTestClasses.entrySet() .stream() .filter(where(Entry::getKey, testClass -> !completeTestClasses.contains(testClass))) .map(entry -> new TestClassRequest(entry.getKey(), entry.getValue())); // @formatter:on } }
package org.languagetool.rules.fr; import com.fasterxml.jackson.databind.ObjectMapper; import org.jetbrains.annotations.NotNull; import org.languagetool.AnalyzedSentence; import org.languagetool.Experimental; import org.languagetool.GlobalConfig; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLHandshakeException; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; /** * Queries a local Grammalecte server. * @since 4.6 */ @Experimental public class GrammalecteRule extends Rule { private static Logger logger = LoggerFactory.getLogger(GrammalecteRule.class); private static final int TIMEOUT_MILLIS = 1; private static final long DOWN_INTERVAL_MILLISECONDS = 5000; private static long lastRequestError = 0; private final ObjectMapper mapper = new ObjectMapper(); private final GlobalConfig globalConfig; private final Set<String> ignoreRules = new HashSet<>(Arrays.asList( "tab_fin_ligne", "apostrophe_typographique", "typo_guillemets_typographiques_doubles_ouvrants", "nbsp_avant_double_ponctuation", "typo_guillemets_typographiques_doubles_fermants", "nbsp_avant_deux_points", // Useful only if we decide to have the rest of the non-breakable space rules. "nbsp_ajout_avant_double_ponctuation", // Useful only if we decide to have the rest of the non-breakable space rules. "apostrophe_typographique_après_t", // Not useful. While being the technically correct character, it does not matter much. "unit_nbsp_avant_unités1", "typo_tiret_début_ligne", // Arguably the same as 50671 and 17342 ; the french special character for lists is a 'tiret cadratin' ; so it should be that instead of a dash. Having it count as a mistake is giving access to the otherwise unaccessible special character. However, lists are a common occurrence, and the special character does not make a real difference. Not really useful but debatable "typo_guillemets_typographiques_simples_fermants", "typo_apostrophe_incorrecte", "unit_nbsp_avant_unités3", "nbsp_après_double_ponctuation", "typo_guillemets_typographiques_simples_ouvrants", "num_grand_nombre_avec_espaces" )); public GrammalecteRule(ResourceBundle messages, GlobalConfig globalConfig) { super(messages); //addExamplePair(Example.wrong(""), // Example.fixed("")); this.globalConfig = globalConfig; } @Override public String getId() { return "FR_GRAMMALECTE"; } @Override public String getDescription() { return "Returns matches of a local Grammalecte server"; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { // very basic health check -> mark server as down after an error for given interval if (System.currentTimeMillis() - lastRequestError < DOWN_INTERVAL_MILLISECONDS) { logger.warn("Warn: Temporarily disabled Grammalecte server because of recent error."); return new RuleMatch[0]; } URL serverUrl = new URL(globalConfig.getGrammalecteServer()); HttpURLConnection huc = (HttpURLConnection) serverUrl.openConnection(); HttpURLConnection.setFollowRedirects(false); huc.setConnectTimeout(TIMEOUT_MILLIS); huc.setReadTimeout(TIMEOUT_MILLIS*2); if (globalConfig.getGrammalecteUser() != null && globalConfig.getGrammalectePassword() != null) { String authString = globalConfig.getGrammalecteUser() + ":" + globalConfig.getGrammalectePassword(); String encoded = Base64.getEncoder().encodeToString(authString.getBytes()); huc.setRequestProperty("Authorization", "Basic " + encoded); } huc.setRequestMethod("POST"); huc.setDoOutput(true); try { huc.connect(); try (DataOutputStream wr = new DataOutputStream(huc.getOutputStream())) { String urlParameters = "text=" + encode(sentence.getText()); byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); wr.write(postData); } InputStream input = huc.getInputStream(); List<RuleMatch> ruleMatches = parseJson(input); return toRuleMatchArray(ruleMatches); } catch (SSLHandshakeException | SocketTimeoutException e) { // "hard" errors that will probably not resolve themselves easily: lastRequestError = System.currentTimeMillis(); // still fail silently, better to return partial results than an error //throw e; logger.warn("Warn: Failed to query Grammalecte server at " + serverUrl + ": " + e.getClass() + ": " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { lastRequestError = System.currentTimeMillis(); // These are issue that can be request-specific, like wrong parameters. We don't throw an // exception, as the calling code would otherwise assume this is a persistent error: logger.warn("Warn: Failed to query Grammalecte server at " + serverUrl + ": " + e.getClass() + ": " + e.getMessage()); e.printStackTrace(); } finally { huc.disconnect(); } return new RuleMatch[0]; } @NotNull private List<RuleMatch> parseJson(InputStream inputStream) throws IOException { Map map = mapper.readValue(inputStream, Map.class); List matches = (ArrayList) map.get("data"); List<RuleMatch> result = new ArrayList<>(); for (Object match : matches) { List<RuleMatch> remoteMatches = getMatches((Map<String, Object>)match); result.addAll(remoteMatches); } return result; } protected String encode(String plainText) throws UnsupportedEncodingException { return URLEncoder.encode(plainText, StandardCharsets.UTF_8.name()); } @NotNull private List<RuleMatch> getMatches(Map<String, Object> match) { List<RuleMatch> remoteMatches = new ArrayList<>(); ArrayList matches = (ArrayList) match.get("lGrammarErrors"); for (Object o : matches) { Map pairs = (Map) o; int offset = (int) pairs.get("nStart"); int endOffset = (int)pairs.get("nEnd"); String id = (String)pairs.get("sRuleId"); if (ignoreRules.contains(id)) { continue; } String message = pairs.get("sMessage").toString(); GrammalecteInternalRule rule = new GrammalecteInternalRule("grammalecte_" + id, message); RuleMatch extMatch = new RuleMatch(rule, null, offset, endOffset, message); List<String> suggestions = (List<String>) pairs.get("aSuggestions"); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZZ"); //System.out.println(sdf.format(new Date()) + " Grammalecte: " + pairs.get("sRuleId") + "; " + pairs.get("sMessage") + " => " + suggestions); extMatch.setSuggestedReplacements(suggestions); remoteMatches.add(extMatch); } return remoteMatches; } class GrammalecteInternalRule extends Rule { private String id; private String desc; GrammalecteInternalRule(String id, String desc) { this.id = id; this.desc = desc; } @Override public String getId() { return id; } @Override public String getDescription() { return desc; } @Override public RuleMatch[] match(AnalyzedSentence sentence) { throw new RuntimeException("Not implemented"); } } }
package org.languagetool.rules.fr; import com.fasterxml.jackson.databind.ObjectMapper; import org.jetbrains.annotations.NotNull; import org.languagetool.AnalyzedSentence; import org.languagetool.GlobalConfig; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; /** * Queries a local Grammalecte server. * @since 4.6 */ public class GrammalecteRule extends Rule { private static final Logger logger = LoggerFactory.getLogger(GrammalecteRule.class); private static final int TIMEOUT_MILLIS = 500; private static final long DOWN_INTERVAL_MILLISECONDS = 5000; private static long lastRequestError = 0; private final ObjectMapper mapper = new ObjectMapper(); private final GlobalConfig globalConfig; private final Set<String> ignoreRules = new HashSet<>(Arrays.asList( "tab_fin_ligne", "apostrophe_typographique", "typo_guillemets_typographiques_doubles_ouvrants", "nbsp_avant_double_ponctuation", "typo_guillemets_typographiques_doubles_fermants", "nbsp_avant_deux_points", // Useful only if we decide to have the rest of the non-breakable space rules. "nbsp_ajout_avant_double_ponctuation", // Useful only if we decide to have the rest of the non-breakable space rules. "apostrophe_typographique_après_t", // Not useful. While being the technically correct character, it does not matter much. "typo_tiret_début_ligne", // Arguably the same as 50671 and 17342 ; the french special character for lists is a 'tiret cadratin' ; so it should be that instead of a dash. Having it count as a mistake is giving access to the otherwise unaccessible special character. However, lists are a common occurrence, and the special character does not make a real difference. Not really useful but debatable "typo_guillemets_typographiques_simples_fermants", "typo_apostrophe_incorrecte", "unit_nbsp_avant_unités1", "unit_nbsp_avant_unités2", "unit_nbsp_avant_unités3", "nbsp_après_double_ponctuation", "typo_guillemets_typographiques_simples_ouvrants", "num_grand_nombre_avec_espaces", "num_grand_nombre_soudé", "typo_parenthèse_ouvrante_collée", // we already have UNPAIRED_BRACKETS "nbsp_après_chevrons_ouvrants", "nbsp_avant_chevrons_fermants", "nbsp_avant_chevrons_fermants1", "nbsp_avant_chevrons_fermants2", "typo_points_suspension1", "typo_points_suspension2", "typo_points_suspension3", "typo_tiret_incise", // picky "esp_avant_après_tiret", // picky "nbsp_après_tiret1", // picky "nbsp_après_tiret2", // picky "esp_mélangés1", // picky "esp_mélangés2", // picky "tab_début_ligne", "esp_milieu_ligne", // we already have WHITESPACE_RULE "typo_ponctuation_superflue1", // false alarm (1, 2, ...) "esp_insécables_multiples", // temp disabled, unsure how this works with the browser add-ons "typo_espace_manquant_après1", // false alarm in urls (e.g. '&rk=...') "typo_espace_manquant_après2", // false alarm in urls (e.g. '&rk=...') "typo_espace_manquant_après3", // false alarm in file names (e.g. 'La teaser.zip') "typo_tiret_incise2", // picky "eepi_écriture_épicène_singulier", "g1__bs_vidéoprotection__b1_a1_1", "g1__eleu_élisions_manquantes__b1_a1_1", // picky "typo_tiret_incise1", // picky "p_sigle2", // picky "g0__imp_verbes_composés_impératifs__b12_a2_1", "g0__imp_verbes_composés_impératifs__b12_a3_1", "g0__imp_verbes_composés_impératifs__b5_a2_1", "g2__gn_tous_det_nom__b1_a2_1", "g2__gn_tous_det_nom__b2_a2_1", "g2__gn_tous_nom__b2_a1_1", "g2__gn_tout_det__b2_a1_1", "g2__gn_tout_nom__b1_a1_1", "g2__gn_tout_nom__b2_a1_1", "g2__gn_toute_nom__b1_a1_1", "g2__gn_toute_nom__b2_a1_1", "g2__gn_toutes_nom__b1_a1_1", "g2__gn_toutes_nom__b2_a1_1", "g2__gn_toutes_nom__b2_a2_1", "g2__maj_Dieu__b1_a1_1", "g3__gn_2m_et_ou__b1_a1_1", "g3__gn_2m_et_ou__b1_a2_1", "g3__gn_adverbe_fort__b1_a1_1", "g3__gn_adverbe_juste__b1_a1_1", "g3__gn_au_1m__b1_a1_1", "g3__gn_au_1m__b1_a2_1", "g3__gn_au_1m__b1_a3_1", "g3__gn_au_1m__b2_a1_1", "g3__gn_aucun_1m__b1_a1_1", "g3__gn_aucun_1m__b1_a2_1", "g3__gn_aucun_1m__b1_a3_1", "g3__gn_aucune_1m__b1_a3_1", "g3__gn_ce_1m__b1_a1_1", "g3__gn_ce_1m__b1_a2_1", "g3__gn_ce_1m__b1_a3_1", "g3__gn_ce_1m__b1_a4_1", "g3__gn_celle__b1_a2_1", "g3__gn_celles__b1_a1_1", "g3__gn_certaines_1m__b1_a2_1", "g3__gn_certaines_1m__b1_a3_1", "g3__gn_certains_1m__b1_a3_1", "g3__gn_ces_aux_pluriel_1m__b1_a1_1", "g3__gn_ces_aux_pluriel_1m__b1_a3_1", "g3__gn_ces_aux_pluriel_1m__b1_a4_1", "g3__gn_cet_1m__b1_a3_1", "g3__gn_cette_1m__b1_a1_1", "g3__gn_cette_1m__b1_a2_1", "g3__gn_cette_1m__b1_a3_1", "g3__gn_des_2m__b1_a2_1", "g3__gn_des_2m__b1_a3_1", "g3__gn_des_2m__b1_a4_1", "g3__gn_det_epi_plur_1m__b1_a1_1", "g3__gn_det_epi_plur_2m__b1_a2_1", "g3__gn_det_epi_plur_2m__b1_a3_1", "g3__gn_det_epi_plur_2m__b1_a4_1", "g3__gn_det_epi_plur_2m__b2_a3_1", "g3__gn_det_epi_plur_2m__b2_a4_1", "g3__gn_det_epi_plur_3m__b1_a3_1", "g3__gn_det_epi_plur_3m__b1_a4_1", "g3__gn_det_epi_sing_2m__b1_a2_1", "g3__gn_det_epi_sing_2m__b1_a3_1", "g3__gn_det_epi_sing_2m__b2_a2_1", "g3__gn_det_epi_sing_2m__b2_a3_1", "g3__gn_det_epi_sing_2m_virg__b1_a1_1", "g3__gn_det_epi_sing_3m__b1_a2_1", "g3__gn_det_fem_plur_2m__b1_a3_1", "g3__gn_det_fem_sing_2m__b1_a2_1", "g3__gn_det_fem_sing_2m__b1_a3_1", "g3__gn_det_fem_sing_2m__b2_a2_1", "g3__gn_det_fem_sing_2m_virg__b1_a1_1", "g3__gn_det_fem_sing_3m__b1_a1_1", "g3__gn_det_les_3m__b1_a2_1", "g3__gn_det_les_3m__b1_a3_1", "g3__gn_det_les_3m__b1_a4_1", "g3__gn_det_les_3m_et__b1_a2_1", "g3__gn_det_les_3m_et__b1_a3_1", "g3__gn_det_les_3m_et__b3_a5_1", "g3__gn_det_les_3m_et__b3_a6_1", "g3__gn_det_mas_plur_2m__b1_a2_1", "g3__gn_det_mas_plur_3m__b1_a1_1", "g3__gn_det_mas_sing_2m__b1_a2_1", "g3__gn_det_mas_sing_2m__b1_a3_1", "g3__gn_det_mas_sing_2m__b2_a2_1", "g3__gn_det_mas_sing_2m__b2_a3_1", "g3__gn_det_mas_sing_2m_virg__b1_a1_1", "g3__gn_det_mas_sing_3m__b1_a1_1", "g3__gn_det_mas_sing_3m_et__b3_a1_1", "g3__gn_det_mon_ton_son_3m__b1_a2_1", "g3__gn_det_mon_ton_son_3m_et__b4_a1_1", "g3__gn_det_nom_de_det_nom_adj_fem_sing__b1_a1_1", "g3__gn_det_nom_de_det_nom_adj_fem_sing__b3_a1_1", "g3__gn_det_nom_de_det_nom_adj_fem_sing__b7_a1_1", "g3__gn_det_nom_de_det_nom_adj_fem_sing__b9_a1_1", "g3__gn_det_nom_de_det_nom_adj_mas_sing__b1_a1_1", "g3__gn_det_nom_de_det_nom_adj_mas_sing__b3_a1_1", "g3__gn_det_nom_de_det_nom_adj_plur__b2_a1_1", "g3__gn_det_nom_de_det_nom_adj_sing__b1_a1_1", "g3__gn_det_nom_de_det_nom_adj_sing_plur__b1_a1_1", "g3__gn_det_nom_de_det_nom_adj_sing_plur__b2_a1_1", "g3__gn_det_nom_de_det_nom_adj_sing_plur__b6_a1_1", "g3__gn_det_nom_et_det_nom__b1_a1_1", "g3__gn_du_1m__b1_a1_1", "g3__gn_du_1m__b1_a2_1", "g3__gn_du_1m__b1_a3_1", "g3__gn_du_1m__b2_a1_1", "g3__gn_du_1m__b2_a2_1", "g3__gn_groupe_de__b2_a1_1", "g3__gn_groupe_de__b3_a1_1", "g3__gn_intérieur_extérieur__b1_a1_1", "g3__gn_l_1m__b1_a1_1", "g3__gn_l_1m__b2_a1_1", "g3__gn_l_1m__b3_a1_1", "g3__gn_l_2m__b1_a2_1", "g3__gn_l_2m__b1_a3_1", "g3__gn_l_2m__b1_a4_1", "g3__gn_l_2m__b2_a2_1", "g3__gn_l_2m__b2_a3_1", "g3__gn_l_2m__b2_a4_1", "g3__gn_l_2m_virg__b1_a1_1", "g3__gn_l_3m__b1_a2_1", "g3__gn_l_3m__b1_a3_1", "g3__gn_la_1m__b1_a2_1", "g3__gn_la_1m__b1_a3_1", "g3__gn_la_1m__b2_a2_1", "g3__gn_la_1m__b2_a3_1", "g3__gn_la_1m__b2_a4_1", "g3__gn_la_1m__b3_a1_1", "g3__gn_la_1m__b3_a2_1", "g3__gn_la_1m__b3_a3_1", "g3__gn_la_2m__b1_a2_1", "g3__gn_la_2m__b1_a3_1", "g3__gn_la_2m__b1_a4_1", "g3__gn_la_2m__b2_a2_1", "g3__gn_la_2m__b2_a4_1", "g3__gn_la_2m__b3_a2_1", "g3__gn_la_2m__b3_a4_1", "g3__gn_la_2m_virg__b1_a1_1", "g3__gn_le_1m__b2_a2_1", "g3__gn_le_1m__b2_a3_1", "g3__gn_le_1m__b2_a4_1", "g3__gn_le_1m__b2_a5_1", "g3__gn_le_1m__b3_a2_1", "g3__gn_le_1m__b3_a3_1", "g3__gn_le_1m__b3_a4_1", "g3__gn_le_1m__b3_a5_1", "g3__gn_le_1m__b4_a1_1", "g3__gn_le_1m__b4_a2_1", "g3__gn_le_1m__b4_a3_1", "g3__gn_le_1m__b4_a4_1", "g3__gn_le_2m__b1_a2_1", "g3__gn_le_2m__b1_a3_1", "g3__gn_le_2m__b1_a4_1", "g3__gn_le_2m__b2_a2_1", "g3__gn_le_2m_virg__b1_a1_1", "g3__gn_le_3m__b1_a1_1", "g3__gn_le_3m_et__b1_a1_1", "g3__gn_le_3m_et__b2_a1_1", "g3__gn_les_1m__b1_a1_1", "g3__gn_les_1m__b2_a1_1", "g3__gn_les_1m__b3_a1_1", "g3__gn_les_2m__b1_a2_1", "g3__gn_les_2m__b1_a3_1", "g3__gn_les_2m__b1_a4_1", "g3__gn_les_2m__b2_a4_1", "g3__gn_leur_1m__b1_a1_1", "g3__gn_leur_1m__b1_a2_1", "g3__gn_leur_1m__b2_a1_1", "g3__gn_leur_1m__b2_a2_1", "g3__gn_leur_2m__b1_a2_1", "g3__gn_leur_2m__b1_a4_1", "g3__gn_leur_2m__b1_a5_1", "g3__gn_leur_2m__b1_a5_1", "g3__gn_leur_2m__b2_a2_1", "g3__gn_leur_2m__b2_a4_1", "g3__gn_leurs_1m__b1_a1_1", "g3__gn_leurs_1m__b1_a2_1", "g3__gn_ma_ta_sa_1m__b1_a2_1", "g3__gn_ma_ta_sa_1m__b1_a3_1", "g3__gn_ma_ta_sa_1m__b1_a4_1", "g3__gn_mon_ton_son_1m__b1_a2_1", "g3__gn_mon_ton_son_1m__b1_a3_1", "g3__gn_mon_ton_son_1m__b1_a4_1", "g3__gn_mon_ton_son_2m__b1_a2_1", "g3__gn_mon_ton_son_2m__b1_a3_1", "g3__gn_mon_ton_son_2m__b1_a4_1", "g3__gn_mon_ton_son_2m__b2_a2_1", "g3__gn_nom_adj_2m__b1_a2_1", "g3__gn_nom_adj_2m__b1_a3_1", "g3__gn_nom_adj_2m__b1_a4_1", "g3__gn_nom_adj_2m__b1_a5_1", "g3__gn_nombre_chiffres_1m__b1_a1_1", "g3__gn_nombre_chiffres_1m__b2_a1_1", "g3__gn_nombre_chiffres_1m__b3_a2_1", "g3__gn_nombre_chiffres_1m__b3_a3_1", "g3__gn_nombre_chiffres_1m__b3_a4_1", "g3__gn_nombre_de_1m__b1_a1_1", "g3__gn_nombre_lettres_1m__b2_a1_1", "g3__gn_nombre_lettres_1m__b4_a1_1", "g3__gn_nombre_lettres_1m__b5_a1_1", "g3__gn_nombre_lettres_1m__b6_a1_1", "g3__gn_nombre_plur_2m__b1_a2_1", "g3__gn_nombre_plur_2m__b1_a3_1", "g3__gn_nombre_plur_2m__b1_a4_1", "g3__gn_notre_votre_chaque_1m__b1_a1_1", "g3__gn_nul_1m__b1_a1_1", "g3__gn_pfx_de_2m__b1_a2_1", "g3__gn_pfx_de_2m__b1_a3_1", "g3__gn_pfx_de_2m__b1_a4_1", "g3__gn_pfx_en_2m__b1_a1_1", "g3__gn_pfx_en_2m__b1_a2_1", "g3__gn_pfx_en_2m__b1_a3_1", "g3__gn_pfx_en_2m__b1_a4_1", "g3__gn_pfx_sur_avec_après_2m__b1_a1_1", "g3__gn_pfx_sur_avec_après_2m__b1_a2_1", "g3__gn_pfx_sur_avec_après_2m__b1_a3_1", "g3__gn_pfx_sur_avec_après_2m__b1_a4_1", "g3__gn_pfx_à_par_pour_sans_2m__b1_a1_1", "g3__gn_pfx_à_par_pour_sans_2m__b1_a2_1", "g3__gn_pfx_à_par_pour_sans_2m__b1_a3_1", "g3__gn_pfx_à_par_pour_sans_2m__b1_a4_1", "g3__gn_plein_de__b1_a1_1", "g3__gn_plusieurs_1m__b1_a1_1", "g3__gn_start_2m__b1_a1_1", "g3__gn_start_2m__b1_a2_1", "g3__gn_start_2m__b1_a3_1", "g3__gn_start_2m__b1_a4_1", "g3__gn_start_3m__b1_a1_1", "g3__gn_start_3m__b1_a2_1", "g3__gn_start_3m__b1_a3_1", "g3__gn_start_3m__b1_a4_1", "g3__gn_start_3m__b1_a5_1", "g3__gn_start_3m__b1_a6_1", "g3__gn_start_3m_et__b2_a2_1", "g3__gn_start_prn_1m__b1_a2_1", "g3__gn_un_1m__b2_a1_1", "g3__gn_un_1m__b2_a2_1", "g3__gn_un_1m__b2_a3_1", "g3__gn_un_2m__b1_a2_1", "g3__gn_un_2m__b1_a3_1", "g3__gn_un_2m__b1_a4_1", "g3__gn_un_2m__b2_a2_1", "g3__gn_un_2m__b2_a3_1", "g3__gn_un_2m__b2_a4_1", "g3__gn_un_des_1m__b1_a1_1", "g3__gn_un_des_1m__b1_a2_1", "g3__gn_une_1m__b1_a1_1", "g3__gn_une_1m__b1_a2_1", "g3__gn_une_1m__b1_a3_1", "g3__gn_une_2m__b1_a2_1", "g3__gn_une_2m__b1_a3_1", "g3__gn_une_2m__b1_a4_1", "g3__gn_une_2m__b2_a2_1", "g3__gn_une_2m__b2_a3_1", "g3__gn_une_2m__b2_a4_1", "g3__gn_une_2m_virg__b1_a1_1", "g3__gn_une_des_1m__b1_a1_1", "gv1__ppas_3pl_fem_verbe_état__b2_a1_1", "gv1__ppas_3pl_mas_verbe_état__b2_a1_1", "gv1__ppas_3pl_mas_verbe_état__b8_a1_1", "gv1__ppas_3sg_fem_verbe_état__b3_a1_1", "gv1__ppas_3sg_mas_verbe_état__b10_a1_1", "gv1__ppas_3sg_mas_verbe_état__b12_a1_2", "gv1__ppas_3sg_mas_verbe_état__b15_a1_1", "gv1__ppas_3sg_mas_verbe_état__b4_a1_1", "gv1__ppas_3sg_mas_verbe_état__b4_a1_2", "gv1__ppas_3sg_mas_verbe_état__b5_a1_1", "gv1__ppas_3sg_mas_verbe_état__b6_a2_1", "gv1__ppas_adj_accord_il__b1_a1_1", "gv1__ppas_adj_accord_ils__b1_a1_1", "gv1__ppas_adj_être_det_nom__b2_a1_1", "gv1__ppas_adj_être_det_nom__b3_a2_1", "gv1__ppas_avoir__b1_a1_1", "gv1__ppas_avoir_l_air__b5_a1_1", "gv1__ppas_avoir_l_air__b9_a2_1", "gv1__ppas_avoir_été__b2_a1_1", "gv1__ppas_det_plur_COD_que_avoir__b1_a3_1", "gv1__ppas_det_sing_COD_que_avoir__b4_a3_1", "gv1__ppas_fin_loc_verb_état_adj_et_adj__b1_a1_1", "gv1__ppas_je_tu_verbe_état__b1_a1_1", "gv1__ppas_je_tu_verbe_état__b2_a1_1", "gv1__ppas_je_tu_verbe_état__b3_a1_1", "gv1__ppas_le_verbe_pensée__b1_a1_1", "gv1__ppas_nous_verbe_état__b2_a1_1", "gv1__ppas_être_accord_plur__b2_a1_1", "gv1__ppas_être_accord_sing__b1_a1_1", "gv2__conf_ait_confiance_été_faim_tort__b1_a2_1", "gv2__conj_les_nom__b1_a2_1", "gv2__conj_quiconque__b1_a1_1", "g2__conf_a_à_substantifs__b1_a1_1", "g2__conf_a_à_verbe__b14_a2_1", "g2__conf_a_à_verbe__b14_a3_1", "g2__conf_a_à_verbe__b14_a6_1", "g2__conf_a_à_verbe__b15_a2_1", "g2__conf_a_à_verbe__b15_a3_1", "g2__conf_a_à_verbe__b1_a1_1", "g2__conf_celui_celle_à_qui__b1_a1_1", "g2__conf_à_a__b1_a1_1", "g2__conf_à_a__b2_a1_1", "g2__conf_à_a__b7_a1_1", "g2__conf_à_a_infinitif__b1_a1_1", "g2__conf_à_a__b3_a1_1", "g2__conf_à_a__b4_a1_1", "g2__conf_à_a__b5_a1_1", "g2__conf_à_qui_infinitif__b1_a1_1", "g3__conf_à_a_après_verbes__b2_a1_1", "g3__infi_à_verbe__b2_a1_1", "g3__infi_à_verbe__b3_a1_1", "gv1__ppas_avoir__b2_a1_1", "gv1__ppas_avoir__b3_a1_1", "gv1__ppas_avoir__b4_a1_1" )); public GrammalecteRule(ResourceBundle messages, GlobalConfig globalConfig) { super(messages); //addExamplePair(Example.wrong(""), // Example.fixed("")); this.globalConfig = globalConfig; } @Override public String getId() { return "FR_GRAMMALECTE"; } @Override public String getDescription() { return "Returns matches of a local Grammalecte server"; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { // very basic health check -> mark server as down after an error for given interval if (System.currentTimeMillis() - lastRequestError < DOWN_INTERVAL_MILLISECONDS) { logger.warn("Warn: Temporarily disabled Grammalecte server because of recent error."); return new RuleMatch[0]; } URL serverUrl = new URL(globalConfig.getGrammalecteServer()); HttpURLConnection huc = (HttpURLConnection) serverUrl.openConnection(); HttpURLConnection.setFollowRedirects(false); huc.setConnectTimeout(TIMEOUT_MILLIS); huc.setReadTimeout(TIMEOUT_MILLIS*2); if (globalConfig.getGrammalecteUser() != null && globalConfig.getGrammalectePassword() != null) { String authString = globalConfig.getGrammalecteUser() + ":" + globalConfig.getGrammalectePassword(); String encoded = Base64.getEncoder().encodeToString(authString.getBytes()); huc.setRequestProperty("Authorization", "Basic " + encoded); } huc.setRequestMethod("POST"); huc.setDoOutput(true); try { huc.connect(); try (DataOutputStream wr = new DataOutputStream(huc.getOutputStream())) { String urlParameters = "text=" + encode(sentence.getText()); byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); wr.write(postData); } InputStream input = huc.getInputStream(); List<RuleMatch> ruleMatches = parseJson(input); return toRuleMatchArray(ruleMatches); } catch (Exception e) { lastRequestError = System.currentTimeMillis(); // These are issue that can be request-specific, like wrong parameters. We don't throw an // exception, as the calling code would otherwise assume this is a persistent error: logger.warn("Warn: Failed to query Grammalecte server at " + serverUrl + ": " + e.getClass() + ": " + e.getMessage()); e.printStackTrace(); } finally { huc.disconnect(); } return new RuleMatch[0]; } @NotNull private List<RuleMatch> parseJson(InputStream inputStream) throws IOException { Map map = mapper.readValue(inputStream, Map.class); List matches = (ArrayList) map.get("data"); if (matches == null) { throw new RuntimeException("No 'data' found in grammalecte JSON: " + map); // handled in match() } List<RuleMatch> result = new ArrayList<>(); for (Object match : matches) { List<RuleMatch> remoteMatches = getMatches((Map<String, Object>)match); result.addAll(remoteMatches); } return result; } protected String encode(String plainText) throws UnsupportedEncodingException { return URLEncoder.encode(plainText, StandardCharsets.UTF_8.name()); } @NotNull private List<RuleMatch> getMatches(Map<String, Object> match) { List<RuleMatch> remoteMatches = new ArrayList<>(); ArrayList matches = (ArrayList) match.get("lGrammarErrors"); for (Object o : matches) { Map pairs = (Map) o; int offset = (int) pairs.get("nStart"); int endOffset = (int)pairs.get("nEnd"); String id = (String)pairs.get("sRuleId"); if (ignoreRules.contains(id)) { continue; } String message = pairs.get("sMessage").toString(); GrammalecteInternalRule rule = new GrammalecteInternalRule("grammalecte_" + id, message); RuleMatch extMatch = new RuleMatch(rule, null, offset, endOffset, message); List<String> suggestions = (List<String>) pairs.get("aSuggestions"); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZZ"); //System.out.println(sdf.format(new Date()) + " Grammalecte: " + pairs.get("sRuleId") + "; " + pairs.get("sMessage") + " => " + suggestions); extMatch.setSuggestedReplacements(suggestions); remoteMatches.add(extMatch); } return remoteMatches; } static class GrammalecteInternalRule extends Rule { private final String id; private final String desc; GrammalecteInternalRule(String id, String desc) { this.id = id; this.desc = desc; } @Override public String getId() { return id; } @Override public String getDescription() { return desc; } @Override public RuleMatch[] match(AnalyzedSentence sentence) { throw new RuntimeException("Not implemented"); } } }
package com.dqc.qlibrary.utils; import com.orhanobut.logger.Logger; public class QLog { private static boolean mAllowLog = true; public static void init(boolean allowLog, String tag) { mAllowLog = allowLog; Logger.init(tag).hideThreadInfo(); } /** * verbose * * @param msg */ public static void v(String msg) { if (mAllowLog) { Logger.v(msg); } } /** * debug * * @param o */ public static void d(Object o) { if (mAllowLog) { Logger.d(o); } } /** * info * * @param msg */ public static void i(String msg) { if (mAllowLog) { Logger.i(msg); } } /** * warning * * @param msg */ public static void w(String msg) { if (mAllowLog) { Logger.w(msg); } } /** * error * * @param msg */ public static void e(String msg) { if (mAllowLog) { Logger.e(msg); } } /** * error * * @param msg */ public static void e(Throwable throwable, String msg) { if (mAllowLog) { Logger.e(throwable, msg); } } /** * wtf * * @param msg */ public static void wtf(String msg) { if (mAllowLog) { Logger.wtf(msg); } } /** * json * * @param json */ public static void json(String json) { if (mAllowLog) { Logger.json(json); } } /** * xml * * @param xml */ public static void xml(String xml) { if (mAllowLog) { Logger.xml(xml); } } }
package com.orm.util; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.util.Log; import com.orm.SugarRecord; import com.orm.dsl.Ignore; import com.orm.dsl.Table; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.net.URL; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import static com.orm.util.ContextUtil.getContext; public class ReflectionUtil { public static List<Field> getTableFields(Class table) { List<Field> fieldList = SugarConfig.getFields(table); if (fieldList != null) return fieldList; Log.d("Sugar", "Fetching properties"); List<Field> typeFields = new ArrayList<>(); getAllFields(typeFields, table); List<Field> toStore = new ArrayList<>(); for (Field field : typeFields) { if (!field.isAnnotationPresent(Ignore.class) && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { toStore.add(field); } } SugarConfig.setFields(table, toStore); return toStore; } private static List<Field> getAllFields(List<Field> fields, Class<?> type) { Collections.addAll(fields, type.getDeclaredFields()); if (type.getSuperclass() != null) { fields = getAllFields(fields, type.getSuperclass()); } return fields; } public static void addFieldValueToColumn(ContentValues values, Field column, Object object, Map<Object, Long> entitiesMap) { column.setAccessible(true); Class<?> columnType = column.getType(); try { String columnName = NamingHelper.toSQLName(column); Object columnValue = column.get(object); if (columnType.isAnnotationPresent(Table.class)) { Field field; try { field = columnType.getDeclaredField("id"); field.setAccessible(true); values.put(columnName, (field != null) ? String.valueOf(field.get(columnValue)) : "0"); } catch (NoSuchFieldException e) { if (entitiesMap.containsKey(columnValue)) { values.put(columnName, entitiesMap.get(columnValue)); } } } else if (SugarRecord.class.isAssignableFrom(columnType)) { values.put(columnName, (columnValue != null) ? String.valueOf(((SugarRecord) columnValue).getId()) : "0"); } else { if (columnType.equals(Short.class) || columnType.equals(short.class)) { values.put(columnName, (Short) columnValue); } else if (columnType.equals(Integer.class) || columnType.equals(int.class)) { values.put(columnName, (Integer) columnValue); } else if (columnType.equals(Long.class) || columnType.equals(long.class)) { values.put(columnName, (Long) columnValue); } else if (columnType.equals(Float.class) || columnType.equals(float.class)) { values.put(columnName, (Float) columnValue); } else if (columnType.equals(Double.class) || columnType.equals(double.class)) { values.put(columnName, (Double) columnValue); } else if (columnType.equals(Boolean.class) || columnType.equals(boolean.class)) { values.put(columnName, (Boolean) columnValue); } else if (columnType.equals(BigDecimal.class)) { try { values.put(columnName, column.get(object).toString()); } catch (NullPointerException e) { values.putNull(columnName); } } else if (Timestamp.class.equals(columnType)) { try { values.put(columnName, ((Timestamp) column.get(object)).getTime()); } catch (NullPointerException e) { values.put(columnName, (Long) null); } } else if (Date.class.equals(columnType)) { try { values.put(columnName, ((Date) column.get(object)).getTime()); } catch (NullPointerException e) { values.put(columnName, (Long) null); } } else if (Calendar.class.equals(columnType)) { try { values.put(columnName, ((Calendar) column.get(object)).getTimeInMillis()); } catch (NullPointerException e) { values.put(columnName, (Long) null); } } else if (columnType.equals(byte[].class)) { if (columnValue == null) { values.put(columnName, "".getBytes()); } else { values.put(columnName, (byte[]) columnValue); } } else { if (columnValue == null) { values.putNull(columnName); } else if (columnType.isEnum()) { values.put(columnName, ((Enum) columnValue).name()); } else { values.put(columnName, String.valueOf(columnValue)); } } } } catch (IllegalAccessException e) { Log.e("Sugar", e.getMessage()); } } public static void setFieldValueFromCursor(Cursor cursor, Field field, Object object) { field.setAccessible(true); try { Class fieldType = field.getType(); String colName = NamingHelper.toSQLName(field); int columnIndex = cursor.getColumnIndex(colName); //TODO auto upgrade to add new columns if (columnIndex < 0) { Log.e("SUGAR", "Invalid colName, you should upgrade database"); return; } if (cursor.isNull(columnIndex)) { return; } if (colName.equalsIgnoreCase("id")) { long cid = cursor.getLong(columnIndex); field.set(object, cid); } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) { field.set(object, cursor.getLong(columnIndex)); } else if (fieldType.equals(String.class)) { String val = cursor.getString(columnIndex); field.set(object, val != null && val.equals("null") ? null : val); } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) { field.set(object, cursor.getDouble(columnIndex)); } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) { field.set(object, cursor.getString(columnIndex).equals("1")); } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) { field.set(object, cursor.getInt(columnIndex)); } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) { field.set(object, cursor.getFloat(columnIndex)); } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) { field.set(object, cursor.getShort(columnIndex)); } else if (fieldType.equals(BigDecimal.class)) { String val = cursor.getString(columnIndex); field.set(object, val != null && val.equals("null") ? null : new BigDecimal(val)); } else if (fieldType.equals(Timestamp.class)) { long l = cursor.getLong(columnIndex); field.set(object, new Timestamp(l)); } else if (fieldType.equals(Date.class)) { long l = cursor.getLong(columnIndex); field.set(object, new Date(l)); } else if (fieldType.equals(Calendar.class)) { long l = cursor.getLong(columnIndex); Calendar c = Calendar.getInstance(); c.setTimeInMillis(l); field.set(object, c); } else if (fieldType.equals(byte[].class)) { byte[] bytes = cursor.getBlob(columnIndex); if (bytes == null) { field.set(object, "".getBytes()); } else { field.set(object, cursor.getBlob(columnIndex)); } } else if (Enum.class.isAssignableFrom(fieldType)) { try { Method valueOf = field.getType().getMethod("valueOf", String.class); String strVal = cursor.getString(columnIndex); Object enumVal = valueOf.invoke(field.getType(), strVal); field.set(object, enumVal); } catch (Exception e) { Log.e("Sugar", "Enum cannot be read from Sqlite3 database. Please check the type of field " + field.getName()); } } else Log.e("Sugar", "Class cannot be read from Sqlite3 database. Please check the type of field " + field.getName() + "(" + field.getType().getName() + ")"); } catch (IllegalArgumentException | IllegalAccessException e) { Log.e("field set error", e.getMessage()); } } private static Field getDeepField(String fieldName, Class<?> type) throws NoSuchFieldException { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class superclass = type.getSuperclass(); if (superclass != null) { return getDeepField(fieldName, superclass); } else { throw e; } } } public static void setFieldValueForId(Object object, Long value) { try { Field field = getDeepField("id", object.getClass()); field.setAccessible(true); field.set(object, value); } catch (Exception e) { e.printStackTrace(); } } public static List<Class> getDomainClasses() { List<Class> domainClasses = new ArrayList<>(); try { for (String className : getAllClasses()) { Class domainClass = getDomainClass(className); if (domainClass != null) domainClasses.add(domainClass); } } catch (IOException | PackageManager.NameNotFoundException e) { Log.e("Sugar", e.getMessage()); } return domainClasses; } private static Class getDomainClass(String className) { Class<?> discoveredClass = null; try { discoveredClass = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); } catch (Throwable e) { String error = (e.getMessage() == null) ? "getDomainClass " + className + " error" : e.getMessage(); Log.e("Sugar", error); } if ((discoveredClass != null) && ((SugarRecord.class.isAssignableFrom(discoveredClass) && !SugarRecord.class.equals(discoveredClass)) || discoveredClass.isAnnotationPresent(Table.class)) && !Modifier.isAbstract(discoveredClass.getModifiers())) { Log.i("Sugar", "domain class : " + discoveredClass.getSimpleName()); return discoveredClass; } else { return null; } } private static List<String> getAllClasses() throws PackageManager.NameNotFoundException, IOException { String packageName = ManifestHelper.getDomainPackageName(); List<String> classNames = new ArrayList<>(); try { List<String> allClasses = MultiDexHelper.getAllClasses(); for (String classString : allClasses) { if (classString.startsWith(packageName)) classNames.add(classString); } } catch (NullPointerException e) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> urls = classLoader.getResources(""); while (urls.hasMoreElements()) { List<String> fileNames = new ArrayList<>(); String classDirectoryName = urls.nextElement().getFile(); if (classDirectoryName.contains("bin") || classDirectoryName.contains("classes") || classDirectoryName.contains("retrolambda")) { File classDirectory = new File(classDirectoryName); for (File filePath : classDirectory.listFiles()) { populateFiles(filePath, fileNames, ""); } for (String fileName : fileNames) { if (fileName.startsWith(packageName)) classNames.add(fileName); } } } } // } finally { // if (null != dexfile) dexfile.close(); return classNames; } private static void populateFiles(File path, List<String> fileNames, String parent) { if (path.isDirectory()) { for (File newPath : path.listFiles()) { if ("".equals(parent)) { populateFiles(newPath, fileNames, path.getName()); } else { populateFiles(newPath, fileNames, parent + "." + path.getName()); } } } else { String pathName = path.getName(); String classSuffix = ".class"; pathName = pathName.endsWith(classSuffix) ? pathName.substring(0, pathName.length() - classSuffix.length()) : pathName; if ("".equals(parent)) { fileNames.add(pathName); } else { fileNames.add(parent + "." + pathName); } } } private static String getSourcePath(Context context) throws PackageManager.NameNotFoundException { return context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir; } }
package wyc.io; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.util.List; import java.util.Map; import wybs.util.Pair; import wyc.lang.Expr; import wyc.lang.Stmt; import wyc.lang.SyntacticType; import wyc.lang.WhileyFile; import wyil.lang.*; /** * Responsible for "pretty printing" a Whiley File. This is useful for * formatting Whiley Files. Also, it can be used to programatically generate * Whiley Files. * * @author David J. Pearce * */ public class WhileyFilePrinter { private PrintStream out; public WhileyFilePrinter(OutputStream stream) { try { this.out = new PrintStream(stream, true, "UTF-8"); } catch(Exception e) { this.out = new PrintStream(stream); } } public void print(WhileyFile wf) { for(WhileyFile.Declaration d : wf.declarations) { print(d); } out.flush(); } public void print(WhileyFile.Declaration decl) { if(decl instanceof WhileyFile.Import) { print((WhileyFile.Import)decl); } else if(decl instanceof WhileyFile.Constant) { print((WhileyFile.Constant)decl); } else if(decl instanceof WhileyFile.TypeDef) { print((WhileyFile.TypeDef)decl); } else if(decl instanceof WhileyFile.FunctionOrMethod) { print((WhileyFile.FunctionOrMethod)decl); } else { throw new RuntimeException("Unknown construct encountered: " + decl.getClass().getName()); } } public void print(WhileyFile.FunctionOrMethod fm) { out.println(); print(fm.modifiers); print(fm.ret); out.print(" "); int paramStart = 0; if(fm instanceof WhileyFile.Method) { WhileyFile.Method m = (WhileyFile.Method) fm; // FIXME: this is a hack!! if(m.parameters.size() > 0 && m.parameters.get(0).name.equals("this")) { print(m.parameters.get(0).type); paramStart++; } out.print("::"); } out.print(fm.name); out.print("("); boolean firstTime = true; for(int i = paramStart; i < fm.parameters.size();++i) { WhileyFile.Parameter p = fm.parameters.get(i); if(!firstTime) { out.print(", "); } firstTime=false; print(p.type); out.print(" "); out.print(p.name); } out.print(")"); if(!(fm.throwType instanceof SyntacticType.Void)) { out.print(" throws "); print(fm.throwType); } firstTime = true; for(Expr r : fm.requires) { if(!firstTime) { out.println(","); } else { out.println(); firstTime = false; } out.print("requires "); print(r); } for(Expr r : fm.ensures) { if(!firstTime) { out.println(","); } else { out.println(); firstTime = false; } out.print("ensures "); print(r); } out.println(":"); print(fm.statements,1); } public void print(WhileyFile.Import decl) { out.print("import "); if(decl.name != null) { out.print(decl.name); out.print(" from "); } for(int i=0;i!=decl.filter.size();++i) { if(i != 0) { out.print("."); } String item = decl.filter.get(i); if(!item.equals("**")) { out.print(decl.filter.get(i)); } } out.println(); } public void print(WhileyFile.Constant decl) { out.println(); out.print("define "); out.print(decl.name); out.print(" as "); print(decl.constant); out.println(); } public void print(WhileyFile.TypeDef decl) { out.println(); out.print("define "); out.print(decl.name); out.print(" as "); print(decl.unresolvedType); out.println(); // TODO: constraints } public void print(List<Stmt> statements, int indent) { for(Stmt s : statements) { print(s,indent); } } public void print(Stmt stmt, int indent) { indent(indent); if(stmt instanceof Stmt.Assert) { print((Stmt.Assert) stmt); } else if(stmt instanceof Stmt.Assign) { print((Stmt.Assign) stmt); } else if(stmt instanceof Stmt.Assume) { print((Stmt.Assume) stmt); } else if(stmt instanceof Stmt.Break) { print((Stmt.Break) stmt); } else if(stmt instanceof Stmt.Continue) { print((Stmt.Continue) stmt); } else if(stmt instanceof Stmt.Debug) { print((Stmt.Debug) stmt); } else if(stmt instanceof Stmt.DoWhile) { print((Stmt.DoWhile) stmt, indent); } else if(stmt instanceof Stmt.ForAll) { print((Stmt.ForAll) stmt, indent); } else if(stmt instanceof Stmt.IfElse) { print((Stmt.IfElse) stmt, indent); } else if(stmt instanceof Stmt.Return) { print((Stmt.Return) stmt); } else if(stmt instanceof Stmt.Skip) { print((Stmt.Skip) stmt); } else if(stmt instanceof Stmt.Switch) { print((Stmt.Switch) stmt, indent); } else if(stmt instanceof Stmt.Throw) { print((Stmt.Throw) stmt); } else if(stmt instanceof Stmt.TryCatch) { print((Stmt.TryCatch) stmt, indent); } else if(stmt instanceof Stmt.While) { print((Stmt.While) stmt, indent); } else if(stmt instanceof Expr.AbstractInvoke) { print((Expr.AbstractInvoke) stmt); out.println(); } else { // should be dead-code throw new RuntimeException("Unknown statement kind encountered: " + stmt.getClass().getName()); } } public void print(Stmt.Assert s) { out.print("assert "); print(s.expr); out.println(); } public void print(Stmt.Assume s) { out.print("assert "); print(s.expr); out.println(); } public void print(Stmt.Debug s) { out.print("debug "); print(s.expr); out.println(); } public void print(Stmt.Throw s) { out.print("throw "); print(s.expr); out.println(); } public void print(Stmt.Break s) { out.println("break"); } public void print(Stmt.Continue s) { out.println("break"); } public void print(Stmt.Skip s) { out.println("skip"); } public void print(Stmt.Return s) { out.print("return"); if(s.expr != null) { out.print(" "); print(s.expr); } out.println(); } public void print(Stmt.Assign s) { print(s.lhs); out.print(" = "); print(s.rhs); out.println(); } public void print(Stmt.IfElse s, int indent) { out.print("if "); print(s.condition); out.println(":"); print(s.trueBranch,indent+1); if(!s.falseBranch.isEmpty()) { indent(indent); out.println("else:"); print(s.falseBranch, indent+1); } } public void print(Stmt.DoWhile s, int indent) { out.println("do:"); print(s.body,indent+1); indent(indent); // TODO: loop invariant out.print("while "); print(s.condition); out.println(); } public void print(Stmt.While s, int indent) { out.print("while "); print(s.condition); boolean firstTime = true; for(Expr i : s.invariants) { if(!firstTime) { out.print(","); } else { firstTime = false; } out.print(" where "); print(i); } // TODO: loop invariant out.println(":"); print(s.body,indent+1); } public void print(Stmt.ForAll s, int indent) { out.print("for "); boolean firstTime = true; for(String v : s.variables) { if(!firstTime) { out.print(", "); } firstTime=false; out.print(v); } out.print(" in "); print(s.source); if(s.invariant != null) { out.print(" where "); print(s.invariant); } out.println(":"); print(s.body,indent+1); } public void print(Stmt.Switch s, int indent) { out.print("switch "); print(s.expr); out.println(":"); for(Stmt.Case cas : s.cases) { indent(indent+1); boolean firstTime = true; if(cas.expr.isEmpty()) { out.print("default"); } else { out.print("case "); for(Expr e : cas.expr) { if(!firstTime) { out.print(", "); } firstTime=false; print(e); } } out.println(":"); print(cas.stmts,indent+2); } } public void print(Stmt.TryCatch s, int indent) { out.println("try:"); print(s.body,indent+1); for(Stmt.Catch handler : s.catches) { indent(indent); out.print("catch("); print(handler.unresolvedType); out.print(" " + handler.variable); out.println("):"); print(handler.stmts, indent+1); } } public void printWithBrackets(Expr expression, Class<? extends Expr>... matches) { boolean withBrackets = false; // First, decide whether brackets are needed or not for(Class<? extends Expr> match : matches) { if(match.isInstance(expression)) { withBrackets = true; break; } } // Second, print with brackets if needed if(withBrackets) { out.print("("); print(expression); out.print(")"); } else { print(expression); } } public void print(Expr expression) { if (expression instanceof Expr.Constant) { print ((Expr.Constant) expression); } else if (expression instanceof Expr.AbstractVariable) { print ((Expr.AbstractVariable) expression); } else if (expression instanceof Expr.ConstantAccess) { print ((Expr.ConstantAccess) expression); } else if (expression instanceof Expr.Set) { print ((Expr.Set) expression); } else if (expression instanceof Expr.List) { print ((Expr.List) expression); } else if (expression instanceof Expr.SubList) { print ((Expr.SubList) expression); } else if (expression instanceof Expr.SubString) { print ((Expr.SubString) expression); } else if (expression instanceof Expr.BinOp) { print ((Expr.BinOp) expression); } else if (expression instanceof Expr.LengthOf) { print ((Expr.LengthOf) expression); } else if (expression instanceof Expr.Dereference) { print ((Expr.Dereference) expression); } else if (expression instanceof Expr.Convert) { print ((Expr.Convert) expression); } else if (expression instanceof Expr.IndexOf) { print ((Expr.IndexOf) expression); } else if (expression instanceof Expr.UnOp) { print ((Expr.UnOp) expression); } else if (expression instanceof Expr.AbstractInvoke) { print ((Expr.AbstractInvoke) expression); } else if (expression instanceof Expr.IndirectFunctionCall) { print ((Expr.IndirectFunctionCall) expression); } else if (expression instanceof Expr.IndirectMethodCall) { print ((Expr.IndirectMethodCall) expression); } else if (expression instanceof Expr.Comprehension) { print ((Expr.Comprehension) expression); } else if (expression instanceof Expr.AbstractDotAccess) { print ((Expr.AbstractDotAccess) expression); } else if (expression instanceof Expr.Record) { print ((Expr.Record) expression); } else if (expression instanceof Expr.Tuple) { print ((Expr.Tuple) expression); } else if (expression instanceof Expr.Map) { print ((Expr.Map) expression); } else if (expression instanceof Expr.AbstractFunctionOrMethod) { print ((Expr.AbstractFunctionOrMethod) expression); } else if (expression instanceof Expr.Lambda) { print ((Expr.Lambda) expression); } else if (expression instanceof Expr.New) { print ((Expr.New) expression); } else if (expression instanceof Expr.TypeVal) { print ((Expr.TypeVal) expression); } else if (expression instanceof Expr.RationalLVal) { print ((Expr.RationalLVal) expression); } else { // should be dead-code throw new RuntimeException("Unknown expression kind encountered: " + expression.getClass().getName()); } } public void print(Expr.Constant c) { out.print(c.value); } public void print(Expr.AbstractVariable v) { out.print(v); } public void print(Expr.ConstantAccess v) { out.print(v.nid); } public void print(Expr.Set e) { out.print("{"); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print("}"); } public void print(Expr.List e) { out.print("["); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print("]"); } public void print(Expr.SubList e) { print(e.src); out.print("["); print(e.start); out.print(".."); print(e.end); out.print("]"); } public void print(Expr.SubString e) { print(e.src); out.print("["); print(e.start); out.print(".."); print(e.end); out.print("]"); } public void print(Expr.BinOp e) { printWithBrackets(e.lhs, Expr.BinOp.class, Expr.Convert.class); out.print(" "); out.print(e.op); out.print(" "); printWithBrackets(e.rhs, Expr.BinOp.class, Expr.Convert.class); } public void print(Expr.LengthOf e) { out.print("|"); print(e.src); out.print("|"); } public void print(Expr.Dereference e) { out.print("*"); print(e.src); } public void print(Expr.Convert e) { out.print("("); print(e.unresolvedType); out.print(") "); printWithBrackets(e.expr,Expr.BinOp.class,Expr.Convert.class); } public void print(Expr.IndexOf e) { print(e.src); out.print("["); print(e.index); out.print("]"); } public void print(Expr.UnOp e) { switch(e.op) { case NEG: out.print("-"); break; case NOT: out.print("!"); break; case INVERT: out.print("~"); break; } printWithBrackets(e.mhs,Expr.BinOp.class,Expr.Convert.class); } public void print(Expr.AbstractInvoke<Expr> e) { if(e.qualification != null) { printWithBrackets(e.qualification,Expr.New.class); out.print("."); } out.print(e.name); out.print("("); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.IndirectFunctionCall e) { print(e.src); out.print("("); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.IndirectMethodCall e) { print(e.src); out.print("("); boolean firstTime = true; for(Expr i : e.arguments) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.Comprehension e) { switch(e.cop) { case NONE: out.print("no "); break; case SOME: out.print("some "); break; case ALL: out.print("all "); break; } out.print("{ "); if(e.value != null) { print(e.value); out.print(" | "); boolean firstTime=true; for(Pair<String,Expr> src : e.sources) { if(!firstTime) { out.print(", "); } firstTime=false; out.print(src.first()); out.print(" in "); print(src.second()); } if(e.condition != null) { out.print(", "); print(e.condition); } } else { boolean firstTime=true; for(Pair<String,Expr> src : e.sources) { if(!firstTime) { out.print(", "); } firstTime=false; out.print(src.first()); out.print(" in "); print(src.second()); } out.print(" | "); print(e.condition); } out.print(" }"); } public void print(Expr.AbstractDotAccess e) { if(e.src instanceof Expr.Dereference) { printWithBrackets(((Expr.Dereference)e.src).src,Expr.New.class); out.print("->"); out.print(e.name); } else { printWithBrackets(e.src,Expr.New.class); out.print("."); out.print(e.name); } } public void print(Expr.Record e) { out.print("{"); boolean firstTime = true; for(Map.Entry<String,Expr> i : e.fields.entrySet()) { if(!firstTime) { out.print(", "); } firstTime=false; out.print(i.getKey()); out.print(": "); print(i.getValue()); } out.print("}"); } public void print(Expr.Tuple e) { out.print("("); boolean firstTime = true; for(Expr i : e.fields) { if(!firstTime) { out.print(", "); } firstTime=false; print(i); } out.print(")"); } public void print(Expr.Map e) { out.print("{"); if(e.pairs.isEmpty()) { out.print("=>"); } else { boolean firstTime = true; for(Pair<Expr,Expr> p : e.pairs) { if(!firstTime) { out.print(", "); } firstTime=false; print(p.first()); out.print("=>"); print(p.second()); } } out.print("}"); } public void print(Expr.AbstractFunctionOrMethod e) { out.print("&"); out.print(e.name); if(e.paramTypes != null && e.paramTypes.size() > 0) { out.print("("); boolean firstTime = true; for(SyntacticType t : e.paramTypes) { if(!firstTime) { out.print(", "); } firstTime=false; print(t); } out.print(")"); } } public void print(Expr.Lambda e) { out.print("&("); boolean firstTime = true; for(WhileyFile.Parameter p : e.parameters) { if(!firstTime) { out.print(", "); } firstTime=false; print(p.type); out.print(" "); out.print(p.name); } out.print(" -> "); print(e.body); out.print(")"); } public void print(Expr.New e) { out.print("new "); print(e.expr); } public void print(Expr.TypeVal e) { print(e.unresolvedType); } public void print(Expr.RationalLVal e) { print(e.numerator); out.print(" / "); print(e.denominator); } public void print(List<Modifier> modifiers) { for(Modifier m : modifiers) { out.print(m); out.print(" "); } } public void print(SyntacticType t) { if(t instanceof SyntacticType.Any) { out.print("any"); } else if(t instanceof SyntacticType.Bool) { out.print("bool"); } else if(t instanceof SyntacticType.Byte) { out.print("byte"); } else if(t instanceof SyntacticType.Char) { out.print("char"); } else if(t instanceof SyntacticType.Int) { out.print("int"); } else if(t instanceof SyntacticType.Null) { out.print("null"); } else if(t instanceof SyntacticType.Strung) { out.print("string"); } else if(t instanceof SyntacticType.Real) { out.print("real"); } else if(t instanceof SyntacticType.Void) { out.print("void"); } else if(t instanceof SyntacticType.Nominal) { SyntacticType.Nominal nt = (SyntacticType.Nominal) t; boolean firstTime = true; for(String name : nt.names) { if(!firstTime) { out.print("."); } firstTime=false; out.print(name); } } else if(t instanceof SyntacticType.Set) { out.print("{"); print(((SyntacticType.Set)t).element); out.print("}"); } else if(t instanceof SyntacticType.List) { out.print("["); print(((SyntacticType.List)t).element); out.print("]"); } else if(t instanceof SyntacticType.Map) { out.print("{"); print(((SyntacticType.Map)t).key); out.print("=>"); print(((SyntacticType.Map)t).value); out.print("}"); } else if(t instanceof SyntacticType.Tuple) { SyntacticType.Tuple tt = (SyntacticType.Tuple) t; out.print("("); boolean firstTime = true; for(SyntacticType et : tt.types) { if(!firstTime) { out.print(", "); } firstTime=false; print(et); } out.print(")"); } else if(t instanceof SyntacticType.FunctionOrMethod) { SyntacticType.FunctionOrMethod tt = (SyntacticType.FunctionOrMethod) t; print(tt.ret); if(t instanceof SyntacticType.Method) { out.print(" ::"); } out.print("("); boolean firstTime = true; for(SyntacticType et : tt.paramTypes) { if(!firstTime) { out.print(", "); } firstTime=false; print(et); } out.print(")"); } else if(t instanceof SyntacticType.Record) { SyntacticType.Record tt = (SyntacticType.Record) t; out.print("{"); boolean firstTime = true; for(Map.Entry<String, SyntacticType> et : tt.types.entrySet()) { if(!firstTime) { out.print(", "); } firstTime=false; print(et.getValue()); out.print(" "); out.print(et.getKey()); } if(tt.isOpen) { out.print(", ..."); } out.print("}"); } else if(t instanceof SyntacticType.Reference) { out.print("ref "); print(((SyntacticType.Reference) t).element); } else if(t instanceof SyntacticType.Not) { out.print("!"); print(((SyntacticType.Not) t).element); } else if(t instanceof SyntacticType.Union) { SyntacticType.Union ut = (SyntacticType.Union) t; boolean firstTime = true; for(SyntacticType et : ut.bounds) { if(!firstTime) { out.print(" | "); } firstTime=false; print(et); } } else if(t instanceof SyntacticType.Intersection) { SyntacticType.Intersection ut = (SyntacticType.Intersection) t; boolean firstTime = true; for(SyntacticType et : ut.bounds) { if(!firstTime) { out.print(" & "); } firstTime=false; print(et); } } else { // should be dead-code throw new RuntimeException("Unknown type kind encountered: " + t.getClass().getName()); } } public void indent(int level) { for(int i=0;i!=level;++i) { out.print(" "); } } }
package com.lightcrafts.platform.linux; import static com.lightcrafts.platform.linux.Locale.LOCALE; import com.lightcrafts.ui.toolkit.TextAreaFactory; import com.lightcrafts.utils.WebBrowser; import javax.swing.*; import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.InputStream; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.regex.Matcher; import java.util.regex.Pattern; class TestSSE2 { private static String simdRegex; private static String modelRegex; private static String[] cmd; static { String osname = System.getProperty("os.name"); if (osname.contains("Linux")) { cmd = new String[] {"cat", "/proc/cpuinfo"}; simdRegex = "^flags\t\t:.*sse2"; modelRegex = "^model name\t: "; } else if (osname.contains("SunOS")) { cmd = new String[] {"sh", "-c", "isainfo -nv ; psrinfo -pv"}; simdRegex = "^\t.*sse2"; modelRegex = "^\t"; } else if (osname.contains("FreeBSD")) { cmd = new String[] {"sysctl", "hw"}; simdRegex = "^hw.instruction_sse: 1"; modelRegex = "^hw.model: "; } else { cmd = new String[] {"dmesg"}; simdRegex = "^ Features=.*SSE2"; modelRegex = "^CPU: "; } } static boolean hasSSE2() { return getCpuInfoLine(simdRegex) != null; } private static String getCpuInfoLine(String regex) { String line = null; try { Process process = Runtime.getRuntime().exec(cmd); try (InputStream in = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { while ((line = reader.readLine()) != null) { if (Pattern.compile(regex).matcher(line).find()) break; } } } catch (IOException e) { e.printStackTrace(); } return line; } private static String getCpuModel() { String model = getCpuInfoLine(modelRegex); if (model != null) model = model.replaceFirst(Matcher.quoteReplacement(modelRegex), ""); return model; } static void showDialog() { String messageA = LOCALE.get("CantRunSSE2Title"); String messageB = LOCALE.get("CantRunSSE2"); String messageC = LOCALE.get("FoundProcCpuinfo", getCpuModel()); String messageD = LOCALE.get("LearnMoreSSE2"); String messageE = LOCALE.get("LearnMoreSSE2URL"); JLabel title = new JLabel(messageA); title.setFont(title.getFont().deriveFont(22f)); title.setAlignmentX(.5f); StringBuilder buffer = new StringBuilder(); buffer.append(messageB); buffer.append("\n\n"); buffer.append(messageC); buffer.append("\n\n"); buffer.append(messageD); final String url = messageE; JLabel link = new JLabel(url); link.setForeground(Color.blue); link.setAlignmentX(.5f); link.setCursor(new Cursor(Cursor.HAND_CURSOR)); link.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent event) { WebBrowser.browse(url); } } ); JTextArea text = TextAreaFactory.createTextArea(buffer.toString(), 40); text.setBackground((new JPanel()).getBackground()); Box box = Box.createVerticalBox(); box.add(title); box.add(Box.createVerticalStrut(8)); box.add(text); box.add(Box.createVerticalStrut(8)); box.add(link); JOptionPane.showMessageDialog( null, box, messageA, JOptionPane.ERROR_MESSAGE ); } }
/** * The context of the solve method. The fields in this class are cloned * for every recursion of the solve() method. */ public final class SATContext implements java.io.Serializable { /** * A symbolic name for the `unassigned' value in * the `assignment' array. */ private static final int UNASSIGNED = -1; /** The number of open terms of each clause. */ private int terms[]; /** The assignments to all variables. */ int assignment[]; /** * The antecedent clause of each variable, or -1 if it is a decision * variable, or isn't assigned yet. */ int antecedent[]; /** * The decision level of each variable, or -1 if * it isn't assigned yet. */ int dl[]; /** The number of positive clauses of each variable. */ private int posclauses[]; /** The number of negative clauses of each variable. */ private int negclauses[]; /** The information of a positive assignment of each variable. */ private float posinfo[]; /** The information of a negative assignment of each variable. */ private float neginfo[]; /** Satisified flags for each clause in the problem. */ private boolean satisfied[]; /** The number of unsatisfied clauses. */ public int unsatisfied; // One step in the chain of resolutions that help to construct // a good conflict clause. private final class Resolution { Resolution next; // The next one in the chain. int cno; // The clause to resolve with. int var; // The variable to resolve on. int dist; // The distance to the dominator. Resolution( Resolution next, int cno, int var, int dist ) { this.next = next; this.cno = cno; this.var = var; this.dist = dist; } public String toString() { return "[(" + cno + "),v" + var + "]"; } } /** * Constructs a Context with the specified elements. */ private SATContext( int tl[], int al[], int atc[], int dl[], int poscl[], int negcl[], float posinfo[], float neginfo[], boolean sat[], int us ){ terms = tl; assignment = al; antecedent = atc; this.dl = dl; satisfied = sat; unsatisfied = us; posclauses = poscl; negclauses = negcl; this.posinfo = posinfo; this.neginfo = neginfo; } private static final boolean tracePropagation = false; private static final boolean traceLearning = false; private static final boolean traceResolutionChain = false; private static final boolean doVerification = false; private static final boolean doLearning = true; private static final boolean propagatePureVariables = true; /** * Constructs a SAT context based on the given SAT problem. * @param p The SAT problem to create the context for. * @return the constructed context */ public static SATContext buildSATContext( SATProblem p ) { int cno = p.getClauseCount(); int assignment[] = p.buildInitialAssignments(); int antecedent[] = new int[assignment.length]; int dl[] = new int[assignment.length]; for( int i=0; i<antecedent.length; i++ ){ antecedent[i] = -1; dl[i] = -1; } return new SATContext( p.buildTermCounts(), assignment, antecedent, dl, p.buildPosClauses(), p.buildNegClauses(), p.buildPosInfo(), p.buildNegInfo(), new boolean[cno], cno ); } /** * Returns a clone of this Context. * @return The clone. */ public Object clone() { return new SATContext( (int []) terms.clone(), (int []) assignment.clone(), (int []) antecedent.clone(), (int []) dl.clone(), (int []) posclauses.clone(), (int []) negclauses.clone(), (float []) posinfo.clone(), (float []) neginfo.clone(), (boolean []) satisfied.clone(), unsatisfied ); } /** * Verifies that the term count of the specified clause is correct. * @param p The SAT problem. * @param cno The clause to verify. */ private void verifyTermCount( SATProblem p, int cno ) { int termcount = 0; if( satisfied[cno] ){ // We don't care. return; } Clause c = p.clauses[cno]; int arr[] = c.pos; // Now count the unsatisfied variables. for( int j=0; j<arr.length; j++ ){ int v = arr[j]; if( assignment[v] == 1 ){ System.err.println( "Error: positive variable " + v + " of clause " + c + " has positive assignment, but clause is not satisfied" ); IntVector pos = p.getPosClauses( v ); String verdict; if( pos.contains( cno ) ){ verdict = "yes"; } else { verdict = "no"; } System.err.println( " Does variable " + v + " list clause " + cno + " as positive occurence? " + verdict ); } else if( assignment[v] == UNASSIGNED ){ // Count this unassigned variable. termcount++; } } // Also count the negative variables. arr = c.neg; for( int j=0; j<arr.length; j++ ){ int v = arr[j]; if( assignment[v] == 0 ){ System.err.println( "Error: negative variable " + v + " of clause " + c + " has negative assignment, but clause is not satisfied" ); IntVector neg = p.getNegClauses( v ); String verdict; if( neg.contains( cno ) ){ verdict = "yes"; } else { verdict = "no"; } System.err.println( " Does variable " + v + " list clause " + cno + " as negative occurence? " + verdict ); } else if( assignment[v] == UNASSIGNED ){ termcount++; } } if( termcount != terms[cno] ){ System.err.println( "Error: I count " + termcount + " unassigned variables in clause " + c + " but the administration says " + terms[cno] ); } } /** * Verifies that the clause counts of the specified variable are correct. * @param p The SAT problem. * @param var The variable to verify. */ private void verifyClauseCount( SATProblem p, int var ) { int poscount = 0; int negcount = 0; // Count the positive clauses IntVector pos = p.getPosClauses( var ); int sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); if( !satisfied[cno] ){ poscount++; } } // Count the negative clauses IntVector neg = p.getNegClauses( var ); sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); if( !satisfied[cno] ){ negcount++; } } if( posclauses[var] != poscount || negclauses[var] != negcount ){ System.err.println( "Error: clause count of v" + var + " says (" + posclauses[var] + "," + negclauses[var] + "), not (" + poscount + "," + negcount + ")" ); posclauses[var] = poscount; negclauses[var] = negcount; } } private void dumpAntecedents( String indent, SATProblem p, int cno ) { Clause c = p.clauses[cno]; System.err.println( indent + c ); int arr[] = c.pos; String indent1 = indent + " "; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( a>=0 ){ if( a == cno ){ System.err.println( indent1 + "implication: v" + v + "=" + assignment[v] + "@" + dl[v] ); } else { dumpAntecedents( indent1, p, a ); } } else { System.err.println( indent1 + "decision variable v" + v + "=" + assignment[v] + "@" + dl[v] ); } } arr = c.neg; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( a>=0 ){ if( a == cno ){ System.err.println( indent1 + "implication: v" + v + "=" + assignment[v] + "@" + dl[v] ); } else { dumpAntecedents( indent1, p, a ); } } else { System.err.println( indent1 + "decision variable v" + v + "=" + assignment[v] + "@" + dl[v] ); } } } /** * Given a clause, returns the implication of this clause. * @param c The clause to examine. * @return The variable that is implied by this clause, or -1 if there is none (i.e. the clause is in conflict), or -2 if there is morethan one. */ private int getImplication( Clause c, int cno ) { int arr[] = c.pos; int res = -1; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( a == cno ){ if( res != -1 ){ // There already is an implication. This isn't right. return -2; } res = v; } } arr = c.neg; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( a == cno ){ if( res != -1 ){ // There already is an implication. This isn't right. return -2; } res = v; } } return res; } /** * Given a clause index, print the implications that cause this * clause to be satisfied/conflicting. * @param indent The indent string to use for the output. * @param p The sat problem. * @param cno The clause to dump. */ private void dumpImplications( String indent, SATProblem p, int cno ) { Clause c = p.clauses[cno]; int impl = getImplication( c, cno ); String conclusion; if( impl == -2 ){ conclusion = "(nothing to conclude)"; } else if( impl == -1 ){ conclusion = "(conflict)"; } else { conclusion = "==> v" + impl + "=" + assignment[impl]; } System.err.println( indent + c + " " + conclusion ); int arr[] = c.pos; String indent1 = indent + " "; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( a>=0 ){ if( a != cno ){ dumpImplications( indent1, p, a ); } } } arr = c.neg; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( a>=0 ){ if( a != cno ){ dumpImplications( indent1, p, a ); } } } } /** * Given a link in the resolution chain, print that chain. */ static void dumpResolutionChain( Clause cl[], Resolution p ) { if( p == null ){ return; } System.err.print( "Resolution chain: " ); while( p != null ){ System.err.print( "(" + cl[p.cno].label + ") on v" + p.var ); if( p.next != null ){ System.err.print( " -> " ); } p = p.next; } System.err.println(); } private int calculateNearestDominator( SATProblem p, int arr[], int cno, int level, int dist[], int distFromConflict ) { int bestDom = -1; int bestDist = satisfied.length; int bestVar = -1; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( dl[v] == level ){ // The variable was deduced at our level, so it's // interesting. if( a<0 ){ // The decision variable at our level, not interesting. } else { // The variable is not a decision variable. if( a == cno ){ // The implication variable of this clause, // not interesting. } else { // Variable is not implied by this clause, we're // still interested. int newDom = calculateNearestDominator( p, a, level, dist, distFromConflict+1 ); if( newDom != -1 ){ if( bestDom == -1 || (dist[newDom]<bestDist) ){ bestDom = newDom; bestDist = dist[newDom]; bestVar = v; } } } } } } return bestDom; } /** * Returns the index of the nearest dominator clause, or -1 if there * is no dominator. */ private int calculateNearestDominator( SATProblem p, int cno, int level, int dist[], int distFromConflict ) { Clause c = p.clauses[cno]; if( traceResolutionChain ){ System.err.println( "Calculating nearest dominator of clause " + c ); } if( dist[cno] != 0 ){ // We've been here before, so this is a dominator. if( dist[cno]>distFromConflict ){ dist[cno] = distFromConflict; } if( traceResolutionChain ){ System.err.println( "We cross an earlier path with clause " + c + " in it: dominator" ); } return cno; } dist[cno] = distFromConflict; int bestDom; int bestPosDom = calculateNearestDominator( p, c.pos, cno, level, dist, distFromConflict ); int bestNegDom = calculateNearestDominator( p, c.neg, cno, level, dist, distFromConflict ); if( bestPosDom == -1 ){ bestDom = bestNegDom; } else { if( bestNegDom == -1 ){ bestDom = bestPosDom; } else { if( dist[bestNegDom]<dist[bestPosDom] ){ bestDom = bestNegDom; } else { bestDom = bestPosDom; } } } if( traceResolutionChain ){ System.err.println( "Nearest dominator of clause " + c + " is " + bestDom ); } return bestDom; } private Resolution calculateDominatorPath( SATProblem p, int arr[], int cno, int level, int dom ) { Resolution bestPath = null; int bestDist = satisfied.length; int bestVar = -1; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; int a = antecedent[v]; if( dl[v] == level ){ // The variable was deduced at our level, so it's // interesting. if( a<0 ){ // The decision variable at our level, not interesting. } else { // The variable is not a decision variable. if( a == cno ){ // The implication variable of this clause, // not interesting. } else { // Variable is not implied by this clause, we're // still interested. Resolution newPath = calculateDominatorPath( p, a, level, dom ); if( newPath != null ){ if( bestPath == null || (newPath.dist<bestDist) ){ bestPath = newPath; bestDist = newPath.dist; bestVar = v; } } } } } } if( bestPath == null ){ return null; } bestPath.var = bestVar; return new Resolution( bestPath, cno, -1, bestPath.dist+1 ); } /** * Returns the index of the nearest dominator clause, or -1 if there * is no dominator. */ private Resolution calculateDominatorPath( SATProblem p, int cno, int level, int dom ) { Clause c = p.clauses[cno]; if( traceResolutionChain ){ System.err.println( "Calculating path to dominator of clause " + c ); } if( cno == dom ){ if( traceResolutionChain ){ System.err.println( "This is the dominator: " + c ); } return new Resolution( null, cno, -1, 0 ); } Resolution bestPath; Resolution bestPosPath = calculateDominatorPath( p, c.pos, cno, level, dom ); Resolution bestNegPath = calculateDominatorPath( p, c.neg, cno, level, dom ); if( bestPosPath == null ){ bestPath = bestNegPath; } else { if( bestNegPath == null ){ bestPath = bestPosPath; } else { if( bestNegPath.dist<bestPosPath.dist ){ bestPath = bestNegPath; } else { bestPath = bestPosPath; } } } if( traceResolutionChain ){ System.err.println( "Best path of clause " + c + " is " + bestPath ); } return bestPath; } /** * Given the SAT problem and the index of the conflicting clause, * compute the first variable thas dominates the conflict in the * deductions at this level. */ Resolution computeResolutionChain( SATProblem p, int cno, int level ) { // The distance of each clause to the conflicting clause. The // conflicting clause itself gets distance 1, so that we can use // the default value 0 // as indication that we haven't considered this clause yet. int dist[] = new int[satisfied.length]; int bestDom = calculateNearestDominator( p, cno, level, dist, 1 ); if( bestDom == -1 ){ if( traceResolutionChain ){ System.err.println( "There is no dominator for clause " + p.clauses[cno] ); } return null; } if( traceResolutionChain ){ System.err.println( "Nearest dominator is " + p.clauses[bestDom] + " at distance " + dist[bestDom] ); } Resolution bestPath = calculateDominatorPath( p, cno, level, bestDom ); if( bestPath == null ){ System.err.println( "Error: clause " + p.clauses[cno] + " has dominator " + p.clauses[bestDom] + " but no path to it" ); return null; } if( traceResolutionChain ){ dumpResolutionChain( p.clauses, bestPath ); } return bestPath.next; } /** * Given the index of a conflicting clause, builds a conflict clause. * Returns null if no helpful clause can be constructed. * @param p The SAT problem. * @param cno The clause that is in conflict. * @param var The variable that is in conflict. * @param level The decision level of the conflict. * @return A new clause that should improve the efficiency of the search process, or null if no helpful clause can be constructed. */ private Clause buildConflictClause( SATProblem p, int cno, int var, int level ) { if( false ){ boolean changed = false; boolean anyChange = false; Clause res = p.clauses[cno]; do { changed = false; int arr[] = res.pos; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; if( dl[v] == level ){ int a = antecedent[v]; if( a>=0 ){ Clause newres = Clause.resolve( res, p.clauses[a], v ); if( traceLearning ){ System.err.println( "Resolving on v" + v + ":" ); System.err.println( " " + res ); System.err.println( " " + p.clauses[a] + " =>" ); System.err.println( " " + newres ); } changed = true; anyChange = true; res = newres; break; } } } arr = res.neg; for( int i=0; i<arr.length; i++ ){ int v = arr[i]; if( dl[v] == level ){ int a = antecedent[v]; if( a>=0 ){ Clause newres = Clause.resolve( res, p.clauses[a], v ); if( traceLearning ){ System.err.println( "Resolving on v" + v + ":" ); System.err.println( " " + res ); System.err.println( " " + p.clauses[a] + " =>" ); System.err.println( " " + newres ); } changed = true; anyChange = true; res = newres; break; } } } } while( changed ); if( !anyChange ){ return null; } return res; } else { int a = antecedent[var]; Resolution chain = computeResolutionChain( p, cno, level ); if( chain == null ){ // No interesting clause to learn. return null; } if( traceLearning ){ System.err.println( "Resolution chain:" ); Resolution r = chain; while( r != null ){ System.err.println( "-- Resolve v" + r.var + " on " + p.clauses[r.cno] ); r = r.next; } } Resolution r = chain; Clause res = p.clauses[cno]; while( r != null ){ res = Clause.resolve( res, p.clauses[r.cno], r.var ); r = r.next; } return res; } } /** * Registers the fact that the specified clause is in conflict with * the current assignments. This method throws a * restart exception if that is useful. * @param p The SAT problem. * @param cno The clause that is in conflict. */ private void analyzeConflict( SATProblem p, int cno, int var, int level ) throws SATRestartException { if( tracePropagation | traceLearning | traceResolutionChain ){ System.err.println( "Clause " + p.clauses[cno] + " conflicts with v" + var + "=" + assignment[var] ); dumpAssignments(); if( traceResolutionChain ){ dumpImplications( "", p, cno ); } } if( doLearning ){ Clause cc = buildConflictClause( p, cno, var, level ); if( cc == null ){ if( traceLearning ){ System.err.println( "No interesting conflict clause could be constructed" ); } } else { if( traceLearning ){ System.err.println( "Added conflict clause " + cc ); } p.addConflictClause( cc ); } } throw new SATRestartException(); } /** * Propagates the specified unit clause. * @param p the SAT problem to solve * @param i the index of the unit clause * @return CONFLICTING if the problem is now in conflict, SATISFIED if the problem is now satisified, or UNDETERMINED otherwise */ private int propagateUnitClause( SATProblem p, int i, int level ) throws SATRestartException { if( satisfied[i] ){ // Not interesting. return SATProblem.UNDETERMINED; } Clause c = p.clauses[i]; if( doVerification ){ if( terms[i] != 1 ){ System.err.println( "Error: cannot propagate clause " + c + " since it's not a unit clause" ); return SATProblem.UNDETERMINED; } } int arr[] = c.pos; boolean foundIt = false; if( tracePropagation ){ System.err.println( "Propagating unit clause " + c ); } // Now search for the variable that isn't satisfied. for( int j=0; j<arr.length; j++ ){ int v = arr[j]; if( assignment[v] == UNASSIGNED ){ if( foundIt ){ System.err.println( "Error: a unit clause with multiple unassigned variables" ); return SATProblem.UNDETERMINED; } // We have found the unassigned one, propagate it. if( tracePropagation ){ System.err.println( "Propagating positive unit variable " + v + " from clause " + c ); } antecedent[v] = i; int res = propagatePosAssignment( p, v, level ); if( res != 0 ){ // The problem is now conflicting/satisfied, we're // done. return res; } foundIt = true; } } // Keep searching for the unassigned variable arr = c.neg; for( int j=0; j<arr.length; j++ ){ int v = arr[j]; if( assignment[v] == UNASSIGNED ){ if( foundIt ){ System.err.println( "Error: a unit clause with multiple unassigned variables" ); return SATProblem.UNDETERMINED; } // We have found the unassigned one, propagate it. if( tracePropagation ){ System.err.println( "Propagating negative unit variable " + v + " from clause " + c ); } antecedent[v] = i; int res = propagateNegAssignment( p, v, level ); if( res != 0 ){ // The problem is now conflicting/satisfied, we're // done. return res; } foundIt = true; } } if( !satisfied[i] && !foundIt ){ System.err.println( "Error: unit clause " + c + " does not contain unassigned variables" ); } return SATProblem.UNDETERMINED; } /** * Update the adminstration for any new clauses in the specified * SAT problem. * @param p The SAT problem. */ public void update( SATProblem p ) { int newCount = p.getClauseCount(); if( newCount>terms.length ){ int oldCount = terms.length; // New clauses have been added. Enlarge the arrays related // to the clauses, and fill them with the correct values. int newterms[] = new int[newCount]; System.arraycopy( terms, 0, newterms, 0, terms.length ); terms = newterms; boolean newsatisfied[] = new boolean[newCount]; System.arraycopy( satisfied, 0, newsatisfied, 0, satisfied.length ); satisfied = newsatisfied; for( int i=oldCount; i<newCount; i++ ){ Clause cl = p.clauses[i]; int nterm = cl.getTermCount( assignment ); terms[i] = nterm; boolean issat = cl.isSatisfied( assignment ); if( !issat ){ unsatisfied++; cl.registerInfo( assignment, posinfo, neginfo, nterm ); } cl.registerVariableCounts( posclauses, negclauses ); if( doVerification ){ verifyTermCount( p, i ); } } } } /** * Registers the fact that the specified clause is satisfied. * @param p The SAT problem. * @param cno The index of the clause that is now satisifed. * @return CONFLICTING if the problem is now in conflict, SATISFIED if the problem is now satisified, or UNDETERMINED otherwise */ private int markClauseSatisfied( SATProblem p, int cno, int level ) throws SATRestartException { boolean hasPure = false; satisfied[cno] = true; unsatisfied if( unsatisfied == 0 ){ return SATProblem.SATISFIED; } Clause c = p.clauses[cno]; if( tracePropagation ){ System.err.println( "Clause " + c + " is now satisfied, " + unsatisfied + " to go" ); } int pos[] = c.pos; for( int i=0; i<pos.length; i++ ){ int var = pos[i]; int pc = --posclauses[var]; if( doVerification ){ verifyClauseCount( p, var ); } if( pc == 0 ){ if( assignment[var] == UNASSIGNED ){ if( negclauses[var] != 0 ){ if( tracePropagation ){ System.err.println( "Variable " + var + " only occurs negatively (0," + negclauses[var] + ")" ); } // Only register the fact that there is an pure // variable. Don't propagate it yet, since the // adminstration is inconsistent at the moment. hasPure = propagatePureVariables; } } } } int neg[] = c.neg; for( int i=0; i<neg.length; i++ ){ int var = neg[i]; int nc = --negclauses[var]; if( doVerification ){ verifyClauseCount( p, var ); } if( nc == 0 ){ if( assignment[var] == UNASSIGNED ){ if( posclauses[var] != 0 ){ if( tracePropagation ){ System.err.println( "Variable " + var + " only occurs positively (" + posclauses[var] + ",0)" ); } // Only register the fact that there is an pure // variable. Don't propagate it yet, since the // adminstration is inconsistent at the moment. hasPure = propagatePureVariables; } } } } if( hasPure ){ // Now propagate the pure variables. for( int i=0; i<pos.length; i++ ){ int var = pos[i]; if( assignment[var] == UNASSIGNED && posclauses[var] == 0 && negclauses[var] != 0 ){ antecedent[var] = cno; int res = propagateNegAssignment( p, var, level ); if( res != 0 ){ return res; } } } for( int i=0; i<neg.length; i++ ){ int var = neg[i]; if( assignment[var] == UNASSIGNED && negclauses[var] == 0 && posclauses[var] != 0 ){ antecedent[var] = cno; int res = propagatePosAssignment( p, var, level ); if( res != 0 ){ return res; } } } } return SATProblem.UNDETERMINED; } private void dumpAssignments() { Helpers.dumpAssignments( "Assignments", assignment ); } /** * Propagates the fact that variable 'var' is true. * @return CONFLICTING if the problem is now in conflict, SATISFIED if the problem is now satisified, or UNDETERMINED otherwise */ public int propagatePosAssignment( SATProblem p, int var, int level ) throws SATRestartException { assignment[var] = 1; dl[var] = level; boolean hasUnitClauses = false; if( tracePropagation ){ System.err.println( "Propagating assignment v" + var + "=true" ); } // Deduct this clause from all clauses that contain this as a // negative term. IntVector neg = p.getNegClauses( var ); int sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); // Deduct the old info of this clause. posinfo[var] -= Helpers.information( terms[cno] ); terms[cno] if( terms[cno] == 0 ){ analyzeConflict( p, cno, var, level ); return SATProblem.CONFLICTING; } if( terms[cno] == 1 ){ // Remember that we saw a unit clause, but don't // propagate it yet, since the administration is inconsistent. hasUnitClauses = true; } else { // Add the new information of this clause. posinfo[var] += Helpers.information( terms[cno] ); } } // Mark all clauses that contain this variable as a positive // term as satisfied. IntVector pos = p.getPosClauses( var ); sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); if( !satisfied[cno] ){ posinfo[var] -= Helpers.information( terms[cno] ); int res = markClauseSatisfied( p, cno, level ); if( res != 0 ){ return res; } } } // Now propagate unit clauses if there are any. if( hasUnitClauses ){ sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); if( doVerification ){ verifyTermCount( p, cno ); } if( terms[cno] == 1 ){ int res = propagateUnitClause( p, cno, level ); if( res != 0 ){ return res; } } } } return SATProblem.UNDETERMINED; } /** * Propagates the fact that variable 'var' is false. * @return CONFLICTING if the problem is now in conflict, SATISFIED if the problem is now satisified, or UNDETERMINED otherwise */ public int propagateNegAssignment( SATProblem p, int var, int level ) throws SATRestartException { assignment[var] = 0; dl[var] = level; boolean hasUnitClauses = false; if( tracePropagation ){ System.err.println( "Propagating assignment v" + var + "=false" ); } // Deduct this clause from all clauses that contain this as a // Positive term. IntVector pos = p.getPosClauses( var ); int sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); // Deduct the old info of this clause. posinfo[var] -= Helpers.information( terms[cno] ); terms[cno] if( terms[cno] == 0 ){ analyzeConflict( p, cno, var, level ); return SATProblem.CONFLICTING; } if( terms[cno] == 1 ){ // Remember that we saw a unit clause, but don't // propagate it yet, since the administration is inconsistent. hasUnitClauses = true; } else { // Add the new information of this clause. posinfo[var] += Helpers.information( terms[cno] ); } } // Mark all clauses that contain this variable as a negative // term as satisfied. IntVector neg = p.getNegClauses( var ); sz = neg.size(); for( int i=0; i<sz; i++ ){ int cno = neg.get( i ); if( !satisfied[cno] ){ neginfo[var] -= Helpers.information( terms[cno] ); int res = markClauseSatisfied( p, cno, level ); if( res != 0 ){ return res; } } } // Now propagate unit clauses if there are any. if( hasUnitClauses ){ sz = pos.size(); for( int i=0; i<sz; i++ ){ int cno = pos.get( i ); if( doVerification ){ verifyTermCount( p, cno ); } if( terms[cno] == 1 ){ int res = propagateUnitClause( p, cno, level ); if( res != 0 ){ return res; } } } } return SATProblem.UNDETERMINED; } /** * Returns the best decision variable to branch on, or -1 if there is none. */ public int getDecisionVariable() { int bestvar = -1; float bestinfo = -1; int bestmaxcount = 0; for( int i=0; i<assignment.length; i++ ){ if( assignment[i] != UNASSIGNED ){ // Already assigned, so not interesting. continue; } if( doVerification ){ if( posinfo[i]<-0.01 || neginfo[i]<-0.01 ){ System.err.println( "Weird info for variable " + i + ": posinfo=" + posinfo[i] + ", neginfo=" + neginfo[i] ); } } float info = Math.max( posinfo[i], neginfo[i] ); if( info>=bestinfo ){ int maxcount = Math.max( posclauses[i], negclauses[i] ); if( (info>bestinfo) || (maxcount<bestmaxcount) ){ // This is a better one. bestvar = i; bestinfo = info; bestmaxcount = maxcount; } } } return bestvar; } /** * Returns true iff the given variable has more information as * positive variable than as negative variable. * @param var the variable */ public boolean posDominant( int var ) { return (posinfo[var]>neginfo[var]); } /** * Given a variable, returns the maximum number of clauses it will satisfy. * @param var the variable * @return the solve count */ public int getSolveCount( int var ) { if( posclauses[var]>negclauses[var] ){ return posclauses[var]; } else { return negclauses[var]; } } /** * Optimize the problem by searching for and propagating all unit * clauses and pure variables that we can find. * @param p The SAT problem this is the context for. * @return CONFLICTING if the problem is now in conflict, SATISFIED if the problem is now satisified, or UNDETERMINED otherwise */ public int optimize( SATProblem p ) throws SATRestartException { // Search for and propagate unit clauses. for( int i=0; i<terms.length; i++ ){ if( terms[i] == 1 ){ int res = propagateUnitClause( p, i, 0 ); if( res != 0 ){ return res; } } } // Search for and propagate pure variables. for( int i=0; i<assignment.length; i++ ){ if( assignment[i] != UNASSIGNED || (posclauses[i] == 0 && negclauses[i] == 0) ){ // Unused variable, not interesting. continue; } if( posclauses[i] == 0 ){ int res = propagateNegAssignment( p, i, 0 ); if( res != 0 ){ return res; } } else if( negclauses[i] == 0 ){ int res = propagatePosAssignment( p, i, 0 ); if( res != 0 ){ return res; } } } return SATProblem.UNDETERMINED; } }
package matlabcontrol; import java.rmi.MarshalException; import java.rmi.NoSuchObjectException; import java.rmi.RemoteException; import java.rmi.UnmarshalException; import java.rmi.server.UnicastRemoteObject; import java.util.Timer; import java.util.TimerTask; /** * Allows for calling MATLAB from <strong>outside</strong> of MATLAB. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class RemoteMatlabProxy extends MatlabProxy { /** * The remote JMI wrapper which is a remote object connected over RMI. */ private final JMIWrapperRemote _jmiWrapper; /** * The receiver for the proxy. While the receiver is bound to the RMI registry and a reference is maintained * (the RMI registry uses weak references), the connection to MATLAB's JVM will remain active. The JMI wrapper, * while a remote object, is not bound to the registry, and will not keep the RMI thread running. */ private final RequestReceiver _receiver; /** * A timer that periodically checks if still connected. */ private final Timer _connectionTimer; /** * Whether the proxy is connected. If the value is {@code false} the proxy is definitely disconnected. If the value * is {@code true} then the proxy <i>may</i> be disconnected. The accuracy of this will be checked then the next * time {@link #isConnected()} is called and this value will be updated if necessary. */ private volatile boolean _isConnected = true; /** * The duration (in milliseconds) between checks to determine if still connected. */ private static final int CONNECTION_CHECK_PERIOD = 1000; /** * The proxy is never to be created outside of this package, it is to be constructed after a * {@link JMIWrapperRemote} has been received via RMI. * * @param internalProxy * @param receiver * @param id * @param existingSession */ RemoteMatlabProxy(JMIWrapperRemote internalProxy, RequestReceiver receiver, Identifier id, boolean existingSession) { super(id, existingSession); _connectionTimer = new Timer("MLC Connection Listener " + id); _jmiWrapper = internalProxy; _receiver = receiver; } /** * Initializes aspects of the proxy that cannot be done safely in the constructor without leaking a reference to * {@code this}. */ void init() { _connectionTimer.schedule(new CheckConnectionTask(), CONNECTION_CHECK_PERIOD, CONNECTION_CHECK_PERIOD); } private class CheckConnectionTask extends TimerTask { @Override public void run() { if(!RemoteMatlabProxy.this.isConnected()) { //If not connected, perform disconnection so RMI thread can terminate RemoteMatlabProxy.this.disconnect(); //Notify listeners notifyDisconnectionListeners(); //Cancel timer, which will terminate the timer's thread _connectionTimer.cancel(); } //else // System.out.println(getIdentifier() + " is connected"); } } @Override public boolean isRunningInsideMatlab() { return false; } @Override public boolean isConnected() { //If believed to be connected, verify this is up to date information if(_isConnected) { boolean connected; //Call a remote method, if it throws a RemoteException then it is no longer connected try { _jmiWrapper.checkConnection(); connected = true; } catch(RemoteException e) { connected = false; } _isConnected = connected; } return _isConnected; } @Override public boolean disconnect() { _connectionTimer.cancel(); //Unexport the receiver so that the RMI threads can shut down try { //If succesfully exported, then definitely not connected //If the export failed, we still might be connected, isConnected() will check _isConnected = !UnicastRemoteObject.unexportObject(_receiver, true); } //If it is not exported, that's ok because we were trying to unexport it catch(NoSuchObjectException e) { } return this.isConnected(); } // Methods which interact with MATLAB (and helper methods and interfaces) private static interface RemoteInvocation<T> { public T invoke() throws RemoteException, MatlabInvocationException; } private <T> T invoke(RemoteInvocation<T> invocation) throws MatlabInvocationException { if(!_isConnected) { throw MatlabInvocationException.Reason.PROXY_NOT_CONNECTED.asException(); } else { try { return invocation.invoke(); } catch(UnmarshalException e) { throw MatlabInvocationException.Reason.UNMARSHAL.asException(e); } catch(MarshalException e) { throw MatlabInvocationException.Reason.MARSHAL.asException(e); } catch(RemoteException e) { if(this.isConnected()) { throw MatlabInvocationException.Reason.UNKNOWN.asException(e); } else { throw MatlabInvocationException.Reason.PROXY_NOT_CONNECTED.asException(e); } } } } @Override public void setVariable(final String variableName, final Object value) throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.setVariable(variableName, value); return null; } }); } @Override public Object getVariable(final String variableName) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<Object>() { @Override public Object invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.getVariable(variableName); } }); } @Override public void exit() throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.exit(); return null; } }); } @Override public void eval(final String command) throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.eval(command); return null; } }); } @Override public Object[] returningEval(final String command, final int nargout) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<Object[]>() { @Override public Object[] invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.returningEval(command, nargout); } }); } @Override public void feval(final String functionName, final Object... args) throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.feval(functionName, args); return null; } }); } @Override public Object[] returningFeval(final String functionName, final int nargout, final Object... args) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<Object[]>() { @Override public Object[] invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.returningFeval(functionName, nargout, args); } }); } @Override public <T> T invokeAndWait(final MatlabThreadCallable<T> callable) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<T>() { @Override public T invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.invokeAndWait(callable); } }); } }
package businessmodel.assemblyline; import businessmodel.MainScheduler; import businessmodel.category.VehicleModel; import businessmodel.observer.Observer; import businessmodel.observer.Subject; import businessmodel.order.Order; import businessmodel.util.IteratorConverter; import businessmodel.util.SafeIterator; import org.joda.time.DateTime; import java.util.*; /** * A class representing an assembly line. It currently holds 3 work post. * * @author SWOP team 10 2014 */ public class AssemblyLine implements Subject { private List<VehicleModel> responsibleModels; private AssemblyLineState broken; private AssemblyLineState maintenance; private AssemblyLineState operational; private AssemblyLineState state; private AssemblyLineScheduler assemblylineScheduler; private MainScheduler mainscheduler; private int timeCurrentStatus = 0; private LinkedList<WorkPost> workPosts = new LinkedList<>(); private ArrayList<Observer> subscribers = new ArrayList<Observer>(); private String name; /** * Creates a new assembly line. */ protected AssemblyLine() { this.broken = new BrokenState(this); this.maintenance = new MaintenanceState(this); this.operational = new OperationalState(this); } /** * Checks whether an order can be placed on this assembly line. * * @param order The order that has to be placed. * @return True if the order can be placed. */ public boolean canAddOrder(Order order) { // als het order geen model heeft is het oke, anders checken of model kan geplaatst worden boolean bool = couldAcceptModel(order.getVehicleModel()); // is true when the assembly line can accept orders in this state. if (bool) bool = this.state.canPlaceOrder(); if (bool) return this.getAssemblyLineScheduler().canAddOrder(order); else return bool; } /** * Checks whether the assembly line can move forward. * * @return True if all the WorkPosts are completed and the current state allows it. */ protected boolean canAdvance() { boolean ready = true; for (WorkPost wp : this.getWorkPosts()) { if (!wp.isCompleted()) ready = false; } if (ready) ready = this.state.canAdvance(); return ready; } protected void advance(Order newOrder) throws IllegalStateException { if (!this.canAdvance()) throw new IllegalStateException("Cannot advance assembly line!"); LinkedList<WorkPost> reversed = (LinkedList<WorkPost>) this.getWorkPosts().clone(); Collections.reverse(reversed); // get the potentially finished order. Order temp = reversed.getFirst().getOrder(); reversed.getFirst().setNewOrder(null); for (int i = 1; i < reversed.size(); i++) { // get the Order from the current work post. Order nextOrder = reversed.get(i).getOrder(); if (nextOrder != null) { reversed.get(i).setNewOrder(null); // if there is a real order try and shift it to the next work post // where it will have pending orders WorkPost workPostForOrder = this.getNextWorkPost(reversed.get(i), reversed, nextOrder); if (workPostForOrder == null) // this order is completed nextOrder.setCompleted(); else workPostForOrder.setNewOrder(nextOrder); } } // set the new order on the first post. reversed.getLast().setNewOrder(newOrder); if (temp != null) temp.setCompleted(); this.timeCurrentStatus = 0; } private WorkPost getNextWorkPost(WorkPost workPost, LinkedList<WorkPost> reversed, Order order) { // get the next work post WorkPost nextWorkPost = this.previousWorkPost(workPost, reversed); nextWorkPost.setNewOrder(order); IteratorConverter<AssemblyTask> converter = new IteratorConverter<>(); while (converter.convert(nextWorkPost.getPendingTasks()).size() == 0) { // there are no pending tasks so try to get the next work post. WorkPost next = this.previousWorkPost(nextWorkPost, reversed); if (next != null && next.getOrder() == null) { // there is a next work post and an order can be placed. // so remove the order from the current place nextWorkPost.setNewOrder(null); // put it on the next one next.setNewOrder(order); // update the current workpost nextWorkPost = next; } else if (next != null && next.getOrder() != null) { // the next workpost can not accept the order // because there already is an order in process return nextWorkPost; } else { // if eventualy we find no next workpost the order can be finished nextWorkPost.setNewOrder(null); return null; } } return nextWorkPost; } private WorkPost previousWorkPost(WorkPost workPost, LinkedList<WorkPost> reversed) { int index = reversed.indexOf(workPost); if (index - 1 < 0) return null; else return reversed.get(index - 1); } /** * Updates the time on the current status of the assembly line and notifies the scheduler. * * @param timeCurrentStatus The time spent on the current status. */ protected void workPostCompleted(int timeCurrentStatus) { if (timeCurrentStatus > this.timeCurrentStatus) this.timeCurrentStatus = timeCurrentStatus; this.notifyScheduler(); } /** * Advances (if possible) and notifies the assembly line scheduler. */ private void notifyScheduler() { if (canAdvance()) { this.getAssemblyLineScheduler().advance(this.timeCurrentStatus); notifyObservers(); } } /** * Returns an iterator over the list of work posts at the assembly line. * * @return The list of work posts at the assembly line. */ @SuppressWarnings("unchecked") public Iterator<WorkPost> getWorkPostsIterator() { SafeIterator<WorkPost> safe = new SafeIterator<WorkPost>(); safe.convertIterator(this.workPosts.iterator()); return safe; } /** * Returns the list of work posts of the assembly line * * @return The list of work posts. */ private LinkedList<WorkPost> getWorkPosts() { return this.workPosts; } /** * Sets the work posts of the assembly line to the given work posts. * * @param workPosts The work posts of the assembly line. */ protected void setWorkPosts(List<WorkPost> workPosts) { if (workPosts == null) throw new IllegalArgumentException("There were no workPosts supplied"); LinkedList<WorkPost> list = new LinkedList<WorkPost>(); list.addAll(workPosts); this.workPosts = list; } /** * Returns the assembly line scheduler of the assembly line. * * @return The assembly line scheduler. */ public AssemblyLineScheduler getAssemblyLineScheduler() { return assemblylineScheduler; } /** * Returns the models for which the assembly line is responsible. * * @return The responsible models. */ protected Iterator<VehicleModel> getResponsibleModelsIterator() { return this.responsibleModels.iterator(); } /** * Returns the number of work posts at the assembly line. * * @return The number of work posts at the assembly line. */ protected int getNumberOfWorkPosts() { return this.getWorkPosts().size(); } /** * Returns the time spent working on the current status of the AssemblyLine. * * @return The current status of the assembly line. */ protected int getTimeCurrentStatus() { return timeCurrentStatus; } /** * Returns all the orders that are on the assembly line. * * @return A list with all the orders that are currently on the assembly line. */ protected LinkedList<Order> getWorkPostOrders() { LinkedList<Order> orders = new LinkedList<Order>(); for (WorkPost wp : this.getWorkPosts()) if (wp.getOrder() != null) orders.add(wp.getOrder()); return orders; } /** * Sets the name of the assembly line. * * @param name The name of the assembly line. */ protected void setName(String name) { this.name = name; } /** * Sets the assembly line scheduler of the assembly line to the given scheduler. * * @param scheduler The assembly line scheduler of the assembly line. */ protected void setAssemblylineScheduler(AssemblyLineScheduler scheduler) { if (scheduler == null) throw new IllegalArgumentException("There was no scheduler supplied"); this.assemblylineScheduler = scheduler; } /** * Sets the vehicle models for which the assembly line is responsible to the given models. * * @param models The models for which the assembly line is responsible. */ protected void setResponsibleModels(List<VehicleModel> models) { if (models == null) throw new IllegalArgumentException("There were no models supplied"); this.responsibleModels = models; } @Override public void subscribeObserver(Observer observer) { if (!subscribers.contains(observer)) this.subscribers.add(observer); } @Override public void unSubscribeObserver(Observer observer) { if (this.subscribers.contains(observer)) this.subscribers.remove(observer); } @Override public void notifyObservers() { for (Observer obs : this.subscribers) obs.update(this); } /** * Transition to the maintenance state. */ public void transitionToMaintenance() { this.state.markAssemblyLineAsMaintenance(); } /** * Transition to the broken state. */ public void transitionToBroken() { this.state.markAssemblyLineAsBroken(); } /** * Transition to the operational state. */ public void transitionToOperational() { this.state.markAssemblyLineAsOperational(); } /** * Returns the broken state of the assembly line. * * @return The broken state of the assembly line. */ public AssemblyLineState getBrokenState() { return this.broken; } /** * Returns the operational state of the assembly line. * * @return The operational state of the assembly line. */ public AssemblyLineState getOperationalState() { return this.operational; } /** * Returns the maintenance state of the assembly line. * * @return The maintenance state of the assembly line. */ public AssemblyLineState getMaintenanceState() { return maintenance; } /** * Sets the state of the assembly line to the given state. * * @param state The state the assembly line needs to be set to. */ protected void setState(AssemblyLineState state) { this.state = state; this.state.initialize(); } /** * Returns the current state of the assembly line. * * @return The current state of the assembly line. */ protected AssemblyLineState getCurrentState() { return this.state; } /** * Returns the estimated completion time of the given order. * * @param order The order the estimated completion time is requested for. * @return The estimated completion time of the given order. */ public DateTime getEstimatedCompletionTimeOfNewOrder(Order order) throws IllegalArgumentException { if (order == null) throw new IllegalArgumentException("Bad order!"); return this.getAssemblyLineScheduler().getEstimatedCompletionTimeOfNewOrder(order); } /** * Returns the main scheduler of the assembly line. * * @return The main scheduler of the assembly line. */ protected MainScheduler getMainScheduler() { return this.mainscheduler; } /** * Sets the main scheduler of the assembly line to the given scheduler. * * @param scheduler The main scheduler of the assembly line. */ protected void setMainScheduler(MainScheduler scheduler) { if (scheduler == null) throw new IllegalArgumentException("There was no MainScheduler supplied"); this.mainscheduler = scheduler; } /** * Returns a string representation of the current state of the assembly line. * * @return A string representation of the current state of the assembly line. */ public String currentState() { return this.state.toString(); } /** * Returns all the possible states of the assembly line. * * @return An iterator over all the possible states of the assembly line. */ public Iterator<String> getAllPossibleStates() { ArrayList<String> possible = new ArrayList<>(); possible.add(this.getBrokenState().toString()); possible.add(this.getMaintenanceState().toString()); possible.add(this.getOperationalState().toString()); return possible.iterator(); } /** * Returns a string representation of the assembly line. */ @Override public String toString() { return this.name + " " + this.getWorkPosts().size(); } /** * A method to check if this AssemblyLine can process the given VehicleModel. * * @return true if it can handle the given VehicleModel */ public boolean couldAcceptModel(VehicleModel vehicleModel) { Iterator<VehicleModel> models = this.getResponsibleModelsIterator(); if (vehicleModel == null) { return true; } else { while (models.hasNext()) { VehicleModel model = models.next(); if (vehicleModel.getName() .equalsIgnoreCase(model.getName())) return true; } return false; } } }
package tp.pr5.logic; import java.util.ArrayList; public abstract class Move { protected Counter currentPlayer; protected int column; protected int row; public Move(Counter color, int column) { currentPlayer = color; this.column = column; } public void addswapped() { SwappedMove i = new SwappedMove(); swapTiles.add(i); } // ejecutaMovimiento(Tablero tab) public abstract boolean executeMove(Board board) throws InvalidMove; // getJugador() devuelve el color del jugador al que pertenece el movimiento public Counter getPlayer() { return currentPlayer; } // undo(Tablero tab) deshace el ultimo movimiento del tablero recibido como parametro public abstract void undo(Board board); public abstract int getColumn(); public abstract int getRow(); }
package beast.evolution.operators; import java.text.DecimalFormat; import beast.core.Description; import beast.core.Input; import beast.core.Operator; import beast.core.parameter.BooleanParameter; import beast.core.parameter.RealParameter; import beast.evolution.tree.Node; import beast.evolution.tree.Tree; import beast.util.Randomizer; @Description("Scales a parameter or a complete beast.tree (depending on which of the two is specified.") public class ScaleOperator extends Operator { public final Input<Tree> treeInput = new Input<>("tree", "if specified, all beast.tree divergence times are scaled"); public final Input<RealParameter> parameterInput = new Input<>("parameter", "if specified, this parameter is scaled", Input.Validate.XOR, treeInput); public final Input<Double> scaleFactorInput = new Input<>("scaleFactor", "scaling factor: range from 0 to 1. Close to zero is very large jumps, close to 1.0 is very small jumps.", 0.75); public final Input<Boolean> scaleAllInput = new Input<>("scaleAll", "if true, all elements of a parameter (not beast.tree) are scaled, otherwise one is randomly selected", false); public final Input<Boolean> scaleAllIndependentlyInput = new Input<>("scaleAllIndependently", "if true, all elements of a parameter (not beast.tree) are scaled with " + "a different factor, otherwise a single factor is used", false); final public Input<Integer> degreesOfFreedomInput = new Input<>("degreesOfFreedom", "Degrees of freedom used when " + "scaleAllIndependently=false and scaleAll=true to override default in calculation of Hasting ratio. " + "Ignored when less than 1, default 0.", 0); final public Input<BooleanParameter> indicatorInput = new Input<>("indicator", "indicates which of the dimension " + "of the parameters can be scaled. Only used when scaleAllIndependently=false and scaleAll=false. If not specified " + "it is assumed all dimensions are allowed to be scaled."); final public Input<Boolean> rootOnlyInput = new Input<>("rootOnly", "scale root of a tree only, ignored if tree is not specified (default false)", false); final public Input<Boolean> optimiseInput = new Input<>("optimise", "flag to indicate that the scale factor is automatically changed in order to achieve a good acceptance rate (default true)", true); final public Input<Double> scaleUpperLimit = new Input<>("upper", "Upper Limit of scale factor", 1.0 - 1e-8); final public Input<Double> scaleLowerLimit = new Input<>("lower", "Lower limit of scale factor", 1e-8); /** * shadows input * */ private double scaleFactor; private double upper, lower; /** * flag to indicate this scales trees as opposed to scaling a parameter * */ boolean isTreeScaler = true; @Override public void initAndValidate() { scaleFactor = scaleFactorInput.get(); isTreeScaler = (treeInput.get() != null); upper = scaleUpperLimit.get(); lower = scaleLowerLimit.get(); final BooleanParameter indicators = indicatorInput.get(); if (indicators != null) { if (isTreeScaler) { throw new IllegalArgumentException("indicator is specified which has no effect for scaling a tree"); } final int dataDim = parameterInput.get().getDimension(); final int indsDim = indicators.getDimension(); if (!(indsDim == dataDim || indsDim + 1 == dataDim)) { throw new IllegalArgumentException("indicator dimension not compatible from parameter dimension"); } } } protected boolean outsideBounds(final double value, final RealParameter param) { final Double l = param.getLower(); final Double h = param.getUpper(); return (value < l || value > h); //return (l != null && value < l || h != null && value > h); } protected double getScaler() { return (scaleFactor + (Randomizer.nextDouble() * ((1.0 / scaleFactor) - scaleFactor))); } /** * override this for proposals, * * @return log of Hastings Ratio, or Double.NEGATIVE_INFINITY if proposal should not be accepted * */ @Override public double proposal() { try { double hastingsRatio; final double scale = getScaler(); if (isTreeScaler) { final Tree tree = treeInput.get(this); if (rootOnlyInput.get()) { final Node root = tree.getRoot(); final double newHeight = root.getHeight() * scale; if (newHeight < Math.max(root.getLeft().getHeight(), root.getRight().getHeight())) { return Double.NEGATIVE_INFINITY; } root.setHeight(newHeight); return -Math.log(scale); } else { // scale the beast.tree final int internalNodes = tree.scale(scale); return Math.log(scale) * (internalNodes - 2); } } // not a tree scaler, so scale a parameter final boolean scaleAll = scaleAllInput.get(); final int specifiedDoF = degreesOfFreedomInput.get(); final boolean scaleAllIndependently = scaleAllIndependentlyInput.get(); final RealParameter param = parameterInput.get(this); assert param.getLower() != null && param.getUpper() != null; final int dim = param.getDimension(); if (scaleAllIndependently) { // update all dimensions independently. hastingsRatio = 0; final BooleanParameter indicators = indicatorInput.get(); if (indicators != null) { final int dimCount = indicators.getDimension(); final Boolean[] indicator = indicators.getValues(); final boolean impliedOne = dimCount == (dim - 1); for (int i = 0; i < dim; i++) { if( (impliedOne && (i == 0 || indicator[i-1])) || (!impliedOne && indicator[i]) ) { final double scaleOne = getScaler(); final double newValue = scaleOne * param.getValue(i); hastingsRatio -= Math.log(scaleOne); if (outsideBounds(newValue, param)) { return Double.NEGATIVE_INFINITY; } param.setValue(i, newValue); } } } else { for (int i = 0; i < dim; i++) { final double scaleOne = getScaler(); final double newValue = scaleOne * param.getValue(i); hastingsRatio -= Math.log(scaleOne); if( outsideBounds(newValue, param) ) { return Double.NEGATIVE_INFINITY; } param.setValue(i, newValue); } } } else if (scaleAll) { // update all dimensions // hasting ratio is dim-2 times of 1dim case. would be nice to have a reference here // for the proof. It is supposed to be somewhere in an Alexei/Nicholes article. // all Values assumed independent! final int computedDoF = param.scale(scale); final int usedDoF = (specifiedDoF > 0) ? specifiedDoF : computedDoF ; hastingsRatio = (usedDoF - 2) * Math.log(scale); } else { hastingsRatio = -Math.log(scale); // which position to scale final int index; final BooleanParameter indicators = indicatorInput.get(); if (indicators != null) { final int dimCount = indicators.getDimension(); final Boolean[] indicator = indicators.getValues(); final boolean impliedOne = dimCount == (dim - 1); // available bit locations. there can be hundreds of them. scan list only once. final int[] loc = new int[dimCount + 1]; int locIndex = 0; if (impliedOne) { loc[locIndex] = 0; ++locIndex; } for (int i = 0; i < dimCount; i++) { if (indicator[i]) { loc[locIndex] = i + (impliedOne ? 1 : 0); ++locIndex; } } if (locIndex > 0) { final int rand = Randomizer.nextInt(locIndex); index = loc[rand]; } else { return Double.NEGATIVE_INFINITY; // no active indicators } } else { // any is good index = Randomizer.nextInt(dim); } final double oldValue = param.getValue(index); if (oldValue == 0) { // Error: parameter has value 0 and cannot be scaled return Double.NEGATIVE_INFINITY; } final double newValue = scale * oldValue; if (outsideBounds(newValue, param)) { // reject out of bounds scales return Double.NEGATIVE_INFINITY; } param.setValue(index, newValue); // provides a hook for subclasses //cleanupOperation(newValue, oldValue); } return hastingsRatio; } catch (Exception e) { // whatever went wrong, we want to abort this operation... return Double.NEGATIVE_INFINITY; } } /** * automatic parameter tuning * */ @Override public void optimize(final double logAlpha) { if (optimiseInput.get()) { double delta = calcDelta(logAlpha); delta += Math.log(1.0 / scaleFactor - 1.0); setCoercableParameterValue(1.0 / (Math.exp(delta) + 1.0)); } } @Override public double getCoercableParameterValue() { return scaleFactor; } @Override public void setCoercableParameterValue(final double value) { scaleFactor = Math.max(Math.min(value, upper), lower); } @Override public String getPerformanceSuggestion() { final double prob = m_nNrAccepted / (m_nNrAccepted + m_nNrRejected + 0.0); final double targetProb = getTargetAcceptanceProbability(); double ratio = prob / targetProb; if (ratio > 2.0) ratio = 2.0; if (ratio < 0.5) ratio = 0.5; // new scale factor final double sf = Math.pow(scaleFactor, ratio); final DecimalFormat formatter = new DecimalFormat(" if (prob < 0.10) { return "Try setting scaleFactor to about " + formatter.format(sf); } else if (prob > 0.40) { return "Try setting scaleFactor to about " + formatter.format(sf); } else return ""; } } // class ScaleOperator
package beast.app.beauti; import beast.app.util.Utils; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class GuessPatternDialog extends JDialog { private static final long serialVersionUID = 1L; public static final String EXAMPLE_FORMAT = "<html>A proper trait file is tab delimited. <br>" + "The first row is always <font color=red>traits</font> followed by the keyword <br>" + "(e.g. <font color=red>species</font> in *BEAST) in the second column and separated <br>" + "by <font color=red>tab</font>. The rest rows are mapping taxa to species, which list <br>" + "taxon name in the first column and species name in the second column separated by <br>" + "<font color=red>tab</font>. For example: <br>" + "traits\tspecies<br>" + "taxon1\tspeciesA<br>" + "taxon2\tspeciesA<br>" + "taxon3\tspeciesB<br>" + "... ...<br>" + "Once mapping file is loaded, the trait named by keyword <font color=red>species</font> <br>" + "is displayed in the main panel, and the message of using *BEAST is also displayed on <br>" + "the bottom of main frame.<br>" + "For multi-alignment, the default of *BEAST is unlinking all models: substitution model, <br>" + "clock model, and tree models.</html>"; public enum Status { canceled, pattern, trait }; public String trait = null; public String getTrait() { return trait; } Component m_parent; JPanel guessPanel; ButtonGroup group; JRadioButton bUseEverything = new JRadioButton("use everything"); JRadioButton bSplitOnChar = new JRadioButton("split on character"); JRadioButton bUseRegexp = new JRadioButton("use regular expression"); JRadioButton bReadFromFile = new JRadioButton("read from file"); int m_location = 0; int m_splitlocation = 0; String m_sDelimiter = "."; JTextField textRegExp; JComboBox combo; JComboBox combo_1; String pattern; public String getPattern() { return pattern; } private JTextField txtFile; private JTextField textSplitChar; private JTextField textSplitChar2; private JTextField textAddValue; private JTextField textUnlessLessThan; private JTextField textThenAdd; JCheckBox chckbxAddFixedValue; JCheckBox chckbxUnlessLessThan; JLabel lblThenAdd; JLabel lblAndTakeGroups; JButton btnBrowse; private JSeparator separator_2; private JSeparator separator_3; private JSeparator separator_4; private JSeparator separator_5; public GuessPatternDialog(Component parent, String pattern) { m_parent = parent; this.pattern = pattern; guessPanel = new JPanel(); GridBagLayout gbl_guessPanel = new GridBagLayout(); gbl_guessPanel.rowHeights = new int[]{0, 0, 0, 20, 0, 0, 20, 0, 0, 20, 0, 29, 0, 0, 0, 0}; gbl_guessPanel.columnWidths = new int[]{0, 0, 0, 0, 0, 0}; gbl_guessPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; gbl_guessPanel.columnWeights = new double[] { 1.0, 1.0, 1.0, 0.0, 1.0, 0.0 }; guessPanel.setLayout(gbl_guessPanel); group = new ButtonGroup(); group.add(bUseEverything); group.add(bSplitOnChar); group.add(bUseRegexp); group.add(bReadFromFile); group.setSelected(bUseEverything.getModel(), true); bUseEverything.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateFields(); } }); bUseEverything.setName(bUseEverything.getText()); bSplitOnChar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateFields(); } }); bSplitOnChar.setName(bSplitOnChar.getText()); bUseRegexp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateFields(); } }); bUseRegexp.setName(bUseRegexp.getText()); bReadFromFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateFields(); } }); bReadFromFile.setName(bReadFromFile.getText()); createDelimiterBox(bUseEverything); createSplitBox(bSplitOnChar); createRegExtpBox(bUseRegexp); textRegExp = new JTextField(); textRegExp.setText(pattern); textRegExp.setColumns(10); textRegExp.setToolTipText("Enter regular expression to match taxa"); textRegExp.setMaximumSize(new Dimension(1024, 25)); GridBagConstraints gbc2 = new GridBagConstraints(); gbc2.insets = new Insets(0, 0, 5, 5); gbc2.anchor = GridBagConstraints.WEST; gbc2.gridwidth = 4; gbc2.gridx = 1; gbc2.gridy = 7; guessPanel.add(textRegExp, gbc2); textRegExp.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { bUseRegexp.setSelected(true); } @Override public void insertUpdate(DocumentEvent e) { bUseRegexp.setSelected(true); } @Override public void changedUpdate(DocumentEvent e) { bUseRegexp.setSelected(true); } }); separator_4 = new JSeparator(); separator_4.setPreferredSize(new Dimension(5,1)); GridBagConstraints gbc_separator_4 = new GridBagConstraints(); gbc_separator_4.gridwidth = 5; gbc_separator_4.insets = new Insets(5, 0, 15, 5); gbc_separator_4.gridx = 0; gbc_separator_4.gridy = 8; gbc_separator_4.fill = GridBagConstraints.HORIZONTAL; guessPanel.add(separator_4, gbc_separator_4); GridBagConstraints gbc_rdbtnReadFromFile = new GridBagConstraints(); gbc_rdbtnReadFromFile.anchor = GridBagConstraints.WEST; gbc_rdbtnReadFromFile.insets = new Insets(0, 0, 5, 5); gbc_rdbtnReadFromFile.gridx = 0; gbc_rdbtnReadFromFile.gridy = 10; guessPanel.add(bReadFromFile, gbc_rdbtnReadFromFile); btnBrowse = new JButton("Browse"); btnBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File file = Utils.getLoadFile("Load trait from file", new File(Beauti.g_sDir), "Select trait file", "dat","txt"); if (file != null) { txtFile.setText(file.getPath()); bReadFromFile.setSelected(true); updateFields(); } } }); txtFile = new JTextField(); txtFile.setText("File"); GridBagConstraints gbc_txtFile = new GridBagConstraints(); gbc_txtFile.gridwidth = 2; gbc_txtFile.insets = new Insets(0, 0, 5, 5); gbc_txtFile.fill = GridBagConstraints.HORIZONTAL; gbc_txtFile.gridx = 1; gbc_txtFile.gridy = 10; guessPanel.add(txtFile, gbc_txtFile); txtFile.setColumns(10); GridBagConstraints gbc_btnReadFromFile = new GridBagConstraints(); gbc_btnReadFromFile.insets = new Insets(0, 0, 5, 5); gbc_btnReadFromFile.gridx = 3; gbc_btnReadFromFile.gridy = 10; guessPanel.add(btnBrowse, gbc_btnReadFromFile); JButton btnHelp = new JButton("?"); btnHelp.setToolTipText("Show format of trait file"); btnHelp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(m_parent, EXAMPLE_FORMAT); } }); GridBagConstraints gbc_btnHelp = new GridBagConstraints(); gbc_btnHelp.insets = new Insets(0, 0, 5, 5); gbc_btnHelp.gridx = 4; gbc_btnHelp.gridy = 10; guessPanel.add(btnHelp, gbc_btnHelp); chckbxAddFixedValue = new JCheckBox("Add fixed value"); chckbxAddFixedValue.setName("Add fixed value"); chckbxAddFixedValue.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateFields(); } }); separator_5 = new JSeparator(); separator_5.setPreferredSize(new Dimension(5,1)); GridBagConstraints gbc_separator_5 = new GridBagConstraints(); gbc_separator_5.gridwidth = 5; gbc_separator_5.insets = new Insets(5, 0, 15, 5); gbc_separator_5.gridx = 0; gbc_separator_5.gridy = 12; gbc_separator_5.fill = GridBagConstraints.HORIZONTAL; guessPanel.add(separator_5, gbc_separator_5); GridBagConstraints gbc_chckbxAddFixedValue = new GridBagConstraints(); gbc_chckbxAddFixedValue.anchor = GridBagConstraints.WEST; gbc_chckbxAddFixedValue.insets = new Insets(0, 0, 5, 5); gbc_chckbxAddFixedValue.gridx = 0; gbc_chckbxAddFixedValue.gridy = 13; guessPanel.add(chckbxAddFixedValue, gbc_chckbxAddFixedValue); textAddValue = new JTextField("1900"); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.gridwidth = 2; gbc_textField.insets = new Insets(0, 0, 5, 5); gbc_textField.fill = GridBagConstraints.HORIZONTAL; gbc_textField.gridx = 1; gbc_textField.gridy = 13; guessPanel.add(textAddValue, gbc_textField); textAddValue.setColumns(10); chckbxUnlessLessThan = new JCheckBox("Unless less than..."); chckbxUnlessLessThan.setName("Unless less than"); chckbxUnlessLessThan.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateFields(); } }); GridBagConstraints gbc_chckbxUnlessLargerThan = new GridBagConstraints(); gbc_chckbxUnlessLargerThan.anchor = GridBagConstraints.WEST; gbc_chckbxUnlessLargerThan.insets = new Insets(0, 0, 5, 5); gbc_chckbxUnlessLargerThan.gridx = 0; gbc_chckbxUnlessLargerThan.gridy = 14; guessPanel.add(chckbxUnlessLessThan, gbc_chckbxUnlessLargerThan); textUnlessLessThan = new JTextField("13"); GridBagConstraints gbc_textField_1 = new GridBagConstraints(); gbc_textField_1.gridwidth = 2; gbc_textField_1.insets = new Insets(0, 0, 5, 5); gbc_textField_1.fill = GridBagConstraints.HORIZONTAL; gbc_textField_1.gridx = 1; gbc_textField_1.gridy = 14; guessPanel.add(textUnlessLessThan, gbc_textField_1); textUnlessLessThan.setColumns(10); lblThenAdd = new JLabel("...then add"); GridBagConstraints gbc_lblThenAdd = new GridBagConstraints(); gbc_lblThenAdd.anchor = GridBagConstraints.EAST; gbc_lblThenAdd.insets = new Insets(0, 0, 0, 5); gbc_lblThenAdd.gridx = 0; gbc_lblThenAdd.gridy = 15; guessPanel.add(lblThenAdd, gbc_lblThenAdd); textThenAdd = new JTextField("2000"); GridBagConstraints gbc_textField_2 = new GridBagConstraints(); gbc_textField_2.gridwidth = 2; gbc_textField_2.insets = new Insets(0, 0, 0, 5); gbc_textField_2.fill = GridBagConstraints.HORIZONTAL; gbc_textField_2.gridx = 1; gbc_textField_2.gridy = 15; guessPanel.add(textThenAdd, gbc_textField_2); textThenAdd.setColumns(10); chckbxAddFixedValue.setVisible(false); textAddValue.setVisible(false); chckbxUnlessLessThan.setVisible(false); lblThenAdd.setVisible(false); chckbxUnlessLessThan.setVisible(false); textUnlessLessThan.setVisible(false); textThenAdd.setVisible(false); } public void allowAddingValues() { chckbxAddFixedValue.setVisible(true); textAddValue.setVisible(true); chckbxUnlessLessThan.setVisible(true); lblThenAdd.setVisible(true); chckbxUnlessLessThan.setVisible(true); textUnlessLessThan.setVisible(true); textThenAdd.setVisible(true); } protected void updateFields() { if (chckbxAddFixedValue.isSelected()) { textAddValue.setEnabled(true); chckbxUnlessLessThan.setEnabled(true); lblThenAdd.setEnabled(true); if (chckbxUnlessLessThan.isSelected()) { textUnlessLessThan.setEnabled(true); textThenAdd.setEnabled(true); } else { textUnlessLessThan.setEnabled(false); textThenAdd.setEnabled(false); } } else { textAddValue.setEnabled(false); chckbxUnlessLessThan.setEnabled(false); lblThenAdd.setEnabled(false); textUnlessLessThan.setEnabled(false); textThenAdd.setEnabled(false); } txtFile.setEnabled(false); textSplitChar.setEnabled(false); textSplitChar2.setEnabled(false); textRegExp.setEnabled(false); combo.setEnabled(false); combo_1.setEnabled(false); lblAndTakeGroups.setEnabled(false); btnBrowse.setEnabled(false); if (bUseEverything.isSelected()) { textSplitChar.setEnabled(true); combo.setEnabled(true); } if (bSplitOnChar.isSelected()) { textSplitChar2.setEnabled(true); combo_1.setEnabled(true); lblAndTakeGroups.setEnabled(true); } if (bUseRegexp.isSelected()) { textRegExp.setEnabled(true); } if (bReadFromFile.isSelected()) { btnBrowse.setEnabled(true); txtFile.setEnabled(true); } } private void createDelimiterBox(JRadioButton b) { GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(0, 0, 5, 5); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 0; gbc.gridy = 1; guessPanel.add(b, gbc); combo = new JComboBox(new String[] { "after first", "after last", "before first", "before last" }); combo.setName("delimiterCombo"); GridBagConstraints gbc2 = new GridBagConstraints(); gbc2.anchor = GridBagConstraints.WEST; gbc2.gridwidth = 2; gbc2.insets = new Insets(0, 0, 5, 5); gbc2.gridx = 1; gbc2.gridy = 1; guessPanel.add(combo, gbc2); combo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JComboBox combo = (JComboBox) e.getSource(); m_location = combo.getSelectedIndex(); bUseEverything.setSelected(true); updateFields(); } }); } private void createSplitBox(JRadioButton b) { textSplitChar = new JTextField("_"); textSplitChar.setName("SplitChar"); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.anchor = GridBagConstraints.WEST; gbc_textField.insets = new Insets(0, 0, 5, 5); gbc_textField.gridx = 3; gbc_textField.gridy = 1; guessPanel.add(textSplitChar, gbc_textField); textSplitChar.setColumns(2); separator_2 = new JSeparator(); separator_2.setPreferredSize(new Dimension(5,1)); GridBagConstraints gbc_separator_2 = new GridBagConstraints(); gbc_separator_2.gridwidth = 5; gbc_separator_2.insets = new Insets(5, 0, 15, 5); gbc_separator_2.gridx = 0; gbc_separator_2.gridy = 2; gbc_separator_2.fill = GridBagConstraints.HORIZONTAL; guessPanel.add(separator_2, gbc_separator_2); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(0, 0, 5, 5); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 0; gbc.gridy = 4; guessPanel.add(b, gbc); } public void createRegExtpBox(JRadioButton b) { textSplitChar2 = new JTextField("_"); textSplitChar2.setName("SplitChar2"); GridBagConstraints gbc_textField_1 = new GridBagConstraints(); gbc_textField_1.anchor = GridBagConstraints.WEST; gbc_textField_1.insets = new Insets(0, 0, 5, 5); gbc_textField_1.gridx = 1; gbc_textField_1.gridy = 4; guessPanel.add(textSplitChar2, gbc_textField_1); textSplitChar2.setColumns(2); lblAndTakeGroups = new JLabel("and take group(s):"); GridBagConstraints gbc_lblAndTakeGroups = new GridBagConstraints(); gbc_lblAndTakeGroups.gridwidth = 2; gbc_lblAndTakeGroups.insets = new Insets(0, 0, 5, 5); gbc_lblAndTakeGroups.gridx = 2; gbc_lblAndTakeGroups.gridy = 4; guessPanel.add(lblAndTakeGroups, gbc_lblAndTakeGroups); combo_1 = new JComboBox(new String[] { "1", "2", "3", "4", "1-2", "2-3", "3-4", "1-3", "2-4" }); combo_1.setName("splitCombo"); GridBagConstraints gbc_combo_1 = new GridBagConstraints(); gbc_combo_1.anchor = GridBagConstraints.WEST; gbc_combo_1.insets = new Insets(0, 0, 5, 5); gbc_combo_1.gridx = 4; gbc_combo_1.gridy = 4; guessPanel.add(combo_1, gbc_combo_1); combo_1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JComboBox combo = (JComboBox) e.getSource(); m_splitlocation = combo.getSelectedIndex(); bSplitOnChar.setSelected(true); updateFields(); } }); separator_3 = new JSeparator(); separator_3.setPreferredSize(new Dimension(5,1)); GridBagConstraints gbc_separator_3 = new GridBagConstraints(); gbc_separator_3.gridwidth = 5; gbc_separator_3.insets = new Insets(5, 0, 15, 5); gbc_separator_3.gridx = 0; gbc_separator_3.gridy = 5; gbc_separator_3.fill = GridBagConstraints.HORIZONTAL; guessPanel.add(separator_3, gbc_separator_3); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(0, 0, 5, 5); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 0; gbc.gridy = 7; guessPanel.add(b, gbc); } public Status showDialog(String title) { JOptionPane optionPane = new JOptionPane(guessPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, new String[] { "Cancel", "OK" }, "OK"); optionPane.setBorder(new EmptyBorder(12, 12, 12, 12)); final JDialog dialog = optionPane.createDialog(m_parent, title); dialog.setName("GuessTaxonSets"); // dialog.setResizable(true); dialog.pack(); updateFields(); dialog.setVisible(true); if (optionPane.getValue() == null || !optionPane.getValue().equals("OK")) { return Status.canceled; } if (bUseEverything.getModel() == group.getSelection()) { String sDelimiter = normalise(textSplitChar.getText()); switch (m_location) { case 0: // "after first", pattern = "^[^" + sDelimiter + "]+" + sDelimiter + "(.*)$"; break; case 1: // "after last", pattern = "^.*" + sDelimiter + "(.*)$"; break; case 2: // "before first", pattern = "^([^" + sDelimiter + "]+)" + sDelimiter + ".*$"; break; case 3: // "before last" pattern = "^(.*)" + sDelimiter + ".*$"; break; } } if (bSplitOnChar.getModel() == group.getSelection()) { String sDelimiter = normalise(textSplitChar2.getText()); switch (m_splitlocation) { case 0: pattern = "^([^" + sDelimiter + "]+)" + ".*$"; break; case 1: pattern = "^[^" + sDelimiter + "]+" + sDelimiter + "([^" + sDelimiter + "]+)" + ".*$"; break; case 2: pattern = "^[^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+" + sDelimiter + "([^" + sDelimiter + "]+)" + ".*$"; break; case 3: pattern = "^[^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+" + sDelimiter + "([^" + sDelimiter + "]+)" + ".*$"; break; case 4: pattern = "^([^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+)" + ".*$"; break; case 5: pattern = "^[^" + sDelimiter + "]+" + sDelimiter + "([^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+)" + ".*$"; break; case 6: pattern = "^[^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+" + sDelimiter + "([^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+)" + ".*$"; break; case 7: pattern = "^([^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+)" + ".*$"; break; case 8: pattern = "^[^" + sDelimiter + "]+" + sDelimiter + "([^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+" + sDelimiter + "[^" + sDelimiter + "]+)" + ".*$"; } } if (bUseRegexp.getModel() == group.getSelection()) { pattern = textRegExp.getText(); } if (bReadFromFile.getModel() == group.getSelection()) { try { BufferedReader fin = new BufferedReader(new FileReader(txtFile.getText())); StringBuffer buf = new StringBuffer(); // eat up header fin.readLine(); // process data while (fin.ready()) { String str = fin.readLine(); str = str.replaceFirst("\t", "=") + ","; // only add entries that are non-empty if (!str.matches("^\\s+=.*$")) { buf.append(str); } } fin.close(); trait = buf.toString().trim(); while (trait.endsWith(",")) { trait = trait.substring(0, trait.length() - 1).trim(); } } catch (Exception e) { JOptionPane.showMessageDialog(m_parent, "Loading trait from file failed:" + e.getMessage()); return Status.canceled; } return Status.trait; } // sanity check try { pattern.matches(pattern); } catch (PatternSyntaxException e) { JOptionPane.showMessageDialog(this, "This is not a valid regular expression"); return Status.canceled; } if (optionPane.getValue() != null && optionPane.getValue().equals("OK")) { System.err.println("Pattern = " + pattern); return Status.pattern; } else { return Status.canceled; } } private String normalise(String sDelimiter) { if (sDelimiter.length() == 0) { return "."; } sDelimiter = sDelimiter.substring(0, 1); // insert escape chars for anything that might upset a regular expression if ("./\"[]()".indexOf(sDelimiter) > -1) { sDelimiter = "\\" + sDelimiter; } return sDelimiter; } public String match(String s) { Pattern _pattern = Pattern.compile(pattern); Matcher matcher = _pattern.matcher(s); if (matcher.find()) { String match = matcher.group(1); if (chckbxAddFixedValue.isSelected()) { try { Double value = Double.parseDouble(match); Double addValue = Double.parseDouble(textAddValue.getText()); if (chckbxUnlessLessThan.isSelected()) { Double threshold = Double.parseDouble(textUnlessLessThan.getText()); Double addValue2 = Double.parseDouble(textThenAdd.getText()); if (value < threshold) { value += addValue2; } else { value += addValue; } } else { value += addValue; } return value + ""; } catch (Exception e) { // ignore } } return match; } return null; } }
package big.marketing.controller; import java.io.IOException; import java.util.List; import java.util.Observable; import org.apache.log4j.Logger; import big.marketing.data.DataType; import big.marketing.data.Node; import big.marketing.reader.NetworkReader; import big.marketing.reader.ZipReader; public class DataController extends Observable { static Logger logger = Logger.getLogger(DataController.class); private Node[] highlightedNodes = null; private Node selectedNode = null; private MongoController mongoController; private List<Node> network; public DataController() { this.mongoController = new MongoController(); NetworkReader nReader = new NetworkReader(this.mongoController); ZipReader zReader = new ZipReader(this.mongoController); try { // TODO Catch all reading error in DataController network = nReader.readNetwork(); for (int week = 1; week <= 2; week++) { //zReader.read(DataType.FLOW, week); zReader.read(DataType.HEALTH, week); //zReader.read(DataType.IPS, week); } } catch (IOException err) { logger.error("Error while loading network data.", err); } } public List<Node> getNetwork() { return network; } public void setMongoController(MongoController mongoController) { this.mongoController = mongoController; } public MongoController getMongoController() { return mongoController; } public void setHighlightedNodes(Node[] highlightedNodes) { this.highlightedNodes = highlightedNodes; setChanged(); } public void setSelectedNode(Node selectedNode) { this.selectedNode = selectedNode; setChanged(); } public Node[] getHighlightedNodes() { return highlightedNodes; } public Node getSelectedNode() { return selectedNode; } }
package com.appspot.usbhidterminal; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import com.appspot.usbhidterminal.core.Consts; import com.appspot.usbhidterminal.core.USBHIDService; public class MainActivity extends Activity implements View.OnClickListener { private SharedPreferences sharedPreferences; private Intent usbService; private USBServiceResultReceiver usbServiceResultReceiver; private EditText edtlogText; private EditText edtxtHidInput; private Button btnSend; private Button btnSelectHIDDevice; private Button btnClear; private RadioButton rbSendDataType; private String settingsDelimiter; private String receiveDataFormat; private String delimiter; class USBServiceResultReceiver extends ResultReceiver { public USBServiceResultReceiver(Handler handler) { super(handler); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode == Consts.ACTION_USB_LOG) { mLog(resultData.getString("log"), false); } else if (resultCode == Consts.ACTION_USB_LOG_C) { mLog(resultData.getString("log"), true); } else if (resultCode == Consts.ACTION_USB_DEVICE_ATTACHED) { btnSend.setEnabled(true); } else if (resultCode == Consts.ACTION_USB_DEVICE_DETACHED) { btnSend.setEnabled(false); } else if (resultCode == Consts.ACTION_USB_SHOW_DEVICES_LIST_RESULT) { showListOfDevices(resultData.getCharSequenceArray(Consts.ACTION_USB_SHOW_DEVICES_LIST)); } } } private void prepareUSBHIDService() { usbService = new Intent(this, USBHIDService.class); usbServiceResultReceiver = new USBServiceResultReceiver(null); usbService.putExtra("receiver", usbServiceResultReceiver); startService(usbService); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setVersionToTitle(); btnSend = (Button) findViewById(R.id.btnSend); btnSend.setOnClickListener(this); btnSelectHIDDevice = (Button) findViewById(R.id.btnSelectHIDDevice); btnSelectHIDDevice.setOnClickListener(this); btnClear = (Button) findViewById(R.id.btnClear); btnClear.setOnClickListener(this); edtxtHidInput = (EditText) findViewById(R.id.edtxtHidInput); edtlogText = (EditText) findViewById(R.id.edtlogText); rbSendDataType = (RadioButton) findViewById(R.id.rbSendData); rbSendDataType.setOnClickListener(this); mLog("Initialized\nPlease select your USB HID device", false); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); edtxtHidInput.setText("129"); // btnSend.setEnabled(true); } public void onClick(View v) { if (v == btnSend) { usbService.setAction(Consts.ACTION_USB_SEND_DATA); usbService.putExtra(Consts.ACTION_USB_SEND_DATA, edtxtHidInput.getText().toString()); startService(usbService); } else if (v == rbSendDataType) { usbService.setAction(Consts.ACTION_USB_DATA_TYPE); usbService.putExtra(Consts.ACTION_USB_DATA_TYPE, rbSendDataType.isChecked()); startService(usbService); } else if (v == btnClear) { edtlogText.setText(""); } else if (v == btnSelectHIDDevice) { usbService.setAction(Consts.ACTION_USB_SHOW_DEVICES_LIST); startService(usbService); } } void showListOfDevices(CharSequence devicesName[]) { AlertDialog.Builder builder = new AlertDialog.Builder(this); if (devicesName.length == 0) { builder.setTitle(Consts.MESSAGE_CONNECT_YOUR_USB_HID_DEVICE); } else { builder.setTitle(Consts.MESSAGE_SELECT_YOUR_USB_HID_DEVICE); } builder.setItems(devicesName, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { usbService.setAction(Consts.ACTION_USB_SELECT_DEVICE); usbService.putExtra(Consts.ACTION_USB_SELECT_DEVICE, which); startService(usbService); } }); builder.setCancelable(true); builder.show(); } @Override protected void onStart() { super.onStart(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT); prepareUSBHIDService(); setDelimiter(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); setSelectedMenuItemsFromSettings(menu); return true; } private void setSelectedMenuItemsFromSettings(Menu menu) { receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT); if (receiveDataFormat.equals(Consts.BINARY)) { menu.findItem(R.id.menuSettingsReceiveBinary).setChecked(true); } else if (receiveDataFormat.equals(Consts.INTEGER)) { menu.findItem(R.id.menuSettingsReceiveInteger).setChecked(true); } else if (receiveDataFormat.equals(Consts.HEXADECIMAL)) { menu.findItem(R.id.menuSettingsReceiveHexadecimal).setChecked(true); } else if (receiveDataFormat.equals(Consts.TEXT)) { menu.findItem(R.id.menuSettingsReceiveText).setChecked(true); } setDelimiter(); if (settingsDelimiter.equals(Consts.DELIMITER_NONE)) { menu.findItem(R.id.menuSettingsDelimiterNone).setChecked(true); } else if (settingsDelimiter.equals(Consts.DELIMITER_NEW_LINE)) { menu.findItem(R.id.menuSettingsDelimiterNewLine).setChecked(true); } else if (settingsDelimiter.equals(Consts.DELIMITER_SPACE)) { menu.findItem(R.id.menuSettingsDelimiterSpace).setChecked(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { SharedPreferences.Editor editor = sharedPreferences.edit(); item.setChecked(true); switch (item.getItemId()) { case R.id.menuSettingsReceiveBinary: editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.BINARY).commit(); break; case R.id.menuSettingsReceiveInteger: editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.INTEGER).commit(); break; case R.id.menuSettingsReceiveHexadecimal: editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.HEXADECIMAL).commit(); break; case R.id.menuSettingsReceiveText: editor.putString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT).commit(); break; case R.id.menuSettingsDelimiterNone: editor.putString(Consts.DELIMITER, Consts.DELIMITER_NONE).commit(); break; case R.id.menuSettingsDelimiterNewLine: editor.putString(Consts.DELIMITER, Consts.DELIMITER_NEW_LINE).commit(); break; case R.id.menuSettingsDelimiterSpace: editor.putString(Consts.DELIMITER, Consts.DELIMITER_SPACE).commit(); break; } receiveDataFormat = sharedPreferences.getString(Consts.RECEIVE_DATA_FORMAT, Consts.TEXT); setDelimiter(); return true; } private void setDelimiter() { settingsDelimiter = sharedPreferences.getString(Consts.DELIMITER, Consts.DELIMITER_NEW_LINE); if (settingsDelimiter.equals(Consts.DELIMITER_NONE)) { delimiter = ""; } else if (settingsDelimiter.equals(Consts.DELIMITER_NEW_LINE)) { delimiter = Consts.NEW_LINE; } else if (settingsDelimiter.equals(Consts.DELIMITER_SPACE)) { delimiter = Consts.SPACE; } usbService.setAction(Consts.RECEIVE_DATA_FORMAT); usbService.putExtra(Consts.RECEIVE_DATA_FORMAT, receiveDataFormat); usbService.putExtra(Consts.DELIMITER, delimiter); startService(usbService); } private void mLog(String log, boolean newLine) { if (newLine) { edtlogText.append(Consts.NEW_LINE); } edtlogText.append(log); edtlogText.setSelection(edtlogText.getText().length()); } private void setVersionToTitle() { try { this.setTitle(Consts.SPACE + this.getTitle() + Consts.SPACE + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (NameNotFoundException e) { e.printStackTrace(); } } }
package com.backendless.push; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.app.RemoteInput; import android.util.Log; import com.backendless.Backendless; import com.backendless.messaging.Action; import com.backendless.messaging.AndroidPushTemplate; import com.backendless.messaging.PublishOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class PushTemplateHelper { private static Map<String, AndroidPushTemplate> pushNotificationTemplates; public static Map<String, AndroidPushTemplate> getPushNotificationTemplates() { return pushNotificationTemplates; } public static void setPushNotificationTemplates( Map<String, AndroidPushTemplate> pushNotificationTemplates, byte[] rawTemplates ) { PushTemplateHelper.pushNotificationTemplates = Collections.unmodifiableMap( pushNotificationTemplates ); savePushTemplates( rawTemplates ); } private static void savePushTemplates( byte[] rawBytes ) { try { JSONArray jsonArray = new JSONArray( new String( rawBytes)); JSONObject templates = jsonArray.getJSONObject( 1 ); Backendless.savePushTemplates( templates.toString() ); } catch( JSONException e ) { Log.w( PushTemplateHelper.class.getSimpleName(), "Cannot deserialize AndroidPushTemplate to JSONObject.", e ); } } static Notification convertFromTemplate( Context context, AndroidPushTemplate template, String messageText, int messageId ) { // Notification channel ID is ignored for Android 7.1.1 (API level 25) and lower. NotificationCompat.Builder notificationBuilder; // android.os.Build.VERSION_CODES.O == 26 if( android.os.Build.VERSION.SDK_INT >= 26 ) { final String channelId = Backendless.getApplicationId() + ":" + template.getName(); NotificationManager notificationManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE ); NotificationChannel notificationChannel = notificationManager.getNotificationChannel( channelId ); if( notificationChannel == null ) { notificationChannel = PushTemplateHelper.createNotificationChannel( channelId, template ); notificationManager.createNotificationChannel( notificationChannel ); } notificationBuilder = new NotificationCompat.Builder( context.getApplicationContext(), channelId ); notificationBuilder.setDefaults( Notification.DEFAULT_ALL ); if( template.getColorized() != null ) notificationBuilder.setColorized( template.getColorized() ); if( template.getBadge() != null ) notificationBuilder.setBadgeIconType( template.getBadge() ); else notificationBuilder.setBadgeIconType( Notification.BADGE_ICON_NONE ); if( template.getCancelAfter() != null && template.getCancelAfter() != 0 ) notificationBuilder.setTimeoutAfter( template.getCancelAfter() ); } else { notificationBuilder = new NotificationCompat.Builder( context.getApplicationContext() ); notificationBuilder.setDefaults( Notification.DEFAULT_ALL ); if (template.getPriority() != null) notificationBuilder.setPriority( template.getPriority() ); else notificationBuilder.setPriority( Notification.PRIORITY_DEFAULT ); if( template.getButtonTemplate().getSound() != null ) notificationBuilder.setSound( Uri.parse( template.getButtonTemplate().getSound() ) ); if( template.getButtonTemplate().getVibrate() != null ) { long[] vibrate = new long[ template.getButtonTemplate().getVibrate().length ]; int index = 0; for( long l : template.getButtonTemplate().getVibrate() ) vibrate[ index++ ] = l; notificationBuilder.setVibrate( vibrate ); } if (template.getButtonTemplate().getVisibility() != null) notificationBuilder.setVisibility( template.getButtonTemplate().getVisibility() ); else notificationBuilder.setVisibility( template.getButtonTemplate().getVisibility() ); } try { InputStream is = (InputStream) new URL( template.getAttachmentUrl() ).getContent(); Bitmap bitmap = BitmapFactory.decodeStream( is ); if( bitmap != null ) notificationBuilder.setStyle( new NotificationCompat.BigPictureStyle().bigPicture( bitmap ) ); else Log.i( PushTemplateHelper.class.getSimpleName(), "Cannot convert rich media for notification into bitmap." ); } catch( IOException e ) { Log.e( PushTemplateHelper.class.getSimpleName(), "Cannot receive rich media for notification." ); } int icon = 0; if( template.getIcon() != null ) icon = context.getResources().getIdentifier( template.getIcon(), "drawable", context.getPackageName() ); if( icon == 0 ) { icon = context.getResources().getIdentifier( "ic_launcher", "drawable", context.getPackageName() ); if( icon != 0 ) notificationBuilder.setSmallIcon( icon ); } if (template.getLightsColor() != null && template.getLightsOnMs() != null && template.getLightsOffMs() != null) notificationBuilder.setLights(template.getLightsColor(), template.getLightsOnMs(), template.getLightsOffMs()); if (template.getColorCode() != null) notificationBuilder.setColor( template.getColorCode() ); if (template.getCancelOnTap() != null) notificationBuilder.setAutoCancel( template.getCancelOnTap() ); else notificationBuilder.setAutoCancel( false ); notificationBuilder .setDefaults( Notification.DEFAULT_ALL ) .setShowWhen( true ) .setWhen( System.currentTimeMillis() ) .setTicker( template.getTickerText() ) .setContentTitle( template.getFirstRowTitle() ) .setContentText( messageText ); Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage( context.getPackageName() ); notificationIntent.putExtra( BackendlessBroadcastReceiver.EXTRA_MESSAGE_ID, messageId ); notificationIntent.putExtra( PublishOptions.TEMPLATE_NAME, template.getName() ); notificationIntent.putExtra( PublishOptions.MESSAGE_TAG, messageText ); notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); PendingIntent contentIntent = PendingIntent.getActivity( context, messageId * 3, notificationIntent, 0 ); notificationBuilder.setContentIntent( contentIntent ); if (template.getButtonTemplate().getActions() != null) { List<NotificationCompat.Action> actions = createActions( context, template.getButtonTemplate().getActions(), template.getName(), messageId, messageText ); for( NotificationCompat.Action action : actions ) notificationBuilder.addAction( action ); } return notificationBuilder.build(); } static private List<NotificationCompat.Action> createActions( Context context, Action[] actions, String templateName, int messageId, String messageText ) { List<NotificationCompat.Action> notifActions = new ArrayList<>(); int i = 1; for( Action a : actions ) { Intent actionIntent = new Intent( a.getTitle() ); actionIntent.setClassName( context, a.getId() ); actionIntent.putExtra( BackendlessBroadcastReceiver.EXTRA_MESSAGE_ID, messageId ); actionIntent.putExtra( PublishOptions.MESSAGE_TAG, messageText ); actionIntent.putExtra( PublishOptions.TEMPLATE_NAME, templateName ); actionIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); // user should use messageId and tag(templateName) to cancel notification. PendingIntent pendingIntent = PendingIntent.getActivity( context, messageId * 3 + i++, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT ); NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder( 0, a.getTitle(), pendingIntent ); if( a.getOptions() == 1 ) { RemoteInput remoteInput = new RemoteInput.Builder( PublishOptions.INLINE_REPLY ).build(); actionBuilder.setAllowGeneratedReplies( true ).addRemoteInput( remoteInput ); } notifActions.add( actionBuilder.build() ); } return notifActions; } static private NotificationChannel createNotificationChannel( final String channelId, final AndroidPushTemplate template ) { NotificationChannel notificationChannel = new NotificationChannel( channelId, template.getName(), NotificationManager.IMPORTANCE_DEFAULT ); notificationChannel.setShowBadge( template.getButtonTemplate().getShowBadge() ); notificationChannel.setImportance( template.getPriority() ); // NotificationManager.IMPORTANCE_DEFAULT if( template.getButtonTemplate().getSound() != null ) notificationChannel.setSound( Uri.parse( template.getButtonTemplate().getSound() ), null ); notificationChannel.enableLights( true ); notificationChannel.setLightColor( template.getLightsColor() ); if( template.getButtonTemplate().getVibrate() != null ) { long[] vibrate = new long[ template.getButtonTemplate().getVibrate().length ]; int index = 0; for( long l : template.getButtonTemplate().getVibrate() ) vibrate[ index++ ] = l; notificationChannel.setVibrationPattern( vibrate ); } if (template.getButtonTemplate().getVisibility() != null) notificationChannel.setLockscreenVisibility( template.getButtonTemplate().getVisibility() ); else notificationChannel.setLockscreenVisibility( Notification.VISIBILITY_PUBLIC ); if( template.getButtonTemplate().getBypassDND() != null ) notificationChannel.setBypassDnd( template.getButtonTemplate().getBypassDND() ); else notificationChannel.setBypassDnd( false ); return notificationChannel; } static void showNotification( final Context context, final Notification notification, final String tag, final int messageId ) { final NotificationManagerCompat notificationManager = NotificationManagerCompat.from( context.getApplicationContext() ); Handler handler = new Handler( Looper.getMainLooper() ); handler.post( new Runnable() { @Override public void run() { notificationManager.notify( tag, messageId, notification ); } } ); } static void restorePushTemplates() { String rawTemplates = Backendless.getPushTemplatesAsJson(); if (rawTemplates == null) { pushNotificationTemplates = Collections.emptyMap(); return; } Map<String, AndroidPushTemplate> templates; try { templates = (Map<String, AndroidPushTemplate>) weborb.util.io.Serializer.fromBytes( rawTemplates.getBytes(), weborb.util.io.Serializer.JSON, false ); pushNotificationTemplates = Collections.unmodifiableMap( templates); } catch( IOException e ) { pushNotificationTemplates = Collections.emptyMap(); Log.w( PushTemplateHelper.class.getSimpleName(), "Cannot deserialize AndroidPushTemplate to JSONObject.", e ); } } }
package br.edu.ufsc.sudoku42.view; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; public class PainelJogador extends JPanel{ protected static final String TEMPLATE_TIME_1 = ":"; protected static final String TEMPLATE_TIME_2 = ":0"; protected String nome; protected JLabel tempo; protected JLabel pontuacao; protected int minutos; protected int segundos; protected Timer timer; public PainelJogador(String nome) { this.nome = nome; initialize(); } public void initialize() { this.setBorder(BorderFactory.createTitledBorder(this.nome)); this.tempo = new JLabel("00:00"); this.pontuacao = new JLabel("99"); this.add(tempo); this.add(pontuacao); this.setPreferredSize(new Dimension(100,40)); this.iniciarTimer(); } public void iniciarTimer(){ this.converterFormato(600); Timer timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { printTime(); } }); timer.setInitialDelay(0); timer.setRepeats(true); timer.start(); } public void converterFormato(int segundosRestantes){ this.minutos = (int)segundosRestantes /60; this.segundos = segundosRestantes %60; } private void printTime() { StringBuilder text = new StringBuilder("0"); if(segundos <= 0){ minutos segundos = 59; } else { segundos } text.append(minutos); if(segundos< 10){ text.append(TEMPLATE_TIME_2); } else { text.append(TEMPLATE_TIME_1); } text.append(segundos); tempo.setText(text.toString()); } }