answer
stringlengths
17
10.2M
package com.ibm.streamsx.topology.test.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import org.junit.Test; import com.ibm.streamsx.topology.TStream; import com.ibm.streamsx.topology.Topology; import com.ibm.streamsx.topology.context.StreamsContext.Type; import com.ibm.streamsx.topology.function.Function; import com.ibm.streamsx.topology.function.FunctionContainer; import com.ibm.streamsx.topology.function.FunctionContext; import com.ibm.streamsx.topology.function.Initializable; import com.ibm.streamsx.topology.function.Predicate; import com.ibm.streamsx.topology.function.ToIntFunction; import com.ibm.streamsx.topology.streams.BeaconStreams; import com.ibm.streamsx.topology.streams.CollectionStreams; import com.ibm.streamsx.topology.streams.StringStreams; import com.ibm.streamsx.topology.test.AllowAll; import com.ibm.streamsx.topology.test.TestTopology; import com.ibm.streamsx.topology.tester.Condition; import com.ibm.streamsx.topology.tester.Tester; public class StreamTest extends TestTopology { public static void assertStream(Topology f, TStream<?> stream) { TopologyTest.assertFlowElement(f, stream); } @Test public void testBasics() throws Exception { assumeTrue(isMainRun()); final Topology topology = new Topology("BasicStream"); assertEquals("BasicStream", topology.getName()); assertSame(topology, topology.topology()); TStream<String> source = topology.strings("a", "b", "c"); assertStream(topology, source); assertSame(String.class, source.getTupleClass()); assertSame(String.class, source.getTupleType()); } @Test public void testStringFilter() throws Exception { final Topology f = newTopology("StringFilter"); TStream<String> source = f.strings("hello", "goodbye", "farewell"); assertStream(f, source); TStream<String> filtered = source.filter(lengthFilter(5)); completeAndValidate(filtered, 10, "goodbye", "farewell"); } @SuppressWarnings("serial") public static Predicate<String> lengthFilter(final int length) { return new Predicate<String>() { @Override public boolean test(String v1) { return v1.length() > length; } }; } @Test public void testTransform() throws Exception { final Topology f = newTopology("TransformStream"); TStream<String> source = f.strings("325", "457", "9325"); assertStream(f, source); TStream<Integer> i1 = source.transform(stringToInt()); TStream<Integer> i2 = i1.transform(add17()); completeAndValidate(i2, 10, "342", "474", "9342"); } @Test public void testTransformWithDrop() throws Exception { final Topology f = newTopology("TransformStream"); TStream<String> source = f.strings("93", "68", "221"); assertStream(f, source); TStream<Integer> i1 = source.transform(stringToIntExcept68()); TStream<Integer> i2 = i1.transform(add17()); completeAndValidate(i2, 10, "110", "238"); } @Test public void testMultiTransform() throws Exception { final Topology topology = newTopology("MultiTransformStream"); TStream<String> source = topology.strings("mary had a little lamb", "its fleece was white as snow"); assertStream(topology, source); TStream<String> words = source.multiTransform(splitWords()); completeAndValidate(words, 10, "mary", "had", "a", "little", "lamb", "its", "fleece", "was", "white", "as", "snow"); } @Test public void testUnionNops() throws Exception { assumeTrue(isMainRun()); final Topology f = newTopology("Union"); TStream<String> s1 = f.strings("A1", "B1", "C1", "D1"); Set<TStream<String>> empty = Collections.emptySet(); assertSame(s1, s1.union(s1)); assertSame(s1, s1.union(empty)); assertSame(s1, s1.union(Collections.singleton(s1))); } @Test public void testUnion() throws Exception { final Topology topology = newTopology("Union"); TStream<String> s1 = topology.strings("A1", "B1", "C1", "D1"); TStream<String> s2 = topology.strings("A2", "B2", "C2", "D2"); List<String> l3 = new ArrayList<>(); l3.add("A3"); l3.add("B3"); TStream<String> s3 = topology.constants(l3); List<String> l4 = new ArrayList<>(); l4.add("A4"); l4.add("B4"); TStream<String> s4 = topology.constants(l4); assertNotSame(s1, s2); TStream<String> su = s1.union(s2); assertNotSame(su, s1); assertNotSame(su, s2); // Merge with two different schema types // but the primary has the correct direct type. su = su.union(s3); assertEquals(String.class, su.getTupleClass()); assertEquals(String.class, su.getTupleType()); // Merge with two different schema types // but the primary has the generic type assertNull(s4.getTupleClass()); su = s4.union(su); assertEquals(String.class, su.getTupleClass()); assertEquals(String.class, su.getTupleType()); // TODO - testing doesn't work against union streams in embedded. su = su.filter(new AllowAll<String>()); Tester tester = topology.getTester(); Condition<Long> suCount = tester.tupleCount(su, 12); Condition<List<String>> suContents = tester.stringContentsUnordered(su, "A1", "B1", "C1", "D1", "A2", "B2", "C2", "D2", "A3", "B3", "A4", "B4"); //assertTrue(complete(tester, suCount, 10, TimeUnit.SECONDS)); complete(tester, suCount, 10, TimeUnit.SECONDS); assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SU:" + suCount, suCount.valid()); } @Test public void testUnionSet() throws Exception { final Topology topology = newTopology("Union"); TStream<String> s1 = topology.strings("A1", "B1", "C1"); TStream<String> s2 = topology.strings("A2", "B2", "C2", "D2"); TStream<String> s3 = topology.strings("A3", "B3", "C3"); Set<TStream<String>> streams = new HashSet<TStream<String>>(); streams.add(s2); streams.add(s3); TStream<String> su = s1.union(streams); // TODO - testing doesn't work against union streams in embedded. su = su.filter(new AllowAll<String>()); Tester tester = topology.getTester(); Condition<Long> suCount = tester.tupleCount(su, 10); Condition<List<String>> suContents = tester.stringContentsUnordered(su, "A1", "B1", "C1", "A2", "B2", "C2", "D2", "A3", "B3", "C3"); assertTrue(complete(tester, suCount, 10, TimeUnit.SECONDS)); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SU:" + suCount, suCount.valid()); assertTrue("SUContents:" + suContents, suContents.valid()); } @Test public void testSimpleParallel() throws Exception { final Topology topology = newTopology("EmbeddedParallel"); TStream<Number> s1 = topology.numbers(1, 2, 3, 94, 5, 6).parallel(6) .filter(new AllowAll<Number>()).endParallel(); TStream<String> sp = StringStreams.toString(s1); Tester tester = topology.getTester(); Condition<Long> spCount = tester.tupleCount(sp, 6); Condition<List<String>> spContents = tester.stringContentsUnordered(sp, "1", "2", "3", "94", "5", "6"); complete(tester, spCount, 60, TimeUnit.SECONDS); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SP:" + spCount, spCount.valid()); assertTrue("SPContents:" + spContents, spContents.valid()); } @Test public void testSplit() throws Exception { final Topology topology = newTopology("testSplit"); TStream<String> s1 = topology.strings("ch0", "ch1", "ch2", "omit", "another-ch2", "another-ch1", "another-ch0", "another-omit"); List<TStream<String>> splits = s1.split(3, myStringSplitter()); assertEquals("list size", 3, splits.size()); Tester tester = topology.getTester(); List<Condition<List<String>>> contents = new ArrayList<>(); for(int i = 0; i < splits.size(); i++) { TStream<String> ch = splits.get(i); Condition<List<String>> chContents = tester.stringContents(ch, "ch"+i, "another-ch"+i); contents.add(chContents); } TStream<String> all = splits.get(0).union( new HashSet<>(splits.subList(1, splits.size()))); Condition<Long> uCount = tester.tupleCount(all, 6); complete(tester, uCount, 10, TimeUnit.SECONDS); for(int i = 0; i < splits.size(); i++) { assertTrue("chContents["+i+"]:" + contents.get(i), contents.get(i).valid()); } } /** * Partition strings based on the last character of the string. * If the last character is a digit return its value as an int, else return -1. * @return */ @SuppressWarnings("serial") private static ToIntFunction<String> myStringSplitter() { return new ToIntFunction<String>() { @Override public int applyAsInt(String s) { char ch = s.charAt(s.length() - 1); return Character.digit(ch, 10); } }; } @SuppressWarnings("serial") static Function<String, Integer> stringToInt() { return new Function<String, Integer>() { @Override public Integer apply(String v1) { return Integer.valueOf(v1); } }; } @SuppressWarnings("serial") static Function<String, Integer> stringToIntExcept68() { return new Function<String, Integer>() { @Override public Integer apply(String v1) { Integer i = Integer.valueOf(v1); return (i == 68) ? null : i; } }; } @SuppressWarnings("serial") static Function<Integer, Integer> add17() { return new Function<Integer, Integer>() { @Override public Integer apply(Integer v1) { return v1 + 17; } }; } @SuppressWarnings("serial") static Function<String, Iterable<String>> splitWords() { return new Function<String, Iterable<String>>() { @Override public Iterable<String> apply(String v1) { return Arrays.asList(v1.split(" ")); } }; } @Test public void testFunctionContextNonDistributed() throws Exception { assumeTrue(getTesterType() != Type.DISTRIBUTED_TESTER); Topology t = newTopology(); TStream<Map<String, Object>> values = BeaconStreams.single(t).transform(new ExtractFunctionContext()); TStream<String> strings = StringStreams.toString(CollectionStreams.flattenMap(values)); Tester tester = t.getTester(); Condition<Long> spCount = tester.tupleCount(strings, 7); Condition<List<String>> spContents = tester.stringContents(strings, "channel=-1", "domainId=" + System.getProperty("user.name"), "id=0", "instanceId=" + System.getProperty("user.name"), "jobId=0", "maxChannels=0", "relaunchCount=0" ); complete(tester, spCount, 60, TimeUnit.SECONDS); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SP:" + spCount, spCount.valid()); assertTrue("SPContents:" + spContents, spContents.valid()); } public static class ExtractFunctionContext implements Function<Long,Map<String,Object>>, Initializable { private static final long serialVersionUID = 1L; private FunctionContext functionContext; @Override public Map<String, Object> apply(Long v) { Map<String,Object> values = new TreeMap<>(); values.put("channel", functionContext.getChannel()); values.put("maxChannels", functionContext.getMaxChannels()); FunctionContainer container = functionContext.getContainer(); values.put("id", container.getId()); values.put("jobId", container.getJobId()); values.put("relaunchCount", container.getRelaunchCount()); values.put("domainId", container.getDomainId()); values.put("instanceId", container.getInstanceId()); return values; } @Override public void initialize(FunctionContext functionContext) throws Exception { this.functionContext = functionContext; } } }
package com.bugsnag; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Date; import static org.junit.Assert.*; public class NotificationTest { private Report report; private Configuration config; private final ObjectMapper mapper = new ObjectMapper(); @Before public void setUp() throws Throwable { config = new Configuration("api-key"); report = new Report(config, new RuntimeException()); } private JsonNode generateJson(ObjectMapper mapper, Configuration config, Report report) throws IOException { Notification notification = new Notification(config, report); String json = mapper.writeValueAsString(notification); return mapper.readTree(json); } @Test public void testSessionSerialisation() throws Throwable { report.setSession(new Session("123", new Date())); JsonNode rootNode = generateJson(mapper, config, report); validateErrorReport(rootNode); // check contains a session JsonNode session = rootNode.get("events").get(0).get("session"); assertNotNull(session); assertNotNull(session.get("id").asText()); assertNotNull(session.get("startedAt").asText()); JsonNode handledState = session.get("events"); assertNotNull(handledState); assertNotNull(handledState.get("handled")); assertNotNull(handledState.get("unhandled")); } @Test public void testWithoutSessionSerialisation() throws Throwable { report.setSession(new Session("123", new Date())); JsonNode rootNode = generateJson(mapper, config, report); validateErrorReport(rootNode); assertNull(rootNode.get("events").get("session")); } private void validateErrorReport(JsonNode rootNode) throws Throwable { assertNotNull(rootNode); assertNotNull(rootNode.get("apiKey").asText()); assertNotNull(rootNode.get("notifier")); JsonNode events = rootNode.get("events"); assertNotNull(events); JsonNode event = events.get(0); assertNotNull(event); } }
package net.meisen.dissertation.impl.cache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.io.File; import java.util.Arrays; import java.util.Random; import net.meisen.dissertation.config.TestConfig; import net.meisen.dissertation.config.xslt.DefaultValues; import net.meisen.dissertation.help.ModuleBasedTest; import net.meisen.dissertation.help.ThreadForTesting; import net.meisen.dissertation.model.cache.IBitmapIdCacheConfig; import net.meisen.dissertation.model.data.TidaModel; import net.meisen.dissertation.model.indexes.datarecord.IntervalIndex; import net.meisen.dissertation.model.indexes.datarecord.MetaIndex; import net.meisen.dissertation.model.indexes.datarecord.slices.Bitmap; import net.meisen.dissertation.model.indexes.datarecord.slices.BitmapId; import net.meisen.general.genmisc.types.Files; import net.meisen.general.sbconfigurator.runners.annotations.ContextClass; import net.meisen.general.sbconfigurator.runners.annotations.ContextFile; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; /** * Tests the implementation of a {@code FileBitmapCache}. * * @author pmeisen * */ @ContextClass(TestConfig.class) @ContextFile("test-sbconfigurator-core.xml") public class TestFileBitmapCache extends ModuleBasedTest { private TidaModel model; private FileBitmapCache fc; /** * Create a test instance of a {@code FileBitmapCache}. */ @Before public void create() { setModulesHolder("/net/meisen/dissertation/impl/cache/fileBitmapCacheModel.xml"); // create the instance of the cache model = modulesHolder.getModule(DefaultValues.TIDAMODEL_ID); fc = modulesHolder.getModule(DefaultValues.BITMAPCACHE_ID); assertNotNull(fc); // make sure the location is deleted assertTrue(Files.deleteDir(fc.getLocation())); } /** * Creates a {@code BitmapId} with the specified identifier. * * @param nr * the identifier * * @return the created {@code BitmapId} */ protected BitmapId<Integer> createBitmapId(final int nr) { return new BitmapId<Integer>(nr, IntervalIndex.class); } /** * Helper method to cache some generated bitmaps to the {@code fc}. * * @param fc * the {@code FileBitmapCache} to add data to * @param amount * the amount of data to be generated * @param dataOffset * the offset between the id and the data to be set within the * generated bitmap */ protected void cache(final FileBitmapCache fc, final int amount, final int dataOffset) { for (int i = 0; i < amount; i++) { final BitmapId<?> id = createBitmapId(i); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i + dataOffset); // cache the bitmap fc.cache(id, bmp); } } /** * Tests the exception to be thrown if the configuration is changed after * initialization. */ @Test public void testConfigurationChangeException() { thrown.expect(BaseFileBitmapIdCacheException.class); thrown.expectMessage("configuration cannot be changed"); // initialize and change the configuration fc.initialize(model); fc.setConfig(null); } /** * Tests the exception to be thrown if an invalid configuration is used. */ @Test public void testInvalidConfigurationException() { thrown.expect(BaseFileBitmapIdCacheException.class); thrown.expectMessage("cache does not support a configuration of type"); // initialize and change the configuration fc.setConfig(new IBitmapIdCacheConfig() { }); } /** * Tests the exception to be thrown if an invalid modelId is used. */ @Test public void testInvalidModelIdException() { thrown.expect(BaseFileBitmapIdCacheException.class); thrown.expectMessage("unable to create the cache location"); // use an invalid character for a folder final TidaModel model = new TidaModel() { @Override public String getId() { return "?"; } @Override public File getLocation() { return null; }; }; fc.initialize(model); } /** * Tests the exception to be thrown if an invalid location is used. */ @Test public void testInvalidLocationException() { thrown.expect(BaseFileBitmapIdCacheException.class); thrown.expectMessage("unable to create the cache location"); // use an invalid character for a folder final FileBitmapIdCacheConfig config = new FileBitmapIdCacheConfig(); config.setLocation(null); fc.setConfig(config); final TidaModel model = new TidaModel() { @Override public String getId() { return "modelId"; } @Override public File getLocation() { return new File("?"); }; }; fc.initialize(model); } /** * Tests the creation of the model location, when the cache is initialized. */ @Test public void testCreationOfModelLocation() { fc.initialize(model); // make sure the location is created assertNotNull(fc.getModelLocation()); assertTrue(fc.getModelLocation().exists()); } /** * Tests the methods {@link IndexEntry#bytes()} and * {@link IndexEntry#IndexEntry(byte[])}. */ @Test public void testIndexEntrySerializability() { IndexEntry e; // serialize it e = new IndexEntry(1000, 25000, (byte) 5); e.setIndexFileNumber(100); e = new IndexEntry(e.bytes()); // deserialize it assertEquals(1000, e.getSize()); assertEquals(25000, e.getFilePosition()); assertEquals(100, e.getIndexFileNumber()); assertEquals((byte) 5, e.getFileNumber()); } /** * Tests the loading of none-cached bitmaps. */ @Test public void testNoneCachedBitmapRetrieval() { fc.initialize(model); final Bitmap emptyBitmap = model.getIndexFactory().createBitmap(); // retrieve some bitmaps for different identifiers for (int i = 0; i < 1000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, IntervalIndex.class); assertFalse(fc.isCached(id)); assertEquals(emptyBitmap, fc.get(id)); assertTrue(fc.isCached(id)); } } /** * Tests the persisting of bitmaps to the hard-drive. */ @Test public void testPersistance() { fc.initialize(model); for (int i = 0; i < 50000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i); // cache the bitmap fc.cache(id, bmp); // clear the cache fc.clearCache(); // retrieve the bitmap and check the cache status assertFalse(fc.isCached(id)); assertEquals(bmp, fc.get(id)); assertTrue(fc.isCached(id)); } fc.clearCache(); // check to read all the bitmaps for (int i = 0; i < 50000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i); // get the bitmap from the cache assertFalse(fc.isCached(id)); assertEquals(bmp, fc.get(id)); assertTrue(fc.isCached(id)); } } /** * Tests the bulk-write. */ @Test public void testBulkPersistance() { fc.initialize(model); // disable the persistancy fc.setPersistency(false); for (int i = 0; i < 50000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i); // cache the bitmap fc.cache(id, bmp); // retrieve the bitmap and check the cache status assertEquals(bmp, fc.get(id)); assertTrue(fc.isCached(id)); } // everything should be in cache assertEquals(50000, fc.getCacheSize()); // enable it again fc.setPersistency(true); // clear all the cached data fc.clearCache(); // check to read all the bitmaps for (int i = 0; i < 50000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i); // get the bitmap from the cache assertFalse(fc.isCached(id)); assertEquals(bmp, fc.get(id)); assertTrue(fc.isCached(id)); } } /** * Tests the bulk-write with using the * {@link FileBitmapCache#_organizeCache()}. */ @Test public void testBulkPersistanceWithReorganization() { final FileBitmapIdCacheConfig config = new FileBitmapIdCacheConfig(); config.setLocation(fc.getLocation()); config.setCacheSize(10000); config.setCacheCleaningFactor(1.0); fc.setConfig(config); fc.initialize(model); // disable the persistancy fc.setPersistency(false); for (int i = 0; i < 50000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i); // cache the bitmap fc.cache(id, bmp); // retrieve the bitmap and check the cache status assertEquals(bmp, fc.get(id)); assertTrue(fc.isCached(id)); } // enable it again fc.setPersistency(true); // clear all the cached data fc.clearCache(); // check to read all the bitmaps for (int i = 0; i < 50000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i); // get the bitmap from the cache assertFalse(fc.isCached(id)); assertEquals(bmp, fc.get(id)); } } /** * Tests the bulk-write with using the {@link FileBitmapCache#clearCache()}. */ @Test public void testBulkPersistanceWithClearCache() { fc.initialize(model); fc.setPersistency(false); for (int i = 0; i < 50000; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), i); // cache the bitmap fc.cache(id, bmp); // clear the cache fc.clearCache(); // retrieve the bitmap and check the cache status assertFalse(fc.isCached(id)); assertEquals(bmp, fc.get(id)); assertTrue(fc.isCached(id)); } fc.setPersistency(true); } /** * The {@code FileBitmapCache} needs to create {@code lines} within the * index-file, which are used to map a {@code BitmapId} to a * {@code IndexEntry}. The {@code BitmapId} has to be transformed into a * byte-array to be stored. This should only be done once for each new * {@code BitmapId}. This tests checks, that the call is only done once for * each {@code BitmapId}. */ @Test public void testUsageOfGenerateIndexLine() { final FileBitmapCache spy = Mockito.spy(fc); spy.initialize(model); // let's cache 100 bitmaps for testing purposes cache(spy, 100, 0); // the generation of a line should have been called exactly 100 times verify(spy, times(100)).generateIndexLine(Mockito.any(BitmapId.class), Mockito.any(IndexEntry.class)); // modify the Bitmaps cache(spy, 200, 100); /* * The modification shouldn't have triggered the generation again, * therefore in a total the generateIndexLine should only be called 200 * times. */ verify(spy, times(200)).generateIndexLine(Mockito.any(BitmapId.class), Mockito.any(IndexEntry.class)); // release the FileBitmapCache spy.release(); } /** * Tests the usage of the maximal file-size. */ @Test public void testMaxFileSize() { setModulesHolder("/net/meisen/dissertation/impl/cache/fileBitmapCacheModelMaxFileSize.xml"); // create the instance of the cache model = modulesHolder.getModule(DefaultValues.TIDAMODEL_ID); fc = modulesHolder.getModule(DefaultValues.BITMAPCACHE_ID); assertNotNull(fc); // make sure the location is deleted assertTrue(Files.deleteDir(fc.getLocation())); // check the configuration assertEquals(1000, fc.getMaxCacheSize()); assertEquals(0.8, fc.getCacheCleaningFactor(), 0.0); assertEquals(1024 * 1024, fc.getMaxFileSizeInByte()); fc.initialize(model); for (int i = 0; i < 100000; i++) { final Bitmap bmp = Bitmap.createBitmap(model.getIndexFactory(), 1, 1000, 2000, Integer.MAX_VALUE - 2000); fc.cache(createBitmapId(0), bmp); } assertEquals(8, fc.getNumberOfFiles()); } /** * Tests the loading of the internally used index from the hard-drive. * Furthermore the tests checks the amounts of call to * {@link FileBitmapCache#read(IndexEntry)}. */ @Test public void testIndexLoading() { final FileBitmapCache spy = Mockito.spy(fc); final FileBitmapIdCacheConfig config = new FileBitmapIdCacheConfig(); config.setLocation(spy.getLocation()); config.setMaxFileSize("1K"); config.setCacheSize(100); config.setCacheCleaningFactor(1.0); spy.setConfig(config); // create a cache with some data spy.initialize(model); cache(spy, 100, 20); verify(spy, times(100)).cache(Mockito.any(BitmapId.class), Mockito.any(Bitmap.class)); verify(spy, times(100))._index(Mockito.any(BitmapId.class), Mockito.any(IndexEntry.class)); verify(spy, times(100))._cache(Mockito.any(BitmapId.class), Mockito.any(Bitmap.class)); // get the amount of created files final int nrOfFiles = spy.getNumberOfFiles(); spy.release(); // now initialize again and check if the data is loaded spy.initialize(model); assertEquals(nrOfFiles, spy.getNumberOfFiles()); assertEquals(0, fc.getCacheSize()); // get the bitmap for 0, this cannot be empty now for (int i = 0; i < 100; i++) { final Bitmap bmp = spy.get(createBitmapId(i)); assertEquals(1, bmp.getIds().length); assertTrue(Arrays.binarySearch(bmp.getIds(), i + 20) != -1); } // no new files were created and the cache is filled assertEquals(nrOfFiles, spy.getNumberOfFiles()); assertEquals(100, spy.getCacheSize()); // there was no need for reorganization verify(spy, times(0))._organizeCache(); // the cache had to read every bitmap from disk verify(spy, times(100))._getFromCache(Mockito.any(BitmapId.class)); verify(spy, times(100)).read(Mockito.any(IndexEntry.class)); // every Bitmap had to be added to the cache, but not updated verify(spy, times(100)).cache(Mockito.any(BitmapId.class), Mockito.any(Bitmap.class)); verify(spy, times(100))._index(Mockito.any(BitmapId.class), Mockito.any(IndexEntry.class)); verify(spy, times(200))._cache(Mockito.any(BitmapId.class), Mockito.any(Bitmap.class)); // let's also get some values we don't have yet final Bitmap emptyBitmap = model.getIndexFactory().createBitmap(); for (int i = 100; i < 200; i++) { final Bitmap bmp = spy.get(createBitmapId(i)); assertEquals(0, bmp.getIds().length); assertEquals(emptyBitmap, bmp); } verify(spy, times(200))._getFromCache(Mockito.any(BitmapId.class)); verify(spy, times(100)).read(Mockito.any(IndexEntry.class)); verify(spy, times(1))._organizeCache(); assertEquals(100, spy.getCacheSize()); // we need to release the spy spy.release(); assertTrue(Files.deleteDir(spy.getLocation())); } /** * Tests the multi-threading of a {@code FileBitmapCache}. * * @throws InterruptedException * if a thread is interrupted */ @Test public void testMultipleThreadSafety() throws InterruptedException { fc.initialize(model); final ThreadForTesting tCacheSize = new ThreadForTesting() { @Override public void _run() { while (fc.getCacheSize() == 0) { try { Thread.sleep(50); } catch (final InterruptedException e) { fail(e.getMessage()); } } int i = 1; assertEquals(i, fc.getCacheSize()); assertTrue(fc.isCached(createBitmapId(0))); assertFalse(fc.isCached(createBitmapId(1))); // this one is cached by assertNotNull(fc.get(createBitmapId(0))); // the first call 1 isn't cached if (!fc.isCached(createBitmapId(1))) { i++; } assertNotNull(fc.get(createBitmapId(1))); } }; final ThreadForTesting tCache = new ThreadForTesting() { @Override public void _run() { for (int i = 0; i < 100000; i++) { fc.cache(createBitmapId(0), model.getIndexFactory() .createBitmap()); assertTrue(fc.getCacheSize() > 0 && fc.getCacheSize() < 3); } } }; // start the threads tCacheSize.start(); tCache.start(); // join with this one tCacheSize.join(); tCache.join(); // validate the threads tCacheSize.validate(); tCache.validate(); // after everything there should be one left assertEquals(2, fc.getCacheSize()); } /** * Tests the multi-threading using bulk-write. * * @throws InterruptedException * if the threads cannot be found */ @Test public void testMultiThreadWithBulkWrite() throws InterruptedException { final FileBitmapIdCacheConfig config = new FileBitmapIdCacheConfig(); config.setLocation(fc.getLocation()); config.setCacheSize(10000); config.setCacheCleaningFactor(0.3); fc.setConfig(config); fc.initialize(model); final Bitmap empty = model.getIndexFactory().createBitmap(); final int amount = 50000; final ThreadForTesting tGet = new ThreadForTesting() { private Random r = new Random(); @Override public void _run() { for (int i = 0; i < 4 * amount; i++) { int nr = r.nextInt(amount); final BitmapId<?> id = new BitmapId<Integer>(nr, MetaIndex.class, "Classifier1"); final Bitmap res = fc.get(id); final Bitmap bmp = Bitmap.createBitmap( model.getIndexFactory(), nr); assertTrue(res.toString(), empty.equals(res) || bmp.equals(res)); } } }; final ThreadForTesting tBulkLoad = new ThreadForTesting() { @Override public void _run() { fc.setPersistency(false); for (int i = 0; i < amount; i++) { final BitmapId<?> id = new BitmapId<Integer>(i, MetaIndex.class, "Classifier1"); final Bitmap bmp = Bitmap.createBitmap( model.getIndexFactory(), i); // cache the bitmap fc.cache(id, bmp); } fc.setPersistency(true); } }; // start the threads tGet.start(); tBulkLoad.start(); // join with this one tGet.join(); tBulkLoad.join(); // validate the threads tGet.validate(); tBulkLoad.validate(); } /** * Tests the cleaning of the cache. */ @Test public void testCleaning() { // create a new configuration final FileBitmapIdCacheConfig fcc = new FileBitmapIdCacheConfig(); fcc.setCacheCleaningFactor(0.5); fcc.setCacheSize(10); fcc.setLocation(fc.getLocation()); fc.setConfig(fcc); // initialize the model fc.initialize(model); // add 100 values to the cache for (int i = 0; i < 100; i++) { fc.cache(createBitmapId(i), model.getIndexFactory().createBitmap()); // use every 2nd bitmap if (i % 2 == 0) { fc.get(createBitmapId(i)); } // there should never be more than 10 elements cached assertTrue(fc.getCacheSize() <= 10); } } /** * Tests some sample usage scenario. * * @throws InterruptedException * if a thread gets interrupted */ @Test public void testUsageScenario() throws InterruptedException { final int amountOfBitmaps = 30000; final int amountOfRuns = 30000; final FileBitmapIdCacheConfig config = new FileBitmapIdCacheConfig(); config.setLocation(fc.getLocation()); config.setMaxFileSize(30 * amountOfBitmaps + "b"); config.setCacheSize((int) (amountOfBitmaps * 0.7)); fc.setConfig(config); // initialize the model fc.initialize(model); // create some bitmaps final ThreadForTesting tIdBitmap = new ThreadForTesting() { @Override public void _run() { _createBitmaps(amountOfBitmaps, 0); } }; final ThreadForTesting tIdPlus1Bitmap = new ThreadForTesting() { @Override public void _run() { _createBitmaps(amountOfBitmaps, 1); } }; final ThreadForTesting tIdPlus2Bitmap = new ThreadForTesting() { @Override public void _run() { _createBitmaps(amountOfBitmaps, 2); } }; // start the threads tIdBitmap.start(); tIdPlus1Bitmap.start(); tIdPlus2Bitmap.start(); // join with this one tIdBitmap.join(); tIdPlus1Bitmap.join(); tIdPlus2Bitmap.join(); // validate the threads tIdBitmap.validate(); tIdPlus1Bitmap.validate(); tIdPlus2Bitmap.validate(); // now get the bitmaps final ThreadForTesting tGetBitmap1 = new ThreadForTesting() { @Override public void _run() { _getRndBitmaps(new Random(), amountOfRuns, (int) (amountOfBitmaps * 0.5)); } }; final ThreadForTesting tGetBitmap2 = new ThreadForTesting() { @Override public void _run() { _getRndBitmaps(new Random(), amountOfRuns, (int) (amountOfBitmaps * 0.5)); } }; // start the threads tGetBitmap1.start(); tGetBitmap2.start(); // join with this one tGetBitmap1.join(); tGetBitmap2.join(); // validate the threads tGetBitmap1.validate(); tGetBitmap2.validate(); } /** * Helper method for {@link #testUsageScenario()}. The method creates * {@code amount} bitmaps, whereby the id is defined by the number of it's * creation. The created bitmap will have the bit sets defined by * {@code id + offset}. * * @param amount * the amount of bitmaps to be created * @param offset * the offset of the set bit to the bitmap's id */ protected void _createBitmaps(final int amount, final int offset) { for (int i = 0; i < amount; i++) { // get the bitmap and check the cardinality final Bitmap bitmap = fc.get(createBitmapId(i)); assertTrue(bitmap.determineCardinality() == 0 || bitmap.determineCardinality() == 1); // cache a newly created bitmap fc.cache(createBitmapId(i), Bitmap.createBitmap(model.getIndexFactory(), i + offset)); } } /** * Picks random bitmaps and checks the values. * * @param rnd * the randomizer * @param runs * the amounts of runs to check * @param maxNumber * the max-id (exclusive) of a bitmap to be retrieved */ protected void _getRndBitmaps(final Random rnd, final int runs, final int maxNumber) { for (int i = 0; i < runs; i++) { final int nr = rnd.nextInt(maxNumber); final Bitmap bitmap = fc.get(createBitmapId(nr)); final int[] ids = bitmap.getIds(); assertEquals(1, ids.length); assertTrue(bitmap.toString(), ids[0] == nr || ids[0] == nr + 1 || ids[0] == nr + 2); } } /** * CleanUp afterwards */ @After public void cleanUp() { // release the instance fc.release(); model.release(true); // delete all the created files if (fc.getModelLocation() != null && fc.getModelLocation().exists()) { assertTrue("Cannot delete '" + fc.getModelLocation() + "'", Files.deleteDir(fc.getModelLocation())); } if (fc.getLocation() != null && fc.getLocation().exists()) { assertTrue("Cannot delete '" + fc.getLocation() + "'", Files.deleteDir(fc.getLocation())); } } }
package com.jcabi.aspects; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.ConstraintViolationException; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.junit.Test; /** * Test case for {@link JSR-303} annotations and their implementations. * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ public final class JSR303Test { /** * NotNull can throw when invalid method parameters. * @throws Exception If something goes wrong */ @Test(expected = ConstraintViolationException.class) public void throwsWhenMethodParametersAreInvalid() throws Exception { new JSR303Test.Foo().foo(null); } /** * NotNull can throw when regex doesn't match. * @throws Exception If something goes wrong */ @Test(expected = ConstraintViolationException.class) public void throwsWhenRegularExpressionDoesntMatch() throws Exception { new JSR303Test.Foo().foo("some text"); } /** * NotNull can pass for valid parameters. * @throws Exception If something goes wrong */ @Test public void passesWhenMethodParametersAreValid() throws Exception { new JSR303Test.Foo().foo("123"); } /** * NotNull can validate method output. * @throws Exception If something goes wrong */ @Test(expected = ConstraintViolationException.class) public void validatesOutputForNonNull() throws Exception { new JSR303Test.Foo().nullValue(); } /** * NotNull can ignore methods that return VOID. * @throws Exception If something goes wrong */ @Test public void ignoresVoidResponses() throws Exception { new JSR303Test.Foo().voidAlways(); } /** * Validates constructor parameters for directly invoked constructors. */ @Test(expected = ConstraintViolationException.class) public void validatesConstructorParameters() { new JSR303Test.Bar(null); } /** * Validates constructor parameters for other invoked constructors. */ @Test(expected = ConstraintViolationException.class) public void validatesChainedConstructorParameters() { new JSR303Test.Bar(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) private @interface NoMeaning { } /** * Dummy class, for tests above. */ @Loggable(Loggable.INFO) private static final class Foo { /** * Do nothing. * @param text Some text * @return Some data */ @NotNull public int foo( @NotNull @Pattern(regexp = "\\d+") @JSR303Test.NoMeaning final String text) { return -1; } /** * Always return null. * @return Some data */ @NotNull @Valid public Integer nullValue() { return null; } /** * Ignores when void. */ @NotNull public void voidAlways() { // nothing to do } } /** * Dummy class for testing constructor validation. * * @author Carlos Miranda (miranda.cma@gmail.com) * @version $Id$ */ @Loggable(Loggable.INFO) private static final class Bar { /** * Public ctor. * @param param The param. * @checkstyle UnusedFormalParameter (2 lines) */ public Bar(@NotNull final String param) { //Nothing to do. } /** * Public ctor that passes null to another ctor. * Supposed to fail validation. */ public Bar() { this(null); } } }
package com.pivotallabs.api; import com.google.inject.internal.Maps; import com.xtremelabs.robolectric.Robolectric; import com.xtremelabs.robolectric.RobolectricTestRunner; import com.xtremelabs.robolectric.util.HttpRequestInfo; import com.xtremelabs.robolectric.util.Strings; import org.apache.http.HttpRequest; import org.apache.http.auth.AuthScope; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.StringEntity; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URI; import java.util.HashMap; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; @RunWith(RobolectricTestRunner.class) public class HttpTest { @Test public void testGet_FormsCorrectRequest_noBasicAuth() throws Exception { Robolectric.addPendingHttpResponse(200, "OK"); new Http().get("www.example.com", Maps.<String, String>newHashMap(), null, null); assertThat(((HttpUriRequest) Robolectric.getSentHttpRequest(0)).getURI(), equalTo(URI.create("www.example.com"))); } @Test public void testGet_shouldApplyCorrectHeaders() throws Exception { Robolectric.addPendingHttpResponse(200, "OK"); HashMap<String,String> headers = Maps.newHashMap(); headers.put("foo", "bar"); new Http().get("www.example.com", headers, null, null); HttpRequest sentHttpRequest = Robolectric.getSentHttpRequest(0); assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar")); } @Test public void testGet_ShouldUseCorrectHttpMethod() throws Exception { Robolectric.addPendingHttpResponse(200, "OK"); new Http().get("www.example.com", Maps.<String, String>newHashMap(), null, null); HttpUriRequest sentHttpRequest = (HttpUriRequest) Robolectric.getSentHttpRequest(0); assertThat(sentHttpRequest.getMethod(), equalTo(HttpGet.METHOD_NAME)); } @Test public void testGet_FormsCorrectRequest_withBasicAuth() throws Exception { Robolectric.addPendingHttpResponse(200, "OK"); new Http().get("www.example.com", Maps.<String, String>newHashMap(), "username", "password"); HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0); CredentialsProvider credentialsProvider = (CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER); assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), equalTo("username")); assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), equalTo("password")); } @Test public void shouldReturnCorrectResponse() throws Exception { Robolectric.addPendingHttpResponse(666, "it's all cool"); Http.Response response = new Http().get("www.example.com", Maps.<String, String>newHashMap(), null, null); assertThat(response.getResponseBody(), equalTo("it's all cool\n")); assertThat(response.getStatusCode(), equalTo(666)); } @Test public void testPost_ShouldUseCorrectMethod() throws Exception { Robolectric.addPendingHttpResponse(200, "OK"); new Http().post("www.example.com", Maps.<String, String>newHashMap(), "a post body", null, null); HttpUriRequest sentHttpRequest = (HttpUriRequest) Robolectric.getSentHttpRequest(0); assertThat(sentHttpRequest.getMethod(), equalTo(HttpPost.METHOD_NAME)); } @Test public void testPost_ShouldIncludePostBody() throws Exception { Robolectric.addPendingHttpResponse(200, "OK"); new Http().post("www.example.com", Maps.<String, String>newHashMap(), "a post body", null, null); HttpPost sentHttpRequest = (HttpPost) Robolectric.getSentHttpRequest(0); StringEntity entity = (StringEntity) sentHttpRequest.getEntity(); String sentPostBody = Strings.fromStream(entity.getContent()); assertThat(sentPostBody, equalTo("a post body")); assertThat(entity.getContentType().getValue(), equalTo("text/plain; charset=UTF-8")); } }
package com.sixtyfour.test; import java.util.Arrays; import com.sixtyfour.Basic; import com.sixtyfour.config.CompilerConfig; import com.sixtyfour.system.Conversions; /** * Test for floating point conversions * * @author EgonOlsen * */ public class FloatTest { private static CompilerConfig config = new CompilerConfig(); public static void main(String[] args) { testFloat(); testConversions(); testConversions2(); int[] num = Conversions.convertDouble(8d); System.out.println("8: " + Arrays.toString(num)); testExponentHack(); } private static void testExponentHack() { float t = -567.123123344f; int[] fl = Conversions.convertFloat(t); for (int i = 0; i < 100; i++) { System.out.println("Divided by " + (i) + "*2..."); System.out.println("Exponent: " + fl[0]); System.out.println("Number: " + Conversions.convertFloat(fl[0], fl[5], fl[4], fl[3], fl[2], fl[1])); System.out.println("Actual value: " + t); t /= 2; System.out.println(" fl[0] = fl[0] - 1; } } private static void testConversions2() { int[] is = new int[] { 0x7e, 0x4f, 0xcc, 0xad, 0x00 }; int[] should = new int[] { 0x7e, 0x4f, 0xcc, 0xac, 0xc3 }; int[] num = Conversions.convertDouble(0.20292921d); int[] num2 = Conversions.compactFloat(num); System.out.println("IS: " + Arrays.toString(is)); System.out.println("SH: " + Arrays.toString(should)); System.out.println("CP: " + Arrays.toString(num2)); System.out.println("FU: " + Arrays.toString(num)); System.out.println(Conversions.convertDouble(num[0], num[5], num[4], num[3], num[2], num[1])); should = Conversions.extractFloat(should); System.out.println("S2: " + Arrays.toString(should)); System.out.println(Conversions.convertDouble(should[0], should[5], should[4], should[3], should[2], should[1])); } public static void testFloat() { Basic basic = new Basic("10 poke97,152:poke98,53:poke99,68:poke100,122:poke101,0:poke102,0"); basic.run(config); System.out.println(Conversions.convertFloat(basic.getMachine(), 97) + "/" + 11879546.0d); } public static void testConversions() { int[] num = Conversions.convertFloat(11234.5454433f); float res = Conversions.convertFloat(num[0], num[5], num[4], num[3], num[2], num[1]); System.out.println(res); System.out.println(" num = Conversions.convertFloat(-2237.998f); res = Conversions.convertFloat(num[0], num[5], num[4], num[3], num[2], num[1]); System.out.println(res); System.out.println(" num = Conversions.extractFloat(Conversions.compactFloat(Conversions.convertFloat(-(float) Math.PI))); res = Conversions.convertFloat(num[0], num[5], num[4], num[3], num[2], num[1]); System.out.println(res); } }
package io.ipfs.api; import java.io.*; import java.nio.file.*; import java.util.*; import org.junit.Assert; import org.junit.Test; import io.ipfs.multiaddr.MultiAddress; public class RecursiveAddTest { private final IPFS ipfs = new IPFS(new MultiAddress("/ip4/127.0.0.1/tcp/5001")); static Path TMPDATA = Paths.get("target/tmpdata"); @Test public void testAdd() throws Exception { System.out.println("ipfs version: " + ipfs.version()); String EXPECTED = "QmX5fZ6aUxNTAS7ZfYc8f4wPoMx6LctuNbMjuJZ9EmUSr6"; Path base = TMPDATA; base.toFile().mkdirs(); Files.write(base.resolve("index.html"), "<html></html>".getBytes()); Path js = base.resolve("js"); js.toFile().mkdirs(); Files.write(js.resolve("func.js"), "function() {console.log('Hey');}".getBytes()); List<MerkleNode> add = ipfs.add(new NamedStreamable.FileWrapper(base.toFile())); MerkleNode node = add.get(add.size() - 1); Assert.assertEquals(EXPECTED, node.hash.toBase58()); } @Test public void binaryRecursiveAdd() throws Exception { String EXPECTED = "Qmd1dTx4Z1PHxSHDR9jYoyLJTrYsAau7zLPE3kqo14s84d"; Path base = TMPDATA.resolve("bindata"); base.toFile().mkdirs(); byte[] bindata = new byte[1024*1024]; new Random(28).nextBytes(bindata); Files.write(base.resolve("data.bin"), bindata); Path js = base.resolve("js"); js.toFile().mkdirs(); Files.write(js.resolve("func.js"), "function() {console.log('Hey');}".getBytes()); List<MerkleNode> add = ipfs.add(new NamedStreamable.FileWrapper(base.toFile())); MerkleNode node = add.get(add.size() - 1); Assert.assertEquals(EXPECTED, node.hash.toBase58()); } @Test public void largeBinaryRecursiveAdd() throws Exception { String EXPECTED = "QmZdfdj7nfxE68fBPUWAGrffGL3sYGx1MDEozMg73uD2wj"; Path base = TMPDATA.resolve("largebindata"); base.toFile().mkdirs(); byte[] bindata = new byte[100 * 1024*1024]; new Random(28).nextBytes(bindata); Files.write(base.resolve("data.bin"), bindata); new Random(496).nextBytes(bindata); Files.write(base.resolve("data2.bin"), bindata); Path js = base.resolve("js"); js.toFile().mkdirs(); Files.write(js.resolve("func.js"), "function() {console.log('Hey');}".getBytes()); List<MerkleNode> add = ipfs.add(new NamedStreamable.FileWrapper(base.toFile())); MerkleNode node = add.get(add.size() - 1); Assert.assertEquals(EXPECTED, node.hash.toBase58()); } @Test public void largeBinaryInSubdirRecursiveAdd() throws Exception { String EXPECTED = "QmUYuMwCpgaxJhNxRA5Pmje8EfpEgU3eQSB9t3VngbxYJk"; Path base = TMPDATA.resolve("largebininsubdirdata"); base.toFile().mkdirs(); Path bindir = base.resolve("moredata"); bindir.toFile().mkdirs(); byte[] bindata = new byte[100 * 1024*1024]; new Random(28).nextBytes(bindata); Files.write(bindir.resolve("data.bin"), bindata); new Random(496).nextBytes(bindata); Files.write(bindir.resolve("data2.bin"), bindata); Path js = base.resolve("js"); js.toFile().mkdirs(); Files.write(js.resolve("func.js"), "function() {console.log('Hey');}".getBytes()); List<MerkleNode> add = ipfs.add(new NamedStreamable.FileWrapper(base.toFile())); MerkleNode node = add.get(add.size() - 1); Assert.assertEquals(EXPECTED, node.hash.toBase58()); } }
package org.scm4j.wf.conf; import org.scm4j.wf.conf.Coords; import org.scm4j.wf.conf.Version; import junit.framework.TestCase; import nl.jqno.equalsverifier.EqualsVerifier; public class CoordsTest extends TestCase { public void testCoords() { try { new Coords(""); fail(); } catch (IllegalArgumentException e) { } } Coords dc(String coords) { return new Coords(coords); } public void testComment() { assertEquals("", dc("com.myproject:c1").getComment()); assertEquals("#", dc("com.myproject:c1#").getComment()); assertEquals("#...$ #", dc("com.myproject:c1#...$ #").getComment()); } public void testExtension() { assertEquals("", dc("com.myproject:c1").getExtension()); assertEquals("@", dc("com.myproject:c1@").getExtension()); assertEquals("@ext", dc("com.myproject:c1@ext#qw").getExtension()); assertEquals("@ext@", dc("com.myproject:c1@ext@#qw").getExtension()); } public void testClassifier() { assertEquals("", dc("com.myproject:c1").getClassifier()); assertEquals(":", dc("com.myproject:c1::").getClassifier()); assertEquals(":class", dc("com.myproject:c1::class:").getClassifier()); } public void testToSting() { assertEquals("com.myproject:c1:1.0.0", dc("com.myproject:c1:1.0.0").toString()); assertEquals("com.myproject: c1:1.0.0", dc("com.myproject: c1:1.0.0").toString()); assertEquals(" com.myproject: c1:1.0.0", dc(" com.myproject: c1:1.0.0").toString()); assertEquals("com.myproject:c1:1.0.0#comment", dc("com.myproject:c1:1.0.0#comment").toString()); assertEquals("com.myproject:c1:1.0.0@ext #comment", dc("com.myproject:c1:1.0.0@ext #comment").toString()); assertEquals("com.myproject:c1::dfgd@ext #comment", dc("com.myproject:c1::dfgd@ext #comment").toString()); } public void testGroupId() { assertEquals("com.myproject", dc("com.myproject:c1:1.0.0").getGroupId()); assertEquals("com.myproject", dc("com.myproject:c1").getGroupId()); assertEquals(" com.myproject", dc(" com.myproject:c1").getGroupId()); } public void testArtifactId() { assertEquals("c1", dc("com.myproject:c1:1.0.0").getArtifactId()); assertEquals("c1", dc("com.myproject:c1").getArtifactId()); assertEquals("c1", dc(" com.myproject:c1").getArtifactId()); } public void testVersion() { assertEquals(new Version("1.0.0"), dc("com.myproject:c1:1.0.0").getVersion()); assertEquals(new Version("1.0.0"), dc("com.myproject:c1:1.0.0#comment").getVersion()); assertEquals(new Version("1.0.0"), dc("com.myproject:c1:1.0.0@ext #comment").getVersion()); assertEquals(new Version(""), dc("com.myproject:c1::dfgd@ext #comment").getVersion()); assertEquals(new Version("-SNAPSHOT"), dc("com.myproject:c1:-SNAPSHOT:dfgd@ext #comment").getVersion()); } public void testEqualsAndHashCode() { EqualsVerifier .forClass(Coords.class) .withOnlyTheseFields("coordsString") .usingGetClass() .verify(); } }
package org.perl6.rakudo; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import org.perl6.nqp.runtime.*; import org.perl6.nqp.sixmodel.*; import org.perl6.nqp.sixmodel.reprs.CallCaptureInstance; import org.perl6.nqp.sixmodel.reprs.ContextRefInstance; import org.perl6.nqp.sixmodel.reprs.LexoticInstance; import org.perl6.nqp.sixmodel.reprs.NativeRefInstance; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance; /** * Contains implementation of nqp:: ops specific to Rakudo Perl 6. */ @SuppressWarnings("unused") public final class RakOps { public static final boolean DEBUG_MODE = false; public static class ThreadExt { public SixModelObject firstPhaserCodeBlock; public ArrayList<CallFrame> prePhaserFrames = new ArrayList<CallFrame>(); public ThreadExt(ThreadContext tc) { } } public static class GlobalExt { public SixModelObject Mu; public SixModelObject Any; public SixModelObject Parcel; public SixModelObject Code; public SixModelObject Routine; public SixModelObject Signature; public SixModelObject Parameter; public SixModelObject Int; public SixModelObject Num; public SixModelObject Str; public SixModelObject List; public SixModelObject ListIter; public SixModelObject Array; public SixModelObject LoL; public SixModelObject Nil; public SixModelObject EnumMap; public SixModelObject Hash; public SixModelObject Junction; public SixModelObject Scalar; public SixModelObject Capture; public SixModelObject ContainerDescriptor; public SixModelObject False; public SixModelObject True; public SixModelObject AutoThreader; public SixModelObject EMPTYARR; public SixModelObject EMPTYHASH; public RakudoJavaInterop rakudoInterop; public SixModelObject JavaHOW; public SixModelObject defaultContainerDescriptor; boolean initialized; public GlobalExt(ThreadContext tc) {} } public static ContextKey<ThreadExt, GlobalExt> key = new ContextKey< >(ThreadExt.class, GlobalExt.class); /* Parameter hints for fast lookups. */ private static final int HINT_PARCEL_STORAGE = 0; private static final int HINT_CODE_DO = 0; private static final int HINT_CODE_SIG = 1; private static final int HINT_ROUTINE_RW = 8; private static final int HINT_SIG_PARAMS = 0; private static final int HINT_SIG_RETURNS = 1; private static final int HINT_SIG_CODE = 4; public static final int HINT_CD_OF = 0; public static final int HINT_CD_RW = 1; public static final int HINT_CD_NAME = 2; public static final int HINT_CD_DEFAULT = 3; private static final int HINT_LIST_items = 0; private static final int HINT_LIST_flattens = 1; private static final int HINT_LIST_nextiter = 2; private static final int HINT_LISTITER_reified = 0; private static final int HINT_LISTITER_nextiter = 1; private static final int HINT_LISTITER_rest = 2; private static final int HINT_LISTITER_list = 3; public static SixModelObject p6init(ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (!gcx.initialized) { tc.gc.contConfigs.put("rakudo_scalar", new RakudoContainerConfigurer()); SixModelObject BOOTArray = tc.gc.BOOTArray; gcx.EMPTYARR = BOOTArray.st.REPR.allocate(tc, BOOTArray.st); SixModelObject BOOTHash = tc.gc.BOOTHash; gcx.EMPTYHASH = BOOTHash.st.REPR.allocate(tc, BOOTHash.st); gcx.rakudoInterop = new RakudoJavaInterop(tc.gc); gcx.initialized = true; } return null; } public static SixModelObject p6settypes(SixModelObject conf, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.Mu = conf.at_key_boxed(tc, "Mu"); gcx.Any = conf.at_key_boxed(tc, "Any"); gcx.Parcel = conf.at_key_boxed(tc, "Parcel"); gcx.Code = conf.at_key_boxed(tc, "Code"); gcx.Routine = conf.at_key_boxed(tc, "Routine"); gcx.Signature = conf.at_key_boxed(tc, "Signature"); gcx.Parameter = conf.at_key_boxed(tc, "Parameter"); gcx.Int = conf.at_key_boxed(tc, "Int"); gcx.Num = conf.at_key_boxed(tc, "Num"); gcx.Str = conf.at_key_boxed(tc, "Str"); gcx.List = conf.at_key_boxed(tc, "List"); gcx.ListIter = conf.at_key_boxed(tc, "ListIter"); gcx.Array = conf.at_key_boxed(tc, "Array"); gcx.LoL = conf.at_key_boxed(tc, "LoL"); gcx.Nil = conf.at_key_boxed(tc, "Nil"); gcx.EnumMap = conf.at_key_boxed(tc, "EnumMap"); gcx.Hash = conf.at_key_boxed(tc, "Hash"); gcx.Junction = conf.at_key_boxed(tc, "Junction"); gcx.Scalar = conf.at_key_boxed(tc, "Scalar"); gcx.Capture = conf.at_key_boxed(tc, "Capture"); gcx.ContainerDescriptor = conf.at_key_boxed(tc, "ContainerDescriptor"); gcx.False = conf.at_key_boxed(tc, "False"); gcx.True = conf.at_key_boxed(tc, "True"); gcx.JavaHOW = conf.at_key_boxed(tc, "Metamodel").st.WHO.at_key_boxed(tc, "JavaHOW"); SixModelObject defCD = gcx.ContainerDescriptor.st.REPR.allocate(tc, gcx.ContainerDescriptor.st); defCD.bind_attribute_boxed(tc, gcx.ContainerDescriptor, "$!of", HINT_CD_OF, gcx.Mu); tc.native_s = "<element>"; defCD.bind_attribute_native(tc, gcx.ContainerDescriptor, "$!name", HINT_CD_NAME); tc.native_i = 1; defCD.bind_attribute_native(tc, gcx.ContainerDescriptor, "$!rw", HINT_CD_RW); defCD.bind_attribute_boxed(tc, gcx.ContainerDescriptor, "$!default", HINT_CD_DEFAULT, gcx.Any); gcx.defaultContainerDescriptor = defCD; return conf; } public static SixModelObject p6setautothreader(SixModelObject autoThreader, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.AutoThreader = autoThreader; return autoThreader; } public static SixModelObject booleanize(int x, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); return x == 0 ? gcx.False : gcx.True; } public static SixModelObject p6definite(SixModelObject obj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); obj = Ops.decont(obj, tc); return obj instanceof TypeObject ? gcx.False : gcx.True; } public static SixModelObject p6box_i(long value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Int.st.REPR.allocate(tc, gcx.Int.st); res.set_int(tc, value); return res; } public static SixModelObject p6box_n(double value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Num.st.REPR.allocate(tc, gcx.Num.st); res.set_num(tc, value); return res; } public static SixModelObject p6box_s(String value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Str.st.REPR.allocate(tc, gcx.Str.st); res.set_str(tc, value); return res; } public static SixModelObject p6list(SixModelObject arr, SixModelObject type, SixModelObject flattens, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject list = type.st.REPR.allocate(tc, type.st); if (arr != null) list.bind_attribute_boxed(tc, gcx.List, "$!nextiter", HINT_LIST_nextiter, p6listiter(arr, list, tc)); list.bind_attribute_boxed(tc, gcx.List, "$!flattens", HINT_LIST_flattens, flattens); return list; } public static SixModelObject p6listitems(SixModelObject list, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject items = list.get_attribute_boxed(tc, gcx.List, "$!items", HINT_LIST_items); if (!(items instanceof VMArrayInstance)) { items = gcx.EMPTYARR.clone(tc); list.bind_attribute_boxed(tc, gcx.List, "$!items", HINT_LIST_items, items); } return items; } public static long p6arrfindtypes(SixModelObject arr, SixModelObject types, long start, long last, ThreadContext tc) { int ntypes = (int)types.elems(tc); SixModelObject[] typeArr = new SixModelObject[ntypes]; for (int i = 0; i < ntypes; i++) typeArr[i] = types.at_pos_boxed(tc, i); long elems = arr.elems(tc); if (elems < last) last = elems; long index; for (index = start; index < last; index++) { SixModelObject val = arr.at_pos_boxed(tc, index); if (val != null && val.st.ContainerSpec == null) { boolean found = false; for (int typeIndex = 0; typeIndex < ntypes; typeIndex++) { if (Ops.istype(val, typeArr[typeIndex], tc) != 0) { found = true; break; } } if (found) break; } } return index; } public static SixModelObject p6shiftpush(SixModelObject a, SixModelObject b, long total, ThreadContext tc) { long count = total; long elems = b.elems(tc); if (count > elems) count = elems; if (a != null && total > 0) { long getPos = 0; long setPos = a.elems(tc); a.set_elems(tc, setPos + count); while (count > 0) { a.bind_pos_boxed(tc, setPos, b.at_pos_boxed(tc, getPos)); count getPos++; setPos++; } } if (total > 0) { GlobalExt gcx = key.getGC(tc); b.splice(tc, gcx.EMPTYARR, 0, total); } return a; } public static SixModelObject p6listiter(SixModelObject arr, SixModelObject list, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject iter = gcx.ListIter.st.REPR.allocate(tc, gcx.ListIter.st); iter.bind_attribute_boxed(tc, gcx.ListIter, "$!rest", HINT_LISTITER_rest, arr); iter.bind_attribute_boxed(tc, gcx.ListIter, "$!list", HINT_LISTITER_list, list); return iter; } public static SixModelObject p6argvmarray(ThreadContext tc, CallSiteDescriptor csd, Object[] args) { SixModelObject BOOTArray = tc.gc.BOOTArray; SixModelObject res = BOOTArray.st.REPR.allocate(tc, BOOTArray.st); for (int i = 0; i < csd.numPositionals; i++) { SixModelObject toBind; switch (csd.argFlags[i]) { case CallSiteDescriptor.ARG_INT: toBind = p6box_i((long)args[i], tc); break; case CallSiteDescriptor.ARG_NUM: toBind = p6box_n((double)args[i], tc); break; case CallSiteDescriptor.ARG_STR: toBind = p6box_s((String)args[i], tc); break; default: toBind = Ops.hllize((SixModelObject)args[i], tc); break; } res.bind_pos_boxed(tc, i, toBind); } return res; } public static CallSiteDescriptor p6bindsig(ThreadContext tc, CallSiteDescriptor csd, Object[] args) { /* Do any flattening before processing begins. */ CallFrame cf = tc.curFrame; if (csd.hasFlattening) { csd = csd.explodeFlattening(cf, args); args = tc.flatArgs; } cf.csd = csd; cf.args = args; /* Look up parameters to bind. */ if (DEBUG_MODE) { if (cf.codeRef.name != null) System.err.println("Binding for " + cf.codeRef.name); } GlobalExt gcx = key.getGC(tc); SixModelObject sig = cf.codeRef.codeObject .get_attribute_boxed(tc, gcx.Code, "$!signature", HINT_CODE_SIG); SixModelObject params = sig .get_attribute_boxed(tc, gcx.Signature, "$!params", HINT_SIG_PARAMS); /* Run binder, and handle any errors. */ String[] error = new String[1]; switch (Binder.bind(tc, gcx, cf, params, csd, args, false, error)) { case Binder.BIND_RESULT_FAIL: throw ExceptionHandling.dieInternal(tc, error[0]); case Binder.BIND_RESULT_JUNCTION: /* Invoke the auto-threader. */ csd = csd.injectInvokee(tc, args, cf.codeRef.codeObject); args = tc.flatArgs; Ops.invokeDirect(tc, gcx.AutoThreader, csd, args); Ops.return_o( Ops.result_o(cf), cf); /* Return null to indicate immediate return to the routine. */ return null; } /* The binder may, for a variety of reasons, wind up calling Perl 6 code and overwriting flatArgs, so it needs to be set at the end to return reliably */ tc.flatArgs = args; return csd; } public static SixModelObject p6bindcaptosig(SixModelObject sig, SixModelObject cap, ThreadContext tc) { CallFrame cf = tc.curFrame; GlobalExt gcx = key.getGC(tc); CallSiteDescriptor csd = Binder.explodeCapture(tc, gcx, cap); SixModelObject params = sig.get_attribute_boxed(tc, gcx.Signature, "$!params", HINT_SIG_PARAMS); String[] error = new String[1]; switch (Binder.bind(tc, gcx, cf, params, csd, tc.flatArgs, false, error)) { case Binder.BIND_RESULT_FAIL: case Binder.BIND_RESULT_JUNCTION: throw ExceptionHandling.dieInternal(tc, error[0]); default: return sig; } } public static long p6isbindable(SixModelObject sig, SixModelObject cap, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); CallSiteDescriptor csd; Object[] args; if (cap instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)cap; csd = cc.descriptor; args = cc.args; } else { csd = Binder.explodeCapture(tc, gcx, cap); args = tc.flatArgs; } SixModelObject params = sig.get_attribute_boxed(tc, gcx.Signature, "$!params", HINT_SIG_PARAMS); SixModelObject codeObj = sig.get_attribute_boxed(tc, gcx.Signature, "$!code", HINT_SIG_CODE); CodeRef cr = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); CallFrame cf = new CallFrame(tc, cr); try { switch (Binder.bind(tc, gcx, cf, params, csd, args, false, null)) { case Binder.BIND_RESULT_FAIL: return 0; default: return 1; } } finally { tc.curFrame = tc.curFrame.caller; } } public static long p6trialbind(SixModelObject sig, SixModelObject values, SixModelObject flags, ThreadContext tc) { /* Get signature and parameters. */ GlobalExt gcx = key.getGC(tc); SixModelObject params = sig.get_attribute_boxed(tc, gcx.Signature, "$!params", HINT_SIG_PARAMS); /* Form argument array and call site descriptor. */ int numArgs = (int)values.elems(tc); Object[] args = new Object[numArgs]; byte[] argFlags = new byte[numArgs]; for (int i = 0; i < numArgs; i++) { switch ((int)flags.at_pos_boxed(tc, i).get_int(tc)) { case CallSiteDescriptor.ARG_INT: args[i] = 0; argFlags[i] = CallSiteDescriptor.ARG_INT; break; case CallSiteDescriptor.ARG_NUM: args[i] = 0.0; argFlags[i] = CallSiteDescriptor.ARG_NUM; break; case CallSiteDescriptor.ARG_STR: args[i] = ""; argFlags[i] = CallSiteDescriptor.ARG_STR; break; default: args[i] = values.at_pos_boxed(tc, i); argFlags[i] = CallSiteDescriptor.ARG_OBJ; break; } } /* Do trial bind. */ return Binder.trialBind(tc, gcx, params, new CallSiteDescriptor(argFlags, null), args); } public static SixModelObject p6parcel(SixModelObject array, SixModelObject fill, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject parcel = gcx.Parcel.st.REPR.allocate(tc, gcx.Parcel.st); parcel.bind_attribute_boxed(tc, gcx.Parcel, "$!storage", HINT_PARCEL_STORAGE, array); if (fill != null) { long elems = array.elems(tc); for (long i = 0; i < elems; i++) { if (array.at_pos_boxed(tc, i) == null) array.bind_pos_boxed(tc, i, fill); } } return parcel; } private static final CallSiteDescriptor STORE = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); private static final CallSiteDescriptor storeThrower = new CallSiteDescriptor( new byte[] { }, null); public static SixModelObject p6store(SixModelObject cont, SixModelObject value, ThreadContext tc) { ContainerSpec spec = cont.st.ContainerSpec; if (spec != null) { spec.store(tc, cont, Ops.decont(value, tc)); } else { SixModelObject meth = Ops.findmethod(cont, "STORE", tc); if (meth != null) { Ops.invokeDirect(tc, meth, STORE, new Object[] { cont, value }); } else { SixModelObject thrower = getThrower(tc, "X::Assignment::RO"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Cannot assign to a non-container"); else Ops.invokeDirect(tc, thrower, storeThrower, new Object[] { }); } } return cont; } public static SixModelObject p6decontrv(SixModelObject routine, SixModelObject cont, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (cont != null) { if (isRWScalar(tc, gcx, cont)) { routine.get_attribute_native(tc, gcx.Routine, "$!rw", HINT_ROUTINE_RW); if (tc.native_i == 0) { /* Recontainerize to RO. */ SixModelObject roCont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); roCont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont.st.ContainerSpec.fetch(tc, cont)); return roCont; } } else if (cont instanceof NativeRefInstance) { routine.get_attribute_native(tc, gcx.Routine, "$!rw", HINT_ROUTINE_RW); if (tc.native_i == 0) return cont.st.ContainerSpec.fetch(tc, cont); } } return cont; } public static SixModelObject p6scalarfromdesc(SixModelObject desc, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (desc == null || desc instanceof TypeObject) desc = gcx.defaultContainerDescriptor; SixModelObject defVal = desc.get_attribute_boxed(tc, gcx.ContainerDescriptor, "$!default", HINT_CD_DEFAULT); SixModelObject cont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); cont.bind_attribute_boxed(tc, gcx.Scalar, "$!descriptor", RakudoContainerSpec.HINT_descriptor, desc); cont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, defVal); return cont; } public static SixModelObject p6recont_ro(SixModelObject cont, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (isRWScalar(tc, gcx, cont)) { SixModelObject roCont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); roCont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont.st.ContainerSpec.fetch(tc, cont)); return roCont; } return cont; } private static boolean isRWScalar(ThreadContext tc, GlobalExt gcx, SixModelObject check) { if (!(check instanceof TypeObject) && check.st.WHAT == gcx.Scalar) { SixModelObject desc = check.get_attribute_boxed(tc, gcx.Scalar, "$!descriptor", RakudoContainerSpec.HINT_descriptor); if (desc == null) return false; desc.get_attribute_native(tc, gcx.ContainerDescriptor, "$!rw", HINT_CD_RW); return tc.native_i != 0; } return false; } public static SixModelObject p6var(SixModelObject cont, ThreadContext tc) { if (cont != null && cont.st.ContainerSpec != null) { GlobalExt gcx = key.getGC(tc); SixModelObject wrapper = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); wrapper.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont); return wrapper; } else { return cont; } } public static SixModelObject p6reprname(SixModelObject obj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); obj = Ops.decont(obj, tc); SixModelObject name = gcx.Str.st.REPR.allocate(tc, gcx.Str.st); name.set_str(tc, obj.st.REPR.name); return name; } private static final CallSiteDescriptor rvThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6typecheckrv(SixModelObject rv, SixModelObject routine, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject sig = routine.get_attribute_boxed(tc, gcx.Code, "$!signature", HINT_CODE_SIG); SixModelObject rtype = sig.get_attribute_boxed(tc, gcx.Signature, "$!returns", HINT_SIG_RETURNS); if (rtype != null) { SixModelObject decontValue = Ops.decont(rv, tc); if (Ops.istype(decontValue, rtype, tc) == 0) { /* Straight type check failed, but it's possible we're returning * an Int that can unbox into an int or similar. */ StorageSpec spec = rtype.st.REPR.get_storage_spec(tc, rtype.st); if (spec.inlineable == 0 || Ops.istype(rtype, decontValue.st.WHAT, tc) == 0) { SixModelObject failure = Ops.getlex("Failure", tc); if (Ops.istype(failure, decontValue.st.WHAT, tc) == 0) { SixModelObject thrower = getThrower(tc, "X::TypeCheck::Return"); if (thrower == null) throw ExceptionHandling.dieInternal(tc, "Type check failed for return value"); else Ops.invokeDirect(tc, thrower, rvThrower, new Object[] { decontValue, rtype }); } } } } return rv; } private static final CallSiteDescriptor baThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6bindassert(SixModelObject value, SixModelObject type, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (type != gcx.Mu) { SixModelObject decont = Ops.decont(value, tc); if (Ops.istype(decont, type, tc) == 0) { SixModelObject thrower = getThrower(tc, "X::TypeCheck::Binding"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Type check failed in binding"); else Ops.invokeDirect(tc, thrower, baThrower, new Object[] { value, type }); } } return value; } public static SixModelObject p6capturelex(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); StaticCodeInfo wantedStaticInfo = closure.staticInfo.outerStaticInfo; if (tc.curFrame.codeRef.staticInfo == wantedStaticInfo) closure.outer = tc.curFrame; else if (tc.curFrame.outer.codeRef.staticInfo == wantedStaticInfo) closure.outer = tc.curFrame.outer; return codeObj; } public static SixModelObject p6getouterctx(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); codeObj = Ops.decont(codeObj, tc); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = closure.outer; return wrap; } public static SixModelObject p6captureouters(SixModelObject capList, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); long elems = capList.elems(tc); for (long i = 0; i < elems; i++) { SixModelObject codeObj = capList.at_pos_boxed(tc, i); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); CallFrame ctxToDiddle = closure.outer; ctxToDiddle.outer = tc.curFrame; } return capList; } public static SixModelObject p6captureouters2(SixModelObject capList, SixModelObject target, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (!(target instanceof CodeRef)) ExceptionHandling.dieInternal(tc, "p6captureouters target must be a CodeRef"); CallFrame cf = ((CodeRef)target).outer; if (cf == null) return capList; long elems = capList.elems(tc); for (long i = 0; i < elems; i++) { SixModelObject codeObj = capList.at_pos_boxed(tc, i); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); CallFrame ctxToDiddle = closure.outer; ctxToDiddle.outer = cf; } return capList; } public static SixModelObject p6bindattrinvres(SixModelObject obj, SixModelObject ch, String name, SixModelObject value, ThreadContext tc) { obj.bind_attribute_boxed(tc, Ops.decont(ch, tc), name, STable.NO_HINT, value); if (obj.sc != null) Ops.scwbObject(tc, obj); return obj; } public static SixModelObject getThrower(ThreadContext tc, String type) { SixModelObject exHash = Ops.gethllsym("perl6", "P6EX", tc); return exHash == null ? null : Ops.atkey(exHash, type, tc); } private static CallFrame find_common_ctx(CallFrame ctx1, CallFrame ctx2) { int depth1 = 0; int depth2 = 0; CallFrame ctx; for (ctx = ctx1; ctx != null; ctx = ctx.caller, depth1++) if (ctx == ctx2) return ctx; for (ctx = ctx2; ctx != null; ctx = ctx.caller, depth2++) if (ctx == ctx1) return ctx; for (; depth1 > depth2; depth2++) ctx1 = ctx1.caller; for (; depth2 > depth1; depth1++) ctx2 = ctx2.caller; while (ctx1 != ctx2) { ctx1 = ctx1.caller; ctx2 = ctx2.caller; } return ctx1; } private static SixModelObject getremotelex(CallFrame pad, String name) { /* use for sub_find_pad */ CallFrame curFrame = pad; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } return null; } public static SixModelObject p6routinereturn(SixModelObject in, ThreadContext tc) { CallFrame ctx = tc.curFrame; SixModelObject cont = null; for (ctx = ctx.caller; ctx != null; ctx = ctx.caller) { cont = getremotelex(ctx, "RETURN"); if (cont != null) break; } if (!(cont instanceof LexoticInstance)) { SixModelObject thrower = getThrower(tc, "X::ControlFlow::Return"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Attempt to return outside of any Routine"); else Ops.invokeArgless(tc, thrower); } // rewinding is handled by finally blocks in the generated subs LexoticException throwee = tc.theLexotic; throwee.target = ((LexoticInstance)cont).target; throwee.payload = in; throw throwee; } public static String tclc(String in, ThreadContext tc) { if (in.length() == 0) return in; int first = in.codePointAt(0); return new String(Character.toChars(Character.toTitleCase(first))) + in.substring(Character.charCount(first)).toLowerCase(); } private static final CallSiteDescriptor SortCSD = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6sort(SixModelObject indices, final SixModelObject comparator, final ThreadContext tc) { int elems = (int)indices.elems(tc); SixModelObject[] sortable = new SixModelObject[elems]; for (int i = 0; i < elems; i++) sortable[i] = indices.at_pos_boxed(tc, i); Arrays.sort(sortable, new Comparator<SixModelObject>() { public int compare(SixModelObject a, SixModelObject b) { Ops.invokeDirect(tc, comparator, SortCSD, new Object[] { a, b }); return (int)Ops.result_i(tc.curFrame); } }); for (int i = 0; i < elems; i++) indices.bind_pos_boxed(tc, i, sortable[i]); return indices; } public static long p6stateinit(ThreadContext tc) { return tc.curFrame.stateInit ? 1 : 0; } public static SixModelObject p6setfirstflag(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); ThreadExt tcx = key.getTC(tc); tcx.firstPhaserCodeBlock = codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); return codeObj; } public static long p6takefirstflag(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); boolean matches = tcx.firstPhaserCodeBlock == tc.curFrame.codeRef; tcx.firstPhaserCodeBlock = null; return matches ? 1 : 0; } public static SixModelObject p6setpre(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); tcx.prePhaserFrames.add(tc.curFrame); return null; } public static SixModelObject p6clearpre(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); tcx.prePhaserFrames.remove(tc.curFrame); return null; } public static long p6inpre(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); return tcx.prePhaserFrames.remove(tc.curFrame.caller) ? 1 : 0; } private static final CallSiteDescriptor dispVivifier = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); private static final CallSiteDescriptor dispThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_STR }, null); public static SixModelObject p6finddispatcher(String usage, ThreadContext tc) { SixModelObject dispatcher = null; CallFrame ctx = tc.curFrame; while (ctx != null) { /* Do we have a dispatcher here? */ StaticCodeInfo sci = ctx.codeRef.staticInfo; Integer dispLexIdx = sci.oTryGetLexicalIdx("$*DISPATCHER"); if (dispLexIdx != null) { SixModelObject maybeDispatcher = ctx.oLex[dispLexIdx]; if (maybeDispatcher != null) { dispatcher = maybeDispatcher; if (dispatcher instanceof TypeObject) { /* Need to vivify it. */ SixModelObject meth = Ops.findmethod(dispatcher, "vivify_for", tc); SixModelObject p6sub = ctx.codeRef.codeObject; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = ctx; SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = ctx.csd; cc.args = ctx.args; Ops.invokeDirect(tc, meth, dispVivifier, new Object[] { dispatcher, p6sub, wrap, cc }); dispatcher = Ops.result_o(tc.curFrame); ctx.oLex[dispLexIdx] = dispatcher; } break; } } /* Follow dynamic chain. */ ctx = ctx.caller; } if (dispatcher == null) { SixModelObject thrower = getThrower(tc, "X::NoDispatcher"); if (thrower == null) { ExceptionHandling.dieInternal(tc, usage + " is not in the dynamic scope of a dispatcher"); } else { Ops.invokeDirect(tc, thrower, dispThrower, new Object[] { usage }); } } return dispatcher; } public static SixModelObject p6argsfordispatcher(SixModelObject disp, ThreadContext tc) { SixModelObject result = null; CallFrame ctx = tc.curFrame; while (ctx != null) { /* Do we have the dispatcher we're looking for? */ StaticCodeInfo sci = ctx.codeRef.staticInfo; Integer dispLexIdx = sci.oTryGetLexicalIdx("$*DISPATCHER"); if (dispLexIdx != null) { SixModelObject maybeDispatcher = ctx.oLex[dispLexIdx]; if (maybeDispatcher == disp) { /* Found; grab args. */ SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = ctx.csd; cc.args = ctx.args; result = cc; break; } } /* Follow dynamic chain. */ ctx = ctx.caller; } if (result == null) throw ExceptionHandling.dieInternal(tc, "Could not find arguments for dispatcher"); return result; } public static SixModelObject p6decodelocaltime(long sinceEpoch, ThreadContext tc) { // Get calendar for current local host's timezone. Calendar c = Calendar.getInstance(); c.setTimeInMillis(sinceEpoch * 1000); // Populate result int array. SixModelObject BOOTIntArray = tc.gc.BOOTIntArray; SixModelObject result = BOOTIntArray.st.REPR.allocate(tc, BOOTIntArray.st); tc.native_i = c.get(Calendar.SECOND); result.bind_pos_native(tc, 0); tc.native_i = c.get(Calendar.MINUTE); result.bind_pos_native(tc, 1); tc.native_i = c.get(Calendar.HOUR_OF_DAY); result.bind_pos_native(tc, 2); tc.native_i = c.get(Calendar.DAY_OF_MONTH); result.bind_pos_native(tc, 3); tc.native_i = c.get(Calendar.MONTH) + 1; result.bind_pos_native(tc, 4); tc.native_i = c.get(Calendar.YEAR); result.bind_pos_native(tc, 5); return result; } public static SixModelObject p6staticouter(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).staticInfo.outerStaticInfo.staticCode; else throw ExceptionHandling.dieInternal(tc, "p6staticouter must be used on a CodeRef"); } public static SixModelObject jvmrakudointerop(ThreadContext tc) { GlobalExt gcx = key.getGC(tc); return BootJavaInterop.RuntimeSupport.boxJava(gcx.rakudoInterop, gcx.rakudoInterop.getSTableForClass(RakudoJavaInterop.class)); } }
package org.perl6.rakudo; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import org.perl6.nqp.runtime.*; import org.perl6.nqp.sixmodel.*; import org.perl6.nqp.sixmodel.reprs.CallCaptureInstance; import org.perl6.nqp.sixmodel.reprs.ContextRefInstance; import org.perl6.nqp.sixmodel.reprs.NativeRefInstance; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance; /** * Contains implementation of nqp:: ops specific to Rakudo Perl 6. */ @SuppressWarnings("unused") public final class RakOps { public static final boolean DEBUG_MODE = false; public static class ThreadExt { public SixModelObject firstPhaserCodeBlock; public ArrayList<CallFrame> prePhaserFrames = new ArrayList<CallFrame>(); public ThreadExt(ThreadContext tc) { } } public static class GlobalExt { public SixModelObject Mu; public SixModelObject Any; public SixModelObject Code; public SixModelObject Routine; public SixModelObject Signature; public SixModelObject Parameter; public SixModelObject Int; public SixModelObject Num; public SixModelObject Str; public SixModelObject List; public SixModelObject ListIter; public SixModelObject Iterable; public SixModelObject Array; public SixModelObject Nil; public SixModelObject Map; public SixModelObject Hash; public SixModelObject Junction; public SixModelObject Scalar; public SixModelObject Capture; public SixModelObject ContainerDescriptor; public SixModelObject False; public SixModelObject True; public SixModelObject AutoThreader; public SixModelObject Positional; public SixModelObject PositionalBindFailover; public SixModelObject Associative; public SixModelObject EMPTYARR; public SixModelObject EMPTYHASH; public RakudoJavaInterop rakudoInterop; public SixModelObject JavaHOW; public SixModelObject defaultContainerDescriptor; boolean initialized; public GlobalExt(ThreadContext tc) {} } public static ContextKey<ThreadExt, GlobalExt> key = new ContextKey< >(ThreadExt.class, GlobalExt.class); /* Parameter hints for fast lookups. */ private static final int HINT_CODE_DO = 0; private static final int HINT_CODE_SIG = 1; private static final int HINT_ROUTINE_RW = 8; private static final int HINT_SIG_PARAMS = 0; private static final int HINT_SIG_RETURNS = 1; private static final int HINT_SIG_CODE = 4; public static final int HINT_CD_OF = 0; public static final int HINT_CD_RW = 1; public static final int HINT_CD_NAME = 2; public static final int HINT_CD_DEFAULT = 3; public static SixModelObject p6init(ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (!gcx.initialized) { tc.gc.contConfigs.put("rakudo_scalar", new RakudoContainerConfigurer()); SixModelObject BOOTArray = tc.gc.BOOTArray; gcx.EMPTYARR = BOOTArray.st.REPR.allocate(tc, BOOTArray.st); SixModelObject BOOTHash = tc.gc.BOOTHash; gcx.EMPTYHASH = BOOTHash.st.REPR.allocate(tc, BOOTHash.st); gcx.rakudoInterop = new RakudoJavaInterop(tc.gc); gcx.initialized = true; } return null; } public static SixModelObject p6setitertype(SixModelObject type, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.Iterable = type; return type; } public static SixModelObject p6settypes(SixModelObject conf, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.Mu = conf.at_key_boxed(tc, "Mu"); gcx.Any = conf.at_key_boxed(tc, "Any"); gcx.Code = conf.at_key_boxed(tc, "Code"); gcx.Routine = conf.at_key_boxed(tc, "Routine"); gcx.Signature = conf.at_key_boxed(tc, "Signature"); gcx.Parameter = conf.at_key_boxed(tc, "Parameter"); gcx.Int = conf.at_key_boxed(tc, "Int"); gcx.Num = conf.at_key_boxed(tc, "Num"); gcx.Str = conf.at_key_boxed(tc, "Str"); gcx.List = conf.at_key_boxed(tc, "List"); gcx.ListIter = conf.at_key_boxed(tc, "ListIter"); gcx.Iterable = conf.at_key_boxed(tc, "Iterable"); gcx.Array = conf.at_key_boxed(tc, "Array"); gcx.Nil = conf.at_key_boxed(tc, "Nil"); gcx.Map = conf.at_key_boxed(tc, "Map"); gcx.Hash = conf.at_key_boxed(tc, "Hash"); gcx.Junction = conf.at_key_boxed(tc, "Junction"); gcx.Scalar = conf.at_key_boxed(tc, "Scalar"); gcx.Capture = conf.at_key_boxed(tc, "Capture"); gcx.ContainerDescriptor = conf.at_key_boxed(tc, "ContainerDescriptor"); gcx.False = conf.at_key_boxed(tc, "False"); gcx.True = conf.at_key_boxed(tc, "True"); gcx.Associative = conf.at_key_boxed(tc, "Associative"); gcx.JavaHOW = conf.at_key_boxed(tc, "Metamodel").st.WHO.at_key_boxed(tc, "JavaHOW"); SixModelObject defCD = gcx.ContainerDescriptor.st.REPR.allocate(tc, gcx.ContainerDescriptor.st); defCD.bind_attribute_boxed(tc, gcx.ContainerDescriptor, "$!of", HINT_CD_OF, gcx.Mu); tc.native_s = "<element>"; defCD.bind_attribute_native(tc, gcx.ContainerDescriptor, "$!name", HINT_CD_NAME); tc.native_i = 1; defCD.bind_attribute_native(tc, gcx.ContainerDescriptor, "$!rw", HINT_CD_RW); defCD.bind_attribute_boxed(tc, gcx.ContainerDescriptor, "$!default", HINT_CD_DEFAULT, gcx.Any); gcx.defaultContainerDescriptor = defCD; return conf; } public static SixModelObject p6setautothreader(SixModelObject autoThreader, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.AutoThreader = autoThreader; return autoThreader; } public static SixModelObject p6configposbindfailover(SixModelObject p, SixModelObject pbf, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); gcx.Positional = p; gcx.PositionalBindFailover = pbf; return p; } public static SixModelObject booleanize(int x, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); return x == 0 ? gcx.False : gcx.True; } public static SixModelObject p6definite(SixModelObject obj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); obj = Ops.decont(obj, tc); return obj instanceof TypeObject ? gcx.False : gcx.True; } public static SixModelObject p6box_i(long value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Int.st.REPR.allocate(tc, gcx.Int.st); res.set_int(tc, value); return res; } public static SixModelObject p6box_n(double value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Num.st.REPR.allocate(tc, gcx.Num.st); res.set_num(tc, value); return res; } public static SixModelObject p6box_s(String value, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject res = gcx.Str.st.REPR.allocate(tc, gcx.Str.st); res.set_str(tc, value); return res; } public static SixModelObject p6argvmarray(ThreadContext tc, CallSiteDescriptor csd, Object[] args) { SixModelObject BOOTArray = tc.gc.BOOTArray; SixModelObject res = BOOTArray.st.REPR.allocate(tc, BOOTArray.st); for (int i = 0; i < csd.numPositionals; i++) { SixModelObject toBind; switch (csd.argFlags[i]) { case CallSiteDescriptor.ARG_INT: toBind = p6box_i((long)args[i], tc); break; case CallSiteDescriptor.ARG_NUM: toBind = p6box_n((double)args[i], tc); break; case CallSiteDescriptor.ARG_STR: toBind = p6box_s((String)args[i], tc); break; default: toBind = Ops.hllize((SixModelObject)args[i], tc); break; } res.bind_pos_boxed(tc, i, toBind); } return res; } public static CallSiteDescriptor p6bindsig(ThreadContext tc, CallSiteDescriptor csd, Object[] args) { /* Do any flattening before processing begins. */ CallFrame cf = tc.curFrame; if (csd.hasFlattening) { csd = csd.explodeFlattening(cf, args); args = tc.flatArgs; } cf.csd = csd; cf.args = args; /* Look up parameters to bind. */ if (DEBUG_MODE) { if (cf.codeRef.name != null) System.err.println("Binding for " + cf.codeRef.name); } GlobalExt gcx = key.getGC(tc); SixModelObject sig = cf.codeRef.codeObject .get_attribute_boxed(tc, gcx.Code, "$!signature", HINT_CODE_SIG); SixModelObject params = sig .get_attribute_boxed(tc, gcx.Signature, "@!params", HINT_SIG_PARAMS); /* Run binder, and handle any errors. */ Object[] error = new Object[3]; switch (Binder.bind(tc, gcx, cf, params, csd, args, false, error)) { case Binder.BIND_RESULT_FAIL: if (error[0] instanceof String) { throw ExceptionHandling.dieInternal(tc, (String) error[0]); } else { Ops.invokeDirect(tc, (SixModelObject) error[0], (CallSiteDescriptor) error[1], (Object[]) error[2]); } case Binder.BIND_RESULT_JUNCTION: /* Invoke the auto-threader. */ csd = csd.injectInvokee(tc, args, cf.codeRef.codeObject); args = tc.flatArgs; Ops.invokeDirect(tc, gcx.AutoThreader, csd, args); Ops.return_o( Ops.result_o(cf), cf); /* Return null to indicate immediate return to the routine. */ return null; } /* The binder may, for a variety of reasons, wind up calling Perl 6 code and overwriting flatArgs, so it needs to be set at the end to return reliably */ tc.flatArgs = args; return csd; } public static SixModelObject p6bindcaptosig(SixModelObject sig, SixModelObject cap, ThreadContext tc) { CallFrame cf = tc.curFrame; GlobalExt gcx = key.getGC(tc); CallSiteDescriptor csd = Binder.explodeCapture(tc, gcx, cap); SixModelObject params = sig.get_attribute_boxed(tc, gcx.Signature, "@!params", HINT_SIG_PARAMS); Object[] error = new Object[3]; switch (Binder.bind(tc, gcx, cf, params, csd, tc.flatArgs, false, error)) { case Binder.BIND_RESULT_FAIL: case Binder.BIND_RESULT_JUNCTION: if (error[0] instanceof String) { throw ExceptionHandling.dieInternal(tc, (String) error[0]); } else { Ops.invokeDirect(tc, (SixModelObject) error[0], (CallSiteDescriptor) error[1], (Object[]) error[2]); } default: return sig; } } public static long p6isbindable(SixModelObject sig, SixModelObject cap, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); CallSiteDescriptor csd; Object[] args; if (cap instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)cap; csd = cc.descriptor; args = cc.args; } else { csd = Binder.explodeCapture(tc, gcx, cap); args = tc.flatArgs; } SixModelObject params = sig.get_attribute_boxed(tc, gcx.Signature, "@!params", HINT_SIG_PARAMS); SixModelObject codeObj = sig.get_attribute_boxed(tc, gcx.Signature, "$!code", HINT_SIG_CODE); CodeRef cr = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); CallFrame cf = new CallFrame(tc, cr); try { switch (Binder.bind(tc, gcx, cf, params, csd, args, false, null)) { case Binder.BIND_RESULT_FAIL: return 0; default: return 1; } } finally { tc.curFrame = tc.curFrame.caller; } } private static final CallSiteDescriptor STORE = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); private static final CallSiteDescriptor storeThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_STR }, null); public static SixModelObject p6store(SixModelObject cont, SixModelObject value, ThreadContext tc) { ContainerSpec spec = cont.st.ContainerSpec; if (spec != null) { spec.store(tc, cont, Ops.decont(value, tc)); } else { SixModelObject meth = Ops.findmethodNonFatal(cont, "STORE", tc); if (meth != null) { Ops.invokeDirect(tc, meth, STORE, new Object[] { cont, value }); } else { SixModelObject thrower = getThrower(tc, "X::Assignment::RO"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Cannot assign to a non-container"); else Ops.invokeDirect(tc, thrower, storeThrower, new Object[] { Ops.typeName(cont, tc) }); } } return cont; } public static SixModelObject p6decontrv(SixModelObject routine, SixModelObject cont, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (cont != null) { if (isRWScalar(tc, gcx, cont)) { routine.get_attribute_native(tc, gcx.Routine, "$!rw", HINT_ROUTINE_RW); if (tc.native_i == 0) { /* Recontainerize to RO. */ SixModelObject roCont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); roCont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont.st.ContainerSpec.fetch(tc, cont)); return roCont; } } else if (cont instanceof NativeRefInstance) { routine.get_attribute_native(tc, gcx.Routine, "$!rw", HINT_ROUTINE_RW); if (tc.native_i == 0) return cont.st.ContainerSpec.fetch(tc, cont); } } return cont; } public static SixModelObject p6scalarfromdesc(SixModelObject desc, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if ( Ops.isconcrete(desc, tc) == 0 ) desc = gcx.defaultContainerDescriptor; SixModelObject defVal = desc.get_attribute_boxed(tc, gcx.ContainerDescriptor, "$!default", HINT_CD_DEFAULT); SixModelObject cont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); cont.bind_attribute_boxed(tc, gcx.Scalar, "$!descriptor", RakudoContainerSpec.HINT_descriptor, desc); cont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, defVal); return cont; } public static SixModelObject p6recont_ro(SixModelObject cont, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (isRWScalar(tc, gcx, cont)) { SixModelObject roCont = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); roCont.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont.st.ContainerSpec.fetch(tc, cont)); return roCont; } return cont; } private static boolean isRWScalar(ThreadContext tc, GlobalExt gcx, SixModelObject check) { if (!(check instanceof TypeObject) && check.st.WHAT == gcx.Scalar) { SixModelObject desc = check.get_attribute_boxed(tc, gcx.Scalar, "$!descriptor", RakudoContainerSpec.HINT_descriptor); if (desc == null) return false; desc.get_attribute_native(tc, gcx.ContainerDescriptor, "$!rw", HINT_CD_RW); return tc.native_i != 0; } return false; } public static SixModelObject p6var(SixModelObject cont, ThreadContext tc) { if (cont != null && cont.st.ContainerSpec != null) { GlobalExt gcx = key.getGC(tc); SixModelObject wrapper = gcx.Scalar.st.REPR.allocate(tc, gcx.Scalar.st); wrapper.bind_attribute_boxed(tc, gcx.Scalar, "$!value", RakudoContainerSpec.HINT_value, cont); return wrapper; } else { return cont; } } public static SixModelObject p6reprname(SixModelObject obj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); obj = Ops.decont(obj, tc); SixModelObject name = gcx.Str.st.REPR.allocate(tc, gcx.Str.st); name.set_str(tc, obj.st.REPR.name); return name; } private static final CallSiteDescriptor rvThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6typecheckrv(SixModelObject rv, SixModelObject routine, SixModelObject bypassType, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); SixModelObject sig = routine.get_attribute_boxed(tc, gcx.Code, "$!signature", HINT_CODE_SIG); SixModelObject rtype = sig.get_attribute_boxed(tc, gcx.Signature, "$!returns", HINT_SIG_RETURNS); if (rtype != null) { SixModelObject decontValue = Ops.decont(rv, tc); if (Ops.istype(decontValue, rtype, tc) == 0) { /* Straight type check failed, but it's possible we're returning * an Int that can unbox into an int or similar. */ StorageSpec spec = rtype.st.REPR.get_storage_spec(tc, rtype.st); if (spec.inlineable == 0 || Ops.istype(rtype, decontValue.st.WHAT, tc) == 0) { if (Ops.istype(decontValue.st.WHAT, bypassType, tc) == 0) { SixModelObject thrower = getThrower(tc, "X::TypeCheck::Return"); if (thrower == null) throw ExceptionHandling.dieInternal(tc, "Type check failed for return value"); else Ops.invokeDirect(tc, thrower, rvThrower, new Object[] { decontValue, rtype }); } } } } return rv; } private static final CallSiteDescriptor baThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6bindassert(SixModelObject value, SixModelObject type, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (type != gcx.Mu) { SixModelObject decont = Ops.decont(value, tc); if (Ops.istype(decont, type, tc) == 0) { SixModelObject thrower = getThrower(tc, "X::TypeCheck::Binding"); if (thrower == null) ExceptionHandling.dieInternal(tc, "Type check failed in binding"); else Ops.invokeDirect(tc, thrower, baThrower, new Object[] { value, type }); } } return value; } public static SixModelObject p6capturelex(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); StaticCodeInfo wantedStaticInfo = closure.staticInfo.outerStaticInfo; if (tc.curFrame.codeRef.staticInfo == wantedStaticInfo) closure.outer = tc.curFrame; else if (tc.curFrame.outer.codeRef.staticInfo == wantedStaticInfo) closure.outer = tc.curFrame.outer; return codeObj; } public static SixModelObject p6getouterctx(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); codeObj = Ops.decont(codeObj, tc); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = closure.outer; return wrap; } public static SixModelObject p6captureouters2(SixModelObject capList, SixModelObject target, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); if (!(target instanceof CodeRef)) ExceptionHandling.dieInternal(tc, "p6captureouters target must be a CodeRef"); CallFrame cf = ((CodeRef)target).outer; if (cf == null) return capList; long elems = capList.elems(tc); for (long i = 0; i < elems; i++) { SixModelObject codeObj = capList.at_pos_boxed(tc, i); CodeRef closure = (CodeRef)codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); CallFrame ctxToDiddle = closure.outer; ctxToDiddle.outer = cf; } return capList; } public static SixModelObject p6bindattrinvres(SixModelObject obj, SixModelObject ch, String name, SixModelObject value, ThreadContext tc) { obj.bind_attribute_boxed(tc, Ops.decont(ch, tc), name, STable.NO_HINT, value); if (obj.sc != null) Ops.scwbObject(tc, obj); return obj; } public static SixModelObject getThrower(ThreadContext tc, String type) { SixModelObject exHash = Ops.gethllsym("perl6", "P6EX", tc); return exHash == null ? null : Ops.atkey(exHash, type, tc); } private static CallFrame find_common_ctx(CallFrame ctx1, CallFrame ctx2) { int depth1 = 0; int depth2 = 0; CallFrame ctx; for (ctx = ctx1; ctx != null; ctx = ctx.caller, depth1++) if (ctx == ctx2) return ctx; for (ctx = ctx2; ctx != null; ctx = ctx.caller, depth2++) if (ctx == ctx1) return ctx; for (; depth1 > depth2; depth2++) ctx1 = ctx1.caller; for (; depth2 > depth1; depth1++) ctx2 = ctx2.caller; while (ctx1 != ctx2) { ctx1 = ctx1.caller; ctx2 = ctx2.caller; } return ctx1; } private static SixModelObject getremotelex(CallFrame pad, String name) { /* use for sub_find_pad */ CallFrame curFrame = pad; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } return null; } public static String tclc(String in, ThreadContext tc) { if (in.length() == 0) return in; int first = in.codePointAt(0); return new String(Character.toChars(Character.toTitleCase(first))) + in.substring(Character.charCount(first)).toLowerCase(); } private static final CallSiteDescriptor SortCSD = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static SixModelObject p6sort(SixModelObject indices, final SixModelObject comparator, final ThreadContext tc) { int elems = (int)indices.elems(tc); SixModelObject[] sortable = new SixModelObject[elems]; for (int i = 0; i < elems; i++) sortable[i] = indices.at_pos_boxed(tc, i); Arrays.sort(sortable, new Comparator<SixModelObject>() { public int compare(SixModelObject a, SixModelObject b) { Ops.invokeDirect(tc, comparator, SortCSD, new Object[] { a, b }); return (int)Ops.result_i(tc.curFrame); } }); for (int i = 0; i < elems; i++) indices.bind_pos_boxed(tc, i, sortable[i]); return indices; } public static long p6stateinit(ThreadContext tc) { return tc.curFrame.stateInit ? 1 : 0; } public static SixModelObject p6setfirstflag(SixModelObject codeObj, ThreadContext tc) { GlobalExt gcx = key.getGC(tc); ThreadExt tcx = key.getTC(tc); tcx.firstPhaserCodeBlock = codeObj.get_attribute_boxed(tc, gcx.Code, "$!do", HINT_CODE_DO); return codeObj; } public static long p6takefirstflag(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); boolean matches = tcx.firstPhaserCodeBlock == tc.curFrame.codeRef; tcx.firstPhaserCodeBlock = null; return matches ? 1 : 0; } public static SixModelObject p6setpre(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); tcx.prePhaserFrames.add(tc.curFrame); return null; } public static SixModelObject p6clearpre(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); tcx.prePhaserFrames.remove(tc.curFrame); return null; } public static long p6inpre(ThreadContext tc) { ThreadExt tcx = key.getTC(tc); return tcx.prePhaserFrames.remove(tc.curFrame.caller) ? 1 : 0; } private static final CallSiteDescriptor dispVivifier = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); private static final CallSiteDescriptor dispThrower = new CallSiteDescriptor( new byte[] { CallSiteDescriptor.ARG_STR }, null); public static SixModelObject p6finddispatcher(String usage, ThreadContext tc) { SixModelObject dispatcher = null; CallFrame ctx = tc.curFrame.caller; while (ctx != null) { /* Do we have a dispatcher here? */ StaticCodeInfo sci = ctx.codeRef.staticInfo; Integer dispLexIdx = sci.oTryGetLexicalIdx("$*DISPATCHER"); if (dispLexIdx != null) { SixModelObject maybeDispatcher = ctx.oLex[dispLexIdx]; if (maybeDispatcher != null) { dispatcher = maybeDispatcher; if (dispatcher instanceof TypeObject) { /* Need to vivify it. */ SixModelObject meth = Ops.findmethod(dispatcher, "vivify_for", tc); SixModelObject p6sub = ctx.codeRef.codeObject; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = ctx; SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = ctx.csd; cc.args = ctx.args; Ops.invokeDirect(tc, meth, dispVivifier, new Object[] { dispatcher, p6sub, wrap, cc }); dispatcher = Ops.result_o(tc.curFrame); ctx.oLex[dispLexIdx] = dispatcher; } break; } } /* Follow dynamic chain. */ ctx = ctx.caller; } if (dispatcher == null) { SixModelObject thrower = getThrower(tc, "X::NoDispatcher"); if (thrower == null) { ExceptionHandling.dieInternal(tc, usage + " is not in the dynamic scope of a dispatcher"); } else { Ops.invokeDirect(tc, thrower, dispThrower, new Object[] { usage }); } } return dispatcher; } public static SixModelObject p6argsfordispatcher(SixModelObject disp, ThreadContext tc) { SixModelObject result = null; CallFrame ctx = tc.curFrame; while (ctx != null) { /* Do we have the dispatcher we're looking for? */ StaticCodeInfo sci = ctx.codeRef.staticInfo; Integer dispLexIdx = sci.oTryGetLexicalIdx("$*DISPATCHER"); if (dispLexIdx != null) { SixModelObject maybeDispatcher = ctx.oLex[dispLexIdx]; if (maybeDispatcher == disp) { /* Found; grab args. */ SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = ctx.csd; cc.args = ctx.args; result = cc; break; } } /* Follow dynamic chain. */ ctx = ctx.caller; } if (result == null) throw ExceptionHandling.dieInternal(tc, "Could not find arguments for dispatcher"); return result; } public static SixModelObject p6decodelocaltime(long sinceEpoch, ThreadContext tc) { // Get calendar for current local host's timezone. Calendar c = Calendar.getInstance(); c.setTimeInMillis(sinceEpoch * 1000); // Populate result int array. SixModelObject BOOTIntArray = tc.gc.BOOTIntArray; SixModelObject result = BOOTIntArray.st.REPR.allocate(tc, BOOTIntArray.st); tc.native_i = c.get(Calendar.SECOND); result.bind_pos_native(tc, 0); tc.native_i = c.get(Calendar.MINUTE); result.bind_pos_native(tc, 1); tc.native_i = c.get(Calendar.HOUR_OF_DAY); result.bind_pos_native(tc, 2); tc.native_i = c.get(Calendar.DAY_OF_MONTH); result.bind_pos_native(tc, 3); tc.native_i = c.get(Calendar.MONTH) + 1; result.bind_pos_native(tc, 4); tc.native_i = c.get(Calendar.YEAR); result.bind_pos_native(tc, 5); return result; } public static SixModelObject p6staticouter(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).staticInfo.outerStaticInfo.staticCode; else throw ExceptionHandling.dieInternal(tc, "p6staticouter must be used on a CodeRef"); } public static SixModelObject jvmrakudointerop(ThreadContext tc) { GlobalExt gcx = key.getGC(tc); return BootJavaInterop.RuntimeSupport.boxJava(gcx.rakudoInterop, gcx.rakudoInterop.getSTableForClass(RakudoJavaInterop.class)); } }
package rsv.process.control; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import org.apache.log4j.Logger; import rsv.process.Configuration; import rsv.process.TimeRange; import rsv.process.model.OIMModel; import rsv.process.model.StatusChangeModel; import rsv.process.model.OIMModel.ResourcesType; import rsv.process.model.record.Downtime; import rsv.process.model.record.ServiceStatus; import rsv.process.model.record.Status; public class RSVAvailability implements RSVProcess { private static final Logger logger = Logger.getLogger(RSVCache.class); OIMModel oim = new OIMModel(); StatusChangeModel scm = new StatusChangeModel(); public int run(String args[]) { int ret = RSVMain.exitcode_ok; int start_time; int end_time; if(args.length == 3) { start_time = Integer.parseInt(args[1]); end_time = Integer.parseInt(args[2]); } else if(args.length == 2) { if(args[1].compareTo("yesterday") == 0) { Calendar cal = Calendar.getInstance(); Date current_date = cal.getTime(); int currenttime = (int) (current_date.getTime()/1000); end_time = currenttime / 86400 * 86400; start_time = end_time - 86400; } else if(args[1].compareTo("lastweek") == 0) { Calendar cal = Calendar.getInstance(); Date current_date = cal.getTime(); int currenttime = (int) (current_date.getTime()/1000); end_time = currenttime / 86400 * 86400; start_time = end_time - 86400*7; } else { logger.error("Unknown duration token: " + args[1]); return RSVMain.exitcode_invalid_arg; } } else { System.out.println("Please provide start & end time"); return RSVMain.exitcode_invalid_arg; } int r = outputARCache(start_time, end_time); if(r != RSVMain.exitcode_ok) { logger.error("Error while executing outputARCache()"); ret = RSVMain.exitcode_error; } return ret; } private int outputARCache(int start_time, int end_time) { int ret = RSVMain.exitcode_ok; try { ResourcesType resources = oim.getResources(); Calendar cal = Calendar.getInstance(); Date current_date = cal.getTime(); int currenttime = (int) (current_date.getTime()/1000); int total_time = end_time - start_time; String allxml = "<?xml version=\"1.0\"?>\n"; allxml += "<ARCache>"; allxml += "<CalculateTimestamp>"+currenttime+"</CalculateTimestamp>"; allxml += "<ReportStartTime>"+start_time+"</ReportStartTime>"; allxml += "<ReportEndTime>"+end_time+"</ReportEndTime>"; allxml += "<ReportTotalTime>"+total_time+"</ReportTotalTime>"; logger.info("Calculating Availability and reliability for all resources/services"); Date start_date = new Date(); start_date.setTime(start_time*1000L); Date end_date = new Date(); end_date.setTime(end_time*1000L); logger.info("Resport Start Time: " + start_date + " ~ End Time: " + end_date); logger.info("Resport Start Time: " + start_time + " ~ End Time: " + end_time); allxml += "<Resources>"; for(Integer resource_id : resources.keySet()) { //debug //if(resource_id != 1) continue; allxml += "<Resource>"; ArrayList<Downtime> downtimes = oim.getDowntimes(resource_id); ArrayList<Integer> services = oim.getResourceService(resource_id); allxml += "<ResourceID>" + resource_id + "</ResourceID>"; allxml += "<Services>"; for(Integer service_id : services) { allxml += "<Service>"; allxml += "<ServiceID>"+service_id+"</ServiceID>"; logger.info(resource_id + " " + service_id); ServiceStatus init_status = scm.getInitServiceStatus(resource_id, service_id, start_time); if(init_status == null) { init_status = new ServiceStatus(); init_status.status_id = Status.UNKNOWN; logger.info("\tNo initial status"); } else { logger.info("\tInitial Status: " + init_status.status_id); } ArrayList<ServiceStatus> changes = scm.getServiceStatusChanges(resource_id, service_id, start_time, end_time); int available_time = calculateUptime(init_status, changes, start_time, end_time); logger.info("\t Available Time: " + available_time); allxml += "<AvailableTime>"+available_time+"</AvailableTime>"; allxml += "<Availability>"+((double)available_time/total_time)+"</Availability>"; int reliable_time; if(downtimes != null) { //dump changes list logger.debug("\tBefore imposing"); dump(changes); changes = superImposeDowntime(init_status, changes, start_time, end_time, downtimes, service_id); logger.debug("\tAfter imposing"); dump(changes); reliable_time = calculateUptime(init_status, changes, start_time, end_time); } else { //if there are no downtime info.. reliable_time = available_time; } allxml += "<ReliableTime>"+reliable_time+"</ReliableTime>"; allxml += "<Reliability>"+((double)reliable_time/total_time)+"</Reliability>"; allxml += "</Service>"; logger.info("\t Reliable Time: " + reliable_time); } allxml += "</Services>"; allxml += "</Resource>"; } allxml += "</Resources>"; allxml += "</ARCache>"; //output all AR status cache String filename_template = RSVMain.conf.getProperty(Configuration.aandr_cache); filename_template = filename_template.replaceFirst("<start_time>", String.valueOf(start_time)); String filename = filename_template.replaceFirst("<end_time>", String.valueOf(end_time)); FileWriter fstream; try { fstream = new FileWriter(filename); BufferedWriter out = new BufferedWriter(fstream); out.write(allxml); out.close(); } catch (IOException e) { logger.error("Caught exception while outputing xml cache: " + filename, e); ret = RSVMain.exitcode_error; } } catch (SQLException e) { logger.error("SQL Error", e); ret = RSVMain.exitcode_error; } return ret; } void dump(ArrayList<ServiceStatus> changes) { for(ServiceStatus status : changes) { logger.debug("At: " + status.timestamp + " status: " + status.status_id + " note:" + status.note); } } int calculateUptime(ServiceStatus current_status, ArrayList<ServiceStatus> changes, int start_time, int end_time) { int up_time = 0; int current_time = start_time; for(ServiceStatus new_status : changes) { switch(current_status.status_id) { case Status.OK: case Status.WARNING: case Status.DOWNTIME: up_time += new_status.timestamp - current_time; break; } current_time = new_status.timestamp; current_status = new_status; } //process last period switch(current_status.status_id) { case Status.OK: case Status.WARNING: case Status.DOWNTIME: up_time += end_time - current_time; } return up_time; } ArrayList<ServiceStatus> superImposeDowntime(ServiceStatus init_status, ArrayList<ServiceStatus> changes, int start_time, int end_time, ArrayList<Downtime> downtimes, int service_id) throws SQLException { for(Downtime downtime : downtimes) { ArrayList<Integer> service_ids = downtime.getServiceIDs(); if(service_ids == null) continue; if(service_ids.contains(service_id)) { int down_start = downtime.getStartTime(); int down_end = downtime.getEndTime(); //if this downtime ends before start time, ignore if(down_end < start_time) continue; //if this downtime starts after end_time, ignore if(down_start > end_time) continue; logger.debug("\t\tImposing downtime start:" + down_start + " end:" + down_end); //find the beginning status that I am superimposing ServiceStatus first = null; for(ServiceStatus status : changes) { if(status.timestamp < down_start) continue; first = status; break; } //clear status changes occured between start_time, and end_time //while remembering the last change ArrayList<ServiceStatus> newlist = new ArrayList<ServiceStatus>(); ServiceStatus last = null; for(ServiceStatus status : changes) { if(status.timestamp < down_start || status.timestamp > down_end) { newlist.add(status); } else { last = status; } } changes = newlist; //use init_status if there is no status changes if(first == null) { first = init_status; } //use first if there is no last if(last == null) { last = first; } //now we have everything there is know if(down_start < start_time) { down_start = start_time; } newlist = new ArrayList<ServiceStatus>(); //copy all status changes before down_start for(ServiceStatus status : changes) { if(status.timestamp > down_start) break; newlist.add(status); } //insert new downtime begin if not already downtime if(first.status_id != Status.DOWNTIME) { ServiceStatus newdown = new ServiceStatus(); newdown.status_id = Status.DOWNTIME; newdown.timestamp = down_start; newlist.add(newdown); } //if downtime ends before end_time, add the end of end_time and rest of status changes if(down_end <= end_time) { //insert end downtime last.timestamp = down_end; newlist.add(last); //copy all the rest for(ServiceStatus status : changes) { if(status.timestamp <= down_end) continue; newlist.add(status); } } changes = newlist; } } return changes; } }
package crystal.server; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import crystal.client.ClientPreferences; import crystal.client.ProjectPreferences; import crystal.model.ConflictResult.ResultStatus; import crystal.model.DataSource; import crystal.model.DataSource.RepoKind; import crystal.server.HgStateChecker.InvalidHgRepositoryException; import crystal.util.RunIt; public class TestHgStateChecker { private ProjectPreferences _prefs; public TestHgStateChecker() { generatePreferences(); } public ProjectPreferences getPreferences() { return _prefs; } /** * Rebuild the test environment by erasing the old one and extracting a new set of repositories from a zip file. */ @BeforeClass public static void ensureEnvironment() { String projectPath = TestConstants.PROJECT_PATH; Assert.assertNotNull(projectPath); File pp = new File(projectPath); Assert.assertTrue(pp.exists()); Assert.assertTrue(pp.isDirectory()); File[] files = pp.listFiles(); Assert.assertNotNull(files); // make sure the repo zip file exists File repoZipFile = null; for (File f : files) { if (f.getAbsolutePath().endsWith("test-repos.zip")) repoZipFile = f; if (f.getAbsolutePath().endsWith(TestConstants.TEST_REPOS) && f.isDirectory()) { // not sure what the significance of this test is anymore } } Assert.assertNotNull(repoZipFile); // clear the output location File repoDir = new File(projectPath + TestConstants.TEST_REPOS); if (repoDir.exists()) { Assert.assertTrue(repoDir.isDirectory()); RunIt.deleteDirectory(repoDir); Assert.assertFalse(repoDir.exists()); } // unzip the repo zip into the directory File zipOutDir = pp; unzipTestRepositories(repoZipFile, zipOutDir); Assert.assertTrue(repoDir.exists()); // clean the temp space File testTempDir = new File(projectPath + TestConstants.TEST_TEMP); if (testTempDir.exists()) { RunIt.deleteDirectory(testTempDir); Assert.assertFalse(testTempDir.exists()); } boolean testTempDirCreated = testTempDir.mkdir(); Assert.assertTrue(testTempDirCreated); Assert.assertTrue(testTempDir.exists()); Assert.assertTrue(testTempDir.isDirectory()); } @SuppressWarnings("unchecked") private static void unzipTestRepositories(File repoZipFile, File zipOutDir) { try { String outPath = zipOutDir.getAbsolutePath(); if (!outPath.endsWith(File.separator)) outPath += File.separator; System.out.println("Unzipping repository to: " + outPath); ZipFile zipFile = new ZipFile(repoZipFile); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { File outDir = new File(outPath + entry.getName()); outDir.mkdirs(); continue; } copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(outPath + entry.getName()))); } zipFile.close(); } catch (IOException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } System.out.println("Unzipping repository complete."); } private static final void copyInputStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >= 0) out.write(buffer, 0, len); in.close(); out.close(); } @Before public void generatePreferences() { String path = TestConstants.PROJECT_PATH + TestConstants.TEST_REPOS; //TODO: we need to come up with a name for the local master copy of the repository and add it as the 3rd argument below DataSource myEnvironment = new DataSource("myRepository", path + "one", RepoKind.HG); String tempDirectory = TestConstants.PROJECT_PATH + TestConstants.TEST_TEMP; //TODO: we need to come up with a name for the local master copy of the repository and add it as the 3rd argument below DataSource twoSource = new DataSource("twoRepository", path + "two", RepoKind.HG); DataSource threeSource = new DataSource("threeRepository", path + "three", RepoKind.HG); DataSource fourSource = new DataSource("fourRepository", path + "four", RepoKind.HG); DataSource fiveSource = new DataSource("fiveRepository", path + "five", RepoKind.HG); DataSource sixSource = new DataSource("sixRepository", path + "six", RepoKind.HG); ClientPreferences prefs = new ClientPreferences(tempDirectory, TestConstants.HG_COMMAND); _prefs = new ProjectPreferences(myEnvironment, prefs); _prefs.addDataSource(twoSource); _prefs.addDataSource(threeSource); _prefs.addDataSource(fourSource); _prefs.addDataSource(fiveSource); _prefs.addDataSource(sixSource); } @Test public void testBasicMergeConflict() { try { ResultStatus answer = HgStateChecker.getState(_prefs, _prefs.getDataSource("twoRepository")); Assert.assertEquals(ResultStatus.MERGECONFLICT, answer); } catch (IOException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } catch (InvalidHgRepositoryException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } } @Test public void testBasicCleanMerge() { try { ResultStatus answer = HgStateChecker.getState(_prefs, _prefs.getDataSource("sixRepository")); Assert.assertEquals(ResultStatus.MERGECLEAN, answer); } catch (IOException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } catch (InvalidHgRepositoryException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } } @Test public void testBasicAhead() { try { ResultStatus answer = HgStateChecker.getState(_prefs, _prefs.getDataSource("threeRepository")); Assert.assertEquals(ResultStatus.AHEAD, answer); } catch (IOException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } catch (InvalidHgRepositoryException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } } @Test public void testBasicBehind() { try { ResultStatus answer = HgStateChecker.getState(_prefs, _prefs.getDataSource("fourRepository")); Assert.assertEquals(ResultStatus.BEHIND, answer); } catch (IOException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } catch (InvalidHgRepositoryException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } } @Test public void testBasicSame() { try { ResultStatus answer = HgStateChecker.getState(_prefs, _prefs.getDataSource("fiveRepository")); Assert.assertEquals(ResultStatus.SAME, answer); } catch (IOException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } catch (InvalidHgRepositoryException ioe) { ioe.printStackTrace(); Assert.fail(ioe.getMessage()); } } }
package sp.util.function; import java.util.Objects; import java.util.function.Function; /** * <p> * {@link Throwable} 1 . * </p> * * @author Se-foo * @param <X> * . * @since 0.1 */ public interface FunctionWithThrown<X extends Throwable> { /** * <p> * 1 . * </p> * <p> * , {@link #apply(Object)} . * </p> * * @author Se-foo * @param <T> * . * @param <R> * . * @param <X> * . * @since 0.1 */ @FunctionalInterface static interface OfObj<T, R, X extends Throwable> extends FunctionWithThrown<X> { /** * . * * @param target * . * @return . * @throws X * . */ R apply(T target) throws X; /** * before , . * * @param <V> * before . * @param before * . * @return before , . * @throws NullPointerException * before NULL . */ default <V> FunctionWithThrown.OfObj<V, R, X> compose( FunctionWithThrown.OfObj<? super V, ? extends T, ? extends X> before) { Objects.requireNonNull(before); return target -> this.apply(before.apply(target)); } /** * before , . * * @param <V> * before . * @param before * . * @return before , . * @throws NullPointerException * before NULL . */ default <V> FunctionWithThrown.OfObj<V, R, X> composeFunction(Function<? super V, ? extends T> before) { Objects.requireNonNull(before); return target -> this.apply(before.apply(target)); } /** * , after . * * @param <V> * after . * @param after * . * @return , after . * @throws NullPointerException * after NULL . */ default <V> FunctionWithThrown.OfObj<T, V, X> andThen( FunctionWithThrown.OfObj<? super R, ? extends V, ? extends X> after) { Objects.requireNonNull(after); return target -> after.apply(this.apply(target)); } /** * , after . * * @param <V> * after . * @param after * . * @return , after . * @throws NullPointerException * after NULL . */ default <V> FunctionWithThrown.OfObj<T, V, X> andThenFunction(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return target -> after.apply(this.apply(target)); } /** * <p> * {@link java.util.function.Function} . * </p> * <p> * . {@link Throwable} * throwable , . * </p> * * @param throwable * . * @return . * @throws NullPointerException * NULL, NULL . */ default Function<T, R> toFunction(Function<? super Throwable, ? extends RuntimeException> throwable) { Objects.requireNonNull(throwable); return target -> { try { return this.apply(target); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw Objects.requireNonNull(throwable.apply(e)); } catch (Error e) { throw e; } catch (Throwable e) { throw Objects.requireNonNull(throwable.apply(e)); } }; } /** * <p> * {@link java.util.function.Function} . * </p> * <p> * . {@link Throwable} * {@link RuntimeException} . * </p> * * @return . */ default Function<T, R> toFunction() { return this.toFunction(cause -> new RuntimeException(cause)); } } /** * <p> * . * </p> * <p> * , {@link #apply(Object)} . * </p> * * @author Se-foo * @param <T> * . * @param <X> * . * @since 0.1 */ @FunctionalInterface static interface OfObjUnary<T, X extends Throwable> extends FunctionWithThrown.OfObj<T, T, X> { } }
package api.top; import java.util.List; import api.soup.MySoup; //TODO add user and tags. /** * The Class Results. * * @author Gwindow */ public class Results { /** The artist. */ private String artist; /** The data. */ private Number data; /** The encoding. */ private String encoding; /** The format. */ private String format; /** The group category. */ private Number groupCategory; /** The group id. */ private Number groupId; /** The group name. */ private String groupName; /** The group year. */ private Number groupYear; /** The has cue. */ private boolean hasCue; /** The has log. */ private boolean hasLog; /** The leechers. */ private Number leechers; /** The media. */ private String media; /** The remaster title. */ private String remasterTitle; /** The scene. */ private boolean scene; /** The seeders. */ private Number seeders; /** The snatched. */ private Number snatched; /** The size of the torrent */ private Number size; /** The tags. */ private List<String> tags; /** The torrent id. */ private Number torrentId; /** The year. */ private Number year; /** The name. */ private String name; /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Gets the artist. * * @return the artist */ public String getArtist() { return this.artist; } /** * Gets the data. * * @return the data */ public Number getData() { return this.data; } /** * Gets the encoding. * * @return the encoding */ public String getEncoding() { return this.encoding; } /** * Gets the format. * * @return the format */ public String getFormat() { return this.format; } /** * Gets the group category. * * @return the group category */ public Number getGroupCategory() { return this.groupCategory; } /** * Gets the group id. * * @return the group id */ public Number getGroupId() { return this.groupId; } /** * Gets the group name. * * @return the group name */ public String getGroupName() { return this.groupName; } /** * Gets the group year. * * @return the group year */ public Number getGroupYear() { return this.groupYear; } /** * Gets the checks for cue. * * @return the checks for cue */ public boolean getHasCue() { return this.hasCue; } /** * Gets the checks for log. * * @return the checks for log */ public boolean getHasLog() { return this.hasLog; } /** * Gets the leechers. * * @return the leechers */ public Number getLeechers() { return this.leechers; } /** * Gets the media. * * @return the media */ public String getMedia() { return this.media; } /** * Gets the remaster title. * * @return the remaster title */ public String getRemasterTitle() { return this.remasterTitle; } /** * Gets the scene. * * @return the scene */ public boolean getScene() { return this.scene; } /** * Gets the seeders. * * @return the seeders */ public Number getSeeders() { return this.seeders; } /** * Gets the snatched. * * @return the snatched */ public Number getSnatched() { return this.snatched; } /** * Get the size of the torrent, in bytes * * @return torrent size in bytes */ public Number getSize() { return this.size; } /** * Gets the tags. * * @return the tags */ public List<String> getTags() { return this.tags; } /** * Gets the torrent id. * * @return the torrent id */ public Number getTorrentId() { return this.torrentId; } /** * Gets the year. * * @return the year */ public Number getYear() { return this.year; } /** * Gets the download link. * * @return the download link */ public String getDownloadLink() { String authkey = MySoup.getAuthKey(); String passkey = MySoup.getPassKey(); return MySoup.getSite() + "torrents.php?action=download&id=" + torrentId + "&authkey=" + authkey + "&torrent_pass=" + passkey; } @Override public String toString() { return "Results [getArtist()=" + getArtist() + ", getData()=" + getData() + ", getEncoding()=" + getEncoding() + ", getFormat()=" + getFormat() + ", getGroupCategory()=" + getGroupCategory() + ", getGroupId()=" + getGroupId() + ", getGroupName()=" + getGroupName() + ", getGroupYear()=" + getGroupYear() + ", getHasCue()=" + getHasCue() + ", getHasLog()=" + getHasLog() + ", getLeechers()=" + getLeechers() + ", getMedia()=" + getMedia() + ", getRemasterTitle()=" + getRemasterTitle() + ", getScene()=" + getScene() + ", getSeeders()=" + getSeeders() + ", getSnatched()=" + getSnatched() + ", getTags()=" + getTags() + ", getTorrentId()=" + getTorrentId() + ", getYear()=" + getYear() + ", getDownloadLink()=" + getDownloadLink() + "]"; } }
package app; import java.util.Stack; import controllers.common.Move; import view.ButtonGroupView; /** * Singleton for handling undo and redo. * @author Dylan */ public class UndoManager{ /**Holds the only instance if the undoManager that can be reached.**/ private static UndoManager instance = new UndoManager(); /**Stack for tracking moves to be undone**/ static Stack<Move> undoStack; /**Stack for tracking moves to be redone**/ static Stack<Move> redoStack; /**Breaks singleton standard to micro manage the undo/redo buttons for the current view. * This value is set in the constructor of ButtonGroupView, essentially telling the * Undo Manager that the button group view will be using this set of buttons for the given * view instantiation. */ ButtonGroupView bgv; /**Private constructor prevents further instantiations**/ private UndoManager(){ if(instance != null){throw new IllegalStateException("Alredy Instantiated");} undoStack = new Stack<Move>(); redoStack = new Stack<Move>(); } public void pushMove(Move m){ if(bgv != null){ bgv.setUndoEnabled(true); //TODO set undo button enabled } UndoManager.undoStack.push(m); UndoManager.redoStack.clear(); } /** * Undoes the move on top of the undo stack by: * 1) Popping the move * 2) Calling the move's undo * 3) Pushing the move onto the redo stack * Undo fails if there are no moves in the stack for it to undo. * @return true if the undo could be done */ public boolean undo(){ if(UndoManager.undoStack.empty()){return false;} bgv.setRedoEnabled(true);//TODO enable the redo button Move m = UndoManager.undoStack.pop(); m.undo(); UndoManager.redoStack.push(m); if(UndoManager.undoStack.empty()){bgv.setUndoEnabled(false);}//TODO IF emptied, disable return true; } /** * Redoes the move on top of the redo stack by: * 1) Popping the move * 2) Calling the move's redo * 3) Pushing the move onto the undo stack * Redo fails if there are no moves in the stack for it to redo. * @return true if the redo could be done */ public boolean redo(){ if(UndoManager.redoStack.empty()){ return false;} bgv.setUndoEnabled(true);//TODO enable the undo button Move m = UndoManager.redoStack.pop(); m.redo(); UndoManager.undoStack.push(m); if(UndoManager.redoStack.empty()){bgv.setRedoEnabled(false);}//TODO if emptied, disable return true; } /** * Gives the singleton a button group to be modified. This value is a changing value, * given when a button group view is instantiated/ * @param bgv - the button group being manipulated */ public void giveButtonGroup(ButtonGroupView bgv){ this.bgv = bgv; } /** * Clears the stacks of all undos and redos. This is for the * sake of operating between builder view instances. */ public void flush(){ UndoManager.redoStack.clear(); UndoManager.undoStack.clear(); } /** * Returns the singular instance of the UndoManager that is created * @return the UndoManager object */ public static UndoManager getInstance(){ return instance; } }
package ed.util; import java.io.File; import org.testng.annotations.Test; import ed.js.JSFunction; import ed.js.func.JSFunctionCalls0; import ed.util.ScriptTestInstance; import ed.js.engine.Scope; import ed.js.Shell; import ed.MyAsserts; /** * Dynamic test instance for testing any 10genPlatform script * * Code stolen lock, stock and barrel from ConvertTest. Uses exact same convention * and scheme for comparing output */ public abstract class ScriptTestInstanceBase extends MyAsserts implements ScriptTestInstance{ File _file; public ScriptTestInstanceBase() { } public void setTestScriptFile(File f) { _file = f; } public File getTestScriptFile() { return _file; } /** * Test method for running a script * * @throws Exception in case of failure */ @Test public void test() throws Exception { System.out.println("ScriptTestInstanceBase : running " + _file); JSFunction f = convert(); Scope scope = Scope.GLOBAL.child(new File("/tmp")); /* * augment the scope */ preTest(scope); Shell.addNiceShellStuff(scope); scope.put( "exit" , new JSFunctionCalls0(){ public Object call( Scope s , Object crap[] ){ System.err.println("JSTestInstance : exit() called from " + _file.toString() + " Ignoring."); return null; } } , true ); try { f.call(scope); validateOutput(scope); } catch (RuntimeException re) { throw new Exception("For file " + _file.toString(), re); } } }
package com.brettonw.bag; import com.brettonw.AppTest; import org.junit.Test; import java.io.IOException; public class HttpTest { @Test public void test () { } @Test public void testGet () throws IOException { BagObject brettonw = BagObjectFrom.url ("https://httpbin.org/ip", () -> null); AppTest.report (brettonw.getString ("origin") != null, true, "Got a valid BagObject"); BagArray repos = BagArrayFrom.url ("https://api.github.com/users/brettonw/repos", () -> null); AppTest.report (repos.getCount () > 0, true, "Got a valid BagArray"); } @Test public void testPost () throws IOException { BagObject postResponseBagObject = BagObjectFrom.url ("http://jsonplaceholder.typicode.com/posts/", new BagObject () .put ("login", "brettonw") .put ("First Name", "Bretton") .put ("Last Name", "Wade"), MimeType.JSON, () -> null ); AppTest.report (postResponseBagObject.getString ("login"), "brettonw", "Got a valid BagObject - 1"); postResponseBagObject = BagObjectFrom.url ("http://jsonplaceholder.typicode.com/posts/", new BagObject () .put ("login", "brettonw") .put ("First Name", "Bretton") .put ("Last Name", "Wade"), MimeType.JSON ); AppTest.report (postResponseBagObject.getString ("login"), "brettonw", "Got a valid BagObject - 2"); BagArray postResponseBagArray = BagArrayFrom.url ("http://jsonplaceholder.typicode.com/posts/", new BagArray () .add ("login") .add ("brettonw") .add ("First Name") .add ("Bretton") .add ("Last Name") .add ("Wade"), MimeType.JSON ); AppTest.report (postResponseBagArray.getString (1), "brettonw", "Got a valid BagArray - 1"); postResponseBagArray = BagArrayFrom.url ("http://jsonplaceholder.typicode.com/posts/", new BagArray () .add ("login") .add ("brettonw") .add ("First Name") .add ("Bretton") .add ("Last Name") .add ("Wade"), MimeType.JSON, () -> null ); AppTest.report (postResponseBagArray.getString (1), "brettonw", "Got a valid BagArray - 2"); } @Test public void testBogusGet () throws IOException { BagObject bogus = BagObjectFrom.url ("http://gojsonogle.com", () -> null); AppTest.report (bogus, null, "Not a valid URL"); } @Test public void testBogusPost () throws IOException { BagObject bogus = BagObjectFrom.url ("http://gojsonogle.com", new BagObject ().put ("a", "b"), MimeType.JSON, () -> null); AppTest.report (bogus, null, "Not a valid URL"); } }
package com.k13n.lt_codes; import java.io.*; import java.net.URL; import org.junit.Test; import static org.junit.Assert.*; public class AppTest { private static final String FILENAME = "firework.jpg"; private static final String OUTFILE = "/tmp/" + FILENAME + ".out"; private static final int PACKET_SIZE = 1024; @Test public void itWorksWithPerfectChannel() throws Exception { byte[] data = readFile(FILENAME); Encoder enc = new Encoder(data, PACKET_SIZE); // final Decoder dec = new DefaultDecoder(enc.getSeed(), enc.getNPackets()); final Decoder dec = new IncrementalDecoder(enc.getNPackets(), PACKET_SIZE); enc.encode(new Encoder.Callback() { public boolean call(Encoder encoder, TransmissonPacket packet) { return dec.receive(packet); } }); dec.write(new FileOutputStream(OUTFILE)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); dec.write(bos); assertArrayEquals(data, bos.toByteArray()); } @Test public void itWorksWithLossyChannel() throws Exception { byte[] data = readFile(FILENAME); Encoder enc = new Encoder(data, PACKET_SIZE); // final Decoder dec = new DefaultDecoder(enc.getSeed(), enc.getNPackets()); final Decoder dec = new IncrementalDecoder(enc.getNPackets(), PACKET_SIZE); final ErasureChannel channel = new ErasureChannel( new ErasureChannel.Callback() { @Override public void call(ErasureChannel channel, TransmissonPacket packet) { dec.receive(packet); } }, 0.3); enc.encode(new Encoder.Callback() { public boolean call(Encoder encoder, TransmissonPacket packet) { channel.transmit(packet); return dec.isDecodingFinished(); } }); dec.write(new FileOutputStream(OUTFILE)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); dec.write(bos); assertArrayEquals(data, bos.toByteArray()); } private byte[] readFile(String filename) { filename = "/" + filename; byte[] data = null; try { URL url = this.getClass().getResource(filename); InputStream is = getClass().getResourceAsStream(filename); assertNotNull(url); File file = new File(url.getFile()); data = new byte[(int) file.length()]; DataInputStream s = new DataInputStream(is); s.readFully(data); s.close(); } catch (IOException e) { e.printStackTrace(); } return data; } }
package objektwerks; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class CustomException extends Exception { CustomException(String message) { super(message); } } class ExceptionTest { @Test void checkedTest() { assertThrows(IOException.class, () -> { var path = Paths.get("build.gradle"); var lines = Files.readAllLines(path); assert(!lines.isEmpty()); }); } @Test void uncheckedTest() { assertThrows(NumberFormatException.class, () -> { var i = Integer.parseInt("one"); assert(i == 1); }); } @Test void tryCatchTest() { var i = 0; try { i = Integer.parseInt("one"); } catch (NumberFormatException exception) { i = -1; } assert(i == -1); } @Test void customTest() { assertThrows(CustomException.class, () -> { if (new Random().nextInt() != 0) throw new CustomException("int != 0"); }); } }
package org.opennars.core; import org.junit.Test; import org.junit.experimental.ParallelComputer; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runners.Parameterized; import org.opennars.io.events.TextOutputHandler; import org.opennars.main.Nar; import org.opennars.main.MiscFlags; import org.opennars.storage.Memory; import org.opennars.util.io.ExampleFileInput; import org.opennars.util.test.OutputCondition; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.*; import static org.junit.Assert.assertTrue; @RunWith(Parameterized.class) public class NALTest { final int minCycles = 1550; //TODO reduce this to one or zero to avoid wasting any extra time during tests static public boolean showOutput = false; static public boolean showSuccess = false; static public final boolean showFail = true; static public final boolean showReport = true; static public final boolean requireSuccess = true; static public final int similarsToSave = 5; protected static final Map<String, String> examples = new HashMap<>(); //path -> script data public static final Map<String, Boolean> tests = new HashMap<>(); public static final Map<String, Double> scores = new HashMap<>(); final String scriptPath; public static String getExample(final String path) { try { String existing = examples.get(path); if (existing!=null) return existing; existing = ExampleFileInput.load(path); examples.put(path, existing); return existing; } catch (final IOException e) { throw new IllegalStateException("Could not load path", e); } } public Nar newNAR() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { return new Nar(); } @Parameterized.Parameters public static Collection params() { final String[] directories = new String[] { "/nal/single_step/", "/nal/multi_step/", "/nal/application/" }; final Map<String, Object> et = ExampleFileInput.getUnitTests(directories); final Collection t = et.values(); for (final String x : et.keySet()) addTest(x); return t; } public static void addTest(String name) { name = name.substring(3, name.indexOf(".nal")); tests.put(name, true); } public static double runTests(final Class c) { tests.clear(); scores.clear(); final Result result = JUnitCore.runClasses(new ParallelComputer(true, true), c); for (final Failure f : result.getFailures()) { final String test = f.getMessage().substring(f.getMessage().indexOf("/nal/single_step") + 8, f.getMessage().indexOf(".nal")); tests.put(test, false); } final int[] levelSuccess = new int[10]; final int[] levelTotals = new int[10]; for (final Map.Entry<String, Boolean> e : tests.entrySet()) { final String name = e.getKey(); int level = 0; level = Integer.parseInt(name.split("\\.")[0]); levelTotals[level]++; if (e.getValue()) { levelSuccess[level]++; } } double totalScore = 0; for (final Double d : scores.values()) totalScore += d; if (showReport) { int totalSucceeded = 0, total = 0; for (int i = 0; i < 9; i++) { final float rate = (levelTotals[i] > 0) ? ((float)levelSuccess[i]) / levelTotals[i] : 0; final String prefix = (i > 0) ? ("NAL" + i) : "Other"; System.out.println(prefix + ": " + (rate*100.0) + "% (" + levelSuccess[i] + "/" + levelTotals[i] + ")" ); totalSucceeded += levelSuccess[i]; total += levelTotals[i]; } System.out.println(totalSucceeded + " / " + total); System.out.println("Score: " + totalScore); } return totalScore; } public NALTest(final String scriptPath) { this.scriptPath = scriptPath; } public double testNAL(final String path) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { Memory.resetStatic(); final String example = getExample(path); if (showOutput) { System.out.println(example); System.out.println(); } Nar n = newNAR(); final List<OutputCondition> extractedExpects = OutputCondition.getConditions(n, example, similarsToSave); final List<OutputCondition> expects = new ArrayList<>(extractedExpects); if (showOutput) { new TextOutputHandler(n, System.out); } n.addInputFile(path); n.cycles(minCycles); if (showOutput) { System.err.flush(); System.out.flush(); } boolean success = expects.size() > 0; for (final OutputCondition e: expects) { if (!e.succeeded) { success = false; } } double score = Double.POSITIVE_INFINITY; if (success) { long lastSuccess = -1; for (final OutputCondition e: expects) { if (e.getTrueTime()!=-1) { if (lastSuccess < e.getTrueTime()) { lastSuccess = e.getTrueTime(); } } } if (lastSuccess!=-1) { //score = 1.0 + 1.0 / (1+lastSuccess); score = lastSuccess; scores.put(path, score); } } else { scores.put(path, Double.POSITIVE_INFINITY); } //System.out.println(lastSuccess + " , " + path + " \t excess cycles=" + (n.time() - lastSuccess) + " end=" + n.time()); if ((!success & showFail) || (success && showSuccess)) { System.err.println('\n' + path + " @" + n.time()); for (final OutputCondition e: expects) { System.err.println(" " + e); } } if (requireSuccess) { assertTrue(path, success); } return score; } @Test public void test() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { testNAL(scriptPath); } public static void main(final String[] args) { runTests(NALTest.class); } static { Memory.randomNumber.setSeed(1); MiscFlags.DEBUG = false; MiscFlags.TEST = true; } }
package product; import operators.base.BuildOperator; import operators.base.RefreshOperator; import operators.configurations.BuildConfigurationSetPageOperator; import operators.products.ProductPageOperator; import operators.projects.ProjectPageOperator; import operators.products.ImportPageOperator; import org.junit.Test; import ui.UITest; public class ImportProductTest extends UITest { @Test public void pncSimpleProject() { importConfig("pnc-simple-test", "1.0", "PNC Simple Test", "https://github.com/project-ncl/pnc-simple-test-project.git", "master", "mvn clean deploy"); } @Test public void sso() { ssoConfig("1.9.x-redhat"); } @Test public void sso190() { ssoConfig("1.9.0.Final-redhat"); } @Test public void jdg() { importConfig("jdg-infinispan", "7.0", "JDG Infinispan", "http://git.app.eng.bos.redhat.com/infinispan/infinispan.git", "JDG_7.0.0.ER4_pnc_wa_4", "mvn clean deploy -Pdistribution -DskipTests=true"); } @Test public void fabric8() { importConfig("fabric8", "8.0", "Fabric8", "https://github.com/fabric8io/fabric8.git", "master", "mvn clean deploy -DskipTests=true"); } @Test public void keycloak() { importConfig("keycloak", "1.9", "Keycloak", "https://github.com/keycloak/keycloak.git", "master", "mvn clean deploy -Pdistribution -DskipTests=true"); } @Test public void pnc() { importConfig("pnc-ncl", "1.0", "PNC NCL", "https://github.com/project-ncl/pnc.git", "master", "mvn clean deploy -DskipTests=true"); } @Test public void pnc09() { importConfig("pnc-ncl", "1.0", "PNC NCL", "https://github.com/project-ncl/pnc.git", "v0.9", "mvn clean deploy -DskipTests=true"); } private void ssoConfig(String branch) { importConfig("keycloak", "1.9", "RH SSO", "http://git.app.eng.bos.redhat.com/git/keycloak-prod.git", branch, "mvn clean deploy -Pdistribution -DskipTests=true"); } private void importConfig(String... param) { new ProductPageOperator(param[0]).createProduct(param[2] + " product"); new RefreshOperator().refresh(); new ProjectPageOperator(param[0]).createProject(param[2] + " project"); new RefreshOperator().refresh(); ImportPageOperator product = new ImportPageOperator(param[0]); product.importProduct(param[1], param[3], param[4], param[5]); product.buildConfigurationSet(); String buildName = product.getConfigSetName(); new BuildConfigurationSetPageOperator(buildName).menuBuildGroups(); assertLinkExists(buildName); } }
package tests; import backend.resource.Model; import backend.resource.TurboLabel; import backend.resource.TurboMilestone; import filter.Parser; import filter.expression.FilterExpression; import filter.expression.Qualifier; import org.junit.Test; import static org.junit.Assert.*; import backend.interfaces.IModel; import filter.expression.QualifierType; import java.time.LocalDate; import java.util.*; public class MilestoneAliasTests { private IModel model; public static final String REPO = "test/test"; @Test public void replaceMilestoneAliasesTest() { // test: overdue open milestone with no open issues would not be current milestone TurboMilestone msCurrMin3 = new TurboMilestone(REPO, 10, "V0.1"); msCurrMin3.setOpen(true); msCurrMin3.setOpenIssues(0); msCurrMin3.setDueDate(Optional.of(LocalDate.now().minusMonths(2))); // test: sort by due date is correct TurboMilestone msCurrMin2 = new TurboMilestone(REPO, 9, "V0.2"); msCurrMin2.setOpen(false); msCurrMin2.setDueDate(Optional.of(LocalDate.now().minusMonths(1))); // test: future closed milestone will not be current milestone TurboMilestone msCurrMin1 = new TurboMilestone(REPO, 8, "V0.3"); msCurrMin1.setOpen(false); msCurrMin1.setDueDate(Optional.of(LocalDate.now().plusDays(1))); // test: earliest future open milestone with 0 open issues will // be current milestone TurboMilestone msCurr = new TurboMilestone(REPO, 7, "V0.4"); msCurr.setOpen(true); msCurr.setOpenIssues(0); msCurr.setDueDate(Optional.of(LocalDate.now().plusMonths(1))); // test: sort by due date is correct, even if in the future but // closed TurboMilestone msCurrPlus1 = new TurboMilestone(REPO, 6, "V0.5"); msCurrPlus1.setOpen(false); msCurrPlus1.setDueDate(Optional.of(LocalDate.now().plusMonths(2))); // test: sort by due date is correct TurboMilestone msCurrPlus2 = new TurboMilestone(REPO, 5, "V0.6"); msCurrPlus2.setOpen(true); msCurrPlus2.setDueDate(Optional.of(LocalDate.now().plusMonths(3))); // test: milestone with no due date should not be included TurboMilestone msCurrPlus3 = new TurboMilestone(REPO, 4, "V0.7"); msCurrPlus3.setDueDate(Optional.empty()); model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(msCurrMin3, msCurrMin2, msCurrMin1, msCurr, msCurrPlus1, msCurrPlus2, msCurrPlus3)), new ArrayList<>())); FilterExpression noMilestoneAlias; List<Qualifier> milestoneQualifiers; // test correct conversion noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current-3")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(false, msQ.getContent().get().equalsIgnoreCase("current-3")); assertEquals(true, msQ.getContent().get().equalsIgnoreCase("V0.1")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr-2")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(false, msQ.getContent().get().equalsIgnoreCase("curr-2")); assertEquals(true, msQ.getContent().get().equalsIgnoreCase("V0.2")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr-1")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(false, msQ.getContent().get().equalsIgnoreCase("curr-1")); assertEquals(true, msQ.getContent().get().equalsIgnoreCase("V0.3")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(false, msQ.getContent().get().equalsIgnoreCase("curr")); assertEquals(true, msQ.getContent().get().equalsIgnoreCase("V0.4")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current+1")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(false, msQ.getContent().get().equalsIgnoreCase("current+1")); assertEquals(true, msQ.getContent().get().equalsIgnoreCase("V0.5")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr+2")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(false, msQ.getContent().get().equalsIgnoreCase("curr+2")); assertEquals(true, msQ.getContent().get().equalsIgnoreCase("V0.6")); }); // test milestone no due date not included assertMilestoneAliasFalseQualifierSize1("milestone:curr+3"); // test alias out of bound will be converted to Qualifier.FALSE assertMilestoneAliasFalseQualifierSize1("milestone:curr-4"); assertMilestoneAliasFalseQualifierSize1("milestone:current+4"); // test wrong alias will not be converted noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr-")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("curr-")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current-")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("current-")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr-asdf")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("curr-asdf")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr+")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("curr+")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current+")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("current+")); }); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current+4asdf")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("current+4asdf")); }); // test disjunction and conjunction noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr+2 || milestone:curr+3")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); assertEquals(false, milestoneQualifiers.get(0).getContent().get().equalsIgnoreCase("curr+2")); assertEquals(true, milestoneQualifiers.get(0).getContent().get().equalsIgnoreCase("V0.6")); noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:curr+2 && milestone:curr+3")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); assertEquals(false, milestoneQualifiers.get(0).isFalse()); } @Test public void replaceMilestoneAliasesTestNoRelevantMilestone() { //every milestone with due date is irrelevant TurboMilestone msIrrelevant1 = new TurboMilestone(REPO, 1, "irrelevant1"); msIrrelevant1.setDueDate(Optional.of(LocalDate.now().minusDays(1))); msIrrelevant1.setOpen(true); TurboMilestone msIrrelevant2 = new TurboMilestone(REPO, 2, "irrelevant2"); msIrrelevant2.setDueDate(Optional.of(LocalDate.now().minusDays(2))); msIrrelevant1.setOpen(true); TurboMilestone msRelevant1 = new TurboMilestone(REPO, 3, "relevant1"); msRelevant1.setDueDate(Optional.empty()); msRelevant1.setOpen(true); TurboMilestone msRelevant2 = new TurboMilestone(REPO, 4, "relevant2"); msRelevant2.setDueDate(Optional.empty()); msRelevant2.setOpen(true); model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(msIrrelevant1, msIrrelevant2)), new ArrayList<>() )); FilterExpression expr = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current")); List<Qualifier> milestoneQualifiers = expr.find(Qualifier::isMilestoneQualifier); assertEquals(0, milestoneQualifiers.size()); model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(msIrrelevant1, msIrrelevant2, msRelevant1)), new ArrayList<>() )); expr = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current")); milestoneQualifiers = expr.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals("relevant1", msQ.getContent().get()); }); expr = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current-2")); milestoneQualifiers = expr.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals("irrelevant2", msQ.getContent().get()); }); expr = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current-3")); milestoneQualifiers = expr.find(Qualifier::isMilestoneQualifier); assertEquals(0, milestoneQualifiers.size()); model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(msIrrelevant1, msIrrelevant2, msRelevant1, msRelevant2)), new ArrayList<>() )); expr = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current")); milestoneQualifiers = expr.find(Qualifier::isMilestoneQualifier); assertEquals(0, milestoneQualifiers.size()); } @Test public void replaceMilestoneAliasesTestNoOpenMilestone() { // - expect next to last milestone (i.e. don't exist yet) to be set as current // - all milestones are closed and due in the future TurboMilestone msClose1 = new TurboMilestone(REPO, 1, "future1"); msClose1.setOpen(false); msClose1.setDueDate(Optional.of(LocalDate.now().plusMonths(2))); TurboMilestone msClose2 = new TurboMilestone(REPO, 2, "future2"); msClose2.setOpen(false); msClose2.setDueDate(Optional.of(LocalDate.now().plusMonths(3))); TurboMilestone msClose3 = new TurboMilestone(REPO, 3, "future3"); msClose3.setOpen(false); msClose3.setDueDate(Optional.of(LocalDate.now().plusMonths(4))); model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(msClose1, msClose2, msClose3)), new ArrayList<>())); assertMilestoneAliasFalseQualifierSize1("milestone:current"); assertMilestoneAliasFalseQualifierSize1("milestone:current+1"); FilterExpression noMilestoneAlias; List<Qualifier> milestoneQualifiers; noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse("milestone:current-1")); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); milestoneQualifiers.stream().forEach(msQ -> { assertEquals(true, msQ.getContent().get().equalsIgnoreCase("future3")); }); } public void assertMilestoneAliasFalseQualifierSize1(String filterText) { FilterExpression noMilestoneAlias; List<Qualifier> milestoneQualifiers; noMilestoneAlias = Qualifier.replaceMilestoneAliases(model, Parser.parse(filterText)); assertEquals(noMilestoneAlias.getQualifierTypes().size(), 1); assertEquals(noMilestoneAlias.getQualifierTypes().get(0), QualifierType.FALSE); milestoneQualifiers = noMilestoneAlias.find(Qualifier::isMilestoneQualifier); assertEquals(milestoneQualifiers.size(), 0); } }
package twitter4j; import junit.framework.TestCase; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Properties; /** * @author Yusuke Yamamoto - yusuke at mac.com */ public class TwitterTestUnit extends TestCase { protected Twitter twitterAPI1 = null; protected Twitter twitterAPI2 = null; protected Twitter unauthenticated = null; protected Properties p = new Properties(); public TwitterTestUnit(String name) { super(name); } protected String id1,id2,id3,pass1,pass2,pass3; protected void setUp() throws Exception { super.setUp(); p.load(new FileInputStream("test.properties")); id1 = p.getProperty("id1"); id2 = p.getProperty("id2"); id3 = p.getProperty("id3"); pass1 = p.getProperty("pass1"); pass2 = p.getProperty("pass2"); pass3 = p.getProperty("pass3"); twitterAPI1 = new Twitter(id1, pass1); // twitterAPI1.setRetryCount(5); // twitterAPI1.setRetryIntervalSecs(5); twitterAPI2 = new Twitter(id2, pass2); // twitterAPI2.setRetryCount(5); // twitterAPI2.setRetryIntervalSecs(5); unauthenticated = new Twitter(); // unauthenticated.setRetryCount(5); // unauthenticated.setRetryIntervalSecs(5); } protected void tearDown() throws Exception { super.tearDown(); } public void testGetPublicTimeline() throws Exception { List<Status> statuses; statuses = twitterAPI1.getPublicTimeline(); assertTrue("size", 5 < statuses.size()); statuses = twitterAPI1.getPublicTimeline(12345l); assertTrue("size", 5 < statuses.size()); } public void testGetFriendsTimeline()throws Exception { Date startDate = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); String dateStr = (cal.get(Calendar.MONTH)+1)+"/"+cal.get(Calendar.DATE); String id1status = dateStr+":id1"; String id2status = dateStr+":id2"; Status status = twitterAPI1.updateStatus(id1status); assertEquals(id1status, status.getText()); Thread.sleep(3000); Status status2 = twitterAPI2.updateStatus(id2status); assertEquals(id2status, status2.getText()); List<Status> actualReturn; actualReturn = twitterAPI1.getFriendsTimeline(); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFriendsTimeline(new Paging(1l)); assertTrue(actualReturn.size() > 0); //this is necessary because the twitter server's clock tends to delay actualReturn = twitterAPI1.getFriendsTimeline(new Paging(1000l)); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFriendsTimeline(new Paging(1)); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFriendsTimeline(new Paging(1)); assertTrue(actualReturn.size() > 0); } public void testShowUser() throws Exception{ User uws = twitterAPI1.showUser(id1); assertEquals(id1, uws.getName()); assertEquals(id1,uws.getScreenName()); assertNotNull(uws.getLocation()); assertNotNull(uws.getDescription()); assertNotNull(uws.getProfileImageURL()); assertNotNull(uws.getURL()); assertFalse(uws.isProtected()); assertTrue(0 <= uws.getFavouritesCount()); assertTrue(0 <= uws.getFollowersCount()); assertTrue(0 <= uws.getFriendsCount()); assertNotNull(uws.getCreatedAt()); assertNotNull(uws.getTimeZone()); assertNotNull(uws.getProfileBackgroundImageUrl()); assertNotNull(uws.getProfileBackgroundTile()); assertTrue(0 <= uws.getStatusesCount()); assertNotNull(uws.getProfileBackgroundColor()); assertNotNull(uws.getProfileTextColor()); assertNotNull(uws.getProfileLinkColor()); assertNotNull(uws.getProfileSidebarBorderColor()); assertNotNull(uws.getProfileSidebarFillColor()); assertNotNull(uws.getProfileTextColor()); assertTrue(1 < uws.getFollowersCount()); assertNotNull(uws.getStatusCreatedAt()); assertNotNull(uws.getStatusText()); assertNotNull(uws.getStatusSource()); assertFalse(uws.isStatusFavorited()); assertEquals(-1,uws.getStatusInReplyToStatusId()); assertEquals(-1,uws.getStatusInReplyToUserId()); assertFalse(uws.isStatusFavorited()); assertNull(uws.getStatusInReplyToScreenName()); //test case for TFJ-91 null pointer exception getting user detail on users with no statuses unauthenticated.showUser("twit4jnoupdate"); twitterAPI1.showUser("tigertest"); } public void testGetUserTimeline_Show() throws Exception{ List<Status> statuses; statuses = twitterAPI1.getUserTimeline(); assertTrue("size", 0 < statuses.size()); statuses = unauthenticated.getUserTimeline(id1); assertTrue("size", 0 < statuses.size()); statuses = twitterAPI1.getUserTimeline(new Paging(999383469l)); assertTrue("size", 0 < statuses.size()); statuses = twitterAPI2.getUserTimeline(id1, new Paging().count(10)); assertTrue("size", 0 < statuses.size()); // statuses = twitterAPI1.getUserTimeline(15, new Date(0)); // assertTrue("size", 0 < statuses.size()); statuses = twitterAPI1.getUserTimeline(new Paging(999383469l).count(15)); assertTrue("size", 0 < statuses.size()); // statuses = twitterAPI1.getUserTimeline(id1, new Date(0)); // assertTrue("size", 0 < statuses.size()); statuses = twitterAPI1.getUserTimeline(id1,new Paging(999383469l)); assertTrue("size", 0 < statuses.size()); } public void testShow() throws Exception{ Status status = twitterAPI2.showStatus(1000l); assertEquals(52,status.getUser().getId()); Status status2 = unauthenticated.showStatus(1000l); assertEquals(52,status2.getUser().getId()); assertTrue(50 < status.getRateLimitLimit()); assertTrue(1 < status.getRateLimitRemaining()); assertTrue(1 < status.getRateLimitReset()); status2 = unauthenticated.showStatus(999383469l); assertEquals("01010100 01110010 01101001 01110101 01101101 01110000 01101000 <3",status2.getText()); } public void testStatusMethods() throws Exception{ String date = new java.util.Date().toString()+"test"; Status status = twitterAPI1.updateStatus(date); assertEquals(date, status.getText()); Status status2 = twitterAPI2.updateStatus("@" + id1 + " " + date, status.getId()); assertEquals("@" + id1 + " " + date, status2.getText()); assertEquals(status.getId(), status2.getInReplyToStatusId()); assertEquals(twitterAPI1.verifyCredentials().getId(), status2.getInReplyToUserId()); twitterAPI1.destroyStatus(status.getId()); } public void testGetFriendsStatuses() throws Exception{ List<User> actualReturn = twitterAPI1.getFriendsStatuses(); assertNotNull("friendsStatuses", actualReturn); actualReturn = twitterAPI1.getFriendsStatuses("yusukey"); assertNotNull("friendsStatuses", actualReturn); actualReturn = unauthenticated.getFriendsStatuses("yusukey"); assertNotNull("friendsStatuses", actualReturn); } public void testSocialGraphMethods() throws Exception { IDs ids; ids = twitterAPI1.getFriendsIDs(); int yusukey = 4933401; assertIDExsits("twit4j is following yusukey", ids, yusukey); int JBossNewsJP = 28074579; int RedHatNewsJP = 28074306; ids = twitterAPI1.getFriendsIDs(JBossNewsJP); assertIDExsits("JBossNewsJP is following RedHatNewsJP", ids, RedHatNewsJP); ids = twitterAPI1.getFriendsIDs("RedHatNewsJP"); assertIDExsits("RedHatNewsJP is following JBossNewsJP", ids, 28074579); followEachOther(); ids = twitterAPI1.getFollowersIDs(); assertTrue("number of followers", ids.getIDs().length > 1); ids = twitterAPI1.getFollowersIDs(28074579); assertIDExsits("RedHatNewsJP is following JBossNewsJP", ids, 28074306); ids = twitterAPI1.getFollowersIDs("JBossNewsJP"); assertIDExsits("RedHatNewsJP is following JBossNewsJP", ids, 28074306); } private void assertIDExsits(String assertion, IDs ids, int idToFind) { boolean found = false; for (int id : ids.getIDs()) { if (id == idToFind) { found = true; break; } } assertTrue(assertion, found); } public void testAccountMethods() throws Exception { User original = twitterAPI1.verifyCredentials(); if(original.getScreenName().endsWith("new") || original.getName().endsWith("new")){ original = twitterAPI1.updateProfile( "twit4j", null, "http://yusuke.homeip.net/twitter4j/" , "location:" , "Hi there, I do test a lot!new"); } String newName, newURL, newLocation, newDescription; String neu = "new"; newName = original.getName() + neu; newURL = original.getURL() + neu; newLocation = original.getLocation()+neu; newDescription = original.getDescription()+neu; User altered = twitterAPI1.updateProfile( newName, null, newURL, newLocation, newDescription); twitterAPI1.updateProfile(original.getName() , null, original.getURL().toString(), original.getLocation(), original.getDescription()); assertEquals(newName, altered.getName()); assertEquals(newURL, altered.getURL().toString()); assertEquals(newLocation, altered.getLocation()); assertEquals(newDescription, altered.getDescription()); try { new Twitter("doesnotexist--", "foobar").verifyCredentials(); fail("should throw TwitterException"); } catch (TwitterException te) { } twitterAPI1.updateDeliverlyDevice(Twitter.SMS); assertTrue(twitterAPI1.existsFriendship("JBossNewsJP", "RedHatNewsJP")); assertFalse(twitterAPI1.existsFriendship(id1,"al3x")); User eu; eu = twitterAPI1.updateProfileColors("f00", "f0f", "0ff", "0f0", "f0f"); assertEquals("f00", eu.getProfileBackgroundColor()); assertEquals("f0f", eu.getProfileTextColor()); assertEquals("0ff", eu.getProfileLinkColor()); assertEquals("0f0", eu.getProfileSidebarFillColor()); assertEquals("f0f", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("f0f", "f00", "f0f", "0ff", "0f0"); assertEquals("f0f", eu.getProfileBackgroundColor()); assertEquals("f00", eu.getProfileTextColor()); assertEquals("f0f", eu.getProfileLinkColor()); assertEquals("0ff", eu.getProfileSidebarFillColor()); assertEquals("0f0", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("87bc44", "9ae4e8", "000000", "0000ff", "e0ff92"); assertEquals("87bc44", eu.getProfileBackgroundColor()); assertEquals("9ae4e8", eu.getProfileTextColor()); assertEquals("000000", eu.getProfileLinkColor()); assertEquals("0000ff", eu.getProfileSidebarFillColor()); assertEquals("e0ff92", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("f0f", null, "f0f", null, "0f0"); assertEquals("f0f", eu.getProfileBackgroundColor()); assertEquals("9ae4e8", eu.getProfileTextColor()); assertEquals("f0f", eu.getProfileLinkColor()); assertEquals("0000ff", eu.getProfileSidebarFillColor()); assertEquals("0f0", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors(null, "f00", null, "0ff", null); assertEquals("f0f", eu.getProfileBackgroundColor()); assertEquals("f00", eu.getProfileTextColor()); assertEquals("f0f", eu.getProfileLinkColor()); assertEquals("0ff", eu.getProfileSidebarFillColor()); assertEquals("0f0", eu.getProfileSidebarBorderColor()); eu = twitterAPI1.updateProfileColors("9ae4e8", "000000", "0000ff", "e0ff92", "87bc44"); assertEquals("9ae4e8", eu.getProfileBackgroundColor()); assertEquals("000000", eu.getProfileTextColor()); assertEquals("0000ff", eu.getProfileLinkColor()); assertEquals("e0ff92", eu.getProfileSidebarFillColor()); assertEquals("87bc44", eu.getProfileSidebarBorderColor()); } public void testFavoriteMethods() throws Exception{ Status status = twitterAPI1.updateStatus("test"); twitterAPI2.createFavorite(status.getId()); assertTrue(twitterAPI2.getFavorites().size() > 0); try { twitterAPI2.destroyFavorite(status.getId()); } catch (TwitterException te) { // sometimes destorying favorite fails with 404 assertEquals(404, te.getStatusCode()); } } public void testFollowers() throws Exception{ List<User> actualReturn = twitterAPI1.getFollowersStatuses(); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFollowersStatuses(new Paging(1)); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI1.getFollowersStatuses(new Paging(2)); assertEquals(0,actualReturn.size()); actualReturn = twitterAPI2.getFollowersStatuses(); assertTrue(actualReturn.size() > 0); actualReturn = twitterAPI2.getFollowersStatuses("yusukey"); assertTrue(actualReturn.size() > 60); actualReturn = twitterAPI2.getFollowersStatuses("yusukey",new Paging(2)); assertTrue(actualReturn.size() > 10); } public void testFeatured() throws Exception{ List<User> actualReturn = twitterAPI1.getFeatured(); assertTrue(actualReturn.size() > 9); } public void testDirectMessages() throws Exception { String expectedReturn = new Date() + ":directmessage test"; DirectMessage actualReturn = twitterAPI1.sendDirectMessage("twit4jnoupdate", expectedReturn); assertEquals(expectedReturn, actualReturn.getText()); List<DirectMessage> actualReturnList = twitterAPI1.getDirectMessages(); assertTrue(1<= actualReturnList.size()); } private void followEachOther() { try { twitterAPI1.createFriendship(id2); } catch (TwitterException te) { te.printStackTrace(); } try { twitterAPI2.createFriendship(id1); } catch (TwitterException te) { te.printStackTrace(); } } public void testCreateDestroyFriend() throws Exception{ User user; try { user = twitterAPI2.destroyFriendship(id1); } catch (TwitterException te) { //ensure destory id1 before the actual test //ensure destory id1 before the actual test } try { user = twitterAPI2.destroyFriendship(id1); } catch (TwitterException te) { assertEquals(403, te.getStatusCode()); } user = twitterAPI2.createFriendship(id1, true); assertEquals(id1, user.getName()); // the Twitter API is not returning appropriate notifications value // User detail = twitterAPI2.getUserDetail(id1); // assertTrue(detail.isNotificationEnabled()); try { user = twitterAPI2.createFriendship(id2); fail("shouldn't be able to befrinend yourself"); } catch (TwitterException te) { assertEquals(403, te.getStatusCode()); } try { user = twitterAPI2.createFriendship("doesnotexist fail("non-existing user"); } catch (TwitterException te) { //now befriending with non-existing user returns 404 assertEquals(404, te.getStatusCode()); } } public void testGetReplies() throws Exception{ twitterAPI2.updateStatus("@"+id1+" reply to id1"); List<Status> statuses = twitterAPI1.getMentions(); assertTrue(statuses.size() > 0); assertTrue(-1 != statuses.get(0).getText().indexOf(" reply to id1")); statuses = twitterAPI1.getMentions(new Paging(1)); assertTrue(statuses.size() > 0); statuses = twitterAPI1.getMentions(new Paging(1)); assertTrue(statuses.size() > 0); statuses = twitterAPI1.getMentions(new Paging(1, 1l)); assertTrue(statuses.size() > 0); statuses = twitterAPI1.getMentions(new Paging(1l)); assertTrue(statuses.size() > 0); assertTrue(-1 != statuses.get(0).getText().indexOf(" reply to id1")); } public void testNotification() throws Exception { try { twitterAPI1.disableNotification("twit4jprotected"); } catch (TwitterException te) { } twitterAPI1.enableNotification("twit4jprotected"); twitterAPI1.disableNotification("twit4jprotected"); } public void testBlock() throws Exception { twitterAPI2.createBlock(id1); twitterAPI2.destroyBlock(id1); assertFalse(twitterAPI1.existsBlock("twit4j2")); assertTrue(twitterAPI1.existsBlock("twit4jblock")); List<User> users = twitterAPI1.getBlockingUsers(); assertEquals(1, users.size()); assertEquals(39771963, users.get(0).getId()); users = twitterAPI1.getBlockingUsers(1); assertEquals(1, users.size()); assertEquals(39771963, users.get(0).getId()); IDs ids = twitterAPI1.getBlockingUsersIDs(); assertEquals(1, ids.getIDs().length); assertEquals(39771963, ids.getIDs()[0]); } public void testRateLimitStatus() throws Exception{ RateLimitStatus status = twitterAPI1.rateLimitStatus(); assertTrue(10 < status.getHourlyLimit()); assertTrue(10 < status.getRemainingHits()); } public void testSavedSearches() throws Exception { List<SavedSearch> list = twitterAPI1.getSavedSearches(); for(SavedSearch savedSearch : list){ twitterAPI1.destroySavedSearch(savedSearch.getId()); } SavedSearch ss1 = twitterAPI1.createSavedSearch("my search"); assertEquals("my search", ss1.getQuery()); assertEquals(-1, ss1.getPosition()); list = twitterAPI1.getSavedSearches(); assertEquals(1, list.size()); SavedSearch ss2 = twitterAPI1.destroySavedSearch(ss1.getId()); assertEquals(ss1, ss2); } public void testTest() throws Exception { assertTrue(twitterAPI2.test()); } public void testProperties() throws Exception{ TwitterSupport twitterSupport; String test = "t4j"; String override = "system property"; System.getProperties().remove("twitter4j.user"); twitterSupport = new Twitter(); assertNull(twitterSupport.getUserId()); twitterSupport.setUserId(test); assertEquals(test, twitterSupport.getUserId()); System.setProperty("twitter4j.user", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.getUserId()); twitterSupport.setUserId(test); assertEquals(override, twitterSupport.getUserId()); System.getProperties().remove("twitter4j.user"); System.getProperties().remove("twitter4j.password"); twitterSupport = new Twitter(); assertNull(twitterSupport.getPassword()); twitterSupport.setPassword(test); assertEquals(test, twitterSupport.getPassword()); System.setProperty("twitter4j.password", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.getPassword()); twitterSupport.setPassword(test); assertEquals(override, twitterSupport.getPassword()); System.getProperties().remove("twitter4j.password"); System.getProperties().remove("twitter4j.source"); twitterSupport = new Twitter(); assertEquals("Twitter4J", twitterSupport.getSource()); twitterSupport.setSource(test); assertEquals(test, twitterSupport.getSource()); System.setProperty("twitter4j.source", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.getSource()); twitterSupport.setSource(test); assertEquals(override, twitterSupport.getSource()); System.getProperties().remove("twitter4j.source"); System.getProperties().remove("twitter4j.clientVersion"); twitterSupport = new Twitter(); assertEquals(Version.getVersion(), twitterSupport.getClientVersion()); twitterSupport.setClientVersion(test); assertEquals(test, twitterSupport.getClientVersion()); System.setProperty("twitter4j.clientVersion", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.getClientVersion()); twitterSupport.setClientVersion(test); assertEquals(override, twitterSupport.getClientVersion()); System.getProperties().remove("twitter4j.clientVersion"); System.getProperties().remove("twitter4j.clientURL"); twitterSupport = new Twitter(); assertEquals("http://yusuke.homeip.net/twitter4j/en/twitter4j-" + Version.getVersion() + ".xml", twitterSupport.getClientURL()); twitterSupport.setClientURL(test); assertEquals(test, twitterSupport.getClientURL()); System.setProperty("twitter4j.clientURL", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.getClientURL()); twitterSupport.setClientURL(test); assertEquals(override, twitterSupport.getClientURL()); System.getProperties().remove("twitter4j.clientURL"); System.getProperties().remove("twitter4j.http.userAgent"); twitterSupport = new Twitter(); assertEquals("twitter4j http://yusuke.homeip.net/twitter4j/ /" + Version.getVersion(), twitterSupport.http.getRequestHeader("User-Agent")); twitterSupport.setUserAgent(test); assertEquals(test, twitterSupport.getUserAgent()); System.setProperty("twitter4j.http.userAgent", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.getUserAgent()); twitterSupport.setUserAgent(test); assertEquals(override, twitterSupport.getUserAgent()); System.getProperties().remove("twitter4j.http.userAgent"); System.getProperties().remove("twitter4j.http.proxyHost"); twitterSupport = new Twitter(); assertEquals(null, twitterSupport.http.getProxyHost()); twitterSupport.setHttpProxy(test,10); assertEquals(test, twitterSupport.http.getProxyHost()); System.setProperty("twitter4j.http.proxyHost", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.http.getProxyHost()); twitterSupport.setHttpProxy(test,10); assertEquals(override, twitterSupport.http.getProxyHost()); System.getProperties().remove("twitter4j.http.proxyHost"); System.getProperties().remove("twitter4j.http.proxyPort"); twitterSupport = new Twitter(); assertEquals(-1, twitterSupport.http.getProxyPort()); twitterSupport.setHttpProxy(test,10); assertEquals(10, twitterSupport.http.getProxyPort()); System.setProperty("twitter4j.http.proxyPort", "100"); twitterSupport = new Twitter(); assertEquals(100, twitterSupport.http.getProxyPort()); twitterSupport.setHttpProxy(test,10); assertEquals(100, twitterSupport.http.getProxyPort()); System.getProperties().remove("twitter4j.http.proxyPort"); System.getProperties().remove("twitter4j.http.proxyUser"); twitterSupport = new Twitter(); assertEquals(null, twitterSupport.http.getProxyAuthUser()); twitterSupport.setHttpProxyAuth(test,test); assertEquals(test, twitterSupport.http.getProxyAuthUser()); System.setProperty("twitter4j.http.proxyUser", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.http.getProxyAuthUser()); twitterSupport.setHttpProxyAuth(test,test); assertEquals(override, twitterSupport.http.getProxyAuthUser()); System.getProperties().remove("twitter4j.http.proxyUser"); System.getProperties().remove("twitter4j.http.proxyPassword"); twitterSupport = new Twitter(); assertEquals(null, twitterSupport.http.getProxyAuthPassword()); twitterSupport.setHttpProxyAuth(test,test); assertEquals(test, twitterSupport.http.getProxyAuthPassword()); System.setProperty("twitter4j.http.proxyPassword", override); twitterSupport = new Twitter(); assertEquals(override, twitterSupport.http.getProxyAuthPassword()); twitterSupport.setHttpProxyAuth(test,test); assertEquals(override, twitterSupport.http.getProxyAuthPassword()); System.getProperties().remove("twitter4j.http.proxyPassword"); System.getProperties().remove("twitter4j.http.connectionTimeout"); twitterSupport = new Twitter(); assertEquals(20000, twitterSupport.http.getConnectionTimeout()); twitterSupport.setHttpConnectionTimeout(10); assertEquals(10, twitterSupport.http.getConnectionTimeout()); System.setProperty("twitter4j.http.connectionTimeout", "100"); twitterSupport = new Twitter(); assertEquals(100, twitterSupport.http.getConnectionTimeout()); twitterSupport.setHttpConnectionTimeout(10); assertEquals(100, twitterSupport.http.getConnectionTimeout()); System.getProperties().remove("twitter4j.http.connectionTimeout"); System.getProperties().remove("twitter4j.http.readTimeout"); twitterSupport = new Twitter(); assertEquals(120000, twitterSupport.http.getReadTimeout()); twitterSupport.setHttpReadTimeout(10); assertEquals(10, twitterSupport.http.getReadTimeout()); System.setProperty("twitter4j.http.readTimeout", "100"); twitterSupport = new Twitter(); assertEquals(100, twitterSupport.http.getReadTimeout()); twitterSupport.setHttpConnectionTimeout(10); assertEquals(100, twitterSupport.http.getReadTimeout()); System.getProperties().remove("twitter4j.http.readTimeout"); assertFalse(Configuration.isDalvik()); writeFile("./twitter4j.properties","twitter4j.http.readTimeout=1234"); Configuration.init(); assertEquals(1234, Configuration.getReadTimeout()); writeFile("./twitter4j.properties","twitter4j.http.readTimeout=4321"); Configuration.init(); assertEquals(4321, Configuration.getReadTimeout()); deleteFile("./twitter4j.properties"); Configuration.init(); } private void writeFile(String path, String content) throws IOException { File file = new File(path); file.delete(); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(content); bw.close(); } private void deleteFile(String path) throws IOException { File file = new File(path); file.delete(); } }
package be.ibridge.kettle.core; import junit.framework.TestCase; /** * Test class for the basic functionality of Const. * * @author Sven Boden */ public class ConstTest extends TestCase { private boolean isArraySorted(String [] arr) { if ( arr.length < 2) return true; for (int idx = 0; idx < arr.length - 1; idx++) { if (arr[idx].compareTo(arr[idx + 1]) > 0) return false; } return true; } /** * Test sortString(). */ public void testSortStrings() { String arr1[] = { "Red", "Blue", "Black", "Black", "Green" }; String arr2[] = { "aaa", "zzz", "yyy", "sss", "ttt", "t" }; String arr3[] = { "A", "B", "C", "D" }; String results[] = Const.sortStrings(arr1); assertTrue(isArraySorted(arr1)); assertTrue(isArraySorted(results)); results = Const.sortStrings(arr2); assertTrue(isArraySorted(arr2)); assertTrue(isArraySorted(results)); results = Const.sortStrings(arr3); assertTrue(isArraySorted(arr3)); assertTrue(isArraySorted(results)); } public void testIsEmpty() { assertEquals(true, Const.isEmpty((String)null)); assertEquals(true, Const.isEmpty("")); assertEquals(false, Const.isEmpty("test")); } public void testIsEmptyStringBuffer() { assertEquals(true, Const.isEmpty((StringBuffer)null)); assertEquals(true, Const.isEmpty(new StringBuffer(""))); assertEquals(false, Const.isEmpty(new StringBuffer("test"))); } public void testNVL() { assertNull(Const.NVL(null, null)); assertEquals("test", Const.NVL("test", "test1")); assertEquals("test", Const.NVL("test", null)); assertEquals("test1", Const.NVL(null, "test1")); } public void testNrSpacesBefore() { try { Const.nrSpacesBefore(null); fail("Expected NullPointerException"); } catch (NullPointerException ex) {} assertEquals(0, Const.nrSpacesBefore("")); assertEquals(1, Const.nrSpacesBefore(" ")); assertEquals(3, Const.nrSpacesBefore(" ")); assertEquals(0, Const.nrSpacesBefore("test")); assertEquals(0, Const.nrSpacesBefore("test ")); assertEquals(3, Const.nrSpacesBefore(" test")); assertEquals(4, Const.nrSpacesBefore(" test ")); } public void testNrSpacesAfter() { try { Const.nrSpacesAfter(null); fail("Expected NullPointerException"); } catch (NullPointerException ex) {} assertEquals(0, Const.nrSpacesAfter("")); assertEquals(1, Const.nrSpacesAfter(" ")); assertEquals(3, Const.nrSpacesAfter(" ")); assertEquals(0, Const.nrSpacesAfter("test")); assertEquals(2, Const.nrSpacesAfter("test ")); assertEquals(0, Const.nrSpacesAfter(" test")); assertEquals(2, Const.nrSpacesAfter(" test ")); } public void testLtrim() { assertEquals(null, Const.ltrim(null)); assertEquals("", Const.ltrim("")); assertEquals("", Const.ltrim(" ")); assertEquals("test ", Const.ltrim("test ")); assertEquals("test ", Const.ltrim(" test ")); } public void testRtrim() { assertEquals(null, Const.rtrim(null)); assertEquals("", Const.rtrim("")); assertEquals("", Const.rtrim(" ")); assertEquals("test", Const.rtrim("test ")); assertEquals("test ", Const.ltrim(" test ")); } public void testTrim() { try { Const.trim(null); fail("Expected NullPointerException"); } catch (NullPointerException ex) {} assertEquals("", Const.trim("")); assertEquals("", Const.trim(" ")); assertEquals("test", Const.trim("test ")); assertEquals("test", Const.trim(" test ")); } public void testOnlySpaces() { try { Const.onlySpaces(null); fail("Expected NullPointerException"); } catch (NullPointerException ex) {} assertEquals(true, Const.onlySpaces("")); assertEquals(true, Const.onlySpaces(" ")); assertEquals(false, Const.onlySpaces(" test ")); } /** * Test splitString with String separator. */ public void testSplitString() { assertEquals(0, Const.splitString("", ";").length); assertEquals(0, Const.splitString(null, ";").length); String a[] = Const.splitString(";;", ";"); assertEquals(2, a.length); assertEquals("", a[0]); assertEquals("", a[1]); a = Const.splitString("a;b;c;d", ";"); assertEquals(4, a.length); assertEquals("a", a[0]); assertEquals("b", a[1]); assertEquals("c", a[2]); assertEquals("d", a[3]); a = Const.splitString("a;b;c;d;", ";"); assertEquals(4, a.length); assertEquals("a", a[0]); assertEquals("b", a[1]); assertEquals("c", a[2]); assertEquals("d", a[3]); a = Const.splitString("a;b;c;d;;", ";"); assertEquals(5, a.length); assertEquals("a", a[0]); assertEquals("b", a[1]); assertEquals("c", a[2]); assertEquals("d", a[3]); assertEquals("", a[4]); a = Const.splitString("AACCAADAaAADD", "AA"); assertEquals(4, a.length); assertEquals("", a[0]); assertEquals("CC", a[1]); assertEquals("DA", a[2]); assertEquals("ADD", a[3]); a = Const.splitString("CCAABBAA", "AA"); assertEquals(2, a.length); assertEquals("CC", a[0]); assertEquals("BB", a[1]); } /** * Test splitString with char separator. */ public void testSplitStringChar() { assertEquals(0, Const.splitString("", ';').length); assertEquals(0, Const.splitString(null, ';').length); String a[] = Const.splitString(";;", ';'); assertEquals(2, a.length); assertEquals("", a[0]); assertEquals("", a[1]); a = Const.splitString("a;b;c;d", ';'); assertEquals(4, a.length); assertEquals("a", a[0]); assertEquals("b", a[1]); assertEquals("c", a[2]); assertEquals("d", a[3]); a = Const.splitString("a;b;c;d;", ';'); assertEquals(4, a.length); assertEquals("a", a[0]); assertEquals("b", a[1]); assertEquals("c", a[2]); assertEquals("d", a[3]); a = Const.splitString("a;b;c;d;;", ';'); assertEquals(5, a.length); assertEquals("a", a[0]); assertEquals("b", a[1]); assertEquals("c", a[2]); assertEquals("d", a[3]); assertEquals("", a[4]); a = Const.splitString(";CC;DA;ADD", ';'); assertEquals(4, a.length); assertEquals("", a[0]); assertEquals("CC", a[1]); assertEquals("DA", a[2]); assertEquals("ADD", a[3]); a = Const.splitString("CC;BB;", ';'); assertEquals(2, a.length); assertEquals("CC", a[0]); assertEquals("BB", a[1]); } }
package net.fortuna.ical4j.model; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.fortuna.ical4j.model.property.DtStart; import junit.framework.TestCase; import junit.framework.TestSuite; public class TimeZoneTest extends TestCase { private static final long GMT_PLUS_10 = 10 * 60 * 60 * 1000; private static final long GMT_MINUS_10 = -10 * 60 * 60 * 1000; private static final long GMT_MINUS_1030 = -630 * 60 * 1000; private static final long GMT_MINUS_103126 = GMT_MINUS_1030 - (1 * 60 * 1000) - (26 * 1000); private static final Log LOG = LogFactory.getLog(TimeZoneTest.class); private TimeZoneRegistry registry; private java.util.TimeZone tz; private TimeZone timezone; private String expectedTimezoneId; private boolean expectedUseDaylightTime; private int expectedDstSavings; private long expectedRawOffset; private Date date; private long expectedOffset; /** * @param testMethod * @param timezoneId */ public TimeZoneTest(String testMethod, String timezoneId) { super(testMethod); registry = TimeZoneRegistryFactory.getInstance().createRegistry(); tz = java.util.TimeZone.getTimeZone(timezoneId); timezone = registry.getTimeZone(timezoneId); } /** * @param testMethod * @param timezoneId * @param expectedTimezoneId */ public TimeZoneTest(String testMethod, String timezoneId, String expectedTimezoneId) { this(testMethod, timezoneId); this.expectedTimezoneId = expectedTimezoneId; } /** * @param testMethod * @param timezoneId * @param expectedUseDaylightTime */ public TimeZoneTest(String testMethod, String timezoneId, boolean expectedUseDaylightTime) { this(testMethod, timezoneId); this.expectedUseDaylightTime = expectedUseDaylightTime; } /** * @param testMethod * @param timezoneId * @param expectedDstSavings */ public TimeZoneTest(String testMethod, String timezoneId, int expectedDstSavings) { this(testMethod, timezoneId); this.expectedDstSavings = expectedDstSavings; } /** * @param testMethod * @param timezoneId * @param expectedRawOffset */ public TimeZoneTest(String testMethod, String timezoneId, long expectedRawOffset) { this(testMethod, timezoneId); this.expectedRawOffset = expectedRawOffset; } /** * @param testMethod * @param timezoneId * @param date * @param expectedOffset */ public TimeZoneTest(String testMethod, String timezoneId, Date date, long expectedOffset) { this(testMethod, timezoneId); this.date = date; this.expectedOffset = expectedOffset; } /* * (non-Javadoc) * @see junit.framework.TestCase#setUp() */ // protected void setUp() throws Exception { // super.setUp(); // registry = TimeZoneRegistryFactory.getInstance().createRegistry(); // tz = java.util.TimeZone.getTimeZone("Australia/Melbourne"); // timezone = registry.getTimeZone("Australia/Melbourne"); /** * Assert the zone info id is the same as the Java timezone. */ public void testGetId() { // assertEquals(tz.getID(), timezone.getID()); assertNotNull(timezone.getID()); if (expectedTimezoneId != null) { assertEquals(expectedTimezoneId, timezone.getID()); } } /** * Assert the zone info name is the same as the Java timezone. */ public void testGetDisplayName() { // assertEquals(tz.getDisplayName(), timezone.getDisplayName()); assertNotNull(timezone.getDisplayName()); } /** * Assert the zone info name is the same as the Java timezone. */ public void testGetDisplayNameShort() { // assertEquals(tz.getDisplayName(false, TimeZone.SHORT), timezone.getDisplayName(false, TimeZone.SHORT)); assertNotNull(timezone.getDisplayName(false, TimeZone.SHORT)); } /** * Assert the raw offset is the same as its Java equivalent. */ public void testGetRawOffset() { assertEquals(expectedRawOffset, timezone.getRawOffset()); assertEquals(tz.getRawOffset(), timezone.getRawOffset()); } /** * Assert the zone info has the same rules as its Java equivalent. */ public void testHasSameRules() { assertTrue(timezone.hasSameRules(tz)); } /** * A test to ensure the method TimeZone.inDaylightTime() is working correctly (for the last 10 years). */ public void testInDaylightTime() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, -10); /* * cal.set(Calendar.MONTH, 12); assertEquals(tz.inDaylightTime(cal.getTime()), * timezone.inDaylightTime(cal.getTime())); cal.set(Calendar.MONTH, 6); * assertEquals(tz.inDaylightTime(cal.getTime()), timezone.inDaylightTime(cal.getTime())); */ long start, stop; for (int y = 0; y < 10; y++) { cal.clear(Calendar.DAY_OF_YEAR); for (int i = 0; i < 365; i++) { cal.add(Calendar.DAY_OF_YEAR, 1); start = System.currentTimeMillis(); assertEquals("inDaylightTime() invalid: [" + cal.getTime() + "]", tz.inDaylightTime(cal.getTime()), timezone .inDaylightTime(cal.getTime())); stop = System.currentTimeMillis(); LOG.debug("Time: " + (stop - start) + "ms"); } } } /** * Ensure useDaylightTime() method is working correctly. */ public void testUseDaylightTime() { assertEquals(expectedUseDaylightTime, timezone.useDaylightTime()); assertEquals(tz.useDaylightTime(), timezone.useDaylightTime()); } /** * Assert getOffset() returns the same result as its Java timezone equivalent. */ public void testGetOffset() { if (date != null) { assertEquals(expectedOffset, timezone.getOffset(date.getTime())); assertEquals(tz.getOffset(date.getTime()), timezone.getOffset(date.getTime())); } else { int era = GregorianCalendar.AD; int year = 2005; int month = 9; int day = 18; int dayOfWeek = Calendar.SUNDAY; int millisecods = 0; assertEquals(tz .getOffset(era, year, month, day, dayOfWeek, millisecods), timezone.getOffset(era, year, month, day, dayOfWeek, millisecods)); } } public void testAmericaIndiana() { java.util.TimeZone indianaTz = java.util.TimeZone .getTimeZone("America/Indiana/Indianapolis"); Calendar cal = Calendar.getInstance(indianaTz); cal.set(Calendar.HOUR_OF_DAY, 10); cal.set(Calendar.MINUTE, 20); DateTime dtStart = new DateTime(cal.getTime()); DtStart pDtStart = new DtStart(dtStart); pDtStart.setTimeZone(registry .getTimeZone("America/Indiana/Indianapolis")); } public void testAustraliaSydney() { // java.util.TimeZone sydneyTz = java.util.TimeZone.getTimeZone("Australia/Sydney"); Calendar cal = Calendar.getInstance(); cal.set(2003, 7, 31, 23, 00, 00); assertEquals("inDaylightTime() invalid: [" + cal.getTime() + "]", tz .inDaylightTime(cal.getTime()), timezone.inDaylightTime(cal .getTime())); } /** * Test custom DST savings implementation. */ public void testGetDSTSavings() { assertEquals(expectedDstSavings, timezone.getDSTSavings()); assertEquals(tz.getDSTSavings(), timezone.getDSTSavings()); } /* (non-Javadoc) * @see junit.framework.TestCase#getName() */ public String getName() { return super.getName() + " [" + timezone.getID() + "]"; } /** * @return */ public static TestSuite suite() { TestSuite suite = new TestSuite(TimeZoneTest.class); suite.addTest(new TimeZoneTest("testGetId", "Australia/Melbourne")); suite.addTest(new TimeZoneTest("testGetId", "US/Mountain", "America/Denver")); suite.addTest(new TimeZoneTest("testGetDisplayName", "Australia/Melbourne")); suite.addTest(new TimeZoneTest("testGetDisplayNameShort", "Australia/Melbourne")); suite.addTest(new TimeZoneTest("testGetRawOffset", "Australia/Melbourne", GMT_PLUS_10)); suite.addTest(new TimeZoneTest("testGetRawOffset", "Pacific/Honolulu", GMT_MINUS_10)); suite.addTest(new TimeZoneTest("testHasSameRules", "Australia/Melbourne")); suite.addTest(new TimeZoneTest("testInDaylightTime", "Australia/Melbourne")); suite.addTest(new TimeZoneTest("testUseDaylightTime", "Australia/Melbourne", true)); suite.addTest(new TimeZoneTest("testUseDaylightTime", "Africa/Abidjan", false)); suite.addTest(new TimeZoneTest("testGetDSTSavings", "Australia/Melbourne", 3600000)); suite.addTest(new TimeZoneTest("testGetOffset", "Australia/Melbourne")); //testHonoluluCurrentOffset.. suite.addTest(new TimeZoneTest("testGetOffset", "Pacific/Honolulu", new Date(), GMT_MINUS_10)); //testHonoluluHistoricalOffset.. GregorianCalendar cal = new GregorianCalendar(1925, 0, 1); // suite.addTest(new TimeZoneTest("testGetOffset", "Pacific/Honolulu", cal.getTime(), GMT_MINUS_1030)); //testHonoluluPreHistoricOffset.. cal = new GregorianCalendar(1800, 0, 1); // suite.addTest(new TimeZoneTest("testGetOffset", "Pacific/Honolulu", cal.getTime(), GMT_MINUS_103126)); return suite; } }
package org.nutz.ioc.impl; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.List; import org.hamcrest.core.Is; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class PropertiesProxyTest { private PropertiesProxy pp; private static final String UTF8_CHARSET = "UTF-8"; private static final String CHINESE_STR = "Nutz Framework!"; private static final String CHARSET_KEY = "charset"; private static final String LONG_STR = "longstr"; @Before public void init() { pp = new PropertiesProxy(false, "/config/conf.properties"); } @Test public void testUTF8Properties() { PropertiesProxy i18nPP = new PropertiesProxy(false, "/config/conf-utf8.properties"); i18nPP.setIgnoreResourceNotFound(true); Assert.assertEquals(UTF8_CHARSET, i18nPP.get(CHARSET_KEY)); Assert.assertEquals(CHINESE_STR, i18nPP.get(LONG_STR)); } @Test public void testString() throws UnsupportedEncodingException { Assert.assertEquals("Nutz ", pp.get("str")); Assert.assertEquals("Nutz", pp.getTrim("str")); Assert.assertEquals("", new String(pp.getTrim("chinese"))); } @Test public void testNumber() { Assert.assertEquals(153, pp.getLong("number")); Assert.assertEquals(153, pp.getInt("number")); } @Test public void testBoolean() { Assert.assertEquals(true, pp.getBoolean("bool")); } @Test public void testHas() { Assert.assertTrue(pp.has("str")); } @Test public void testSize() { Assert.assertEquals(pp.getKeys().size(), 4); Assert.assertEquals(pp.getValues().size(), 4); } @Test public void testPrefix() throws Exception { PropertiesProxy proxy = new PropertiesProxy(true, "config/prefix.properties"); assertPrefix(proxy, "test"); assertPrefix(proxy, "test."); } private void assertPrefix(PropertiesProxy proxy, String prefix) { List<String> prefixedKeys = proxy.getKeysWithPrefix(prefix); Assert.assertThat(prefixedKeys, Is.is(Arrays.asList("test.p1", "test.p2"))); } }
package org.pdxfinder.services.constants; import org.junit.Test; import org.pdxfinder.BaseTest; import static org.junit.Assert.assertTrue; public class DataProviderTest extends BaseTest { private final static String ASSERTION_ERROR = "Unknown Data Provider Found: "; @Test public void given_DataProviders_When_EnumListIsChanged_Then_Error() { boolean expected = true; String message = ""; for (DataProvider option : DataProvider.values()) { switch (option) { case Test_Minimal: break; case PDXNet_HCI_BCM: break; case IRCC_CRC: break; case JAX: break; case PDXNet_MDAnderson: break; case PDMR: break; case PDXNet_Wistar_MDAnderson_Penn: break; case PDXNet_WUSTL: break; case CRL: break; case Curie_BC: break; case Curie_LC: break; case Curie_OC: break; case IRCC_GC: break; case PMLB: break; case TRACE: break; case UOC_BC: break; case UOM_BC: break; case VHIO_BC: break; case VHIO_CRC: break; case DFCI_CPDM: break; case NKI: break; case PDMR_XDOG: break; case JAX_XDOG: break; case SJCRH: break; default: message = String.format("%s %s", ASSERTION_ERROR, option); expected = false; } assertTrue(message, expected); } } }
package org.languagetool; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.net.JarURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import java.util.jar.Manifest; import javax.xml.parsers.ParserConfigurationException; import org.languagetool.databroker.DefaultResourceDataBroker; import org.languagetool.databroker.ResourceDataBroker; import org.languagetool.gui.ResourceBundleWithFallback; import org.languagetool.rules.Category; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.RuleMatchFilter; import org.languagetool.rules.SameRuleGroupFilter; import org.languagetool.rules.patterns.FalseFriendRuleLoader; import org.languagetool.rules.patterns.PatternRule; import org.languagetool.rules.patterns.PatternRuleLoader; import org.languagetool.rules.spelling.SpellingCheckRule; import org.languagetool.rules.spelling.SuggestionExtractor; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tokenizers.Tokenizer; import org.xml.sax.SAXException; /** * The main class used for checking text against different rules: * <ul> * <li>the built-in rules (<i>a</i> vs. <i>an</i>, whitespace after commas, ...) * <li>pattern rules loaded from external XML files with * {@link #loadPatternRules(String)} * <li>your own implementation of the abstract {@link Rule} classes added with * {@link #addRule(Rule)} * </ul> * * <p>Note that the constructors create a language checker that uses the built-in * rules only. Other rules (e.g. from XML) need to be added explicitly. * * @author Daniel Naber */ @SuppressWarnings({"UnusedDeclaration"}) public final class JLanguageTool { public static final String VERSION = "1.9-dev"; // keep in sync with build.properties! public static final String BUILD_DATE = getBuildDate(); public static final String PATTERN_FILE = "grammar.xml"; public static final String FALSE_FRIEND_FILE = "false-friends.xml"; public static final String SENTENCE_START_TAGNAME = "SENT_START"; public static final String SENTENCE_END_TAGNAME = "SENT_END"; public static final String PARAGRAPH_END_TAGNAME = "PARA_END"; /** * Returns the build date or <code>null</code> if not run from JAR. */ private static String getBuildDate() { try { final URL res = JLanguageTool.class.getResource(JLanguageTool.class.getSimpleName() + ".class"); final Object connObj = res.openConnection(); if (connObj instanceof JarURLConnection) { final JarURLConnection conn = (JarURLConnection) connObj; final Manifest manifest = conn.getManifest(); return manifest.getMainAttributes().getValue("Implementation-Date"); } else { return null; } } catch (IOException e) { throw new RuntimeException("Could not get build date from JAR", e); } } private static ResourceDataBroker dataBroker = new DefaultResourceDataBroker(); private final List<Rule> builtinRules = new ArrayList<Rule>(); private final List<Rule> userRules = new ArrayList<Rule>(); // rules added via addRule() method private final Set<String> disabledRules = new HashSet<String>(); private final Set<String> enabledRules = new HashSet<String>(); private final Set<String> disabledCategories = new HashSet<String>(); private Language language; private Language motherTongue; private Disambiguator disambiguator; private Tagger tagger; private Tokenizer sentenceTokenizer; private Tokenizer wordTokenizer; private PrintStream printStream; private int sentenceCount; private boolean listUnknownWords; private Set<String> unknownWords; /** * Constants for correct paragraph-rule handling. */ public static enum ParagraphHandling { /** * Handle normally - all kinds of rules run. */ NORMAL, /** * Run only paragraph-level rules. */ ONLYPARA, /** * Run only sentence-level rules. */ ONLYNONPARA } private static List<File> temporaryFiles = new ArrayList<File>(); // just for testing: /* * private Rule[] allBuiltinRules = new Rule[] { new * UppercaseSentenceStartRule() }; */ /** * Create a JLanguageTool and setup the built-in rules appropriate for the * given language, ignoring false friend hints. * * @throws IOException */ public JLanguageTool(final Language language) throws IOException { this(language, null); } /** * Create a JLanguageTool and setup the built-in rules appropriate for the * given language. * * @param language * the language to be used. * @param motherTongue * the user's mother tongue or <code>null</code>. The mother tongue * may also be used as a source language for checking bilingual texts. * * @throws IOException */ public JLanguageTool(final Language language, final Language motherTongue) throws IOException { if (language == null) { throw new NullPointerException("language cannot be null"); } this.language = language; this.motherTongue = motherTongue; final ResourceBundle messages = getMessageBundle(language); final Rule[] allBuiltinRules = getAllBuiltinRules(language, messages); for (final Rule element : allBuiltinRules) { if (element.supportsLanguage(language)) { builtinRules.add(element); } } disambiguator = language.getDisambiguator(); tagger = language.getTagger(); sentenceTokenizer = language.getSentenceTokenizer(); wordTokenizer = language.getWordTokenizer(); } /** * The grammar checker needs resources from following * directories: * * <ul style="list-type: circle"> * <li>{@code /resource}</li> * <li>{@code /rules}</li> * </ul> * * This method is thread-safe. * * @return The currently set data broker which allows to obtain * resources from the mentioned directories above. If no * data broker was set, a new {@link DefaultResourceDataBroker} will * be instantiated and returned. * @since 1.0.1 */ public static synchronized ResourceDataBroker getDataBroker() { if (JLanguageTool.dataBroker == null) { JLanguageTool.dataBroker = new DefaultResourceDataBroker(); } return JLanguageTool.dataBroker; } /** * The grammar checker needs resources from following * directories: * * <ul style="list-type: circle"> * <li>{@code /resource}</li> * <li>{@code /rules}</li> * </ul> * * This method is thread-safe. * * @param broker The new resource broker to be used. * @since 1.0.1 */ public static synchronized void setDataBroker(ResourceDataBroker broker) { JLanguageTool.dataBroker = broker; } /** * Whether the check() method stores unknown words. If set to * <code>true</code> (default: false), you can get the list of unknown words * using getUnknownWords(). */ public void setListUnknownWords(final boolean listUnknownWords) { this.listUnknownWords = listUnknownWords; } /** * Gets the ResourceBundle for the default language of the user's system. */ public static ResourceBundle getMessageBundle() { try { final ResourceBundle bundle = ResourceBundle.getBundle("org.languagetool.MessagesBundle"); final ResourceBundle fallbackBundle = ResourceBundle.getBundle( "org.languagetool.MessagesBundle", Locale.ENGLISH); return new ResourceBundleWithFallback(bundle, fallbackBundle); } catch (final MissingResourceException e) { return ResourceBundle.getBundle( "org.languagetool.MessagesBundle", Locale.ENGLISH); } } /** * Gets the ResourceBundle for the given user interface language. */ private static ResourceBundle getMessageBundle(final Language lang) { try { final ResourceBundle bundle = ResourceBundle.getBundle("org.languagetool.MessagesBundle", lang.getLocale()); final ResourceBundle fallbackBundle = ResourceBundle.getBundle( "org.languagetool.MessagesBundle", Locale.ENGLISH); return new ResourceBundleWithFallback(bundle, fallbackBundle); } catch (final MissingResourceException e) { return ResourceBundle.getBundle( "org.languagetool.MessagesBundle", Locale.ENGLISH); } } private Rule[] getAllBuiltinRules(final Language language, final ResourceBundle messages) { final List<Rule> rules = new ArrayList<Rule>(); final List<Class<? extends Rule>> languageRules = language.getRelevantRules(); for (Class<? extends Rule> ruleClass : languageRules) { final Constructor[] constructors = ruleClass.getConstructors(); try { if (constructors.length > 0) { final Constructor constructor = constructors[0]; final Class[] paramTypes = constructor.getParameterTypes(); if (paramTypes.length == 1 && paramTypes[0].equals(ResourceBundle.class)) { rules.add((Rule) constructor.newInstance(messages)); } else if (paramTypes.length == 2 && paramTypes[0].equals(ResourceBundle.class) && paramTypes[1].equals(Language.class)) { rules.add((Rule) constructor.newInstance(messages, language)); } else { throw new RuntimeException("No matching constructor found for rule class: " + ruleClass.getName()); } } else { throw new RuntimeException("No public constructor for rule class: " + ruleClass.getName()); } } catch (Exception e) { throw new RuntimeException("Failed to load built-in Java rules for language " + language, e); } } return rules.toArray(new Rule[rules.size()]); } /** * Set a PrintStream that will receive verbose output. Set to * <code>null</code> to disable verbose output. */ public void setOutput(final PrintStream printStream) { this.printStream = printStream; } /** * Load pattern rules from an XML file. Use {@link #addRule(Rule)} to add these * rules to the checking process. * * @throws IOException * @return a List of {@link PatternRule} objects */ public List<PatternRule> loadPatternRules(final String filename) throws IOException { final PatternRuleLoader ruleLoader = new PatternRuleLoader(); final InputStream is = this.getClass().getResourceAsStream(filename); if (is == null) { // happens for external rules plugged in as an XML file: return ruleLoader.getRules(new File(filename)); } else { return ruleLoader.getRules(is, filename); } } /** * Load false friend rules from an XML file. Only those pairs will be loaded * that match the current text language and the mother tongue specified in the * JLanguageTool constructor. Use {@link #addRule(Rule)} to add these rules to the * checking process. * * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @return a List of {@link PatternRule} objects */ public List<PatternRule> loadFalseFriendRules(final String filename) throws ParserConfigurationException, SAXException, IOException { if (motherTongue == null) { return new ArrayList<PatternRule>(); } final FalseFriendRuleLoader ruleLoader = new FalseFriendRuleLoader(); return ruleLoader.getRules(this.getClass().getResourceAsStream(filename), language, motherTongue); } /** * Loads and activates the pattern rules from * <code>rules/&lt;language&gt;/grammar.xml</code>. * * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public void activateDefaultPatternRules() throws IOException { final List<PatternRule> patternRules = new ArrayList<PatternRule>(); for (String patternRuleFileName : language.getRuleFileName()) { patternRules.addAll(loadPatternRules(patternRuleFileName)); } userRules.addAll(patternRules); } /** * Loads and activates the false friend rules from * <code>rules/false-friends.xml</code>. * * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public void activateDefaultFalseFriendRules() throws ParserConfigurationException, SAXException, IOException { final String falseFriendRulesFilename = JLanguageTool.getDataBroker().getRulesDir() + "/" + FALSE_FRIEND_FILE; final List<PatternRule> patternRules = loadFalseFriendRules(falseFriendRulesFilename); userRules.addAll(patternRules); } /** * Add a rule to be used by the next call to {@link #check(String)}. */ public void addRule(final Rule rule) { userRules.add(rule); final SuggestionExtractor extractor = new SuggestionExtractor(language); final List<String> suggestionTokens = extractor.getSuggestionTokens(rule); final List<Rule> allActiveRules = getAllActiveRules(); addIgnoreWords(suggestionTokens, allActiveRules); } private void addIgnoreWords(List<String> suggestionTokens, List<Rule> allActiveRules) { for (Rule activeRule : allActiveRules) { if (activeRule instanceof SpellingCheckRule) { ((SpellingCheckRule)activeRule).addIgnoreTokens(suggestionTokens); } } } private void setIgnoreWords(List<String> suggestionTokens, List<Rule> allActiveRules) { for (Rule activeRule : allActiveRules) { if (activeRule instanceof SpellingCheckRule) { ((SpellingCheckRule)activeRule).resetIgnoreTokens(); ((SpellingCheckRule)activeRule).addIgnoreTokens(suggestionTokens); } } } /** * Disable a given rule so {@link #check(String)} won't use it. * * @param ruleId the id of the rule to disable - no error will be given if the id does not exist */ public void disableRule(final String ruleId) { disabledRules.add(ruleId); reInitSpellCheckIgnoreWords(); } private void reInitSpellCheckIgnoreWords() { final List<Rule> allActiveRules = getAllActiveRules(); final List<String> ignoreTokens = getAllIgnoreWords(allActiveRules); setIgnoreWords(ignoreTokens, allActiveRules); } private List<String> getAllIgnoreWords(List<Rule> allActiveRules) { final List<String> suggestionTokens = new ArrayList<String>(); for (Rule activeRule : allActiveRules) { if (activeRule instanceof PatternRule) { final SuggestionExtractor extractor = new SuggestionExtractor(language); suggestionTokens.addAll(extractor.getSuggestionTokens(activeRule)); } } return suggestionTokens; } /** * Disable a given category so {@link #check(String)} won't use it. * * @param categoryName the id of the category to disable - no error will be given if the id does not exist */ public void disableCategory(final String categoryName) { disabledCategories.add(categoryName); reInitSpellCheckIgnoreWords(); } /** * Get the language that was used to configure this instance. */ public Language getLanguage() { return language; } /** * Get rule ids of the rules that have been explicitly disabled. */ public Set<String> getDisabledRules() { return disabledRules; } /** * Enable a rule that was switched off by default. * * @param ruleId * the id of the turned off rule to enable. * */ public void enableDefaultOffRule(final String ruleId) { enabledRules.add(ruleId); } /** * Get category ids of the rules that have been explicitly disabled. */ public Set<String> getDisabledCategories() { return disabledCategories; } /** * Re-enable a given rule so {@link #check(String)} will use it. * * @param ruleId * the id of the rule to enable */ public void enableRule(final String ruleId) { if (disabledRules.contains(ruleId)) { disabledRules.remove(ruleId); } } /** * Returns tokenized sentences. */ public List<String> sentenceTokenize(final String text) { return sentenceTokenizer.tokenize(text); } /** * The main check method. Tokenizes the text into sentences and matches these * sentences against all currently active rules. * * @param text * the text to check * @return a List of {@link RuleMatch} objects * @throws IOException */ public List<RuleMatch> check(final String text) throws IOException { return check(text, true, ParagraphHandling.NORMAL); } /** * The main check method. Tokenizes the text into sentences and matches these * sentences against all currently active rules. * * @param text * The text to check. Call this method with the complete text to check. If you call it * with smaller chunks like paragraphs or sentence, those rules that work across * paragraphs/sentences won't work (their status gets reset whenever this). * @param tokenizeText * If true, then the text is tokenized into sentences. * Otherwise, it is assumed it's already tokenized. * @param paraMode * Uses paragraph-level rules only if true. * @return a List of {@link RuleMatch} objects * @throws IOException */ public List<RuleMatch> check(final String text, boolean tokenizeText, final ParagraphHandling paraMode) throws IOException { sentenceCount = 0; final List<String> sentences; if (tokenizeText) { sentences = sentenceTokenize(text); } else { sentences = new ArrayList<String>(); sentences.add(text); } final List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>(); final List<Rule> allRules = getAllRules(); printIfVerbose(allRules.size() + " rules activated for language " + language); int charCount = 0; int lineCount = 0; int columnCount = 1; unknownWords = new HashSet<String>(); for (final String sentence : sentences) { sentenceCount++; AnalyzedSentence analyzedText = getAnalyzedSentence(sentence); rememberUnknownWords(analyzedText); if (sentenceCount == sentences.size()) { final AnalyzedTokenReadings[] anTokens = analyzedText.getTokens(); anTokens[anTokens.length - 1].setParaEnd(); analyzedText = new AnalyzedSentence(anTokens); } printIfVerbose(analyzedText.toString()); printIfVerbose(analyzedText.getAnnotations()); final List<RuleMatch> sentenceMatches = checkAnalyzedSentence(paraMode, allRules, charCount, lineCount, columnCount, sentence, analyzedText); Collections.sort(sentenceMatches); ruleMatches.addAll(sentenceMatches); charCount += sentence.length(); lineCount += countLineBreaks(sentence); // calculate matching column: final int lineBreakPos = sentence.indexOf('\n'); if (lineBreakPos == -1) { columnCount += sentence.length(); } else { if (lineBreakPos == 0) { columnCount = sentence.length(); if (!language.getSentenceTokenizer().singleLineBreaksMarksPara()) { columnCount } } else { columnCount = 1; } } } if (!ruleMatches.isEmpty() && !paraMode.equals(ParagraphHandling.ONLYNONPARA)) { // removing false positives in paragraph-level rules for (final Rule rule : allRules) { if (rule.isParagraphBackTrack() && (rule.getMatches() != null)) { final List<RuleMatch> rm = rule.getMatches(); for (final RuleMatch r : rm) { if (rule.isInRemoved(r)) { ruleMatches.remove(r); } } } } } return ruleMatches; } public List<RuleMatch> checkAnalyzedSentence(final ParagraphHandling paraMode, final List<Rule> allRules, int tokenCount, int lineCount, int columnCount, final String sentence, AnalyzedSentence analyzedText) throws IOException { final List<RuleMatch> sentenceMatches = new ArrayList<RuleMatch>(); for (final Rule rule : allRules) { if (disabledRules.contains(rule.getId()) || (rule.isDefaultOff() && !enabledRules.contains(rule.getId()))) { continue; } final Category category = rule.getCategory(); if (category != null && disabledCategories.contains(category.getName())) { continue; } switch (paraMode) { case ONLYNONPARA: { if (rule.isParagraphBackTrack()) { continue; } break; } case ONLYPARA: { if (!rule.isParagraphBackTrack()) { continue; } break; } case NORMAL: default: } final RuleMatch[] thisMatches = rule.match(analyzedText); for (final RuleMatch element1 : thisMatches) { RuleMatch thisMatch = adjustRuleMatchPos(element1, tokenCount, columnCount, lineCount, sentence); sentenceMatches.add(thisMatch); if (rule.isParagraphBackTrack()) { rule.addRuleMatch(thisMatch); } } } final RuleMatchFilter filter = new SameRuleGroupFilter(); return filter.filter(sentenceMatches); } /** * Change RuleMatch positions so they are relative to the complete text, * not just to the sentence: * @param rm RuleMatch * @param sentLen Count of characters * @param columnCount Current column number * @param lineCount Current line number * @param sentence The text being checked * @return * The RuleMatch object with adjustments. */ public RuleMatch adjustRuleMatchPos(final RuleMatch rm, int sentLen, int columnCount, int lineCount, final String sentence) { final RuleMatch thisMatch = new RuleMatch(rm.getRule(), rm.getFromPos() + sentLen, rm.getToPos() + sentLen, rm.getMessage(), rm .getShortMessage()); thisMatch.setSuggestedReplacements(rm .getSuggestedReplacements()); final String sentencePartToError = sentence.substring(0, rm .getFromPos()); final String sentencePartToEndOfError = sentence.substring(0, rm.getToPos()); final int lastLineBreakPos = sentencePartToError.lastIndexOf('\n'); final int column; final int endColumn; if (lastLineBreakPos == -1) { column = sentencePartToError.length() + columnCount; } else { column = sentencePartToError.length() - lastLineBreakPos; } final int lastLineBreakPosInError = sentencePartToEndOfError .lastIndexOf('\n'); if (lastLineBreakPosInError == -1) { endColumn = sentencePartToEndOfError.length() + columnCount; } else { endColumn = sentencePartToEndOfError.length() - lastLineBreakPosInError; } final int lineBreaksToError = countLineBreaks(sentencePartToError); final int lineBreaksToEndOfError = countLineBreaks(sentencePartToEndOfError); thisMatch.setLine(lineCount + lineBreaksToError); thisMatch.setEndLine(lineCount + lineBreaksToEndOfError); thisMatch.setColumn(column); thisMatch.setEndColumn(endColumn); thisMatch.setOffset(rm.getFromPos() + sentLen); return thisMatch; } private void rememberUnknownWords(final AnalyzedSentence analyzedText) { if (listUnknownWords) { final AnalyzedTokenReadings[] atr = analyzedText .getTokensWithoutWhitespace(); for (final AnalyzedTokenReadings t : atr) { if (t.getReadings().toString().contains("null]")) { unknownWords.add(t.getToken()); } } } } public List<String> getUnknownWords() { if (!listUnknownWords) { throw new IllegalStateException( "listUnknownWords is set to false, unknown words not stored"); } final List<String> words = new ArrayList<String>(unknownWords); Collections.sort(words); return words; } static int countLineBreaks(final String s) { int pos = -1; int count = 0; while (true) { final int nextPos = s.indexOf('\n', pos + 1); if (nextPos == -1) { break; } pos = nextPos; count++; } return count; } /** * Tokenizes the given <code>sentence</code> into words and analyzes it, * and then disambiguates POS tags. * * @throws IOException */ public AnalyzedSentence getAnalyzedSentence(final String sentence) throws IOException { // disambiguate assigned tags & return return disambiguator.disambiguate(getRawAnalyzedSentence(sentence)); } /** * Tokenizes the given <code>sentence</code> into words and analyzes it. * * @since 0.9.8 * @param sentence * Sentence to be analyzed * @return * AnalyzedSentence * @throws IOException */ public AnalyzedSentence getRawAnalyzedSentence(final String sentence) throws IOException { final List<String> tokens = wordTokenizer.tokenize(sentence); final Map<Integer, String> softHyphenTokens = new HashMap<Integer, String>(); //for soft hyphens inside words, happens especially in OOo: for (int i = 0; i < tokens.size(); i++) { if (tokens.get(i).indexOf('\u00ad') != -1) { softHyphenTokens.put(i, tokens.get(i)); tokens.set(i, tokens.get(i).replaceAll("\u00ad", "")); } } final List<AnalyzedTokenReadings> aTokens = tagger.tag(tokens); final int numTokens = aTokens.size(); int posFix = 0; for (int i = 1; i < numTokens; i++) { aTokens.get(i).setWhitespaceBefore(aTokens.get(i - 1).isWhitespace()); aTokens.get(i).setStartPos(aTokens.get(i).getStartPos() + posFix); if (!softHyphenTokens.isEmpty()) { if (softHyphenTokens.get(i) != null) { aTokens.get(i).addReading(tagger.createToken(softHyphenTokens.get(i), null)); posFix += softHyphenTokens.get(i).length() - aTokens.get(i).getToken().length(); } } } final AnalyzedTokenReadings[] tokenArray = new AnalyzedTokenReadings[tokens .size() + 1]; final AnalyzedToken[] startTokenArray = new AnalyzedToken[1]; int toArrayCount = 0; final AnalyzedToken sentenceStartToken = new AnalyzedToken("", SENTENCE_START_TAGNAME, null); startTokenArray[0] = sentenceStartToken; tokenArray[toArrayCount++] = new AnalyzedTokenReadings(startTokenArray, 0); int startPos = 0; for (final AnalyzedTokenReadings posTag : aTokens) { posTag.setStartPos(startPos); tokenArray[toArrayCount++] = posTag; startPos += posTag.getToken().length(); } // add additional tags int lastToken = toArrayCount - 1; // make SENT_END appear at last not whitespace token for (int i = 0; i < toArrayCount - 1; i++) { if (!tokenArray[lastToken - i].isWhitespace()) { lastToken -= i; break; } } tokenArray[lastToken].setSentEnd(); if (tokenArray.length == lastToken + 1 && tokenArray[lastToken].isLinebreak()) { tokenArray[lastToken].setParaEnd(); } return new AnalyzedSentence(tokenArray); } /** * Get all rules for the current language that are built-in or that have been * added using {@link #addRule(Rule)}. * @return a List of {@link Rule} objects */ public List<Rule> getAllRules() { final List<Rule> rules = new ArrayList<Rule>(); rules.addAll(builtinRules); rules.addAll(userRules); // Some rules have an internal state so they can do checks over sentence // boundaries. These need to be reset so the checks don't suddenly // work on different texts with the same data. However, it could be useful // to keep the state information if we're checking a continuous text. for (final Rule rule : rules) { rule.reset(); } return rules; } /** * Get all active (not disabled) * rules for the current language that are built-in or that have been * added using {@link #addRule(Rule)}. * @return a List of {@link Rule} objects */ public List<Rule> getAllActiveRules() { final List<Rule> rules = new ArrayList<Rule>(); final List<Rule> rulesActive = new ArrayList<Rule>(); rules.addAll(builtinRules); rules.addAll(userRules); // Some rules have an internal state so they can do checks over sentence // boundaries. These need to be reset so the checks don't suddenly // work on different texts with the same data. However, it could be useful // to keep the state information if we're checking a continuous text. for (final Rule rule : rules) { rule.reset(); if (!disabledRules.contains(rule.getId())) { rulesActive.add(rule); } } return rulesActive; } /** * Number of sentences the latest call to check() has checked. */ public int getSentenceCount() { return sentenceCount; } private void printIfVerbose(final String s) { if (printStream != null) { printStream.println(s); } } /** * Adds a temporary file to the internal list * @param f - the file to be added. */ public static void addTemporaryFile(final File f) { temporaryFiles.add(f); } /** * Clean up all temporary files, if there are any. */ public static void removeTemporaryFiles() { if (!temporaryFiles.isEmpty()) { for (File f : temporaryFiles) { f.delete(); } } } }
// SwingUI.java package imagej.ui.swing; import imagej.ImageJ; import imagej.display.Display; import imagej.display.DisplayWindow; import imagej.display.event.DisplayCreatedEvent; import imagej.display.event.DisplayDeletedEvent; import imagej.event.EventSubscriber; import imagej.event.Events; import imagej.ext.menu.MenuService; import imagej.ext.menu.ShadowMenu; import imagej.ext.ui.swing.SwingJMenuBarCreator; import imagej.platform.PlatformService; import imagej.platform.event.AppMenusCreatedEvent; import imagej.platform.event.AppQuitEvent; import imagej.ui.DialogPrompt; import imagej.ui.DialogPrompt.MessageType; import imagej.ui.DialogPrompt.OptionType; import imagej.ui.OutputWindow; import imagej.ui.UI; import imagej.ui.UserInterface; import imagej.ui.swing.display.SwingDisplayWindow; import imagej.util.Log; import imagej.util.Prefs; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.WindowConstants; /** * Swing-based user interface for ImageJ. * * @author Curtis Rueden * @author Barry DeZonia */ @UI public class SwingUI implements UserInterface { private static final String README_FILE = "README.txt"; private static final String PREF_FIRST_RUN = "firstRun-" + ImageJ.VERSION; private JFrame frame; private SwingToolBar toolBar; private SwingStatusBar statusBar; private ArrayList<EventSubscriber<?>> subscribers; // -- UserInterface methods -- @Override public void initialize() { frame = new JFrame("ImageJ"); toolBar = new SwingToolBar(); statusBar = new SwingStatusBar(); createMenus(); final JPanel pane = new JPanel(); frame.setContentPane(pane); pane.setLayout(new BorderLayout()); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent evt) { Events.publish(new AppQuitEvent()); } }); pane.add(toolBar, BorderLayout.NORTH); pane.add(statusBar, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); // Only for MacOX // PlatformService pService = ImageJ.get(PlatformService.class); // pService.isTargetPlatform(final Platform p) ; // @Platform(osName = "Mac OS X") subscribeToEvents(); displayReadme(); } @Override public void processArgs(final String[] args) { // TODO } @Override public void createMenus() { final JMenuBar menuBar = createMenuBar(frame); Events.publish(new AppMenusCreatedEvent(menuBar)); } @Override public SwingToolBar getToolBar() { return toolBar; } @Override public SwingStatusBar getStatusBar() { return statusBar; } // -- Helper methods -- /** * Creates a {@link JMenuBar} from the master {@link ShadowMenu} structure, * and adds it to the given {@link JFrame}. */ private JMenuBar createMenuBar(final JFrame f) { final MenuService menuService = ImageJ.get(MenuService.class); final JMenuBar menuBar = menuService.createMenus(new SwingJMenuBarCreator(), new JMenuBar()); f.setJMenuBar(menuBar); f.validate(); return menuBar; } private void deleteMenuBar(final JFrame f) { f.setJMenuBar(null); // HACK - w/o this next call the JMenuBars do not get garbage collected. // I hunted on web and have found multiple people with the same problem. // The Apple ScreenMenus don't GC when a Frame disposes. Their workaround // was exactly the same. I have not found any official documentation of // this issue. f.setMenuBar(null); } private void displayReadme() { final String firstRun = Prefs.get(getClass(), PREF_FIRST_RUN); if (firstRun != null) return; Prefs.put(getClass(), PREF_FIRST_RUN, false); final JFrame readmeFrame = new JFrame(); final JTextArea text = new JTextArea(); text.setEditable(false); final JScrollPane scrollPane = new JScrollPane(text); scrollPane.setPreferredSize(new Dimension(600, 500)); readmeFrame.setLayout(new BorderLayout()); readmeFrame.add(scrollPane, BorderLayout.CENTER); readmeFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); readmeFrame.setTitle("ImageJ v" + ImageJ.VERSION + " - " + README_FILE); readmeFrame.pack(); final String readmeText = loadReadmeFile(); text.setText(readmeText); readmeFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); readmeFrame.setVisible(true); } private String loadReadmeFile() { final File baseDir = getBaseDirectory(); final File readmeFile = new File(baseDir, README_FILE); try { final DataInputStream in = new DataInputStream(new FileInputStream(readmeFile)); final int len = (int) readmeFile.length(); final byte[] bytes = new byte[len]; in.readFully(bytes); in.close(); return new String(bytes); } catch (final FileNotFoundException e) { throw new IllegalArgumentException(README_FILE + " not found at " + baseDir.getAbsolutePath()); } catch (final IOException e) { throw new IllegalStateException(e.getMessage()); } } private File getBaseDirectory() { final File pathToClass = getPathToClass(); final String path = pathToClass.getPath(); final File baseDir; if (path.endsWith(".class")) { // assume class is in a subfolder of Maven target File dir = pathToClass; while (dir != null && !dir.getName().equals("target")) { dir = up(dir); } // NB: Base directory is 5 levels up from ui/awt-swing/swing/ui/target. baseDir = up(up(up(up(up(dir))))); } else if (path.endsWith(".jar")) { // assume class is in a library folder of the distribution final File dir = pathToClass.getParentFile(); baseDir = up(dir); } else baseDir = null; // return current working directory if not found return baseDir == null ? new File(".") : baseDir; } /** * Gets the file on disk containing this class. * <p> * This could be a jar archive, or a standalone class file. * </p> */ private File getPathToClass() { final Class<?> c = getClass(); final String className = c.getSimpleName(); String path = getClass().getResource(className + ".class").toString(); path = path.replaceAll("^jar:", ""); path = path.replaceAll("^file:", ""); path = path.replaceAll("^/*/", "/"); path = path.replaceAll("^/([A-Z]:)", "$1"); path = path.replaceAll("!.*", ""); try { path = URLDecoder.decode(path, "UTF-8"); } catch (final UnsupportedEncodingException e) { Log.warn("Cannot parse class: " + className, e); } String slash = File.separator; if (slash.equals("\\")) slash = "\\\\"; path = path.replaceAll("/", slash); return new File(path); } private File up(final File file) { if (file == null) return null; return file.getParentFile(); } @SuppressWarnings("synthetic-access") private void subscribeToEvents() { subscribers = new ArrayList<EventSubscriber<?>>(); final EventSubscriber<DisplayCreatedEvent> createSubscriber = new EventSubscriber<DisplayCreatedEvent>() { @Override public void onEvent(final DisplayCreatedEvent event) { final Display display = event.getObject(); final DisplayWindow window = display.getDisplayWindow(); if (!(window instanceof SwingDisplayWindow)) return; final SwingDisplayWindow swingWindow = (SwingDisplayWindow) window; // add a copy of the JMenuBar to the new display if (swingWindow.getJMenuBar() == null) createMenuBar(swingWindow); } }; subscribers.add(createSubscriber); Events.subscribe(DisplayCreatedEvent.class, createSubscriber); final EventSubscriber<DisplayDeletedEvent> deleteSubscriber = new EventSubscriber<DisplayDeletedEvent>() { @Override public void onEvent(final DisplayDeletedEvent event) { final Display display = event.getObject(); final DisplayWindow window = display.getDisplayWindow(); if (!(window instanceof SwingDisplayWindow)) return; final SwingDisplayWindow swingWindow = (SwingDisplayWindow) window; deleteMenuBar(swingWindow); } }; subscribers.add(deleteSubscriber); Events.subscribe(DisplayDeletedEvent.class, deleteSubscriber); } @Override public OutputWindow newOutputWindow(final String title) { return new SwingOutputWindow(title); } @Override public DialogPrompt dialogPrompt(final String message, final String title, final MessageType msg, final OptionType option) { return new SwingDialogPrompt(message, title, msg, option); } }
package com.home; import java.util.concurrent.ThreadLocalRandom; public class Utils { public static void main(String[] args) { System.out.println(rotateBitsRight(32, 8, 4)); } public static int rotateBitsLeft(final int bits, int n, int times) { return (n << times) | (n >> (bits - times)); } public static int rotateBitsRight(final int bits, int n, int times) { return (n >> times) | (n << (bits - times)); } public static int sumBitDifferences(int[] array) { int result = 0; for (int i = 0; i < 32; i++) { int count = 0; for (int j = 0; j < array.length; j++) { if ((array[j] & (1 << i)) > 0) { count++; } } result += (count * (array.length - count) * 2); } return result; } public static int getKthSmallest(int[] array, int k) { if (array == null || k >= array.length) { return Integer.MAX_VALUE; } int result = quickSelect(array, 0, array.length - 1, k); if (result == Integer.MAX_VALUE) { return array[k - 1]; } return result; } private static int quickSelect(int[] array, int l, int h, int k) { if (l >= h) { return Integer.MAX_VALUE; } int lo = l; int hi = h; int pivotIndex = l; int pivot = array[pivotIndex]; swap(array, pivotIndex, hi); while (lo < hi) { if (array[lo] > pivot) { while (hi > lo) { if (array[hi] < pivot) { swap(array, lo, hi); break; } hi } } lo++; } swap(array, hi, h); if (k == hi + 1) { return array[hi]; } int leftValue = quickSelect(array, l, lo - 1, k); int rightValue = quickSelect(array, lo, h, k); return leftValue == Integer.MAX_VALUE ? rightValue : leftValue; } public int[] getPrimeNumbers(int total) { int[] result = new int[total]; int i = 0; int number = 2; while (i < total) { if (isPrime(number)) { result[i++] = number; } number++; } return result; } public static boolean isPrime(int number) { if (number < 2) { return false; } for (int i = 2; i * i <= number; i++) { if (number % i == 0) { return false; } } return true; } public static int[] generateArrayOfIntegers(int size, int bound) { int[] result = new int[size]; for (int i = 0; i < size; i++) { result[i] = ThreadLocalRandom.current().nextInt(0, bound); } return result; } public static void swap(int[] array, int i1, int i2) { int temp = array[i1]; array[i1] = array[i2]; array[i2] = temp; } }
package com.blankj.utilcode.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.ref.WeakReference; public class CrashUtils implements Thread.UncaughtExceptionHandler { private volatile static CrashUtils mInstance; private UncaughtExceptionHandler mHandler; private boolean mInitialized; private static String dir; private String versionName; private int versionCode; private CrashUtils() { } /** * * <p>Application{@code CrashUtils.getInstance().init(this);}</p> * * @return */ public static CrashUtils getInstance() { synchronized (CrashUtils.class) { if (null == mInstance) { mInstance = new CrashUtils(); } } return mInstance; } /** * * * @param context */ public boolean init(Context context) { if (mInitialized) return true; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { dir = context.getExternalCacheDir().getPath(); } else { dir = context.getCacheDir().getPath(); } try { PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); versionName = pi.versionName; versionCode = pi.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return false; } mHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); return mInitialized = true; } @Override public void uncaughtException(Thread thread, Throwable throwable) { String fullPath = dir + File.separator + "crash_" + TimeUtils.getCurTimeString() + ".txt"; if (!FileUtils.createOrExistsFile(fullPath)) return; StringBuilder sb = new StringBuilder(); sb.append(getCrashHead()); Writer writer = new StringWriter(); PrintWriter pw = null; try { pw = new PrintWriter(writer); throwable.printStackTrace(pw); Throwable cause = throwable.getCause(); while (cause != null) { cause.printStackTrace(pw); cause = cause.getCause(); } } finally { CloseUtils.closeIO(pw); } sb.append(writer.toString()); FileUtils.writeFileFromString(fullPath, sb.toString(), false); if (mHandler != null) { mHandler.uncaughtException(thread, throwable); } } /** * * * @return */ private StringBuilder getCrashHead() { StringBuilder sb = new StringBuilder(); sb.append("\n************* Crash Log Head ****************"); sb.append("\nDevice Manufacturer: ").append(Build.MANUFACTURER); sb.append("\nDevice Model : ").append(Build.MODEL); sb.append("\nAndroid Version : ").append(Build.VERSION.RELEASE); sb.append("\nAndroid SDK : ").append(Build.VERSION.SDK_INT);// SDK sb.append("\nApp VersionName : ").append(versionName); sb.append("\nApp VersionCode : ").append(versionCode); sb.append("\n************* Crash Log Head ****************\n\n"); return sb; } }
package uk.ac.kent.dover.fastGraph; import java.util.ArrayList; import java.util.Random; public class KMedoids { /* Number of clusters to generate */ private int numberOfClusters; /* Random generator for selection of candidate medoids */ private Random r; /* The maximum number of iterations the algorithm is allowed to run. */ private int maxIterations; private FastGraph targetGraph; /** * Constructor * * @param targetGraph The target graph * @param numberOfClusters The number of clusters * @param maxIterations The maximum number of iterations */ public KMedoids(FastGraph targetGraph, int numberOfClusters, int maxIterations) { this.numberOfClusters = numberOfClusters; this.maxIterations = maxIterations; r = new Random(targetGraph.getNodeBuf().getLong(1)); } /** * Clusters the subgraphs * * @param subgraphs The subgraphs to cluster * @return The clusters, as a list of lists of FastGraphs * @throws FastGraphException If the random selection cannot be obtained (i.e. k is too big) */ public ArrayList<ArrayList<FastGraph>> cluster(ArrayList<FastGraph> subgraphs) throws FastGraphException { System.out.println("subs: " + subgraphs.size()); System.out.println("numOfClusters: " + numberOfClusters); ArrayList<FastGraph> medoids = Util.randomSelection(r, numberOfClusters, subgraphs); ArrayList<ArrayList<FastGraph>> output = new ArrayList<ArrayList<FastGraph>>(numberOfClusters); boolean changed = true; int count = 0; while (changed && count < maxIterations) { changed = false; count++; int[] assignment = assign(medoids, subgraphs); Debugger.log("assignment complete"); changed = recalculateMedoids(assignment, medoids, output, subgraphs); } return output; } /** * Assign all instances from the data set to the medoids. * * @param medoids candidate medoids * @param subgraphs the data to assign to the medoids * @return best cluster indices for each instance in the data set */ private int[] assign(ArrayList<FastGraph> medoids, ArrayList<FastGraph> subgraphs) { int[] out = new int[subgraphs.size()]; for (int i = 0; i < subgraphs.size(); i++) { double bestDistance = comparisonScore(subgraphs.get(i), medoids.get(0)); int bestIndex = 0; for (int j = 1; j < medoids.size(); j++) { double tmpDistance = comparisonScore(subgraphs.get(i), medoids.get(j)); if (tmpDistance < bestDistance) { bestDistance = tmpDistance; bestIndex = j; } } out[i] = bestIndex; } return out; } /** * Return a array with on each position the clusterIndex to which the * Instance on that position in the dataset belongs. * * @param medoids the current set of cluster medoids, will be modified to fit the new assignment * @param assigment the new assignment of all instances to the different medoids * @param output the cluster output, this will be modified at the end of the method * @return If any of the medoids have changed */ private boolean recalculateMedoids(int[] assignment, ArrayList<FastGraph> medoids, ArrayList<ArrayList<FastGraph>> output, ArrayList<FastGraph> subgraphs) { boolean changed = false; for (int i = 0; i < numberOfClusters; i++) { if(output.size() > i) { output.set(i, new ArrayList<FastGraph>()); } else { output.add(new ArrayList<FastGraph>()); } for (int j = 0; j < assignment.length; j++) { if (assignment[j] == i) { output.get(i).add(subgraphs.get(j)); } } if (output.get(i).size() == 0) { // new random, empty medoid medoids.set(i,subgraphs.get(r.nextInt(subgraphs.size()))); changed = true; } else { FastGraph centroid = findAverageGraph(output.get(i)); FastGraph oldMedoid = medoids.get(i); medoids.set(i, findClosestGraph(centroid, subgraphs)); if (!medoids.get(i).equals(oldMedoid)) { changed = true; } } } return changed; } /** * Finds the graph closest to the "average" of the given cluster * * @param cluster The cluster * @return The graph closest to the "average" */ private FastGraph findAverageGraph(ArrayList<FastGraph> cluster) { FastGraph averageGraph = null; float bestScore = Float.POSITIVE_INFINITY; for(FastGraph g : cluster) { float currentScore = 0; for(FastGraph h : cluster) { if(g == h) { //skip if the same continue; } currentScore += comparisonScore(g, h); } if(currentScore < bestScore) { bestScore = currentScore; averageGraph = g; } } return averageGraph; } /** * Finds the graph closest to the given centroid * * @param centroid The centroid * @param subgraphs The entire list of subgraphs * @return The graph closest to the centroid */ private FastGraph findClosestGraph(FastGraph centroid, ArrayList<FastGraph> subgraphs) { FastGraph closestGraph = null; double bestScore = Double.POSITIVE_INFINITY; for(FastGraph g : subgraphs) { double currentScore = comparisonScore(g, centroid); if(currentScore < bestScore) { bestScore = currentScore; closestGraph = g; } } return closestGraph; } /** * Returns the comparison score of the two graphs. Normally, GED * @param g1 The first graph * @param g2 The second graph * @return The comparison score */ private double comparisonScore(FastGraph g1, FastGraph g2) { return (g1.getNumberOfNodes() + g1.getNumberOfEdges()) - (g2.getNumberOfNodes() + g2.getNumberOfEdges()); //placeholder //return GedUtil.getGedScore(g1, g2); } }
package uk.co.placona.helloWorld; public class HelloWorld { public String sayHello() { return "Hello Worlddd"; } }
package org.bouncycastle.tsp.test; import java.math.BigInteger; import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.CertStore; import java.security.cert.CollectionCertStoreParameters; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import junit.framework.TestCase; import org.bouncycastle.asn1.cmp.PKIFailureInfo; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.tsp.GenTimeAccuracy; import org.bouncycastle.tsp.TSPAlgorithms; import org.bouncycastle.tsp.TSPValidationException; import org.bouncycastle.tsp.TimeStampRequest; import org.bouncycastle.tsp.TimeStampRequestGenerator; import org.bouncycastle.tsp.TimeStampResponse; import org.bouncycastle.tsp.TimeStampResponseGenerator; import org.bouncycastle.tsp.TimeStampToken; import org.bouncycastle.tsp.TimeStampTokenGenerator; import org.bouncycastle.tsp.TimeStampTokenInfo; import org.bouncycastle.util.Arrays; public class TSPTest extends TestCase { public void testGeneral() throws Exception { String signDN = "O=Bouncy Castle, C=AU"; KeyPair signKP = TSPTestUtil.makeKeyPair(); X509Certificate signCert = TSPTestUtil.makeCACertificate(signKP, signDN, signKP, signDN); String origDN = "CN=Eric H. Echidna, E=eric@bouncycastle.org, O=Bouncy Castle, C=AU"; KeyPair origKP = TSPTestUtil.makeKeyPair(); X509Certificate origCert = TSPTestUtil.makeCertificate(origKP, origDN, signKP, signDN); List certList = new ArrayList(); certList.add(origCert); certList.add(signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); basicTest(origKP.getPrivate(), origCert, certs); responseValidationTest(origKP.getPrivate(), origCert, certs); incorrectHashTest(origKP.getPrivate(), origCert, certs); badAlgorithmTest(origKP.getPrivate(), origCert, certs); badPolicyTest(origKP.getPrivate(), origCert, certs); tokenEncodingTest(origKP.getPrivate(), origCert, certs); certReqTest(origKP.getPrivate(), origCert, certs); testAccuracyZeroCerts(origKP.getPrivate(), origCert, certs); testAccuracyWithCertsAndOrdering(origKP.getPrivate(), origCert, certs); testNoNonse(origKP.getPrivate(), origCert, certs); } private void basicTest( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.SHA1, "1.2"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); tsToken.validate(cert, "BC"); AttributeTable table = tsToken.getSignedAttributes(); assertNotNull("no signingCertificate attribute found", table.get(PKCSObjectIdentifiers.id_aa_signingCertificate)); } private void responseValidationTest( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.MD5, "1.2"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); tsToken.validate(cert, "BC"); // check validation tsResp.validate(request); try { request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(101)); tsResp.validate(request); fail("response validation failed on invalid nonce."); } catch (TSPValidationException e) { // ignore } try { request = reqGen.generate(TSPAlgorithms.SHA1, new byte[22], BigInteger.valueOf(100)); tsResp.validate(request); fail("response validation failed on wrong digest."); } catch (TSPValidationException e) { // ignore } try { request = reqGen.generate(TSPAlgorithms.MD5, new byte[20], BigInteger.valueOf(100)); tsResp.validate(request); fail("response validation failed on wrong digest."); } catch (TSPValidationException e) { // ignore } } private void incorrectHashTest( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.SHA1, "1.2"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[16]); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); if (tsToken != null) { fail("incorrectHash - token not null."); } PKIFailureInfo failInfo = tsResp.getFailInfo(); if (failInfo == null) { fail("incorrectHash - failInfo set to null."); } if (failInfo.intValue() != PKIFailureInfo.BAD_DATA_FORMAT) { fail("incorrectHash - wrong failure info returned."); } } private void badAlgorithmTest( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.SHA1, "1.2"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.generate("1.2.3.4.5", new byte[20]); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); if (tsToken != null) { fail("badAlgorithm - token not null."); } PKIFailureInfo failInfo = tsResp.getFailInfo(); if (failInfo == null) { fail("badAlgorithm - failInfo set to null."); } if (failInfo.intValue() != PKIFailureInfo.BAD_ALG) { fail("badAlgorithm - wrong failure info returned."); } } private void badPolicyTest( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.SHA1, "1.2"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.setReqPolicy("1.1"); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20]); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED, new HashSet()); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); if (tsToken != null) { fail("badPolicy - token not null."); } PKIFailureInfo failInfo = tsResp.getFailInfo(); if (failInfo == null) { fail("badPolicy - failInfo set to null."); } if (failInfo.intValue() != PKIFailureInfo.UNACCEPTED_POLICY) { fail("badPolicy - wrong failure info returned."); } } private void certReqTest( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.MD5, "1.2"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); // request with certReq false reqGen.setCertReq(false); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); assertNull(tsToken.getTimeStampInfo().getGenTimeAccuracy()); // check for abscence of accuracy assertEquals("1.2", tsToken.getTimeStampInfo().getPolicy()); try { tsToken.validate(cert, "BC"); } catch (TSPValidationException e) { fail("certReq(false) verification of token failed."); } CertStore respCerts = tsToken.getCertificatesAndCRLs("Collection", "BC"); Collection certsColl = respCerts.getCertificates(null); if (!certsColl.isEmpty()) { fail("certReq(false) found certificates in response."); } } private void tokenEncodingTest( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.SHA1, "1.2.3.4.5.6"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampResponse tsResponse = new TimeStampResponse(tsResp.getEncoded()); if (!Arrays.areEqual(tsResponse.getEncoded(), tsResp.getEncoded()) || !Arrays.areEqual(tsResponse.getTimeStampToken().getEncoded(), tsResp.getTimeStampToken().getEncoded())) { fail(); } } private void testAccuracyZeroCerts( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.MD5, "1.2"); tsTokenGen.setCertificatesAndCRLs(certs); tsTokenGen.setAccuracySeconds(1); tsTokenGen.setAccuracyMillis(2); tsTokenGen.setAccuracyMicros(3); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); tsToken.validate(cert, "BC"); // check validation tsResp.validate(request); // check tstInfo TimeStampTokenInfo tstInfo = tsToken.getTimeStampInfo(); // check accuracy GenTimeAccuracy accuracy = tstInfo.getGenTimeAccuracy(); assertEquals(1, accuracy.getSeconds()); assertEquals(2, accuracy.getMillis()); assertEquals(3, accuracy.getMicros()); assertEquals(new BigInteger("23"), tstInfo.getSerialNumber()); assertEquals("1.2", tstInfo.getPolicy()); // test certReq CertStore store = tsToken.getCertificatesAndCRLs("Collection", "BC"); Collection certificates = store.getCertificates(null); assertEquals(0, certificates.size()); } private void testAccuracyWithCertsAndOrdering( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.MD5, "1.2.3"); tsTokenGen.setCertificatesAndCRLs(certs); tsTokenGen.setAccuracySeconds(3); tsTokenGen.setAccuracyMillis(1); tsTokenGen.setAccuracyMicros(2); tsTokenGen.setOrdering(true); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.setCertReq(true); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); assertTrue(request.getCertReq()); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("23"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); tsToken.validate(cert, "BC"); // check validation tsResp.validate(request); // check tstInfo TimeStampTokenInfo tstInfo = tsToken.getTimeStampInfo(); // check accuracy GenTimeAccuracy accuracy = tstInfo.getGenTimeAccuracy(); assertEquals(3, accuracy.getSeconds()); assertEquals(1, accuracy.getMillis()); assertEquals(2, accuracy.getMicros()); assertEquals(new BigInteger("23"), tstInfo.getSerialNumber()); assertEquals("1.2.3", tstInfo.getPolicy()); assertEquals(true, tstInfo.isOrdered()); assertEquals(tstInfo.getNonce(), BigInteger.valueOf(100)); // test certReq CertStore store = tsToken.getCertificatesAndCRLs("Collection", "BC"); Collection certificates = store.getCertificates(null); assertEquals(2, certificates.size()); } private void testNoNonse( PrivateKey privateKey, X509Certificate cert, CertStore certs) throws Exception { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TSPAlgorithms.MD5, "1.2.3"); tsTokenGen.setCertificatesAndCRLs(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, new byte[20]); assertFalse(request.getCertReq()); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TSPAlgorithms.ALLOWED); TimeStampResponse tsResp = tsRespGen.generate(request, new BigInteger("24"), new Date(), "BC"); tsResp = new TimeStampResponse(tsResp.getEncoded()); TimeStampToken tsToken = tsResp.getTimeStampToken(); tsToken.validate(cert, "BC"); // check validation tsResp.validate(request); // check tstInfo TimeStampTokenInfo tstInfo = tsToken.getTimeStampInfo(); // check accuracy GenTimeAccuracy accuracy = tstInfo.getGenTimeAccuracy(); assertNull(accuracy); assertEquals(new BigInteger("24"), tstInfo.getSerialNumber()); assertEquals("1.2.3", tstInfo.getPolicy()); assertEquals(false, tstInfo.isOrdered()); assertNull(tstInfo.getNonce()); // test certReq CertStore store = tsToken.getCertificatesAndCRLs("Collection", "BC"); Collection certificates = store.getCertificates(null); assertEquals(0, certificates.size()); } }
/* * $Id: TestV3Poller.java,v 1.69 2014-12-27 03:41:35 tlipkis Exp $ */ package org.lockss.poller.v3; import java.io.*; import java.util.*; import java.security.*; import org.lockss.app.*; import org.lockss.config.ConfigManager; import org.lockss.daemon.ConfigParamDescr; import org.lockss.daemon.ShouldNotHappenException; import org.lockss.plugin.*; import org.lockss.plugin.base.DefaultUrlCacher; import org.lockss.protocol.*; import org.lockss.util.*; import org.lockss.poller.*; import org.lockss.poller.v3.V3Serializer.*; import org.lockss.test.*; import org.lockss.hasher.*; import org.lockss.state.*; import static org.lockss.util.Constants.*; public class TestV3Poller extends LockssTestCase { private MyIdentityManager idMgr; private MockLockssDaemon theDaemon; private PeerIdentity pollerId; private String tempDirPath; private MockArchivalUnit testau; private PollManager pollmanager; private HashService hashService; private PluginManager pluginMgr; private PeerIdentity[] voters; private V3LcapMessage[] pollAcks; private V3LcapMessage[] nominates; private V3LcapMessage[] votes; private V3LcapMessage[] repairs; private byte[][] pollerNonces; private byte[][] voterNonces; private byte[][] voterNonce2s; private String localPeerKey = "TCP:[127.0.0.1]:9729"; private File tempDir; private static final String BASE_URL = "http: private List initialPeers = ListUtil.list("TCP:[10.1.0.1]:9729", "TCP:[10.1.0.2]:9729", "TCP:[10.1.0.3]:9729", "TCP:[10.1.0.4]:9729", "TCP:[10.1.0.5]:9729", "TCP:[10.1.0.6]:9729"); private static String[] urls = { "lockssau:", BASE_URL, BASE_URL + "index.html", BASE_URL + "file1.html", BASE_URL + "file2.html", BASE_URL + "branch1/", BASE_URL + "branch1/index.html", BASE_URL + "branch1/file1.html", BASE_URL + "branch1/file2.html", BASE_URL + "branch2/", BASE_URL + "branch2/index.html", BASE_URL + "branch2/file1.html", BASE_URL + "branch2/file2.html", }; private static List voteBlocks; static { voteBlocks = new ArrayList(); for (int ix = 0; ix < urls.length; ix++) { VoteBlock vb = V3TestUtils.makeVoteBlock(urls[ix]); voteBlocks.add(vb); } } public void setUp() throws Exception { super.setUp(); theDaemon = getMockLockssDaemon(); TimeBase.setSimulated(); this.tempDir = getTempDir(); this.testau = setupAu(); initRequiredServices(); setupRepo(testau); this.pollerId = findPeerIdentity(localPeerKey); this.voters = makeVoters(initialPeers); this.pollerNonces = makeNonces(); this.voterNonces = makeNonces(); this.voterNonce2s = makeNonces(); this.pollAcks = makePollAckMessages(); this.nominates = makeNominateMessages(); this.votes = makeVoteMessages(); this.repairs = makeRepairMessages(); ConfigurationUtil.addFromArgs(PollManager.PARAM_MIN_TIME_BETWEEN_ANY_POLL, "" + (1 * SECOND)); } private MockArchivalUnit setupAu() { MockArchivalUnit mau = new MockArchivalUnit(); mau.setAuId("mock"); MockPlugin plug = new MockPlugin(theDaemon); mau.setPlugin(plug); MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet(); cus.setEstimatedHashDuration(1000); List files = new ArrayList(); for (int ix = 0; ix < urls.length; ix++) { MockCachedUrl cu = (MockCachedUrl)mau.addUrl(urls[ix], false, true); // Add mock file content. cu.setContent("This is content for CUS file " + ix); files.add(cu); } cus.setHashItSource(files); cus.setFlatItSource(files); return mau; } private void setupRepo(ArchivalUnit au) throws Exception { MockLockssRepository repo = new MockLockssRepository("/foo", au); for (int ix = 0; ix < urls.length; ix++) { repo.createNewNode(urls[ix]); } ((MockLockssDaemon)theDaemon).setLockssRepository(repo, au); } PeerIdentity findPeerIdentity(String key) throws Exception { PeerIdentity pid = idMgr.findPeerIdentity(key); // hack to ensure it's created idMgr.findLcapIdentity(pid, pid.getIdString()); return pid; } private PeerIdentity[] makeVoters(List keys) throws Exception { PeerIdentity[] ids = new PeerIdentity[keys.size()]; int idIndex = 0; for (Iterator it = keys.iterator(); it.hasNext(); ) { PeerIdentity pid = findPeerIdentity((String)it.next()); PeerIdentityStatus status = idMgr.getPeerIdentityStatus(pid); ids[idIndex++] = pid; } return ids; } private byte[][] makeNonces() { byte[][] nonces = new byte[voters.length][]; for (int ix = 0; ix < voters.length; ix++) { nonces[ix] = ByteArray.makeRandomBytes(20); } return nonces; } private V3LcapMessage[] makePollAckMessages() { V3LcapMessage[] msgs = new V3LcapMessage[voters.length]; for (int i = 0; i < voters.length; i++) { msgs[i] = new V3LcapMessage("auid", "key", "1", ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), V3LcapMessage.MSG_POLL_ACK, 987654321, voters[i], tempDir, theDaemon); } return msgs; } private V3LcapMessage[] makeNominateMessages() { V3LcapMessage[] msgs = new V3LcapMessage[voters.length]; for (int i = 0; i < voters.length; i++) { V3LcapMessage msg = new V3LcapMessage("auid", "key", "1", ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), V3LcapMessage.MSG_NOMINATE, 987654321, voters[i], tempDir, theDaemon); msg.setNominees(ListUtil.list("TCP:[10.0." + i + ".1]:9729", "TCP:[10.0." + i + ".2]:9729", "TCP:[10.0." + i + ".3]:9729", "TCP:[10.0." + i + ".4]:9729")); msgs[i] = msg; } return msgs; } private V3LcapMessage[] makeVoteMessages() throws IOException { V3LcapMessage[] msgs = new V3LcapMessage[voters.length]; for (int i = 0; i < voters.length; i++) { V3LcapMessage msg = new V3LcapMessage("auid", "key", "1", ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), V3LcapMessage.MSG_VOTE, 987654321, voters[i], tempDir, theDaemon); for (Iterator it = voteBlocks.iterator(); it.hasNext(); ) { msg.addVoteBlock((VoteBlock)it.next()); } msgs[i] = msg; } return msgs; } private V3LcapMessage[] makeRepairMessages() { V3LcapMessage[] msgs = new V3LcapMessage[voters.length]; for (int i = 0; i < voters.length; i++) { V3LcapMessage msg = new V3LcapMessage("auid", "key", "1", ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), ByteArray.makeRandomBytes(20), V3LcapMessage.MSG_REPAIR_REP, 987654321, voters[i], tempDir, theDaemon); msgs[i] = msg; } return msgs; } public void tearDown() throws Exception { theDaemon.getLockssRepository(testau).stopService(); theDaemon.getHashService().stopService(); theDaemon.getDatagramRouterManager().stopService(); theDaemon.getRouterManager().stopService(); theDaemon.getSystemMetrics().stopService(); theDaemon.getPollManager().stopService(); TimeBase.setReal(); super.tearDown(); } double invitationWeight(long lastInvite, long lastMsg) throws Exception { String id = "tcp:[1.2.3.4]:4321"; V3Poller poller = makeV3Poller("testing poll key"); PeerIdentity pid = findPeerIdentity(id); idMgr.findLcapIdentity(pid, id); PeerIdentityStatus status = idMgr.getPeerIdentityStatus(pid); status.setLastMessageTime(lastMsg); status.setLastPollInvitationTime(lastInvite); return poller.weightResponsiveness(status); } String w1 = "tcp:[1.2.3.4]:4321"; String w2 = "tcp:[1.2.3.4]:4322"; String atRiskEntry(ArchivalUnit au, String pidkey) throws Exception { return atRiskEntry(au, findPeerIdentity(pidkey)); } String atRiskEntry(ArchivalUnit au, PeerIdentity pid) { return testau.getAuId() + "," + pid.getIdString(); } double invitationWeight(String pidkey, long lastInvite, long lastMsg) throws Exception { return invitationWeight(findPeerIdentity(pidkey), lastInvite, lastMsg); } double invitationWeight(String pidkey, long lastInvite, long lastMsg, float highestAgreement) throws Exception { return invitationWeight(findPeerIdentity(pidkey), lastInvite, lastMsg, highestAgreement); } double invitationWeight(PeerIdentity pid, long lastInvite, long lastMsg) throws Exception { return invitationWeight(pid, lastInvite, lastMsg, 0.1f); } double invitationWeight(PeerIdentity pid, long lastInvite, long lastMsg, float highestAgreement) throws Exception { ConfigurationUtil.addFromArgs(V3Poller.PARAM_AT_RISK_AU_INSTANCES, atRiskEntry(testau, w2), V3Poller.PARAM_INVITATION_WEIGHT_AT_RISK, "3.0"); V3Poller poller = makeV3Poller("testing poll key"); PeerIdentityStatus status = idMgr.getPeerIdentityStatus(pid); status.setLastMessageTime(lastMsg); status.setLastPollInvitationTime(lastInvite); if (highestAgreement >= 0) { idMgr.signalPartialAgreement(pid, testau, highestAgreement); } return poller.invitationWeight(status); } public void testInvitationWeight() throws Exception { // default age curve: [10d,1.0],[30d,0.1],[40d,0.01] assertEquals(1.0, invitationWeight(w1, -1, -1)); // w2 is listed as having this AU at risk assertEquals(3.0, invitationWeight(w2, -1, -1)); // With high agreement, invitationWeightAlreadyRepairable kicks in (.5) assertEquals(0.5, invitationWeight(w1, -1, -1, .9f)); assertEquals(1.5, invitationWeight(w2, -1, -1, .9f)); } public void testInvitationWeightAgeCurve() throws Exception { // default is [10d,1.0],[30d,0.1],[40d,0.01] double r1 = .01*90.0/16.0; double r2 = .01*9.0/20.0; assertEquals(1.0, invitationWeight(-1, -1)); assertEquals(1.0, invitationWeight(-1, 0)); assertEquals(1.0, invitationWeight(0, -1)); assertEquals(1.0, invitationWeight(0, 0)); assertEquals(1.0, invitationWeight(1, 1)); assertEquals(1.0, invitationWeight(10, 1)); assertEquals(1.0, invitationWeight(1, 10)); assertEquals(1.0, invitationWeight(1*DAY, 0), .01); assertEquals(1.0, invitationWeight(4*DAY, 0), .01); assertEquals(1.0, invitationWeight(44*DAY, 40*DAY), .01); assertEquals(.94, invitationWeight(5*DAY, 0), .01); assertEquals(1.0-r1, invitationWeight(5*DAY, 0), .02); assertEquals(.94, invitationWeight(105*DAY, 100*DAY), .01); assertEquals(.55, invitationWeight(112*DAY, 100*DAY), .01); assertEquals(.10, invitationWeight(120*DAY, 100*DAY), .01); assertEquals(.01, invitationWeight(140*DAY, 100*DAY), .01); ConfigurationUtil.addFromArgs(V3Poller.PARAM_INVITATION_WEIGHT_AGE_CURVE, "[1w,1.0],[20w,.1]"); assertEquals(1.0, invitationWeight(1*WEEK, 0), .01); assertEquals(0.1, invitationWeight(20*WEEK, 0), .01); } /* Test for a specific bug fix. */ public void testNullNomineesShouldntThrow() throws Exception { V3Poller v3Poller = makeInittedV3Poller("foo"); try { v3Poller.nominatePeers(voters[2], null); } catch (NullPointerException ex) { fail("Should not have caused NullPointerException", ex); } } public void testParticipantSizesAll() throws Exception { // All symmetric participants V3Poller v3Poller = makeInittedV3Poller("foo"); doTestParticipantSizes(v3Poller, initialPeers.size(), voters.length); } public void testParticipantSizesTwo() throws Exception { // 2 symmetric participants V3Poller v3Poller = makeInittedV3Poller("foo", 2); doTestParticipantSizes(v3Poller, 2, voters.length); } public void testParticipantSizesNone() throws Exception { // No symmetric participants V3Poller v3Poller = makeInittedV3Poller("foo", 0); doTestParticipantSizes(v3Poller, 0, voters.length); } public void testParticipantSizesNoVoters() throws Exception { // No participants Properties p = new Properties(); // Set PARAM_V3_ENABLE_LOCAL_POLLS true p.setProperty(V3Poller.PARAM_V3_ENABLE_LOCAL_POLLS, "true"); // Set PARAM_V3_ALL_LOCAL_POLLS true p.setProperty(V3Poller.PARAM_V3_ALL_LOCAL_POLLS, "true"); ConfigurationUtil.addFromProps(p); V3Poller v3Poller = makeInittedV3Poller("foo", 0, 0); doTestParticipantSizes(v3Poller, 0, 0); } protected void doTestParticipantSizes(V3Poller v3Poller, int numSym, int numVoters) throws Exception { Map<PeerIdentity,ParticipantUserData> innerCircle = theParticipants(v3Poller); assertEquals(numVoters, innerCircle.size()); List<ParticipantUserData> symmetricParticipants = symmetricParticipants(v3Poller); assertTrue(symmetricParticipants.size() == numSym); } public void testSubstanceChecker() throws Exception { V3Poller v3Poller = makeInittedV3Poller("foo", 0, 0); List<String> pats = ListUtil.list("foo"); testau.setSubstanceUrlPatterns(RegexpUtil.compileRegexps(pats)); SubstanceChecker sub = v3Poller.makeSubstanceChecker(); assertNull(sub); MockPlugin mplug = (MockPlugin)testau.getPlugin(); mplug.setFeatureVersionMap(MapUtil.map(Plugin.Feature.Substance, "2")); sub = v3Poller.makeSubstanceChecker(); assertNotNull(sub); AuState aus = AuUtil.getAuState(testau); assertEquals(SubstanceChecker.State.Unknown, aus.getSubstanceState()); v3Poller.updateSubstance(sub); assertEquals(SubstanceChecker.State.No, aus.getSubstanceState()); sub.checkSubstance("http://foo"); v3Poller.updateSubstance(sub); assertEquals(SubstanceChecker.State.Yes, aus.getSubstanceState()); } public void testMakeHasher() throws Exception { V3Poller v3Poller = makeInittedV3Poller("foo", 0, 0); BlockHasher hasher = v3Poller.makeHasher(testau.getAuCachedUrlSet(), -1, false, null); assertFalse("Hasher: " + hasher + " shouldn't be a SampledBlockHasher", hasher instanceof SampledBlockHasher); assertTrue(hasher.isExcludeSuspectVersions()); hasher = v3Poller.makeHasher(testau.getAuCachedUrlSet(), -1, true, null); assertFalse("Hasher: " + hasher + " shouldn't be a SampledBlockHasher", hasher instanceof SampledBlockHasher); assertTrue(hasher.isExcludeSuspectVersions()); } public void testMakeHasherSampled() throws Exception { ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_ENABLE_POP_POLLS, "true", V3Poller.PARAM_V3_ALL_POP_POLLS, "true", V3Poller.PARAM_V3_MODULUS, "1000"); V3Poller v3Poller = makeInittedV3Poller("foo", 0, 0); BlockHasher hasher = v3Poller.makeHasher(testau.getAuCachedUrlSet(), -1, false, null); assertTrue("Hasher: " + hasher + " should be a SampledBlockHasher", hasher instanceof SampledBlockHasher); assertTrue(hasher.isExcludeSuspectVersions()); // Make a repair hasher, shouldn't be sampled hasher = v3Poller.makeHasher(testau.getAuCachedUrlSet(), -1, true, null); assertFalse("Hasher: " + hasher + " shouldn't be a SampledBlockHasher", hasher instanceof SampledBlockHasher); assertTrue(hasher.isExcludeSuspectVersions()); } public void testMakeHasherNoExcludeSuspect() throws Exception { ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_EXCLUDE_SUSPECT_VERSIONS, "false"); V3Poller v3Poller = makeInittedV3Poller("foo", 0, 0); BlockHasher hasher = v3Poller.makeHasher(testau.getAuCachedUrlSet(), -1, false, null); assertFalse("Hasher: " + hasher + " shouldn't be a SampledBlockHasher", hasher instanceof SampledBlockHasher); assertFalse(hasher.isExcludeSuspectVersions()); } public void testInitHasherByteArraysAll() throws Exception { // All symmetric participants V3Poller v3Poller = makeInittedV3Poller("foo"); doTestInitHasherByteArrays(v3Poller, initialPeers.size()); } public void testInitHasherByteArraysTwo() throws Exception { // 2 symmetric participants V3Poller v3Poller = makeInittedV3Poller("foo", 2); doTestInitHasherByteArrays(v3Poller, 2); } public void testInitHasherByteArraysNone() throws Exception { // No symmetric participants V3Poller v3Poller = makeInittedV3Poller("foo", 0); doTestInitHasherByteArrays(v3Poller, 0); } protected void doTestInitHasherByteArrays(V3Poller v3Poller, int numSym) throws Exception { Map<PeerIdentity,ParticipantUserData> innerCircle = theParticipants(v3Poller); List<ParticipantUserData> symmetricParticipants = symmetricParticipants(v3Poller); byte[][] initBytes = (byte[][])PrivilegedAccessor. invokeMethod(v3Poller, "initHasherByteArrays"); // Expected size is number of inner circle peers hash plus number // of peers that request symmetric polls plus one for the plain. int expectedSize = innerCircle.size() + symmetricParticipants.size() + 1; assertEquals(initBytes.length, expectedSize); byte[][] compareBytes = new byte[expectedSize][]; int ix = 0; for (Iterator<ParticipantUserData> it = innerCircle.values().iterator(); it.hasNext();) { ParticipantUserData proxy = it.next(); compareBytes[ix++] = ByteArray.concat(proxy.getPollerNonce(), proxy.getVoterNonce()); } for (Iterator<ParticipantUserData> it = symmetricParticipants.iterator(); it.hasNext();) { ParticipantUserData proxy = it.next(); assertNotNull(proxy.getVoterNonce2()); compareBytes[ix++] = ByteArray.concat(proxy.getPollerNonce(), proxy.getVoterNonce2()); } compareBytes[ix++] = new byte[0]; // Plain hash for (ix = 0; ix < initBytes.length; ix++) { assertTrue("Index " + ix + " bytes mismatch", Arrays.equals(initBytes[ix], compareBytes[ix])); } } public void testInitHasherDigestsAll() throws Exception { V3Poller v3Poller = makeInittedV3Poller("foo"); doTestInitHasherDigests(v3Poller, initialPeers.size()); } public void testInitHasherDigestsTwo() throws Exception { V3Poller v3Poller = makeInittedV3Poller("foo", 2); doTestInitHasherDigests(v3Poller, 2); } public void testInitHasherDigestsNone() throws Exception { V3Poller v3Poller = makeInittedV3Poller("foo", 0); doTestInitHasherDigests(v3Poller, 0); } public void doTestInitHasherDigests(V3Poller v3Poller, int numSym) throws Exception { Map<PeerIdentity,ParticipantUserData> innerCircle = theParticipants(v3Poller); MessageDigest[] digests = (MessageDigest[])PrivilegedAccessor. invokeMethod(v3Poller, "initHasherDigests"); List<ParticipantUserData> symmetricParticipants = symmetricParticipants(v3Poller); // Expected size is number of inner circle peers hash plus number // of peers that request symmetric polls plus one for the plain. int expectedSize = innerCircle.size() + symmetricParticipants.size() + 1; assertEquals(digests.length, expectedSize); for (int i = 0; i < digests.length; i++) { assertNotNull("Digest " + i + " unexpectedly null.", digests[i]); assertEquals("SHA-1", digests[i].getAlgorithm()); } } private HashBlock makeHashBlock(String url) { MockCachedUrl cu = new MockCachedUrl(url); return new HashBlock(cu); } private HashBlock makeHashBlock(String url, String content) throws Exception { return makeHashBlock(url, content, 5); } private HashBlock makeHashBlock(String url, String content, int nHashes) throws Exception { MockCachedUrl cu = new MockCachedUrl(url); HashBlock hb = new HashBlock(cu); addVersion(hb, content, nHashes); return hb; } private static int hbVersionNum = 1; private void addVersion(HashBlock block, String content) throws Exception { addVersion(block, content, 5); // 4 voters plus plain hash } private void addVersion(HashBlock block, String content, int nHashes) throws Exception { MessageDigest[] digests = new MessageDigest[nHashes]; for (int ix = 0; ix < nHashes; ix++) { digests[ix] = MessageDigest.getInstance("SHA1"); digests[ix].update(content.getBytes()); } block.addVersion(0, content.length(), 0, content.length(), digests.length * content.length(), // total bytes hashed digests, TestV3Poller.hbVersionNum++, null); } private VoteBlock makeVoteBlock(String url) { VoteBlock vb = new VoteBlock(url); return vb; } private VoteBlock makeVoteBlock(String url, String... contents) throws Exception { VoteBlock vb = new VoteBlock(url); for (String content: contents) { addVersion(vb, content); } return vb; } private void addVersion(VoteBlock block, String content) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(content.getBytes()); byte[] hash = md.digest(); block.addVersion(0, content.length(), 0, content.length(), hash, hash, false); } private ParticipantUserData makeParticipant(PeerIdentity id, V3Poller poller, VoteBlock [] votes) throws Exception { byte[] pollerNonce = ByteArray.makeRandomBytes(20); ParticipantUserData ud = new ParticipantUserData(id, poller, tempDir); ud.setPollerNonce(pollerNonce); VoteBlocks vb = new DiskVoteBlocks(tempDir); for (int i = 0; i < votes.length; i++) { vb.addVoteBlock(votes[i]); } ud.setVoteBlocks(vb); return ud; } /* * XXX DSHR this should be in TestPollManager since that's * XXX where the code is now. */ public void testCountLastPoRAgreePeers() throws Exception { TimeBase.setSimulated(1000L); V3Poller v3Poller = makeV3Poller("testing poll key"); ArchivalUnit au = v3Poller.getAu(); assertNotNull(au); assertTrue(au instanceof MockArchivalUnit); MockArchivalUnit mau = (MockArchivalUnit)au; AuState aus = AuUtil.getAuState(au); assertNotNull(aus); assertTrue(aus instanceof MockAuState); MockAuState maus = (MockAuState)aus; maus.setLastTopLevelPollTime(200L); assertEquals(200L, maus.getLastTopLevelPollTime()); maus.setPollDuration(100L); assertEquals(100L, maus.getPollDuration()); Map agreeMap = idMgr.getAgreed(mau); assertNotNull(agreeMap); assertEquals(0L, agreeMap.size()); PeerIdentity p1 = findPeerIdentity("TCP:[127.0.0.1]:5009"); assertFalse(p1.isLocalIdentity()); PeerIdentity p2 = findPeerIdentity("TCP:[1.2.3.4]:5009"); assertFalse(p2.isLocalIdentity()); PeerIdentity p3 = findPeerIdentity("TCP:[1.2.3.7]:1111"); assertFalse(p3.isLocalIdentity()); PeerIdentity p4 = findPeerIdentity("TCP:[1.2.3.8]:1111"); assertFalse(p4.isLocalIdentity()); PeerIdentity p5 = findPeerIdentity("TCP:[4.5.6.2]:1111"); assertFalse(p5.isLocalIdentity()); // Add local ID - local poll finished at 900 agreeMap.put(pollerId, 900L); assertEquals(0, pollmanager.countLastPoRAgreePeers(mau, maus)); // Add result of PoP poll finished at 700 agreeMap.put(p5, 700L); agreeMap.put(p4, 700L); assertEquals(0, pollmanager.countLastPoRAgreePeers(mau, maus)); // Add result of PoR poll between 0 and 100 agreeMap.put(p3, 10L); agreeMap.put(p2, 20L); agreeMap.put(p1, 30L); assertEquals(0, pollmanager.countLastPoRAgreePeers(mau, maus)); // Add result of PoR poll between 100 and 200 agreeMap.put(p3, 150L); agreeMap.put(p2, 160L); agreeMap.put(p1, 170L); assertEquals(3, pollmanager.countLastPoRAgreePeers(mau, maus)); // Make it look like p1 subsequently agreed in a PoP poll agreeMap.put(p3, 500L); assertEquals(2, pollmanager.countLastPoRAgreePeers(mau, maus)); } /* * XXX DSHR these should be in TestPollManager since that's * XXX where the code is now. */ public void testChoosePollVariantPorOnly() throws Exception { testChoosePollVariant(false, false); } public void testChoosePollVariantPoRPoP() throws Exception { testChoosePollVariant(true, false); } public void testChoosePollVariantPoRLocal() throws Exception { testChoosePollVariant(false, true); } public void testChoosePollVariantPoRPoPLocal() throws Exception { testChoosePollVariant(true, true); } private V3Poller.PollVariant choosePollVariant(ArchivalUnit au) { long maxDelayBetweenPoR = PollManager.DEFAULT_MAX_DELAY_BETWEEN_POR_MULTIPLIER * PollManager.DEFAULT_TOPLEVEL_POLL_INTERVAL; return pollmanager.choosePollVariant(au, maxDelayBetweenPoR); } /* * The choosePollVariant() logic has the following cases: * A) Too soon to call poll - NoPoll * B) PoP poll forced - PoP * C) Local poll forced - Local * D) suspect versions found - PoR * E) content changed since last PoR - PoR * F) good agreement last PoR & too few repairers - PoP * G) good agreement last PoR & enough repairers - Local * H) poor agreement last PoR - PoR */ public void testChoosePollVariant(boolean enablePoPPolls, boolean enableLocalPolls) throws Exception { ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_ENABLE_POP_POLLS, "" + enablePoPPolls, V3Poller.PARAM_V3_ENABLE_LOCAL_POLLS, "" + enableLocalPolls, V3Poller.PARAM_THRESHOLD_REPAIRERS_LOCAL_POLLS, "3", PollManager.PARAM_MIN_AGREE_PEERS_LAST_POR_POLL, "2"); ConfigurationUtil.addFromArgs(BlockHasher.PARAM_ENABLE_LOCAL_HASH, "true", BlockHasher.PARAM_LOCAL_HASH_ALGORITHM, BlockHasher.DEFAULT_LOCAL_HASH_ALGORITHM, DefaultUrlCacher.PARAM_CHECKSUM_ALGORITHM, BlockHasher.DEFAULT_LOCAL_HASH_ALGORITHM, V3Poller.PARAM_V3_MODULUS, "2"); TimeBase.setSimulated(1000L); V3Poller v3Poller = makeV3Poller("testing poll key"); ArchivalUnit au = v3Poller.getAu(); assertNotNull(au); assertTrue(au instanceof MockArchivalUnit); MockArchivalUnit mau = (MockArchivalUnit)au; AuState aus = AuUtil.getAuState(au); assertNotNull(aus); assertTrue(aus instanceof MockAuState); MockAuState maus = (MockAuState)aus; PollSpec ps = v3Poller.getPollSpec(); assertNotNull(ps); Map agreeMap = idMgr.getAgreed(mau); assertNotNull(agreeMap); assertEquals(0L, agreeMap.size()); PeerIdentity p1 = findPeerIdentity("TCP:[127.0.0.1]:5009"); assertFalse(p1.isLocalIdentity()); PeerIdentity p2 = findPeerIdentity("TCP:[1.2.3.4]:5009"); assertFalse(p2.isLocalIdentity()); PeerIdentity p3 = findPeerIdentity("TCP:[1.2.3.7]:1111"); assertFalse(p3.isLocalIdentity()); PeerIdentity p4 = findPeerIdentity("TCP:[1.2.3.8]:1111"); assertFalse(p4.isLocalIdentity()); PeerIdentity p5 = findPeerIdentity("TCP:[4.5.6.2]:1111"); assertFalse(p5.isLocalIdentity()); // First poll is PoR - case H assertEquals(V3Poller.PollVariant.PoR, choosePollVariant(au)); // Now crawl and get content maus.setLastContentChange(100); maus.setLastCrawlTime(100); // Case A maus.setLastPollStart(1000L); assertEquals(V3Poller.PollVariant.NoPoll, choosePollVariant(au)); maus.setLastPollStart(0L); // Case E assertEquals(V3Poller.PollVariant.PoR, choosePollVariant(au)); // Now poll but get disagreement maus.setLastTopLevelPollTime(200); maus.setPollDuration(100L); // Case H assertEquals(V3Poller.PollVariant.PoR, choosePollVariant(au)); // Now get 2 agreements, repairer threshold is 3 agreeMap.put(p3, 150L); agreeMap.put(p2, 160L); // We have to update the AuState too aus.setNumAgreePeersLastPoR(2); aus.setNumWillingRepairers(2); // Case F assertEquals( enablePoPPolls ? V3Poller.PollVariant.PoP : V3Poller.PollVariant.PoR, choosePollVariant(au)); // Add another agreement agreeMap.put(p1, 170L); aus.setNumAgreePeersLastPoR(3); aus.setNumWillingRepairers(3); // Case G assertEquals( enableLocalPolls ? V3Poller.PollVariant.Local : V3Poller.PollVariant.PoR, choosePollVariant(au)); // Now crawl again, but get no content maus.setLastCrawlTime(300); // Case G assertEquals( enableLocalPolls ? V3Poller.PollVariant.Local : V3Poller.PollVariant.PoR, choosePollVariant(au)); // Now crawl again, get content maus.setLastCrawlTime(300); maus.setLastContentChange(300); // Case E assertEquals(V3Poller.PollVariant.PoR, choosePollVariant(au)); // Now poll but get disagreement maus.setLastTopLevelPollTime(500); maus.setPollDuration(100L); aus.setNumAgreePeersLastPoR(0); // Case H assertEquals(V3Poller.PollVariant.PoR, choosePollVariant(au)); // Now get 3 agreement, repairer threshold is 3 agreeMap.put(p3, 450L); agreeMap.put(p2, 460L); agreeMap.put(p1, 460L); aus.setNumAgreePeersLastPoR(3); // Case G assertEquals( enableLocalPolls ? V3Poller.PollVariant.Local : V3Poller.PollVariant.PoR, choosePollVariant(au)); // Case D - XXX not yet implemented if (enableLocalPolls) { // Case C ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_ALL_LOCAL_POLLS, "true"); assertEquals(V3Poller.PollVariant.Local, choosePollVariant(au)); } if (enablePoPPolls) { // Case B ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_ALL_POP_POLLS, "true"); assertEquals(V3Poller.PollVariant.PoP, choosePollVariant(au)); } } public void testIsPeerEligible() throws Exception { V3Poller v3Poller = makeV3Poller("testing poll key"); assertFalse(v3Poller.isPeerEligible(pollerId)); PeerIdentity p1 = findPeerIdentity("TCP:[127.0.0.1]:5009"); PeerIdentity p2 = findPeerIdentity("TCP:[1.2.3.4]:5009"); PeerIdentity p3 = findPeerIdentity("TCP:[1.2.3.7]:1111"); PeerIdentity p4 = findPeerIdentity("TCP:[1.2.3.8]:1111"); PeerIdentity p5 = findPeerIdentity("TCP:[4.5.6.2]:1111"); assertTrue(v3Poller.isPeerEligible(p1)); assertTrue(v3Poller.isPeerEligible(p2)); assertTrue(v3Poller.isPeerEligible(p3)); assertTrue(v3Poller.isPeerEligible(p4)); assertTrue(v3Poller.isPeerEligible(p5)); ConfigurationUtil.addFromArgs(V3Poller.PARAM_NO_INVITATION_SUBNETS, "1.2.3.4/30;4.5.6.2"); assertTrue(v3Poller.isPeerEligible(p1)); assertFalse(v3Poller.isPeerEligible(p2)); assertFalse(v3Poller.isPeerEligible(p3)); assertTrue(v3Poller.isPeerEligible(p4)); assertFalse(v3Poller.isPeerEligible(p5)); } Collection getAvailablePeers(V3Poller v3Poller) { return v3Poller.getAvailablePeers().keySet(); } public void testGetAvailablePeers() throws Exception { PeerIdentity p1 = findPeerIdentity("TCP:[10.1.0.100]:9729"); PeerIdentity p2 = findPeerIdentity("TCP:[10.1.0.101]:9729"); DatedPeerIdSet noAuSet = pollmanager.getNoAuPeerSet(testau); synchronized (noAuSet) { noAuSet.add(p2); } assertTrue(noAuSet.contains(p2)); V3Poller v3Poller = makeV3Poller("testing poll key"); Collection avail = getAvailablePeers(v3Poller); log.info("avail: " + avail); assertTrue(avail.contains(p1)); assertFalse(avail.contains(p2)); Set exp = new HashSet(); exp.add(p1); for (PeerIdentity pid : voters) { exp.add(pid); } assertEquals(exp, avail); } public void testGetAvailablePeersInitialPeersOnly() throws Exception { ConfigurationUtil.addFromArgs(V3Poller.PARAM_ENABLE_DISCOVERY, "false"); findPeerIdentity("TCP:[10.1.0.100]:9729"); findPeerIdentity("TCP:[10.1.0.101]:9729"); V3Poller v3Poller = makeV3Poller("testing poll key"); assertNotNull(getAvailablePeers(v3Poller)); assertEquals(6, getAvailablePeers(v3Poller).size()); } public void testGetAvailablePeersDoesNotIncludeLocalIdentity() throws Exception { ConfigurationUtil.addFromArgs(V3Poller.PARAM_ENABLE_DISCOVERY, "false"); // append our local config to the initial Peer List List initialPeersCopy = new ArrayList(initialPeers); initialPeersCopy.add(localPeerKey); ConfigurationUtil.addFromArgs(IdentityManagerImpl.PARAM_INITIAL_PEERS, StringUtil.separatedString(initialPeersCopy, ";")); V3Poller v3Poller = makeV3Poller("testing poll key"); assertNotNull(getAvailablePeers(v3Poller)); // Sanity check assertTrue(findPeerIdentity(localPeerKey).isLocalIdentity()); // Should NOT be included in reference list assertEquals(6, getAvailablePeers(v3Poller).size()); assertFalse(getAvailablePeers(v3Poller).contains(findPeerIdentity(localPeerKey))); } public List<PeerIdentity> makeAdditionalPeers() throws Exception { PeerIdentity[] morePeers = { findPeerIdentity("TCP:[127.0.0.1]:5000"), findPeerIdentity("TCP:[127.0.0.1]:5001"), findPeerIdentity("TCP:[127.0.0.1]:5002"), findPeerIdentity("TCP:[127.0.0.1]:5003"), findPeerIdentity("TCP:[127.0.0.1]:5004"), findPeerIdentity("TCP:[127.0.0.1]:5005"), findPeerIdentity("TCP:[127.0.0.1]:5006"), findPeerIdentity("TCP:[127.0.0.1]:5007"), findPeerIdentity("TCP:[127.0.0.1]:5008"), findPeerIdentity("TCP:[127.0.0.1]:5009"), }; return ListUtil.fromArray(morePeers); } public void testCountParticipatingPeers() throws Exception { MyV3Poller poller = makeV3Poller("testing poll key"); List<String> somePeers = ListUtil.list(initialPeers.get(0), initialPeers.get(1), initialPeers.get(2)); List<PeerIdentity> participatingPeers = pidsFromPeerNames(somePeers); for (PeerIdentity pid : participatingPeers) { ParticipantUserData participant = poller.addInnerCircleVoter(pid); // make it look like it's participating participant.setStatus(V3Poller.PEER_STATUS_ACCEPTED_POLL); } assertEquals(3, poller.countParticipatingPeers()); } public Collection findMorePeersToInvite(int quorum, double invitationMult) throws Exception { Properties p = new Properties(); p.setProperty(V3Poller.PARAM_QUORUM, ""+quorum); p.setProperty(V3Poller.PARAM_INVITATION_SIZE_TARGET_MULTIPLIER, ""+invitationMult); ConfigurationUtil.addFromProps(p); MyV3Poller poller = makeV3Poller("testing poll key"); List<String> somePeers = ListUtil.list(initialPeers.get(0), initialPeers.get(1), initialPeers.get(2)); List<PeerIdentity> allPeers = pidsFromPeerNames(initialPeers); allPeers.addAll(makeAdditionalPeers()); List<PeerIdentity> participatingPeers = pidsFromPeerNames(somePeers); for (PeerIdentity pid : participatingPeers) { ParticipantUserData participant = poller.addInnerCircleVoter(pid); // make it look like it's participating participant.setStatus(V3Poller.PEER_STATUS_ACCEPTED_POLL); } Collection more = poller.findNPeersToInvite(quorum); assertTrue(more + " isn't disjoint with " + participatingPeers, CollectionUtil.isDisjoint(more, participatingPeers)); assertTrue(allPeers + " doesn't contain all of " + more, allPeers.containsAll(more)); return more; } public void testFindMore1() throws Exception { assertEquals(2, findMorePeersToInvite(2, 1).size()); } public void testFindMore2() throws Exception { assertEquals(4, findMorePeersToInvite(2, 2).size()); } public void testFindMore3() throws Exception { assertEquals(6, findMorePeersToInvite(3, 2).size()); } public void testFindMore4() throws Exception { assertEquals(10, findMorePeersToInvite(10, 1).size()); } public void testFindMore5() throws Exception { assertEquals(13, findMorePeersToInvite(10, 2).size()); } List<PeerIdentity> pidsFromPeerNames(Collection<String> names) throws Exception { List<PeerIdentity> res = new ArrayList(); for (String name : names) { res.add(findPeerIdentity(name)); } return res; } public void testTallyBlocksSucceedsOnExtraFileEdgeCase() throws Exception { V3Poller v3Poller = makeV3Poller("testing poll key"); PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); String [] urls_poller = { "http://test.com/foo1", "http://test.com/foo2", "http://test.com/foo3" }; HashBlock [] hashblocks = { makeHashBlock("http://test.com/foo1", "content for foo1"), makeHashBlock("http://test.com/foo2", "content for foo2"), makeHashBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2a", "content for foo2a"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter2_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2a", "content for foo2a"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter3_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; v3Poller.theParticipants.put(id1, makeParticipant(id1, v3Poller, voter1_voteblocks)); v3Poller.theParticipants.put(id2, makeParticipant(id2, v3Poller, voter2_voteblocks)); v3Poller.theParticipants.put(id3, makeParticipant(id3, v3Poller, voter3_voteblocks)); v3Poller.lockParticipants(); // Finally, let's test. BlockTally tally; // The results expected are based on a quorum of 3. assertEquals(3, v3Poller.getQuorum()); assertEquals(75, v3Poller.getVoteMargin()); tally = v3Poller.tallyBlock(hashblocks[0]); assertEquals(BlockTally.Result.WON, tally.getTallyResult()); assertSameElements(v3Poller.theParticipants.values(), tally.getAgreeVoters()); try { tally.getRepairVoters(); fail("expected ShouldNotHappenException was not thrown."); } catch (ShouldNotHappenException ex) { // Expected } tally = v3Poller.tallyBlock(hashblocks[1]); assertEquals(BlockTally.Result.LOST_POLLER_ONLY_BLOCK, tally.getTallyResult()); assertSameElements(v3Poller.theParticipants.values(), tally.getPollerOnlyBlockVoters()); try { tally.getRepairVoters(); fail("expected ShouldNotHappenException was not thrown."); } catch (ShouldNotHappenException ex) { // Expected } tally = v3Poller.tallyBlock(hashblocks[2]); assertEquals(BlockTally.Result.WON, tally.getTallyResult()); assertSameElements(v3Poller.theParticipants.values(), tally.getAgreeVoters()); assertEquals("2/0/1/1/0/0", v3Poller.theParticipants.get(id1).getVoteCounts().votes()); assertEquals("2/0/1/1/0/0", v3Poller.theParticipants.get(id2).getVoteCounts().votes()); // This voter sees a "neither" URL, since neither it nor the // poller has foo2a. assertEquals("2/0/1/0/1/0", v3Poller.theParticipants.get(id3).getVoteCounts().votes()); } public void testTallyBlocksSucceedsWithNoVersionVote() throws Exception { V3Poller v3Poller = makeV3Poller("testing poll key"); PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); PeerIdentity id4 = findPeerIdentity("TCP:[127.0.0.1]:8993"); String [] urls_poller = { "http://test.com/foo1", "http://test.com/foo2", "http://test.com/foo3" }; HashBlock [] hashblocks = { makeHashBlock("http://test.com/foo1", "content for foo1"), makeHashBlock("http://test.com/foo2", "content for foo2"), makeHashBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2a", "content for foo2a"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter2_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2a", "content for foo2a"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter3_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter4_voteblocks = { makeVoteBlock("http://test.com/foo1"), // voter3 votes "present" makeVoteBlock("http://test.com/foo2a", "content for foo2a"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; v3Poller.theParticipants.put(id1, makeParticipant(id1, v3Poller, voter1_voteblocks)); v3Poller.theParticipants.put(id2, makeParticipant(id2, v3Poller, voter2_voteblocks)); v3Poller.theParticipants.put(id3, makeParticipant(id3, v3Poller, voter3_voteblocks)); v3Poller.theParticipants.put(id4, makeParticipant(id4, v3Poller, voter4_voteblocks)); v3Poller.lockParticipants(); // Finally, let's test. BlockTally tally; // The results expected are based on a quorum of 3. assertEquals(3, v3Poller.getQuorum()); assertEquals(75, v3Poller.getVoteMargin()); tally = v3Poller.tallyBlock(hashblocks[0]); assertEquals(BlockTally.Result.WON, tally.getTallyResult()); // All but id4 should agree assertEquals(3, tally.getAgreeVoters().size()); Collection<ParticipantUserData> disagree = tally.getDisagreeVoters(); assertEquals(1, disagree.size()); assertTrue(disagree.contains(v3Poller.theParticipants.get(id4))); try { tally.getRepairVoters(); fail("expected ShouldNotHappenException was not thrown."); } catch (ShouldNotHappenException ex) { // Expected } tally = v3Poller.tallyBlock(hashblocks[1]); assertEquals(BlockTally.Result.LOST_POLLER_ONLY_BLOCK, tally.getTallyResult()); assertSameElements(v3Poller.theParticipants.values(), tally.getPollerOnlyBlockVoters()); try { tally.getRepairVoters(); fail("expected ShouldNotHappenException was not thrown."); } catch (ShouldNotHappenException ex) { // Expected } tally = v3Poller.tallyBlock(hashblocks[2]); assertEquals(BlockTally.Result.WON, tally.getTallyResult()); assertSameElements(v3Poller.theParticipants.values(), tally.getAgreeVoters()); // String is agree/disagree/pollerOnly/voterOnly/neither/spoiled assertEquals("2/0/1/1/0/0", v3Poller.theParticipants.get(id1).getVoteCounts().votes()); assertEquals("2/0/1/1/0/0", v3Poller.theParticipants.get(id2).getVoteCounts().votes()); // This voter sees a "neither" URL, since neither it nor the // poller has foo2a. assertEquals("2/0/1/0/1/0", v3Poller.theParticipants.get(id3).getVoteCounts().votes()); assertEquals("1/1/1/1/0/0", v3Poller.theParticipants.get(id4).getVoteCounts().votes()); } private Collection<String> publisherRepairUrls(V3Poller v3Poller) { PollerStateBean.RepairQueue repairQueue = v3Poller.getPollerStateBean().getRepairQueue(); return repairQueue.getPendingPublisherRepairUrls(); } private Collection<String> peerRepairUrls(V3Poller v3Poller) { PollerStateBean.RepairQueue repairQueue = v3Poller.getPollerStateBean().getRepairQueue(); List<PollerStateBean.Repair> peerRepairs = repairQueue.getPendingPeerRepairs(); Collection<String> peerRepairUrls = new ArrayList<String>(); for (PollerStateBean.Repair repair: peerRepairs) { peerRepairUrls.add(repair.getUrl()); } return peerRepairUrls; } public void testRequestRepair() throws Exception { MyV3Poller v3Poller; // 0% repair from cache: the repair goes to the publisher ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "0"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", theParticipants(v3Poller).values()); assertSameElements(Arrays.asList("http://example.com"), publisherRepairUrls(v3Poller)); assertEmpty(peerRepairUrls(v3Poller)); // 100% repair from cache: the repair goes to a peer ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "100"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", theParticipants(v3Poller).values()); assertEmpty(publisherRepairUrls(v3Poller)); assertSameElements(Arrays.asList("http://example.com"), peerRepairUrls(v3Poller)); // 0% repair from cache, and no repairers: the repair goes to the // publisher ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "0"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", Collections.EMPTY_LIST); assertSameElements(Arrays.asList("http://example.com"), publisherRepairUrls(v3Poller)); assertEmpty(peerRepairUrls(v3Poller)); // 100% repair from cache, BUT no repairers: the repair goes to // the publisher ANYWAY ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "100"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", Collections.EMPTY_LIST); assertSameElements(Arrays.asList("http://example.com"), publisherRepairUrls(v3Poller)); assertEmpty(peerRepairUrls(v3Poller)); } public void testRequestRepairPubDown() throws Exception { MyV3Poller v3Poller; // Mark AU down. testau.setConfiguration( ConfigurationUtil.fromArgs(ConfigParamDescr.PUB_DOWN.getKey(), "true")); // 100% repair from cache ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "100"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", theParticipants(v3Poller).values()); assertEmpty(publisherRepairUrls(v3Poller)); assertSameElements(Arrays.asList("http://example.com"), peerRepairUrls(v3Poller)); // 100% repair from cache, BUT no repairers. ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "100"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", Collections.EMPTY_LIST); assertEmpty(publisherRepairUrls(v3Poller)); assertEmpty(peerRepairUrls(v3Poller)); // 0% repair from cache; repair from cache anyway since pub down. ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "0"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", theParticipants(v3Poller).values()); assertEmpty(publisherRepairUrls(v3Poller)); assertSameElements(Arrays.asList("http://example.com"), peerRepairUrls(v3Poller)); // 0% repair from cache, BUT no repairers. ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "0"); v3Poller = makeInittedV3Poller("foo"); v3Poller.requestRepair("http://example.com", Collections.EMPTY_LIST); assertEmpty(publisherRepairUrls(v3Poller)); assertEmpty(peerRepairUrls(v3Poller)); } public void testRequestRepairUseVersionCounts() throws Exception { MyV3Poller v3Poller; PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); PeerIdentity id4 = findPeerIdentity("TCP:[127.0.0.1]:8993"); String [] urls_poller = { "http://test.com/foo1" }; HashBlock [] hashblocks = { makeHashBlock("http://test.com/foo1", "content for foo1HHH") }; VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1zzz", "content for foo1") }; VoteBlock [] voter2_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1yyy", "content for foo1") }; VoteBlock [] voter3_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1xxx", "content for foo1") }; VoteBlock [] voter4_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1www", "content for foo1") }; BlockTally tally; v3Poller = makeV3Poller("testing poll key"); // The results expected are based on a quorum of 3. assertEquals(3, v3Poller.getQuorum()); assertEquals(75, v3Poller.getVoteMargin()); // Prefer the cache in all cases ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "100"); ConfigurationUtil.addFromArgs(V3Poller.PARAM_USE_VERSION_COUNTS, "true"); v3Poller = makeV3Poller("testing poll key"); v3Poller.theParticipants.put(id1, makeParticipant(id1, v3Poller, voter1_voteblocks)); v3Poller.theParticipants.put(id2, makeParticipant(id2, v3Poller, voter2_voteblocks)); v3Poller.theParticipants.put(id3, makeParticipant(id3, v3Poller, voter3_voteblocks)); v3Poller.theParticipants.put(id4, makeParticipant(id4, v3Poller, voter4_voteblocks)); v3Poller.lockParticipants(); tally = v3Poller.tallyBlock(hashblocks[0]); assertEquals(BlockTally.Result.LOST, tally.getTallyResult()); assertEmpty(tally.getRepairVoters()); assertSameElements(theParticipants(v3Poller).values(), tally.getDisagreeVoters()); assertSameElements(Arrays.asList("http://test.com/foo1"), publisherRepairUrls(v3Poller)); assertEmpty(peerRepairUrls(v3Poller)); ConfigurationUtil.addFromArgs(V3Poller.PARAM_USE_VERSION_COUNTS, "false"); v3Poller = makeV3Poller("testing poll key"); v3Poller.theParticipants.put(id1, makeParticipant(id1, v3Poller, voter1_voteblocks)); v3Poller.theParticipants.put(id2, makeParticipant(id2, v3Poller, voter2_voteblocks)); v3Poller.theParticipants.put(id3, makeParticipant(id3, v3Poller, voter3_voteblocks)); v3Poller.theParticipants.put(id4, makeParticipant(id4, v3Poller, voter4_voteblocks)); v3Poller.lockParticipants(); tally = v3Poller.tallyBlock(hashblocks[0]); assertEquals(BlockTally.Result.LOST, tally.getTallyResult()); assertEmpty(tally.getRepairVoters()); assertSameElements(theParticipants(v3Poller).values(), tally.getDisagreeVoters()); assertEmpty(publisherRepairUrls(v3Poller)); assertSameElements(Arrays.asList("http://test.com/foo1"), peerRepairUrls(v3Poller)); } public void testHeadVersionRepair() throws Exception { MyV3Poller v3Poller; PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); PeerIdentity id4 = findPeerIdentity("TCP:[127.0.0.1]:8993"); String [] urls_poller = { "http://test.com/foo1" }; HashBlock [] hashblocks = { makeHashBlock("http://test.com/foo1", "content for foo1HHH") }; VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1zzz", "content for foo1") }; VoteBlock [] voter2_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1yyy", "content for foo1") }; VoteBlock [] voter3_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1xxx", "content for foo1") }; VoteBlock [] voter4_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1www", "content for foo1") }; BlockTally tally; v3Poller = makeV3Poller("testing poll key"); // The results expected are based on a quorum of 3. assertEquals(3, v3Poller.getQuorum()); assertEquals(75, v3Poller.getVoteMargin()); // Prefer the cache in all cases ConfigurationUtil.addFromArgs(V3Poller.PARAM_V3_REPAIR_FROM_CACHE_PERCENT, "100"); ConfigurationUtil.addFromArgs(V3Poller.PARAM_USE_VERSION_COUNTS, "true"); v3Poller = makeV3Poller("testing poll key"); v3Poller.theParticipants.put(id1, makeParticipant(id1, v3Poller, voter1_voteblocks)); v3Poller.theParticipants.put(id2, makeParticipant(id2, v3Poller, voter2_voteblocks)); v3Poller.theParticipants.put(id3, makeParticipant(id3, v3Poller, voter3_voteblocks)); v3Poller.theParticipants.put(id4, makeParticipant(id4, v3Poller, voter4_voteblocks)); v3Poller.lockParticipants(); tally = v3Poller.tallyBlock(hashblocks[0]); assertEquals(BlockTally.Result.LOST, tally.getTallyResult()); assertEmpty(tally.getRepairVoters()); assertSameElements(theParticipants(v3Poller).values(), tally.getDisagreeVoters()); // Repair from cache not possible; nobody has that head version. assertSameElements(Arrays.asList("http://test.com/foo1"), publisherRepairUrls(v3Poller)); assertEmpty(peerRepairUrls(v3Poller)); // Change voter2 to have the head version be the popular version. VoteBlock[] exposed_content_voter2_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1", "content for foo1yyy") }; v3Poller = makeV3Poller("testing poll key"); v3Poller.theParticipants.put(id1, makeParticipant(id1, v3Poller, voter1_voteblocks)); v3Poller.theParticipants.put(id2, makeParticipant(id2, v3Poller, exposed_content_voter2_voteblocks)); v3Poller.theParticipants.put(id3, makeParticipant(id3, v3Poller, voter3_voteblocks)); v3Poller.theParticipants.put(id4, makeParticipant(id4, v3Poller, voter4_voteblocks)); v3Poller.lockParticipants(); tally = v3Poller.tallyBlock(hashblocks[0]); assertEquals(BlockTally.Result.LOST, tally.getTallyResult()); assertSameElements(Arrays.asList(theParticipants(v3Poller).get(id2)), tally.getRepairVoters()); assertSameElements(theParticipants(v3Poller).values(), tally.getDisagreeVoters()); // Repair from cache assertEmpty(publisherRepairUrls(v3Poller)); assertSameElements(Arrays.asList("http://test.com/foo1"), peerRepairUrls(v3Poller)); } public void testBlockCompare() throws Exception { // V3Poller v3Poller = makeV3Poller("testing poll key"); // PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); // PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); // PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); // PeerIdentity id4 = findPeerIdentity("TCP:[127.0.0.1]:8993"); // String n1v1 = "This is node 1, version 1. It's the oldest."; // String n1v2 = "This is node 1, version 2. It's slightly older."; // String n1v3 = "This is node 1, version 3. This is the current version!"; // // Our hash block only has v1 and v3, not v2 // HashBlock hb1 = makeHashBlock(url); // addVersion(hb1, n1v1); // addVersion(hb1, n1v3); // UrlTallier.HashBlockComparer comparer = // new UrlTallier.HashBlockComparer(hb1); // // Should agree on n1v1. // VoteBlock vb1 = makeVoteBlock(url); // addVersion(vb1, n1v1); // // NOTE: The participantIndex passed to compare is not relevent: // // All the nonces in the HashBlock are the same, so the expected // // hashes are the same for each participant. // assertTrue(comparer.compare(vb1, 0)); // // Should agree on n1v1 and n1v3. // VoteBlock vb2 = makeVoteBlock(url); // addVersion(vb2, n1v1); // addVersion(vb2, n1v3); // assertTrue(comparer.compare(vb2, 1)); // // Should agree on n1v3. // VoteBlock vb3 = makeVoteBlock(url); // addVersion(vb3, n1v2); // addVersion(vb3, n1v3); // assertTrue(comparer.compare(vb3, 2)); // // Should not agree on any version, since the HashBlock doesn't // // have n1v2. // VoteBlock vb4 = makeVoteBlock(url); // addVersion(vb4, n1v2); // assertFalse(comparer.compare(vb4, 3)); } public void testSignalAuEvent() throws Exception { MyV3Poller poller = makeV3Poller("testing poll key"); pluginMgr.registerAuEventHandler(new MyAuEventHandler()); List<String> urls = ListUtil.list("url1", "foo2"); List<PollerStateBean.Repair> rep = new ArrayList<PollerStateBean.Repair>(); for (String u : urls) { rep.add(new PollerStateBean.Repair(u)); } poller.setCompletedRepairs(rep); assertEquals(0, changeEvents.size()); poller.signalAuEvent(); assertEquals(1, changeEvents.size()); AuEventHandler.ChangeInfo ci = changeEvents.get(0); assertEquals(AuEventHandler.ChangeInfo.Type.Repair, ci.getType()); assertTrue(ci.isComplete()); assertEquals(2, ci.getNumUrls()); assertNull(ci.getMimeCounts()); assertEquals(urls, ci.getUrls()); } List<AuEventHandler.ChangeInfo> changeEvents = new ArrayList(); class MyAuEventHandler extends AuEventHandler.Base { @Override public void auContentChanged(AuEvent event, ArchivalUnit au, AuEventHandler.ChangeInfo info) { changeEvents.add(info); } } // Tests that rely on what V3Poller.getPollerUrlTally() and pals return. private void tallyPollerUrl(V3Poller poller, UrlTallier urlTallier, String url, HashBlock hashBlock) { VoteBlockTallier voteBlockTallier = poller.getPollerUrlTally(hashBlock); urlTallier.voteAllParticipants(url, voteBlockTallier); } private BlockTally tallyVoterUrl(V3Poller poller, UrlTallier urlTallier, String url) { VoteBlockTallier voteBlockTallier = poller.getVoterUrlTally(); urlTallier.voteAllParticipants(url, voteBlockTallier); return voteBlockTallier.getBlockTally(); } public void testTallyPollerUrl() throws Exception { V3Poller v3Poller = makeSizedV3Poller("testing poll key", 3); PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); PeerIdentity id4 = findPeerIdentity("TCP:[127.0.0.1]:8994"); HashBlock [] hashblocks = { makeHashBlock("http://test.com/foo1", "content for foo1"), makeHashBlock("http://test.com/foo2", "content for foo2"), makeHashBlock("http://test.com/foo3", "content for foo3"), makeHashBlock("http://test.com/foo4", "content for foo4") }; VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2", "content for foo2"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter2_voteblocks = { makeVoteBlock("http://test.com/foo2", "content for foo2"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter3_voteblocks = { makeVoteBlock("http://test.com/foo3", "content for foo3"), makeVoteBlock("http://test.com/foo4", "content for foo4") }; List<ParticipantUserData> theParticipants = new ArrayList<ParticipantUserData>(); theParticipants.add(makeParticipant(id1, v3Poller, voter1_voteblocks)); theParticipants.add(makeParticipant(id2, v3Poller, voter2_voteblocks)); theParticipants.add(makeParticipant(id3, v3Poller, voter3_voteblocks)); UrlTallier urlTallier = new UrlTallier(theParticipants); assertEquals("http://test.com/foo1", urlTallier.peekUrl()); tallyPollerUrl(v3Poller, urlTallier, "http://test.com/foo1", hashblocks[0]); assertEquals("http://test.com/foo2", urlTallier.peekUrl()); tallyPollerUrl(v3Poller, urlTallier, "http://test.com/foo2", hashblocks[1]); assertEquals("http://test.com/foo3", urlTallier.peekUrl()); tallyPollerUrl(v3Poller, urlTallier, "http://test.com/foo3", hashblocks[2]); assertEquals("http://test.com/foo4", urlTallier.peekUrl()); tallyPollerUrl(v3Poller, urlTallier, "http://test.com/foo4", hashblocks[3]); assertEquals(null, urlTallier.peekUrl()); } public void testTallyVoterUrl() throws Exception { V3Poller v3Poller = makeV3Poller("testing poll key"); PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2", "content for foo2"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter2_voteblocks = { makeVoteBlock("http://test.com/foo2", "content for foo2"), makeVoteBlock("http://test.com/foo3", "content for foo3") }; VoteBlock [] voter3_voteblocks = { makeVoteBlock("http://test.com/foo3", "content for foo3"), makeVoteBlock("http://test.com/foo4", "content for foo4") }; BlockTally tally; List<ParticipantUserData> theParticipants = new ArrayList<ParticipantUserData>(); theParticipants.add(makeParticipant(id1, v3Poller, voter1_voteblocks)); theParticipants.add(makeParticipant(id2, v3Poller, voter2_voteblocks)); theParticipants.add(makeParticipant(id3, v3Poller, voter3_voteblocks)); UrlTallier urlTallier = new UrlTallier(theParticipants); assertEquals("http://test.com/foo1", urlTallier.peekUrl()); tally = tallyVoterUrl(v3Poller, urlTallier, "http://test.com/foo1"); // todo(bhayes): BlockTally needs to have a better interface, both // for testing and for use. assertEquals(tally.getVoterOnlyBlockVoters().size(), 1); // todo(bhayes): This seems incorrect; foo1 was only present at // one voter, but incrementTalliedBlocks will be called for each // voter. // assertEquals(1, tally.getTalliedVoters().size()); assertEquals(1, tally.getVoterOnlyBlockVoters().size()); assertContains(tally.getVoterOnlyBlockVoters(), theParticipants.get(0)); assertEquals("http://test.com/foo2", urlTallier.peekUrl()); tally = tallyVoterUrl(v3Poller, urlTallier, "http://test.com/foo2"); assertEquals(tally.getVoterOnlyBlockVoters().size(), 2); // assertEquals(2, tally.getTalliedVoters().size()); assertContains(tally.getVoterOnlyBlockVoters(), theParticipants.get(0)); assertContains(tally.getVoterOnlyBlockVoters(), theParticipants.get(1)); assertEquals("http://test.com/foo3", urlTallier.peekUrl()); tally = tallyVoterUrl(v3Poller, urlTallier, "http://test.com/foo3"); assertEquals(tally.getVoterOnlyBlockVoters().size(), 3); // assertEquals(3, tally.getTalliedVoters().size()); assertContains(tally.getVoterOnlyBlockVoters(), theParticipants.get(0)); assertContains(tally.getVoterOnlyBlockVoters(), theParticipants.get(1)); assertContains(tally.getVoterOnlyBlockVoters(), theParticipants.get(2)); assertEquals("http://test.com/foo4", urlTallier.peekUrl()); tally = tallyVoterUrl(v3Poller, urlTallier, "http://test.com/foo4"); assertEquals(tally.getVoterOnlyBlockVoters().size(), 1); // assertEquals(1, tally.getTalliedVoters().size()); assertContains(tally.getVoterOnlyBlockVoters(), theParticipants.get(2)); assertEquals(null, urlTallier.peekUrl()); } public void testTallyVoterUrlNotPeek() throws Exception { V3Poller v3Poller = makeV3Poller("testing poll key"); PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2", "content for foo2"), }; BlockTally tally; List<ParticipantUserData> theParticipants = new ArrayList<ParticipantUserData>(); theParticipants.add(makeParticipant(id1, v3Poller, voter1_voteblocks)); UrlTallier urlTallier = new UrlTallier(theParticipants); assertEquals("http://test.com/foo1", urlTallier.peekUrl()); tallyVoterUrl(v3Poller, urlTallier, "http://test.com/foo1"); assertEquals("http://test.com/foo2", urlTallier.peekUrl()); try { // Call tallyVoterUrl with a url after the peekUrl tallyVoterUrl(v3Poller, urlTallier, "http://test.com/goo"); fail("Expected IllegalArgumentException was not thrown."); } catch (IllegalArgumentException e) { // expected } try { // Call tallyVoterUrl with a null url tallyVoterUrl(v3Poller, urlTallier, null); fail("Expected IllegalArgumentException was not thrown."); } catch (IllegalArgumentException e) { // expected } } public void testIteratorFileNotFound() throws Exception { // A VoteBlocks which supports nothing except iterator(), and that // throws FileNotFound. final class FileNotFoundVoteBlocks implements VoteBlocks { boolean thrown = false; public VoteBlocksIterator iterator() throws FileNotFoundException { // The test only calls iterator() once. assertFalse(thrown); thrown = true; throw new FileNotFoundException("Expected exception."); } public void addVoteBlock(VoteBlock b) throws IOException { throw new UnsupportedOperationException(); } public InputStream getInputStream() throws IOException { throw new UnsupportedOperationException(); } public VoteBlock getVoteBlock(String url) { throw new UnsupportedOperationException(); } public int size() { throw new UnsupportedOperationException(); } public long getEstimatedEncodedLength() { throw new UnsupportedOperationException(); } public void release() { throw new UnsupportedOperationException(); } }; V3Poller v3Poller = makeV3Poller("testing poll key"); PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); VoteBlock [] voter1_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2", "content for foo2"), }; VoteBlock [] voter2_voteblocks = { makeVoteBlock("http://test.com/foo1", "content for foo1"), makeVoteBlock("http://test.com/foo2", "content for foo2"), }; List<ParticipantUserData> theParticipants = new ArrayList<ParticipantUserData>(); ParticipantUserData participant1 = new ParticipantUserData(id1, v3Poller, null); FileNotFoundVoteBlocks vb = new FileNotFoundVoteBlocks(); participant1.setVoteBlocks(vb); ParticipantUserData participant2 = makeParticipant(id2, v3Poller, voter2_voteblocks); theParticipants.add(participant1); theParticipants.add(participant2); assertFalse(vb.thrown); UrlTallier urlTallier = new UrlTallier(theParticipants); // The file wasn't found; check to make sure the voter is spoiled. assertTrue(vb.thrown); for (int urlNum = 1; urlNum <=2; urlNum++) { String url = "http://test.com/foo"+urlNum; assertEquals(url, urlTallier.peekUrl()); BlockTally tally = tallyVoterUrl(v3Poller, urlTallier, url); assertSameElements(Arrays.asList(participant2), tally.getVoterOnlyBlockVoters()); } assertEquals(null, urlTallier.peekUrl()); } public void testHashStatsTallier() throws Exception { V3Poller v3Poller = makeV3Poller("testing poll key"); PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); ParticipantUserData participant = new ParticipantUserData(id1, v3Poller, null); VoteBlock vb = new VoteBlock("foo", VoteBlock.CONTENT_VOTE); byte[] testBytes = ByteArray.makeRandomBytes(20); vb.addVersion(0, 123, 0, 155, testBytes, testBytes, false); VoteBlockTallier.VoteCallback callback = V3Poller.makeHashStatsTallier(); callback.vote(vb, participant); assertEquals(286, participant.getBytesHashed()); assertEquals(155, participant.getBytesRead()); } public void testRecordSymmetricHashes() throws Exception { V3Poller v3Poller = makeInittedV3Poller("testing poll key"); int nh = 6+6+1; PeerIdentity id1 = findPeerIdentity("TCP:[127.0.0.1]:8990"); PeerIdentity id2 = findPeerIdentity("TCP:[127.0.0.1]:8991"); PeerIdentity id3 = findPeerIdentity("TCP:[127.0.0.1]:8992"); PeerIdentity id4 = findPeerIdentity("TCP:[127.0.0.1]:8994"); HashBlock [] hashblocks = { makeHashBlock("http://test.com/foo1", "content for foo1", nh), makeHashBlock("http://test.com/foo2", "content for foo2", nh), makeHashBlock("http://test.com/foo3", "content for foo3", nh), makeHashBlock("http://test.com/foo4", "content for foo4", nh) }; addVersion(hashblocks[0], "abc", nh); addVersion(hashblocks[0], "defg", nh); addVersion(hashblocks[2], "1111", nh); addVersion(hashblocks[2], "22222", nh); addVersion(hashblocks[2], "4444444", nh); List<ParticipantUserData> parts = symmetricParticipants(v3Poller); VoteBlocks b0 = parts.get(0).getSymmetricVoteBlocks(); assertEquals(0, b0.size()); v3Poller.recordSymmetricHashes(hashblocks[0]); b0 = parts.get(0).getSymmetricVoteBlocks(); assertEquals(1, b0.size()); VoteBlock vb = b0.iterator().next(); assertEquals(3, vb.size()); v3Poller.recordSymmetricHashes(hashblocks[1]); v3Poller.recordSymmetricHashes(hashblocks[2]); v3Poller.recordSymmetricHashes(hashblocks[3]); b0 = parts.get(0).getSymmetricVoteBlocks(); assertEquals(4, b0.size()); List<VoteBlock> vbs = new ArrayList<VoteBlock>(); for (VoteBlocksIterator iter = b0.iterator(); iter.hasNext();) { vbs.add(iter.next()); } assertEquals(3, vbs.get(0).size()); assertEquals(1, vbs.get(1).size()); assertEquals(4, vbs.get(2).size()); assertEquals(1, vbs.get(3).size()); } private MySizedV3Poller makeSizedV3Poller(String key, int pollSize) throws Exception { PollSpec ps = new MockPollSpec(testau.getAuCachedUrlSet(), null, null, Poll.V3_POLL); return new MySizedV3Poller(ps, theDaemon, pollerId, key, 20000, "SHA-1", pollSize); } private MyV3Poller makeV3Poller(String key) throws Exception { PollSpec ps = new MockPollSpec(testau.getAuCachedUrlSet(), null, null, Poll.V3_POLL); return new MyV3Poller(ps, theDaemon, pollerId, key, 20000, "SHA-1"); } private MyV3Poller makeInittedV3Poller(String key) throws Exception { return makeInittedV3Poller(key, 6, voters.length); } private MyV3Poller makeInittedV3Poller(String key, int numSym) throws Exception { return makeInittedV3Poller(key, numSym, voters.length); } private MyV3Poller makeInittedV3Poller(String key, int numSym, int numVoters) throws Exception { PollSpec ps = new MockPollSpec(testau.getAuCachedUrlSet(), null, null, Poll.V3_POLL); MyV3Poller p = new MyV3Poller(ps, theDaemon, pollerId, key, 20000, "SHA-1"); p.constructInnerCircle(numVoters); Map<PeerIdentity,ParticipantUserData> innerCircle = theParticipants(p); for (int ix = 0; ix < voters.length; ix++) { PeerIdentity pid = voters[ix]; ParticipantUserData ud = innerCircle.get(pid); if (ud != null) { ud.setVoterNonce(voterNonces[ix]); if (ix < numSym) { ud.setVoterNonce2(voterNonce2s[ix]); } } } p.lockParticipants(); return p; } private Map<PeerIdentity,ParticipantUserData> theParticipants(V3Poller v3Poller) throws Exception { return (Map<PeerIdentity,ParticipantUserData>)PrivilegedAccessor. getValue(v3Poller, "theParticipants"); } private List<ParticipantUserData> symmetricParticipants(V3Poller v3Poller) throws Exception { return (List<ParticipantUserData>)PrivilegedAccessor. getValue(v3Poller, "symmetricParticipants"); } private class MyV3Poller extends V3Poller { // For testing: Hashmap of voter IDs to V3LcapMessages. private Map sentMsgs = Collections.synchronizedMap(new HashMap()); private Map semaphores = new HashMap(); private List<PollerStateBean.Repair> repairs; MyV3Poller(PollSpec spec, LockssDaemon daemon, PeerIdentity id, String pollkey, long duration, String hashAlg) throws PollSerializerException { super(spec, daemon, id, pollkey, duration, hashAlg); } public void sendMessageTo(V3LcapMessage msg, PeerIdentity to) { sentMsgs.put(to, msg); SimpleBinarySemaphore sem = (SimpleBinarySemaphore)semaphores.get(to); if (sem == null) { sem = new SimpleBinarySemaphore(); semaphores.put(to, sem); } sem.give(); } public V3LcapMessage getSentMessage(PeerIdentity voter) { SimpleBinarySemaphore sem = (SimpleBinarySemaphore)semaphores.get(voter); if (sem == null) { fail ("Message never sent!"); } sem.take(5000); // Really shouldn't take this long return (V3LcapMessage)sentMsgs.get(voter); } void setCompletedRepairs(List<PollerStateBean.Repair> repairs) { this.repairs = repairs; } @Override public List getCompletedRepairs() { if (repairs != null) { return repairs; } return super.getCompletedRepairs(); } } private class MySizedV3Poller extends V3Poller { private final int pollSize; MySizedV3Poller(PollSpec spec, LockssDaemon daemon, PeerIdentity id, String pollkey, long duration, String hashAlg, int pollSize) throws PollSerializerException { super(spec, daemon, id, pollkey, duration, hashAlg); this.pollSize = pollSize; } @Override public int getPollSize() { return pollSize; } } private void initRequiredServices() throws Exception { pollmanager = theDaemon.getPollManager(); hashService = theDaemon.getHashService(); pluginMgr = theDaemon.getPluginManager(); tempDir = getTempDir(); tempDirPath = tempDir.getAbsolutePath(); System.setProperty("java.io.tmpdir", tempDirPath); Properties p = new Properties(); p.setProperty(IdentityManagerImpl.PARAM_ENABLE_V1, "false"); p.setProperty(LcapDatagramComm.PARAM_ENABLED, "false"); p.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tempDirPath); p.setProperty(IdentityManager.PARAM_LOCAL_IP, "127.0.0.1"); p.setProperty(IdentityManager.PARAM_LOCAL_V3_IDENTITY, localPeerKey); p.setProperty(ConfigManager.PARAM_NEW_SCHEDULER, "true"); p.setProperty(IdentityManagerImpl.PARAM_INITIAL_PEERS, StringUtil.separatedString(initialPeers, ";")); p.setProperty(V3Poller.PARAM_QUORUM, "3"); p.setProperty(V3Poller.PARAM_STATE_PATH, tempDirPath); ConfigurationUtil.setCurrentConfigFromProps(p); idMgr = new MyIdentityManager(); theDaemon.setIdentityManager(idMgr); idMgr.initService(theDaemon); idMgr.startService(); theDaemon.getSchedService().startService(); hashService.startService(); theDaemon.getDatagramRouterManager().startService(); theDaemon.getRouterManager().startService(); theDaemon.getSystemMetrics().startService(); theDaemon.getActivityRegulator(testau).startService(); MockNodeManager nodeManager = new MockNodeManager(); theDaemon.setNodeManager(nodeManager, testau); MockAuState aus = new MockAuState(testau); nodeManager.setAuState(aus); pollmanager.startService(); } static class MyIdentityManager extends IdentityManagerImpl { Map myMap = null; @Override public Map getAgreed(ArchivalUnit au) { if (myMap == null) { myMap = new HashMap(); } return myMap; } @Override public List getCachesToRepairFrom(ArchivalUnit au) { if (myMap == null) { myMap = new HashMap(); } return new ArrayList(myMap.keySet()); } @Override public void storeIdentities() throws ProtocolException { } } }
package org.md2k.datakitapi.source.datasource; public class DataSourceType { public static final String ACCELEROMETER = "ACCELEROMETER"; public static final String GYROSCOPE = "GYROSCOPE"; public static final String COMPASS = "COMPASS"; public static final String AMBIENT_LIGHT = "AMBIENT_LIGHT"; public static final String PRESSURE = "PRESSURE"; public static final String PROXIMITY = "PROXIMITY"; public static final String LOCATION = "LOCATION"; public static final String DISTANCE = "DISTANCE"; public static final String HEART_RATE = "HEART_RATE"; public static final String SPEED = "SPEED"; public static final String STEP_COUNT = "STEP_COUNT"; public static final String PACE = "PACE"; public static final String MOTION_TYPE = "MOTION_TYPE"; public static final String ULTRA_VIOLET_RADIATION = "ULTRA_VIOLET_RADIATION"; public static final String BAND_CONTACT = "BAND_CONTACT"; public static final String CALORY_BURN = "CALORY_BURN"; public static final String ECG = "ECG"; public static final String RESPIRATION = "RESPIRATION"; public static final String GALVANIC_SKIN_RESPONSE = "GALVANIC_SKIN_RESPONSE"; public static final String ALTIMETER = "ALTIMETER"; public static final String AIR_PRESSURE = "AIR_PRESSURE"; public static final String RR_INTERVAL = "RR_INTERVAL"; public static final String AMBIENT_TEMPERATURE = "AMBIENT_TEMPERATURE"; public static final String SKIN_TEMPERATURE = "SKIN_TEMPERATURE"; public static final String BATTERY = "BATTERY"; public static final String CPU = "CPU"; public static final String MEMORY="MEMORY"; public static final String AUTOSENSE = "AUTOSENSE"; public static final String ACCELEROMETER_X = "ACCELEROMETER_X"; public static final String ACCELEROMETER_Y = "ACCELEROMETER_Y"; public static final String ACCELEROMETER_Z = "ACCELEROMETER_Z"; public static final String GYROSCOPE_X = "GYROSCOPE_X"; public static final String GYROSCOPE_Y = "GYROSCOPE_Y"; public static final String GYROSCOPE_Z = "GYROSCOPE_Z"; public static final String SURVEY = "SURVEY"; public static final String STATUS = "STATUS"; public static final String NOTIFICATION = "NOTIFICATION"; }
package org.hellojavaer.ddal.sequence; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; class SummedBlockingQueue { static class Node { InnerIdRange item; Node next; Node(InnerIdRange x) { item = x; } } private final AtomicInteger countForCapacity = new AtomicInteger(0); private transient Node head; private transient Node last; private final ReentrantLock takeLock = new ReentrantLock(); private final Condition notEmpty = takeLock.newCondition(); private final ReentrantLock putLock = new ReentrantLock(); private final Condition notFull = putLock.newCondition(); private final long sum; private final AtomicLong countForSum = new AtomicLong(0); public SummedBlockingQueue(long sum) { this.sum = sum; last = head = new Node(null); } static class InnerIdRange { private final long beginValue; private final long endValue; private final AtomicLong counter; public InnerIdRange(long beginValue, long endValue) { this.beginValue = beginValue; this.endValue = endValue; this.counter = new AtomicLong(beginValue); } public long getBeginValue() { return beginValue; } public long getEndValue() { return endValue; } public AtomicLong getCounter() { return counter; } } public void put(IdRange idRange) throws InterruptedException { if (idRange.getEndValue() < idRange.getBeginValue()) { throw new IllegalArgumentException("end value must be greater than or equal to begin value"); } Node node = new Node(new InnerIdRange(idRange.getBeginValue(), idRange.getEndValue())); final ReentrantLock putLock = this.putLock; final AtomicInteger count = this.countForCapacity; putLock.lockInterruptibly(); long c = -1; try { while (countForSum.get() >= sum) { notFull.await(); } enqueue(node); c = count.incrementAndGet(); long s = countForSum.addAndGet(idRange.getEndValue() - idRange.getBeginValue() + 1); if (s < sum) { notFull.signal(); } } finally { putLock.unlock(); } if (c == 1) signalNotEmpty(); } private ThreadLocal<InnerIdRange> threadLocal = new ThreadLocal(); public long get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { InnerIdRange idRange = threadLocal.get(); if (idRange != null) { long id = idRange.getCounter().getAndIncrement(); if (id <= idRange.getEndValue()) { long c = countForSum.decrementAndGet(); if (c == sum - 1) { signalNotFull(); } if (id == idRange.getEndValue()) { remove(idRange); threadLocal.set(null); } return id; } else { remove(idRange); threadLocal.set(null); return recursiveGetFromQueue(timeout, unit); } } else { return recursiveGetFromQueue(timeout, unit); } } private long recursiveGetFromQueue(long timeout, TimeUnit unit) throws TimeoutException, InterruptedException { long nanoTimeout = unit.toNanos(timeout); while (true) { long now = System.nanoTime(); InnerIdRange idRange = get(nanoTimeout); if (idRange == null) { throw new TimeoutException(unit.toMillis(timeout) + " ms"); } else { long id = idRange.getCounter().getAndIncrement(); if (id <= idRange.getEndValue()) { long c = countForSum.decrementAndGet(); if (c == sum - 1) { signalNotFull(); } if (id == idRange.getEndValue()) { remove(idRange); } else { threadLocal.set(idRange); } return id; } else { remove(idRange); nanoTimeout -= System.nanoTime() - now; if (nanoTimeout <= 0) { throw new TimeoutException(unit.toMillis(timeout) + " ms"); } } } } } private InnerIdRange get(long nanoTimeout) throws InterruptedException { final AtomicInteger count = this.countForCapacity; final ReentrantLock takeLock = this.takeLock; takeLock.lockInterruptibly(); InnerIdRange x = null; try { while (count.get() == 0) { long now = System.nanoTime(); if (nanoTimeout <= 0) { return null; } if (notEmpty.awaitNanos(nanoTimeout) <= 0) { return null; } nanoTimeout -= System.nanoTime() - now; } Node first = head.next; if (first == null) x = null; else x = first.item; if (count.get() > 0) { notEmpty.signal(); } } finally { takeLock.unlock(); } return x; } public boolean remove(Object o) { if (o == null) return false; fullyLock(); try { for (Node trail = head, p = trail.next; p != null; trail = p, p = p.next) { if (o.equals(p.item)) { unlink(p, trail); return true; } } return false; } finally { fullyUnlock(); } } void fullyLock() { putLock.lock(); takeLock.lock(); } void fullyUnlock() { takeLock.unlock(); putLock.unlock(); } void unlink(Node p, Node trail) { p.item = null; trail.next = p.next; if (last == p) last = trail; countForCapacity.getAndDecrement(); } private void signalNotEmpty() { final ReentrantLock takeLock = this.takeLock; takeLock.lock(); try { notEmpty.signal(); } finally { takeLock.unlock(); } } private void signalNotFull() { final ReentrantLock putLock = this.putLock; putLock.lock(); try { notFull.signal(); } finally { putLock.unlock(); } } private void enqueue(Node node) { last = last.next = node; } public long remainingSum() { return sum - countForSum.get(); } }
package io.digdag.standards.operator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.io.File; import java.io.IOException; import java.nio.file.Path; import com.fasterxml.jackson.databind.JsonNode; import com.google.inject.Inject; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import io.digdag.spi.CommandExecutor; import io.digdag.spi.CommandLogger; import io.digdag.spi.TaskRequest; import io.digdag.spi.TaskResult; import io.digdag.spi.Operator; import io.digdag.spi.OperatorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.digdag.client.config.Config; import io.digdag.util.BaseOperator; public class ShOperatorFactory implements OperatorFactory { private static Logger logger = LoggerFactory.getLogger(ShOperatorFactory.class); private static Pattern VALID_ENV_KEY = Pattern.compile("[a-zA-Z_][a-zA-Z_0-9]*"); private final CommandExecutor exec; private final CommandLogger clog; @Inject public ShOperatorFactory(CommandExecutor exec, CommandLogger clog) { this.exec = exec; this.clog = clog; } public String getType() { return "sh"; } @Override public Operator newTaskExecutor(Path workspacePath, TaskRequest request) { return new ShOperator(workspacePath, request); } private class ShOperator extends BaseOperator { public ShOperator(Path workspacePath, TaskRequest request) { super(workspacePath, request); } @Override public TaskResult runTask() { Config params = request.getConfig() .mergeDefault(request.getConfig().getNestedOrGetEmpty("sh")); List<String> shell = params.getListOrEmpty("shell", String.class); String command = params.get("_command", String.class); ImmutableList.Builder<String> cmdline = ImmutableList.builder(); if (shell.isEmpty()) { cmdline.addAll(ImmutableList.of("/bin/sh", "-c")); } else { cmdline.addAll(shell); } cmdline.add(command); ProcessBuilder pb = new ProcessBuilder(cmdline.build()); final Map<String, String> env = pb.environment(); params.getKeys() .forEach(key -> { if (isValidEnvKey(key)) { JsonNode value = params.get(key, JsonNode.class); String string; if (value.isTextual()) { string = value.textValue(); } else { string = value.toString(); } env.put(key, string); } else { logger.trace("Ignoring invalid env var key: {}", key); } }); // add workspace path to the end of $PATH so that bin/cmd works without ./ at the beginning String pathEnv = System.getenv("PATH"); if (pathEnv == null) { pathEnv = workspacePath.toAbsolutePath().toString(); } else { pathEnv = pathEnv + File.pathSeparator + workspacePath.toAbsolutePath().toString(); } pb.redirectErrorStream(true); int ecode; try { Process p = exec.start(workspacePath, request, pb); p.getOutputStream().close(); // copy stdout to System.out and logger clog.copyStdout(p, System.out); ecode = p.waitFor(); } catch (IOException | InterruptedException ex) { throw Throwables.propagate(ex); } if (ecode != 0) { throw new RuntimeException("Command failed with code " + ecode); } return TaskResult.empty(request); } } private static boolean isValidEnvKey(String key) { return VALID_ENV_KEY.matcher(key).matches(); } }
package uk.ac.ebi.quickgo.geneproduct.common.document; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * The fields of a Gene Product document. * * @author Ricardo Antunes */ public class GeneProductFields { public static final String ID = "id"; public static final String DATABASE = "database"; public static final String SYMBOL = "symbol"; public static final String NAME = "name"; public static final String SYNONYM = "synonym"; public static final String TYPE = "type"; public static final String TAXON_ID = "taxonId"; public static final String TAXON_NAME = "taxonName"; public static final String DATABASE_SUBSET = "dbSubset"; public static final String COMPLETE_PROTEOME = "completeProteome"; public static final String REFERENCE_POTEOME = "referenceProteome"; /** * GeneProduct fields that are stored, and can therefore be retrieved. */ public static final class Retrievable extends GeneProductFields { private static final Set<String> VALUES = new HashSet<>(); public static final String ID = storeAndGet(VALUES, GeneProductFields.ID); public static final String DATABASE = storeAndGet(VALUES, GeneProductFields.DATABASE); public static final String SYMBOL = storeAndGet(VALUES, GeneProductFields.SYMBOL); public static final String NAME = storeAndGet(VALUES, GeneProductFields.NAME); public static final String SYNONYM = storeAndGet(VALUES, GeneProductFields.SYNONYM); public static final String TYPE = storeAndGet(VALUES, GeneProductFields.TYPE); public static final String TAXON_ID = storeAndGet(VALUES, GeneProductFields.TAXON_ID); public static final String TAXON_NAME = storeAndGet(VALUES, GeneProductFields.TAXON_NAME); public static final String DATABASE_SUBSET = storeAndGet(VALUES, GeneProductFields.DATABASE_SUBSET); public static final String COMPLETE_PROTEOME = storeAndGet(VALUES, GeneProductFields.COMPLETE_PROTEOME); public static final String REFERENCE_POTEOME = storeAndGet(VALUES, GeneProductFields.REFERENCE_POTEOME); public static boolean isRetrievable(String field) { return VALUES.contains(field); } public static Set<String> retrievableFields() { return Collections.unmodifiableSet(VALUES); } } public static final class Searchable extends GeneProductFields { private static final Set<String> VALUES = new HashSet<>(); public static final String ID = storeAndGet(VALUES, GeneProductFields.ID); public static final String SYMBOL = storeAndGet(VALUES, GeneProductFields.SYMBOL); public static final String NAME = storeAndGet(VALUES, GeneProductFields.NAME); public static final String SYNONYM = storeAndGet(VALUES, GeneProductFields.SYNONYM); public static boolean isSearchable(String field) { return VALUES.contains(field); } public static Set<String> searchableFields() { return Collections.unmodifiableSet(VALUES); } } private static String storeAndGet(Set<String> values, String value) { values.add(value); return value; } }
package com.tinkerpop.gremlin.structure.strategy; import com.tinkerpop.gremlin.process.Traversal; import com.tinkerpop.gremlin.process.olap.GraphComputer; import com.tinkerpop.gremlin.structure.Edge; import com.tinkerpop.gremlin.structure.Graph; import com.tinkerpop.gremlin.structure.Transaction; import com.tinkerpop.gremlin.structure.Vertex; import java.util.Optional; public class StrategyWrappedGraph implements Graph, StrategyWrapped { private final Graph baseGraph; protected Strategy strategy = new Strategy.Simple(); private Strategy.Context<StrategyWrappedGraph> graphContext; public StrategyWrappedGraph(final Graph baseGraph) { this.baseGraph = baseGraph; this.graphContext = new Strategy.Context<>(baseGraph, this); } public Graph getBaseGraph() { return this.baseGraph; } public Strategy strategy() { return this.strategy; } @Override public Vertex addVertex(final Object... keyValues) { final Optional<Vertex> v = Optional.ofNullable(strategy.compose( s -> s.getAddVertexStrategy(graphContext), this.baseGraph::addVertex).apply(keyValues)); return v.isPresent() ? new StrategyWrappedVertex(v.get(), this) : null; } @Override public Vertex v(final Object id) { return new StrategyWrappedVertex(strategy().compose( s -> s.getGraphvStrategy(graphContext), this.baseGraph::v).apply(id), this); } @Override public Edge e(final Object id) { return strategy().compose( s -> s.getGrapheStrategy(graphContext), this.baseGraph::e).apply(id); } @Override public Traversal<Vertex, Vertex> V() { return this.baseGraph.V(); } @Override public Traversal<Edge, Edge> E() { return this.baseGraph.E(); } @Override public GraphComputer compute() { return this.baseGraph.compute(); } @Override public Transaction tx() { return this.baseGraph.tx(); } @Override public Annotations annotations() { return this.baseGraph.annotations(); } @Override public Features getFeatures() { return this.baseGraph.getFeatures(); } @Override public void close() throws Exception { this.baseGraph.close(); } }
package io.dropwizard.jersey; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.jersey2.InstrumentedResourceMethodApplicationListener; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import io.dropwizard.jersey.caching.CacheControlledResponseFeature; import io.dropwizard.jersey.guava.OptionalMessageBodyWriter; import io.dropwizard.jersey.guava.OptionalParamFeature; import io.dropwizard.jersey.sessions.SessionFactoryProvider; import org.glassfish.jersey.message.GZipEncoder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.server.filter.EncodingFilter; import org.glassfish.jersey.server.model.Resource; import org.glassfish.jersey.server.model.ResourceMethod; import org.glassfish.jersey.server.monitoring.ApplicationEvent; import org.glassfish.jersey.server.monitoring.ApplicationEventListener; import org.glassfish.jersey.server.monitoring.RequestEvent; import org.glassfish.jersey.server.monitoring.RequestEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Path; import javax.ws.rs.ext.Provider; import java.lang.annotation.Annotation; import java.util.List; import java.util.Set; public class DropwizardResourceConfig extends ResourceConfig { private static final Logger LOGGER = LoggerFactory.getLogger(DropwizardResourceConfig.class); private static final String NEWLINE = String.format("%n"); private String urlPattern; public DropwizardResourceConfig(MetricRegistry metricRegistry) { this(false, metricRegistry); } public DropwizardResourceConfig() { this(true, null); } @SuppressWarnings("unchecked") public DropwizardResourceConfig(boolean testOnly, MetricRegistry metricRegistry) { super(); if (metricRegistry == null) { metricRegistry = new MetricRegistry(); } /** * Combines types of getClasses() and getSingletons in one Set. * * @return all registered types */ @VisibleForTesting Set<Class<?>> allClasses() { final Set<Class<?>> allClasses = Sets.newHashSet(getClasses()); for (Object singleton : getSingletons()) { allClasses.add(singleton.getClass()); } return allClasses; } private Set<String> canonicalNamesByAnnotation(final Class<? extends Annotation> annotation) { final Set<String> result = Sets.newHashSet(); for (Class<?> clazz : getClasses()) { if (clazz.isAnnotationPresent(annotation)) { result.add(clazz.getCanonicalName()); } } return result; } @VisibleForTesting String logEndpoints() { final StringBuilder msg = new StringBuilder(1024); msg.append("The following paths were found for the configured resources:"); msg.append(NEWLINE).append(NEWLINE); final Set<Class<?>> allResources = Sets.newHashSet(); for (Class<?> clazz : allClasses()) { if (!clazz.isInterface() && Resource.from(clazz) != null) { allResources.add(clazz); } } if (!allResources.isEmpty()) { for (Class<?> klass : allResources) { Joiner.on(NEWLINE).appendTo(msg, new EndpointLogger(urlPattern, klass).getEndpoints()); msg.append(NEWLINE); } } else { msg.append(" NONE").append(NEWLINE); } return msg.toString(); } /** * Takes care of recursively creating all registered endpoints and providing them as Collection of lines to log * on application start. */ private static class EndpointLogger { private final String rootPath; private final List<String> endpoints = Lists.newArrayList(); public EndpointLogger(String urlPattern, Class<?> klass) {
package lukazitnik.jshint; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedList; import org.junit.Assert; import org.junit.Test; import org.netbeans.junit.NbModuleSuite; import org.netbeans.junit.NbTestCase; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; public class JSHintTest extends NbTestCase { public JSHintTest(String name) { super(name); } public static junit.framework.Test suite() { return NbModuleSuite.create(JSHintTest.class, null, null); } @Test public void testLint() throws IOException { FileSystem fs = FileUtil.createMemoryFileSystem(); FileObject fo = fs.getRoot().createData("index.js"); PrintWriter out = (new PrintWriter(fo.getOutputStream())); out.write("a;"); out.close(); JSHint jshint = JSHint.getInstance(); LinkedList<JSHintError> errors = jshint.lint(fo); JSHintError head = errors.element(); Assert.assertEquals(1, errors.size()); Assert.assertTrue(1 == head.getLine()); Assert.assertEquals("Expected an assignment or function call and instead saw an expression.", head.getReason()); } @Test public void testFindFile() throws IOException { FileSystem fs = FileUtil.createMemoryFileSystem(); FileObject hasFile = fs.getRoot().createFolder("hasFile"); FileObject file = hasFile.createData("file"); FileObject childFolder = hasFile.createFolder("childFolder"); FileObject result = JSHint.findFile("file", childFolder); Assert.assertEquals(file, result); } @Test public void testLintWithConfig() throws IOException { FileObject root = FileUtil.createMemoryFileSystem().getRoot(); FileObject jsFo = root.createData("index.js"); PrintWriter jsOut = (new PrintWriter(jsFo.getOutputStream())); jsOut.write("while (day)\n shuffle();"); jsOut.close(); FileObject configFo = root.createData(".jshintrc"); PrintWriter configOut = (new PrintWriter(configFo.getOutputStream())); configOut.write("{\"curly\":true,\"undef\":true}"); configOut.close(); JSHint jshint = JSHint.getInstance(); LinkedList<JSHintError> errors = jshint.lint(jsFo); Assert.assertEquals(3, errors.size()); Assert.assertEquals("'shuffle' is not defined.", errors.pop().getReason()); Assert.assertEquals("'day' is not defined.", errors.pop().getReason()); Assert.assertEquals("Expected '{' and instead saw 'shuffle'.", errors.pop().getReason()); } @Test public void testGlobalsOption() throws IOException { FileObject root = FileUtil.createMemoryFileSystem().getRoot(); FileObject jsFo = root.createData("index.js"); PrintWriter jsOut = (new PrintWriter(jsFo.getOutputStream())); jsOut.write("a(); b = 1;"); jsOut.close(); FileObject config = root.createData(".jshintrc"); PrintWriter configOut = (new PrintWriter(config.getOutputStream())); configOut.write("{\"undef\":true,\"globals\":{\"a\":false,\"b\":true}}"); configOut.close(); JSHint jshint = JSHint.getInstance(); LinkedList<JSHintError> errors = jshint.lint(jsFo); Assert.assertEquals(0, errors.size()); } }
package br.com.softctrl.net.rest; import java.net.Proxy; import java.net.Proxy.Type; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.List; import br.com.softctrl.net.rest.listener.RequestFinishedListener; import br.com.softctrl.net.rest.listener.ResponseErrorListener; import br.com.softctrl.net.rest.listener.ResponseListener; import br.com.softctrl.net.util.HTTPStatusCode.StatusCode; import br.com.softctrl.utils.Objects; /** * * @author carlostimoshenkorodrigueslopes@gmail.com */ public class Sync<R, S> implements IRestfulClient<R, S> { private static class Wrapper<S> { private S value; public void setValue(S value) { this.value = value; } public S getValue() { return value; } } private IRestfulClient<R, S> mRestfulClient; public Sync(){} /** * * @param restfulClient */ public Sync(IRestfulClient<R, S> restfulClient){ this.mRestfulClient = Objects.requireNonNull(restfulClient, "You need to inform a valid Restful Client."); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#getResponseListener() */ @Override public ResponseListener<S> getResponseListener() { return Objects.requireNonNull(this.mRestfulClient).getResponseListener(); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setResponseListener(br.com.softctrl.net.rest.listener.ResponseListener) */ public IRestfulClient<R, S> setResponseListener(ResponseListener<S> responseListener) { Objects.requireNonNull(this.mRestfulClient).setResponseListener(responseListener); return this; } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#getResponseErrorListener() */ @Override public ResponseErrorListener getResponseErrorListener() { return Objects.requireNonNull(this.mRestfulClient).getResponseErrorListener(); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setResponseErrorListener(br.com.softctrl.net.rest.listener.ResponseErrorListener) */ public IRestfulClient<R, S> setResponseErrorListener(ResponseErrorListener responseErrorListener) { Objects.requireNonNull(this.mRestfulClient).setResponseErrorListener(responseErrorListener); return this; } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#getRequestFinishedListener() */ @Override public RequestFinishedListener<S> getRequestFinishedListener() { return Objects.requireNonNull(this.mRestfulClient).getRequestFinishedListener(); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setRequestFinishedListener(br.com.softctrl.net.rest.listener.RequestFinishedListener) */ public IRestfulClient<R, S> setRequestFinishedListener(RequestFinishedListener<S> requestFinishedListener) { Objects.requireNonNull(this.mRestfulClient).setRequestFinishedListener(requestFinishedListener); return this; } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setConnectTimeout(int) */ @Override public IRestfulClient<R, S> setConnectTimeout(int connectTimeout) { return Objects.requireNonNull(this.mRestfulClient).setConnectTimeout(connectTimeout); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setReadTimeout(int) */ @Override public IRestfulClient<R, S> setReadTimeout(int readTimeout) { return Objects.requireNonNull(this.mRestfulClient).setReadTimeout(readTimeout); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setCharset(java.nio.charset.Charset) */ @Override public IRestfulClient<R, S> setCharset(Charset charset) { return Objects.requireNonNull(this.mRestfulClient).setCharset(charset); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setContentType(java.lang.String) */ @Override public IRestfulClient<R, S> setContentType(String contentType) { return Objects.requireNonNull(this.mRestfulClient).setContentType(contentType); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setBasicAuthentication(java.lang.String, java.lang.String) */ @Override public IRestfulClient<R, S> setBasicAuthentication(String username, String password) { return Objects.requireNonNull(this.mRestfulClient).setBasicAuthentication(username, password); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setProxy(java.net.Proxy) */ @Override public IRestfulClient<R, S> setProxy(Proxy proxy) { return Objects.requireNonNull(this.mRestfulClient).setProxy(proxy); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setProxy(java.lang.String, int) */ @Override public IRestfulClient<R, S> setProxy(String hostname, int port) { return Objects.requireNonNull(this.mRestfulClient).setProxy(hostname, port); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setProxy(java.net.Proxy.Type, java.lang.String, int) */ @Override public IRestfulClient<R, S> setProxy(Type type, String hostname, int port) { return Objects.requireNonNull(this.mRestfulClient).setProxy(type, hostname, port); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setProxy(java.lang.String, java.lang.String, java.lang.String, int) */ @Override public IRestfulClient<R, S> setProxy(String username, String password, String hostname, int port) { return Objects.requireNonNull(this.mRestfulClient).setProxy(username, password, hostname, port); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#setProxy(java.net.Proxy.Type, java.lang.String, java.lang.String, java.lang.String, int) */ @Override public IRestfulClient<R, S> setProxy(Type type, String username, String password, String hostname, int port) { return Objects.requireNonNull(this.mRestfulClient).setProxy(type, username, password, hostname, port); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#newURLConnection(br.com.softctrl.net.rest.HttpMethod, java.lang.String) */ @Override public URLConnection newURLConnection(HttpMethod httpMethod, String url) { return Objects.requireNonNull(this.mRestfulClient).newURLConnection(httpMethod, url); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#send(br.com.softctrl.net.rest.Request) */ @Override public void send(Request<R, S> request) { Objects.requireNonNull(this.mRestfulClient).send(request); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#add(br.com.softctrl.net.rest.Parameter) */ @Override public IRestfulClient<R, S> add(Parameter parameter) { return Objects.requireNonNull(this.mRestfulClient).add(parameter); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#add(br.com.softctrl.net.rest.Property) */ @Override public IRestfulClient<R, S> add(Property property) { return Objects.requireNonNull(this.mRestfulClient).add(property); } @Override public R getBody() { return Objects.requireNonNull(this.mRestfulClient).getBody(); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#getParameters() */ @Override public List<Parameter> getParameters() { return Objects.requireNonNull(this.mRestfulClient).getParameters(); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#getProperties() */ @Override public List<Property> getProperties() { return Objects.requireNonNull(this.mRestfulClient).getProperties(); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#send(br.com.softctrl.net.rest.HttpMethod, java.lang.String, java.lang.Object, br.com.softctrl.net.rest.Parameter[]) */ @Override public void send(HttpMethod httpMethod, String url, R body, Parameter... parameters) { Objects.requireNonNull(this.mRestfulClient).send(httpMethod, url, body, parameters); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#send(br.com.softctrl.net.rest.HttpMethod, java.lang.String, java.lang.Object, br.com.softctrl.net.rest.Property[]) */ @Override public void send(HttpMethod httpMethod, String url, R body, Property... properties) { Objects.requireNonNull(this.mRestfulClient).send(httpMethod, url, body, properties); } /* * (non-Javadoc) * @see br.com.softctrl.net.rest.IRestfulClient#send(br.com.softctrl.net.rest.HttpMethod, java.lang.String, java.lang.Object, br.com.softctrl.net.rest.Parameter[], br.com.softctrl.net.rest.Property[]) */ @Override public void send(HttpMethod httpMethod, String url, R body, Parameter[] parameters, Property[] property) { Objects.requireNonNull(this.mRestfulClient).send(httpMethod, url, body, parameters, property); } /** * * @param url */ public synchronized final S get(final String url) { return this.get(url, this.getBody(), (Objects.isNullOrEmpty(this.getParameters()) ? null : this.getParameters().toArray(new Parameter[] {})), (Objects.isNullOrEmpty(this.getProperties()) ? null : this.getProperties().toArray(new Property[] {}))); } /** * * @param url * @param parameters */ public synchronized final S get(final String url, final Parameter... parameters) { return this.get(url, this.getBody(), parameters, (Objects.isNullOrEmpty(this.getProperties()) ? null : this.getProperties().toArray(new Property[] {}))); } /** * * @param url * @param body * @param parameters */ public synchronized final S get(final String url, final R body, final Parameter... parameters) { return this.get(url, body, parameters, (Objects.isNullOrEmpty(this.getProperties()) ? null : this.getProperties().toArray(new Property[] {}))); } /** * * @param url * @param body * @param parameters * @param properties */ public synchronized final S get(final String url, final R body, final Parameter[] parameters, final Property[] properties) { final Wrapper<S> wrapper = new Wrapper<S>(); final RequestFinishedListener<S> rfl1 = this.getRequestFinishedListener(); final RequestFinishedListener<S> rfl2 = new RequestFinishedListener<S>() { @Override public void onRequestFinished(StatusCode statusCode, S response) { rfl1.onRequestFinished(statusCode, response); wrapper.setValue(response); } }; this.setRequestFinishedListener(rfl2); this.send(HttpMethod.GET, url, body, parameters, properties); return wrapper.getValue(); } /** * * @param url * @return */ public synchronized final S post(final String url) { return this.post(url, this.getBody(), (Objects.isNullOrEmpty(this.getParameters()) ? null : this.getParameters().toArray(new Parameter[] {})), (Objects.isNullOrEmpty(this.getProperties()) ? null : this.getProperties().toArray(new Property[] {}))); } /** * * @param url * @param body * @param parameters * @return */ public synchronized final S post(final String url, final R body, final Parameter... parameters) { return this.post(url, body, parameters, (Objects.isNullOrEmpty(this.getProperties()) ? null : this.getProperties().toArray(new Property[] {}))); } /** * * @param url * @param body * @param parameters * @param properties * @return */ public synchronized final S post(final String url, final R body, final Parameter[] parameters, final Property[] properties) { final Wrapper<S> wrapper = new Wrapper<S>(); final RequestFinishedListener<S> rfl1 = this.getRequestFinishedListener(); final RequestFinishedListener<S> rfl2 = new RequestFinishedListener<S>() { @Override public void onRequestFinished(StatusCode statusCode, S response) { rfl1.onRequestFinished(statusCode, response); wrapper.setValue(response); } }; this.setRequestFinishedListener(rfl2); this.send(HttpMethod.POST, url, body, parameters, properties); return wrapper.getValue(); } }
package com.facebook.yoga; import com.facebook.proguard.annotations.DoNotStrip; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; @DoNotStrip public abstract class YogaNodeJNIBase extends YogaNode implements Cloneable { /* Those flags needs be in sync with YGJNI.cpp */ private static final byte MARGIN = 1; private static final byte PADDING = 2; private static final byte BORDER = 4; private static final byte DOES_LEGACY_STRETCH_BEHAVIOUR = 8; private static final byte HAS_NEW_LAYOUT = 16; private static final byte LAYOUT_EDGE_SET_FLAG_INDEX = 0; private static final byte LAYOUT_WIDTH_INDEX = 1; private static final byte LAYOUT_HEIGHT_INDEX = 2; private static final byte LAYOUT_LEFT_INDEX = 3; private static final byte LAYOUT_TOP_INDEX = 4; private static final byte LAYOUT_DIRECTION_INDEX = 5; private static final byte LAYOUT_MARGIN_START_INDEX = 6; private static final byte LAYOUT_PADDING_START_INDEX = 10; private static final byte LAYOUT_BORDER_START_INDEX = 14; @Nullable private YogaNodeJNIBase mOwner; @Nullable private List<YogaNodeJNIBase> mChildren; @Nullable private YogaMeasureFunction mMeasureFunction; @Nullable private YogaBaselineFunction mBaselineFunction; protected long mNativePointer; @Nullable private Object mData; @DoNotStrip private @Nullable float[] arr = null; @DoNotStrip private int mLayoutDirection = 0; private boolean mHasNewLayout = true; protected boolean useVanillaJNI = false; private YogaNodeJNIBase(long nativePointer) { if (nativePointer == 0) { throw new IllegalStateException("Failed to allocate native memory"); } mNativePointer = nativePointer; } YogaNodeJNIBase() { this(YogaNative.jni_YGNodeNew()); } YogaNodeJNIBase(boolean useVanillaJNI) { this(useVanillaJNI ? YogaNative.jni_YGNodeNewJNI() : YogaNative.jni_YGNodeNew()); this.useVanillaJNI = useVanillaJNI; } YogaNodeJNIBase(YogaConfig config) { this(config.useVanillaJNI() ? YogaNative.jni_YGNodeNewWithConfigJNI(((YogaConfigJNIBase)config).mNativePointer) : YogaNative.jni_YGNodeNewWithConfig(((YogaConfigJNIBase)config).mNativePointer)); this.useVanillaJNI = config.useVanillaJNI(); } public void reset() { mMeasureFunction = null; mBaselineFunction = null; mData = null; arr = null; mHasNewLayout = true; mLayoutDirection = 0; if (useVanillaJNI) YogaNative.jni_YGNodeResetJNI(mNativePointer); else YogaNative.jni_YGNodeReset(mNativePointer); } public int getChildCount() { return mChildren == null ? 0 : mChildren.size(); } public YogaNodeJNIBase getChildAt(int i) { if (mChildren == null) { throw new IllegalStateException("YogaNode does not have children"); } return mChildren.get(i); } public void addChildAt(YogaNode c, int i) { YogaNodeJNIBase child = (YogaNodeJNIBase) c; if (child.mOwner != null) { throw new IllegalStateException("Child already has a parent, it must be removed first."); } if (mChildren == null) { mChildren = new ArrayList<>(4); } mChildren.add(i, child); child.mOwner = this; if (useVanillaJNI) YogaNative.jni_YGNodeInsertChildJNI(mNativePointer, child.mNativePointer, i); else YogaNative.jni_YGNodeInsertChild(mNativePointer, child.mNativePointer, i); } public void setIsReferenceBaseline(boolean isReferenceBaseline) { if (useVanillaJNI) YogaNative.jni_YGNodeSetIsReferenceBaselineJNI(mNativePointer, isReferenceBaseline); else YogaNative.jni_YGNodeSetIsReferenceBaseline(mNativePointer, isReferenceBaseline); } public boolean isReferenceBaseline() { return useVanillaJNI ? YogaNative.jni_YGNodeIsReferenceBaselineJNI(mNativePointer) : YogaNative.jni_YGNodeIsReferenceBaseline(mNativePointer); } @Override public YogaNodeJNIBase cloneWithoutChildren() { try { YogaNodeJNIBase clonedYogaNode = (YogaNodeJNIBase) super.clone(); long clonedNativePointer = useVanillaJNI ? YogaNative.jni_YGNodeCloneJNI(mNativePointer) : YogaNative.jni_YGNodeClone(mNativePointer);; clonedYogaNode.mOwner = null; clonedYogaNode.mNativePointer = clonedNativePointer; clonedYogaNode.clearChildren(); return clonedYogaNode; } catch (CloneNotSupportedException ex) { // This class implements Cloneable, this should not happen throw new RuntimeException(ex); } } private void clearChildren() { mChildren = null; if (useVanillaJNI) YogaNative.jni_YGNodeClearChildrenJNI(mNativePointer); else YogaNative.jni_YGNodeClearChildren(mNativePointer); } public YogaNodeJNIBase removeChildAt(int i) { if (mChildren == null) { throw new IllegalStateException( "Trying to remove a child of a YogaNode that does not have children"); } final YogaNodeJNIBase child = mChildren.remove(i); child.mOwner = null; if (useVanillaJNI) YogaNative.jni_YGNodeRemoveChildJNI(mNativePointer, child.mNativePointer); else YogaNative.jni_YGNodeRemoveChild(mNativePointer, child.mNativePointer); return child; } /** * @returns the {@link YogaNode} that owns this {@link YogaNode}. * The owner is used to identify the YogaTree that a {@link YogaNode} belongs * to. * This method will return the parent of the {@link YogaNode} when the * {@link YogaNode} only belongs to one YogaTree or null when the * {@link YogaNode} is shared between two or more YogaTrees. */ @Nullable public YogaNodeJNIBase getOwner() { return mOwner; } /** @deprecated Use #getOwner() instead. This will be removed in the next version. */ @Deprecated @Nullable public YogaNodeJNIBase getParent() { return getOwner(); } public int indexOf(YogaNode child) { return mChildren == null ? -1 : mChildren.indexOf(child); } public void calculateLayout(float width, float height) { long[] nativePointers = null; YogaNodeJNIBase[] nodes = null; ArrayList<YogaNodeJNIBase> n = new ArrayList<>(); n.add(this); for (int i = 0; i < n.size(); ++i) { List<YogaNodeJNIBase> children = n.get(i).mChildren; if (children != null) { n.addAll(children); } } nodes = n.toArray(new YogaNodeJNIBase[n.size()]); nativePointers = new long[nodes.length]; for (int i = 0; i < nodes.length; ++i) { nativePointers[i] = nodes[i].mNativePointer; } if (useVanillaJNI) YogaNative.jni_YGNodeCalculateLayoutJNI(mNativePointer, width, height, nativePointers, nodes); else YogaNative.jni_YGNodeCalculateLayout(mNativePointer, width, height, nativePointers, nodes); } public void dirty() { if (useVanillaJNI) YogaNative.jni_YGNodeMarkDirtyJNI(mNativePointer); else YogaNative.jni_YGNodeMarkDirty(mNativePointer); } public void dirtyAllDescendants() { if (useVanillaJNI) YogaNative.jni_YGNodeMarkDirtyAndPropogateToDescendantsJNI(mNativePointer); else YogaNative.jni_YGNodeMarkDirtyAndPropogateToDescendants(mNativePointer); } public boolean isDirty() { return useVanillaJNI ? YogaNative.jni_YGNodeIsDirtyJNI(mNativePointer) : YogaNative.jni_YGNodeIsDirty(mNativePointer); } @Override public void copyStyle(YogaNode srcNode) { if (useVanillaJNI) YogaNative.jni_YGNodeCopyStyleJNI(mNativePointer, ((YogaNodeJNIBase) srcNode).mNativePointer); else YogaNative.jni_YGNodeCopyStyle(mNativePointer, ((YogaNodeJNIBase) srcNode).mNativePointer); } public YogaDirection getStyleDirection() { return YogaDirection.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetDirectionJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetDirection(mNativePointer)); } public void setDirection(YogaDirection direction) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetDirectionJNI(mNativePointer, direction.intValue()); else YogaNative.jni_YGNodeStyleSetDirection(mNativePointer, direction.intValue()); } public YogaFlexDirection getFlexDirection() { return YogaFlexDirection.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetFlexDirectionJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetFlexDirection(mNativePointer)); } public void setFlexDirection(YogaFlexDirection flexDirection) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetFlexDirectionJNI(mNativePointer, flexDirection.intValue()); else YogaNative.jni_YGNodeStyleSetFlexDirection(mNativePointer, flexDirection.intValue()); } public YogaJustify getJustifyContent() { return YogaJustify.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetJustifyContentJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetJustifyContent(mNativePointer)); } public void setJustifyContent(YogaJustify justifyContent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetJustifyContentJNI(mNativePointer, justifyContent.intValue()); else YogaNative.jni_YGNodeStyleSetJustifyContent(mNativePointer, justifyContent.intValue()); } public YogaAlign getAlignItems() { return YogaAlign.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetAlignItemsJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetAlignItems(mNativePointer)); } public void setAlignItems(YogaAlign alignItems) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetAlignItemsJNI(mNativePointer, alignItems.intValue()); else YogaNative.jni_YGNodeStyleSetAlignItems(mNativePointer, alignItems.intValue()); } public YogaAlign getAlignSelf() { return YogaAlign.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetAlignSelfJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetAlignSelf(mNativePointer)); } public void setAlignSelf(YogaAlign alignSelf) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetAlignSelfJNI(mNativePointer, alignSelf.intValue()); else YogaNative.jni_YGNodeStyleSetAlignSelf(mNativePointer, alignSelf.intValue()); } public YogaAlign getAlignContent() { return YogaAlign.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetAlignContentJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetAlignContent(mNativePointer)); } public void setAlignContent(YogaAlign alignContent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetAlignContentJNI(mNativePointer, alignContent.intValue()); else YogaNative.jni_YGNodeStyleSetAlignContent(mNativePointer, alignContent.intValue()); } public YogaPositionType getPositionType() { return YogaPositionType.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetPositionTypeJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetPositionType(mNativePointer)); } public void setPositionType(YogaPositionType positionType) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetPositionTypeJNI(mNativePointer, positionType.intValue()); else YogaNative.jni_YGNodeStyleSetPositionType(mNativePointer, positionType.intValue()); } public YogaWrap getWrap() { return YogaWrap.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetFlexWrapJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetFlexWrap(mNativePointer)); } public void setWrap(YogaWrap flexWrap) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetFlexWrapJNI(mNativePointer, flexWrap.intValue()); else YogaNative.jni_YGNodeStyleSetFlexWrap(mNativePointer, flexWrap.intValue()); } public YogaOverflow getOverflow() { return YogaOverflow.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetOverflowJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetOverflow(mNativePointer)); } public void setOverflow(YogaOverflow overflow) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetOverflowJNI(mNativePointer, overflow.intValue()); else YogaNative.jni_YGNodeStyleSetOverflow(mNativePointer, overflow.intValue()); } public YogaDisplay getDisplay() { return YogaDisplay.fromInt(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetDisplayJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetDisplay(mNativePointer)); } public void setDisplay(YogaDisplay display) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetDisplayJNI(mNativePointer, display.intValue()); else YogaNative.jni_YGNodeStyleSetDisplay(mNativePointer, display.intValue()); } public float getFlex() { return useVanillaJNI ? YogaNative.jni_YGNodeStyleGetFlexJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetFlex(mNativePointer); } public void setFlex(float flex) { if (useVanillaJNI) { YogaNative.jni_YGNodeStyleSetFlexJNI(mNativePointer, flex); } else { YogaNative.jni_YGNodeStyleSetFlex(mNativePointer, flex); } } public float getFlexGrow() { return useVanillaJNI ? YogaNative.jni_YGNodeStyleGetFlexGrowJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetFlexGrow(mNativePointer); } public void setFlexGrow(float flexGrow) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetFlexGrowJNI(mNativePointer, flexGrow); else YogaNative.jni_YGNodeStyleSetFlexGrow(mNativePointer, flexGrow); } public float getFlexShrink() { return useVanillaJNI ? YogaNative.jni_YGNodeStyleGetFlexShrinkJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetFlexShrink(mNativePointer); } public void setFlexShrink(float flexShrink) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetFlexShrinkJNI(mNativePointer, flexShrink); else YogaNative.jni_YGNodeStyleSetFlexShrink(mNativePointer, flexShrink); } public YogaValue getFlexBasis() { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetFlexBasisJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetFlexBasis(mNativePointer)); } public void setFlexBasis(float flexBasis) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetFlexBasisJNI(mNativePointer, flexBasis); else YogaNative.jni_YGNodeStyleSetFlexBasis(mNativePointer, flexBasis); } public void setFlexBasisPercent(float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetFlexBasisPercentJNI(mNativePointer, percent); else YogaNative.jni_YGNodeStyleSetFlexBasisPercent(mNativePointer, percent); } public void setFlexBasisAuto() { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetFlexBasisAutoJNI(mNativePointer); else YogaNative.jni_YGNodeStyleSetFlexBasisAuto(mNativePointer); } public YogaValue getMargin(YogaEdge edge) { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetMarginJNI(mNativePointer, edge.intValue()) : YogaNative.jni_YGNodeStyleGetMargin(mNativePointer, edge.intValue())); } public void setMargin(YogaEdge edge, float margin) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMarginJNI(mNativePointer, edge.intValue(), margin); else YogaNative.jni_YGNodeStyleSetMargin(mNativePointer, edge.intValue(), margin); } public void setMarginPercent(YogaEdge edge, float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMarginPercentJNI(mNativePointer, edge.intValue(), percent); else YogaNative.jni_YGNodeStyleSetMarginPercent(mNativePointer, edge.intValue(), percent); } public void setMarginAuto(YogaEdge edge) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMarginAutoJNI(mNativePointer, edge.intValue()); else YogaNative.jni_YGNodeStyleSetMarginAuto(mNativePointer, edge.intValue()); } public YogaValue getPadding(YogaEdge edge) { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetPaddingJNI(mNativePointer, edge.intValue()) : YogaNative.jni_YGNodeStyleGetPadding(mNativePointer, edge.intValue())); } public void setPadding(YogaEdge edge, float padding) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetPaddingJNI(mNativePointer, edge.intValue(), padding); else YogaNative.jni_YGNodeStyleSetPadding(mNativePointer, edge.intValue(), padding); } public void setPaddingPercent(YogaEdge edge, float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetPaddingPercentJNI(mNativePointer, edge.intValue(), percent); else YogaNative.jni_YGNodeStyleSetPaddingPercent(mNativePointer, edge.intValue(), percent); } public float getBorder(YogaEdge edge) { return useVanillaJNI ? YogaNative.jni_YGNodeStyleGetBorderJNI(mNativePointer, edge.intValue()) : YogaNative.jni_YGNodeStyleGetBorder(mNativePointer, edge.intValue()); } public void setBorder(YogaEdge edge, float border) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetBorderJNI(mNativePointer, edge.intValue(), border); else YogaNative.jni_YGNodeStyleSetBorder(mNativePointer, edge.intValue(), border); } public YogaValue getPosition(YogaEdge edge) { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetPositionJNI(mNativePointer, edge.intValue()) : YogaNative.jni_YGNodeStyleGetPosition(mNativePointer, edge.intValue())); } public void setPosition(YogaEdge edge, float position) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetPositionJNI(mNativePointer, edge.intValue(), position); else YogaNative.jni_YGNodeStyleSetPosition(mNativePointer, edge.intValue(), position); } public void setPositionPercent(YogaEdge edge, float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetPositionPercentJNI(mNativePointer, edge.intValue(), percent); else YogaNative.jni_YGNodeStyleSetPositionPercent(mNativePointer, edge.intValue(), percent); } public YogaValue getWidth() { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetWidthJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetWidth(mNativePointer)); } public void setWidth(float width) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetWidthJNI(mNativePointer, width); else YogaNative.jni_YGNodeStyleSetWidth(mNativePointer, width); } public void setWidthPercent(float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetWidthPercentJNI(mNativePointer, percent); else YogaNative.jni_YGNodeStyleSetWidthPercent(mNativePointer, percent); } public void setWidthAuto() { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetWidthAutoJNI(mNativePointer); else YogaNative.jni_YGNodeStyleSetWidthAuto(mNativePointer); } public YogaValue getHeight() { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetHeightJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetHeight(mNativePointer)); } public void setHeight(float height) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetHeightJNI(mNativePointer, height); else YogaNative.jni_YGNodeStyleSetHeight(mNativePointer, height); } public void setHeightPercent(float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetHeightPercentJNI(mNativePointer, percent); else YogaNative.jni_YGNodeStyleSetHeightPercent(mNativePointer, percent); } public void setHeightAuto() { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetHeightAutoJNI(mNativePointer); else YogaNative.jni_YGNodeStyleSetHeightAuto(mNativePointer); } public YogaValue getMinWidth() { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetMinWidthJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetMinWidth(mNativePointer)); } public void setMinWidth(float minWidth) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMinWidthJNI(mNativePointer, minWidth); else YogaNative.jni_YGNodeStyleSetMinWidth(mNativePointer, minWidth); } public void setMinWidthPercent(float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMinWidthPercentJNI(mNativePointer, percent); else YogaNative.jni_YGNodeStyleSetMinWidthPercent(mNativePointer, percent); } public YogaValue getMinHeight() { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetMinHeightJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetMinHeight(mNativePointer)); } public void setMinHeight(float minHeight) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMinHeightJNI(mNativePointer, minHeight); else YogaNative.jni_YGNodeStyleSetMinHeight(mNativePointer, minHeight); } public void setMinHeightPercent(float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMinHeightPercentJNI(mNativePointer, percent); else YogaNative.jni_YGNodeStyleSetMinHeightPercent(mNativePointer, percent); } public YogaValue getMaxWidth() { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetMaxWidthJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetMaxWidth(mNativePointer)); } public void setMaxWidth(float maxWidth) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMaxWidthJNI(mNativePointer, maxWidth); else YogaNative.jni_YGNodeStyleSetMaxWidth(mNativePointer, maxWidth); } public void setMaxWidthPercent(float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMaxWidthPercentJNI(mNativePointer, percent); else YogaNative.jni_YGNodeStyleSetMaxWidthPercent(mNativePointer, percent); } public YogaValue getMaxHeight() { return valueFromLong(useVanillaJNI ? YogaNative.jni_YGNodeStyleGetMaxHeightJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetMaxHeight(mNativePointer)); } public void setMaxHeight(float maxheight) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMaxHeightJNI(mNativePointer, maxheight); else YogaNative.jni_YGNodeStyleSetMaxHeight(mNativePointer, maxheight); } public void setMaxHeightPercent(float percent) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetMaxHeightPercentJNI(mNativePointer, percent); else YogaNative.jni_YGNodeStyleSetMaxHeightPercent(mNativePointer, percent); } public float getAspectRatio() { return useVanillaJNI ? YogaNative.jni_YGNodeStyleGetAspectRatioJNI(mNativePointer) : YogaNative.jni_YGNodeStyleGetAspectRatio(mNativePointer); } public void setAspectRatio(float aspectRatio) { if (useVanillaJNI) YogaNative.jni_YGNodeStyleSetAspectRatioJNI(mNativePointer, aspectRatio); else YogaNative.jni_YGNodeStyleSetAspectRatio(mNativePointer, aspectRatio); } public void setMeasureFunction(YogaMeasureFunction measureFunction) { mMeasureFunction = measureFunction; YogaNative.jni_YGNodeSetHasMeasureFunc(mNativePointer, measureFunction != null); } // Implementation Note: Why this method needs to stay final // We cache the jmethodid for this method in Yoga code. This means that even if a subclass // were to override measure, we'd still call this implementation from layout code since the // overriding method will have a different jmethodid. This is final to prevent that mistake. @DoNotStrip public final long measure(float width, int widthMode, float height, int heightMode) { if (!isMeasureDefined()) { throw new RuntimeException("Measure function isn't defined!"); } return mMeasureFunction.measure( this, width, YogaMeasureMode.fromInt(widthMode), height, YogaMeasureMode.fromInt(heightMode)); } public void setBaselineFunction(YogaBaselineFunction baselineFunction) { mBaselineFunction = baselineFunction; YogaNative.jni_YGNodeSetHasBaselineFunc(mNativePointer, baselineFunction != null); } @DoNotStrip public final float baseline(float width, float height) { return mBaselineFunction.baseline(this, width, height); } public boolean isMeasureDefined() { return mMeasureFunction != null; } @Override public boolean isBaselineDefined() { return mBaselineFunction != null; } public void setData(Object data) { mData = data; } @Override public @Nullable Object getData() { return mData; } /** * Use the set logger (defaults to adb log) to print out the styles, children, and computed * layout of the tree rooted at this node. */ public void print() { if (useVanillaJNI) YogaNative.jni_YGNodePrintJNI(mNativePointer); else YogaNative.jni_YGNodePrint(mNativePointer); } public void setStyleInputs(float[] styleInputsArray, int size) { if (useVanillaJNI) YogaNative.jni_YGNodeSetStyleInputsJNI(mNativePointer, styleInputsArray, size); else YogaNative.jni_YGNodeSetStyleInputs(mNativePointer, styleInputsArray, size); } /** * This method replaces the child at childIndex position with the newNode received by parameter. * This is different than calling removeChildAt and addChildAt because this method ONLY replaces * the child in the mChildren datastructure. @DoNotStrip: called from JNI * * @return the nativePointer of the newNode {@linl YogaNode} */ @DoNotStrip private final long replaceChild(YogaNodeJNIBase newNode, int childIndex) { if (mChildren == null) { throw new IllegalStateException("Cannot replace child. YogaNode does not have children"); } mChildren.remove(childIndex); mChildren.add(childIndex, newNode); newNode.mOwner = this; return newNode.mNativePointer; } private static YogaValue valueFromLong(long raw) { return new YogaValue(Float.intBitsToFloat((int) raw), (int) (raw >> 32)); } @Override public float getLayoutX() { return arr != null ? arr[LAYOUT_LEFT_INDEX] : 0; } @Override public float getLayoutY() { return arr != null ? arr[LAYOUT_TOP_INDEX] : 0; } @Override public float getLayoutWidth() { return arr != null ? arr[LAYOUT_WIDTH_INDEX] : 0; } @Override public float getLayoutHeight() { return arr != null ? arr[LAYOUT_HEIGHT_INDEX] : 0; } public boolean getDoesLegacyStretchFlagAffectsLayout() { return arr != null && (((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX] & DOES_LEGACY_STRETCH_BEHAVIOUR) == DOES_LEGACY_STRETCH_BEHAVIOUR); } @Override public float getLayoutMargin(YogaEdge edge) { if (arr != null && ((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX] & MARGIN) == MARGIN) { switch (edge) { case LEFT: return arr[LAYOUT_MARGIN_START_INDEX]; case TOP: return arr[LAYOUT_MARGIN_START_INDEX + 1]; case RIGHT: return arr[LAYOUT_MARGIN_START_INDEX + 2]; case BOTTOM: return arr[LAYOUT_MARGIN_START_INDEX + 3]; case START: return getLayoutDirection() == YogaDirection.RTL ? arr[LAYOUT_MARGIN_START_INDEX + 2] : arr[LAYOUT_MARGIN_START_INDEX]; case END: return getLayoutDirection() == YogaDirection.RTL ? arr[LAYOUT_MARGIN_START_INDEX] : arr[LAYOUT_MARGIN_START_INDEX + 2]; default: throw new IllegalArgumentException("Cannot get layout margins of multi-edge shorthands"); } } else { return 0; } } @Override public float getLayoutPadding(YogaEdge edge) { if (arr != null && ((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX] & PADDING) == PADDING) { int paddingStartIndex = LAYOUT_PADDING_START_INDEX - ((((int)arr[LAYOUT_EDGE_SET_FLAG_INDEX] & MARGIN) == MARGIN) ? 0 : 4); switch (edge) { case LEFT: return arr[paddingStartIndex]; case TOP: return arr[paddingStartIndex + 1]; case RIGHT: return arr[paddingStartIndex + 2]; case BOTTOM: return arr[paddingStartIndex + 3]; case START: return getLayoutDirection() == YogaDirection.RTL ? arr[paddingStartIndex + 2] : arr[paddingStartIndex]; case END: return getLayoutDirection() == YogaDirection.RTL ? arr[paddingStartIndex] : arr[paddingStartIndex + 2]; default: throw new IllegalArgumentException("Cannot get layout paddings of multi-edge shorthands"); } } else { return 0; } } @Override public float getLayoutBorder(YogaEdge edge) { if (arr != null && ((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX] & BORDER) == BORDER) { int borderStartIndex = LAYOUT_BORDER_START_INDEX - ((((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX] & MARGIN) == MARGIN) ? 0 : 4) - ((((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX] & PADDING) == PADDING) ? 0 : 4); switch (edge) { case LEFT: return arr[borderStartIndex]; case TOP: return arr[borderStartIndex + 1]; case RIGHT: return arr[borderStartIndex + 2]; case BOTTOM: return arr[borderStartIndex + 3]; case START: return getLayoutDirection() == YogaDirection.RTL ? arr[borderStartIndex + 2] : arr[borderStartIndex]; case END: return getLayoutDirection() == YogaDirection.RTL ? arr[borderStartIndex] : arr[borderStartIndex + 2]; default: throw new IllegalArgumentException("Cannot get layout border of multi-edge shorthands"); } } else { return 0; } } @Override public YogaDirection getLayoutDirection() { return YogaDirection.fromInt(arr != null ? (int) arr[LAYOUT_DIRECTION_INDEX] : mLayoutDirection); } @Override public boolean hasNewLayout() { if (arr != null) { return (((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX]) & HAS_NEW_LAYOUT) == HAS_NEW_LAYOUT; } else { return mHasNewLayout; } } @Override public void markLayoutSeen() { if (arr != null) { arr[LAYOUT_EDGE_SET_FLAG_INDEX] = ((int) arr[LAYOUT_EDGE_SET_FLAG_INDEX]) & ~(HAS_NEW_LAYOUT); } mHasNewLayout = false; } }
package com.spun.util.filters; /** * @deprecated use Query.where(fromList, f -> filter.isExtracted(f)) **/ public class FilterUtils { }
package squeek.tictooltips; import net.minecraftforge.common.MinecraftForge; import squeek.tictooltips.helpers.ToolPartHelper; import squeek.tictooltips.proxy.ProxyExtraTiC; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @Mod(modid = ModTiCTooltips.MODID, version = ModTiCTooltips.VERSION, dependencies = "required-after:TConstruct;after:ExtraTiC;after:TSteelworks") public class ModTiCTooltips { public static final String MODID = "TiCTooltips"; public static final String VERSION = "${version}"; @SideOnly(Side.CLIENT) @EventHandler public void init(FMLInitializationEvent event) { if (!Loader.isModLoaded("IguanaTweaksTConstruct")) { MinecraftForge.EVENT_BUS.register(new TooltipHandler()); } } @SideOnly(Side.CLIENT) @EventHandler public void postInit(FMLPostInitializationEvent event) { if (Loader.isModLoaded("ExtraTiC")) { ProxyExtraTiC.registerParts(); } ToolPartHelper.determineMinAndMaxValues(); } }
package io.warp10.hadoop; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import com.google.common.base.Charsets; import io.warp10.script.WarpScriptException; import io.warp10.script.WarpScriptExecutor; import io.warp10.script.WarpScriptExecutor.StackSemantics; public class WarpScriptInputFormat extends InputFormat<Writable, Writable> { /** * Name of symbol under which the Hadoop Configuration will be made available * to the executing script. */ private static final String CONFIG_SYMBOL = ".conf"; /** * Suffix to use for the configuration */ public static final String WARPSCRIPT_INPUTFORMAT_SUFFIX = "warpscript.inputformat.suffix"; /** * Class of the wrapped InputFormat */ public static final String WARPSCRIPT_INPUTFORMAT_CLASS = "warpscript.inputformat.class"; public static final String WARPSCRIPT_INPUTFORMAT_SCRIPT = "warpscript.inputformat.script"; /** * Suffix to remove from configuration keys to override or create specific configuration entries */ public static final String WARPSCRIPT_INPUTFORMAT_CONF_SUFFIX = "warpscript.inputformat.conf.suffix"; private InputFormat wrappedInputFormat; private RecordReader wrappedRecordReader; private String suffix = ""; @Override public List<InputSplit> getSplits(JobContext context) throws IOException,InterruptedException { String sfx = Warp10InputFormat.getProperty(context.getConfiguration(), this.suffix, WARPSCRIPT_INPUTFORMAT_SUFFIX, ""); if (null != sfx) { if (!"".equals(sfx)) { this.suffix = "." + sfx; } else { this.suffix = ""; } } ensureInnerFormat(context.getConfiguration()); return this.wrappedInputFormat.getSplits(context); } private void ensureInnerFormat(Configuration conf) throws IOException { if (null == this.wrappedInputFormat) { try { String cls = Warp10InputFormat.getProperty(conf, this.suffix, WARPSCRIPT_INPUTFORMAT_CLASS, null); // Tweak the configuration if a conf suffix was specified String confsfx = Warp10InputFormat.getProperty(conf, this.suffix, WARPSCRIPT_INPUTFORMAT_CONF_SUFFIX, ""); if (!"".equals(confsfx)) { confsfx = "." + confsfx; List<Entry<String,String>> keys = new ArrayList<Entry<String,String>>(); Iterator<Entry<String,String>> iter = conf.iterator(); while(iter.hasNext()) { Entry<String,String> entry = iter.next(); if (entry.getKey().endsWith(confsfx)) { keys.add(entry); } } // Override or create the unsuffixed configuration parameters for (Entry<String,String> entry: keys) { String key = entry.getKey().substring(0, entry.getKey().length() - confsfx.length()); conf.set(key, entry.getValue()); } } Class innerClass = Class.forName(cls); this.wrappedInputFormat = (InputFormat) innerClass.newInstance(); } catch (Throwable t) { throw new IOException(t); } } } @Override public RecordReader<Writable, Writable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { if (null == this.wrappedRecordReader) { ensureInnerFormat(context.getConfiguration()); this.wrappedRecordReader = this.wrappedInputFormat.createRecordReader(split, context); } return new WarpScriptRecordReader(this); } /** * Return the actual WarpScript code executor given the script * which was passed as parameter. */ public WarpScriptExecutor getWarpScriptExecutor(Configuration conf, String code) throws IOException,WarpScriptException { if (code.startsWith("@") || code.startsWith("%")) { // delete the @/% character String originalfilePath = code.substring(1); String mc2 = parseWarpScript(originalfilePath); Map<String,Object> symbols = new HashMap<String,Object>(); Map<String, List<String>> config = new HashMap<String,List<String>>(); Iterator<Entry<String,String>> iter = conf.iterator(); while(iter.hasNext()) { Entry<String,String> entry = iter.next(); List<String> target = config.get(entry.getKey()); if (null == target) { target = new ArrayList<String>(); config.put(entry.getKey(), target); } target.add(entry.getValue()); } symbols.put(CONFIG_SYMBOL, config); WarpScriptExecutor executor = new WarpScriptExecutor(StackSemantics.PERTHREAD, mc2, symbols, null, code.startsWith("@")); return executor; } else { // String with Warpscript commands // Compute the hash against String content to identify this run WarpScriptExecutor executor = new WarpScriptExecutor(StackSemantics.PERTHREAD, code, null, null); return executor; } } public String parseWarpScript(String filepath) throws IOException { // Load the WarpsScript file // Warning: provide target directory when file has been copied on each node StringBuffer scriptSB = new StringBuffer(); InputStream fis = null; BufferedReader br = null; try { fis = getWarpScriptInputStream(filepath); br = new BufferedReader(new InputStreamReader(fis, Charsets.UTF_8)); while (true) { String line = br.readLine(); if (null == line) { break; } scriptSB.append(line).append("\n"); } } catch (IOException ioe) { throw new IOException("WarpScript file could not be loaded", ioe); } finally { if (null == br) { try { br.close(); } catch (Exception e) {} } if (null == fis) { try { fis.close(); } catch (Exception e) {} } } return scriptSB.toString(); } /** * Create an InputStream from a file path. * * This method can be overriden if custom loading is needed. In Spark for * example SparkFiles#get could be called. */ public InputStream getWarpScriptInputStream(String originalFilePath) throws IOException { String filepath = Paths.get(originalFilePath).toString(); InputStream fis = WarpScriptInputFormat.class.getClassLoader().getResourceAsStream(filepath); if (null == fis) { fis = new FileInputStream(filepath); } if (null == fis) { throw new IOException("WarpScript file '" + filepath + "' could not be found."); } return fis; } public String getSuffix() { return this.suffix; } public RecordReader getWrappedRecordReader() { return this.wrappedRecordReader; } }
package org.archive.wayback.surt; /** * @author brad * */ public class SvnTest { public static String CURRENT_SVN_VERSION = "$Rev$"; public String foo() { String tmp = CURRENT_SVN_VERSION.substring(5); return tmp.substring(0,tmp.length()-2); } public static void main(String[] args) { SvnTest s = new SvnTest(); System.out.println("SvnTest version is " + s.foo()); } }
public class insertion_sort { /** * Show how it works * @param args */ public static void main(String[] args) { int Array[] = new int[]{6,40,70,55,2,9,54,34,22,78,65,245}; System.out.println("This is the Array Before Bubble Sort"); for(int i=0; i < Array.length; i++) { System.out.print(Array[i] + " "); } // sort the array using insertion sort algorithm insertionSort(Array); System.out.println(""); System.out.println("Array After Bubble Sort"); for(int i=0; i < Array.length; i++) { System.out.print(Array[i] + " "); } } /** * Insertion Sort Algorithm * @param i array of integers */ public static void insertionSort(int[] i) { int l = i.length; int tmp; for (int k = 1; k < l; k++) { tmp = i[k]; int j = k; while (j > 0 && i[j-1] > tmp) { i[j] = i[j-1]; j } i[j] = tmp; } } }
package tlc2.tool.fp; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.LongAccumulator; import java.util.function.LongBinaryOperator; import java.util.function.ToLongFunction; import java.util.logging.Level; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.fp.LongArrays.LongComparator; import tlc2.tool.fp.management.DiskFPSetMXWrapper; import tlc2.util.BufferedRandomAccessFile; import tlc2.util.Striped; import util.Assert; /** * see OpenAddressing.tla */ @SuppressWarnings({ "serial" }) public final class OffHeapDiskFPSet extends NonCheckpointableDiskFPSet implements FPSetStatistic { private static final int PROBE_LIMIT = Integer.getInteger(OffHeapDiskFPSet.class.getName() + ".probeLimit", 128); static final long EMPTY = 0L; private final LongAccumulator reprobe; private final LongArray array; /** * The indexer maps a fingerprint to a in-memory bucket and the associated lock */ private final Indexer indexer; private CyclicBarrier barrier; protected OffHeapDiskFPSet(final FPSetConfiguration fpSetConfig) throws RemoteException { super(fpSetConfig); final long positions = fpSetConfig.getMemoryInFingerprintCnt(); // Determine base address which varies depending on machine architecture. this.array = new LongArray(positions); this.reprobe = new LongAccumulator(new LongBinaryOperator() { public long applyAsLong(long left, long right) { return Math.max(left, right); } }, 0); // If Hamming weight is 1, the logical index address can be calculated // significantly faster by bit-shifting. However, with large memory // sizes, only supporting increments of 2^n sizes would waste memory // (e.g. either 32GiB or 64Gib). Hence, we check if the bitCount allows // us to use bit-shifting. If not, we fall back to less efficient // calculations. if (Long.bitCount(positions) == 1) { this.indexer = new BitshiftingIndexer(positions, fpSetConfig.getFpBits()); } else { // non 2^n buckets cannot use a bit shifting indexer this.indexer = new Indexer(positions, fpSetConfig.getFpBits()); } } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#init(int, java.lang.String, java.lang.String) */ public void init(final int numThreads, String aMetadir, String filename) throws IOException { super.init(numThreads, aMetadir, filename); array.zeroMemory(numThreads); // This barrier gets run after one thread signals the need to suspend // put and contains operations to evict to secondary. Signaling is done // via the flusherChoosen AtomicBoolean. All threads (numThreads) will // then await on the barrier and the Runnable be executed when the // last of numThreads arrives. // Compared to an AtomicBoolean, the barrier operation use locks and // are thus comparably expensive. barrier = new CyclicBarrier(numThreads, new Runnable() { // Atomically evict and reset flusherChosen to make sure no // thread re-read flusherChosen=true after an eviction and // waits again. public void run() { // statistics growDiskMark++; final long timestamp = System.currentTimeMillis(); final long insertions = tblCnt.longValue(); final double lf = tblCnt.doubleValue() / (double) maxTblCnt; final int r = reprobe.intValue(); // Only pay the price of creating threads when array is sufficiently large. if (array.size() > 8192) { OffHeapDiskFPSet.this.flusher = new ConcurrentOffHeapMSBFlusher(array, r, numThreads, insertions); } else { OffHeapDiskFPSet.this.flusher = new OffHeapMSBFlusher(array, r); } try { flusher.flushTable(); // Evict() } catch (Exception notExpectedToHappen) { notExpectedToHappen.printStackTrace(); } // statistics and logging again. long l = System.currentTimeMillis() - timestamp; flushTime += l; LOGGER.log(Level.FINE, "Flushed disk {0} {1}. time, in {2} sec after {3} insertions, load factor {4} and reprobe of {5}.", new Object[] { ((DiskFPSetMXWrapper) diskFPSetMXWrapper).getObjectName(), getGrowDiskMark(), l, insertions, lf, r }); // Release exclusive access. It has to be done by the runnable // before workers waiting on the barrier wake up again. Assert.check(flusherChosen.compareAndSet(true, false), EC.GENERAL); } }); } private boolean checkEvictPending() { if (flusherChosen.get()) { try { barrier.await(); } catch (InterruptedException notExpectedToHappen) { notExpectedToHappen.printStackTrace(); } catch (BrokenBarrierException notExpectedToHappen) { notExpectedToHappen.printStackTrace(); } return true; } return false; } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#sizeof() */ public long sizeof() { long size = 44; // approx size of this DiskFPSet object size += maxTblCnt * (long) LongSize; size += getIndexCapacity() * 4; return size; } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#needsDiskFlush() */ protected final boolean needsDiskFlush() { return loadFactorExceeds(1d) || forceFlush; } /** * This limits the (primary) in-memory hash table to grow beyond the given * limit. * * @param limit * A limit in the domain [0, 1] which restricts the hash table * from growing past it. * @return true iff the current hash table load exceeds the given limit */ private final boolean loadFactorExceeds(final double limit) { final double d = (this.tblCnt.doubleValue()) / (double) this.maxTblCnt; return d >= limit; } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#memLookup(long) */ final boolean memLookup(final long fp0) { int r = reprobe.intValue(); for (int i = 0; i <= r; i++) { final long position = indexer.getIdx(fp0, i); final long l = array.get(position); if (fp0 == (l & FLUSHED_MASK)) { // zero the long msb (which is 1 if fp has been flushed to disk) return true; } else if (l == EMPTY) { return false; } } return false; } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#memInsert(long) */ final boolean memInsert(final long fp0) throws IOException { for (int i = 0; i < PROBE_LIMIT; i++) { final long position = indexer.getIdx(fp0, i); final long expected = array.get(position); if (expected == EMPTY || (expected < 0 && fp0 != (expected & FLUSHED_MASK))) { // Increment reprobe if needed. Other threads might have // increased concurrently. Since reprobe is strictly // monotonic increasing, we need no retry when r larger. reprobe.accumulate(i); // Try to CAS the new fingerprint. In case of failure, reprobe // is too large which we ignore. Will be eventually corrected // by eviction. if (array.trySet(position, expected, fp0)) { this.tblCnt.increment(); return false; } // Cannot reduce reprobe to its value before we increased it. // Another thread could have caused an increase to i too which // would be lost. } // Expected is the fingerprint to be inserted. if ((expected & FLUSHED_MASK) == fp0) { return true; } } // We failed to insert into primary. Consequently, lets try and make // some room by signaling all threads to wait for eviction. forceFlush(); // We've signaled for eviction to start or failed because some other // thread beat us to it. Actual eviction and setting flusherChosen back // to false is done by the Barrier's Runnable. We cannot set // flusherChosen back to false after barrier.awaits returns because it // leaves a window during which other threads read the old true value of // flusherChosen a second time and immediately wait again. return put(fp0); } /* (non-Javadoc) * @see tlc2.tool.fp.FPSet#put(long) */ public final boolean put(final long fp) throws IOException { if (checkEvictPending()) { return put(fp); } // zeros the msb final long fp0 = fp & FLUSHED_MASK; // Only check primary and disk iff there exists a disk file. index is // created when we wait and thus cannot race. if (index != null) { // Lookup primary memory if (memLookup(fp0)) { this.memHitCnt.increment(); return true; } // Lookup on disk if (this.diskLookup(fp0)) { this.diskHitCnt.increment(); return true; } } // Lastly, try to insert into memory. return memInsert(fp0); } /* (non-Javadoc) * @see tlc2.tool.fp.FPSet#contains(long) */ public final boolean contains(final long fp) throws IOException { // maintains happen-before with regards to successful put if (checkEvictPending()) { return contains(fp); } // zeros the msb final long fp0 = fp & FLUSHED_MASK; // Lookup in primary if (memLookup(fp0)) { return true; } // Lookup on secondary/disk if (this.diskLookup(fp0)) { diskHitCnt.increment(); return true; } return false; } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#forceFlush() */ public void forceFlush() { flusherChosen.compareAndSet(false, true); } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#acquireTblWriteLock() */ void acquireTblWriteLock() { // no-op for now } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#releaseTblWriteLock() */ void releaseTblWriteLock() { // no-op for now } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#getTblCapacity() */ public long getTblCapacity() { return maxTblCnt; } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#getTblLoad() */ public long getTblLoad() { return getTblCnt(); } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#getOverallCapacity() */ public long getOverallCapacity() { return array.size(); } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet#getBucketCapacity() */ public long getBucketCapacity() { // A misnomer, but bucketCapacity is obviously not applicable with open // addressing. return reprobe.longValue(); } // public static class Indexer { private static final long minFingerprint = 1L; //Minimum possible fingerprint (0L marks an empty position) private final float tblScalingFactor; private final long maxFingerprint; protected final long positions; public Indexer(final long positions, final int fpBits) { this(positions, fpBits, 0xFFFFFFFFFFFFFFFFL >>> fpBits); assert fpBits > 0; } public Indexer(final long positions, final int fpBits, final long maxValue) { this.positions = positions; this.maxFingerprint = maxValue; // (position-1L) because array is zero indexed. this.tblScalingFactor = (positions - 1L) / ((maxFingerprint - minFingerprint) * 1f); } protected long getIdx(final long fp) { return getIdx(fp, 0); } protected long getIdx(final long fp, final int probe) { long idx = Math.round(tblScalingFactor * (fp - minFingerprint)) + probe; return idx % positions; } } public static class BitshiftingIndexer extends Indexer { private final long prefixMask; private final int rShift; public BitshiftingIndexer(final long positions, final int fpBits) throws RemoteException { super(positions, fpBits); this.prefixMask = 0xFFFFFFFFFFFFFFFFL >>> fpBits; long n = (0xFFFFFFFFFFFFFFFFL >>> fpBits) - (positions - 1); int moveBy = 0; while (n >= positions) { moveBy++; n = n >>> 1; } this.rShift = moveBy; } @Override protected long getIdx(final long fp) { return ((fp & prefixMask) >>> rShift); } @Override protected long getIdx(final long fp, int probe) { // Have to mod positions because probe might cause us to overshoot. return (((fp & prefixMask) >>> rShift) + probe) % positions; } } // private LongComparator getLongComparator() { return new LongComparator() { public int compare(long fpA, long posA, long fpB, long posB) { // Elements not in Nat \ {0} remain at their current // position. if (fpA <= EMPTY || fpB <= EMPTY) { return 0; } final boolean wrappedA = indexer.getIdx(fpA) > posA; final boolean wrappedB = indexer.getIdx(fpB) > posB; if (wrappedA == wrappedB && posA > posB) { return fpA < fpB ? -1 : 1; } else if ((wrappedA ^ wrappedB)) { if (posA < posB && fpA < fpB) { return -1; } if (posA > posB && fpA > fpB) { return -1; } } return 0; } }; } /** * Returns the number of fingerprints stored on disk in the range lo,hi. */ private long getOffset(final int id, final long lo, final long hi) throws IOException { if (this.index == null) { return 0L; } final long lo0 = lo & FLUSHED_MASK; final long hi0 = hi & FLUSHED_MASK; return getOffset(id, hi0) - getOffset(id, lo0); } /** * The number of fingerprints stored on disk smaller than fp. */ private long getOffset(final int id, final long fp) throws IOException { final int indexLength = this.index.length; int loPage = 0, hiPage = indexLength - 1; long loVal = this.index[loPage]; long hiVal = this.index[hiPage]; if (fp <= loVal) { return 0L; } if (fp >= hiVal) { return indexLength * NumEntriesPerPage; } // See DiskFPSet#diskLookup for comments. // Lookup the corresponding disk page in index. final double dfp = (double) fp; while (loPage < hiPage - 1) { final double dhi = (double) hiPage; final double dlo = (double) loPage; final double dhiVal = (double) hiVal; final double dloVal = (double) loVal; int midPage = (loPage + 1) + (int) ((dhi - dlo - 1.0) * (dfp - dloVal) / (dhiVal - dloVal)); if (midPage == hiPage) { midPage } final long v = this.index[midPage]; if (fp < v) { hiPage = midPage; hiVal = v; } else if (fp > v) { loPage = midPage; loVal = v; } else { return midPage * NumEntriesPerPage; } } // no page is in between loPage and hiPage at this point Assert.check(hiPage == loPage + 1, EC.SYSTEM_INDEX_ERROR); // Read the disk page and try to find the given fingerprint or the next // smaller one. Calculate its offset in file. long midEntry = -1L; long loEntry = ((long) loPage) * NumEntriesPerPage; long hiEntry = ((loPage == indexLength - 2) ? this.fileCnt - 1 : ((long) hiPage) * NumEntriesPerPage); final BufferedRandomAccessFile raf = this.braf[id]; while (loEntry < hiEntry) { midEntry = calculateMidEntry(loVal, hiVal, dfp, loEntry, hiEntry); raf.seek(midEntry * LongSize); final long v = raf.readLong(); if (fp < v) { hiEntry = midEntry; hiVal = v; } else if (fp > v) { loEntry = midEntry + 1; loVal = v; } else { break; } } return midEntry; } public class ConcurrentOffHeapMSBFlusher extends OffHeapMSBFlusher { private final int numThreads; private final ExecutorService executorService; private final Striped striped; private final long insertions; /** * The length of a single partition. */ private final long length; private List<Future<Result>> offsets; public ConcurrentOffHeapMSBFlusher(final LongArray array, final int r, final int numThreads, final long insertions) { super(array, r); this.numThreads = numThreads; this.insertions = insertions; this.length = (long) Math.floor(a.size() / numThreads); this.striped = Striped.readWriteLock(numThreads); this.executorService = Executors.newFixedThreadPool(numThreads); } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet.Flusher#prepareTable() */ protected void prepareTable() { final Collection<Callable<Result>> tasks = new ArrayList<Callable<Result>>(numThreads); for (int i = 0; i < numThreads; i++) { final int id = i; tasks.add(new Callable<Result>() { @Override public Result call() throws Exception { final long start = id * length; final long end = id == numThreads - 1 ? a.size() - 1L : start + length - 1L; // Sort partition p_n while holding its // corresponding lock. Sort requires exclusive // access. striped.getAt(id).writeLock().lock(); LongArrays.sort(a, start, end, getLongComparator()); striped.getAt(id).writeLock().unlock(); // Sort the range between partition p_n and // p_n+1 bounded by reprobe. We need no hold // lock for p_n because p_n is done (except for // its non-overlapping lower end). striped.getAt((id + 1) % numThreads).writeLock().lock(); LongArrays.sort(a, end - r, end + r, getLongComparator()); striped.getAt((id + 1) % numThreads).writeLock().unlock(); // Count the occupied positions for this // partition. Occupied positions are those which // get evicted (written to disk). // This could be done as part of (insertion) sort // above at the price of higher complexity. Thus, // it's done here until it becomes a bottleneck. long occupied = 0L; for (long pos = start; pos < end; pos++) { if (a.get(pos) <= EMPTY || indexer.getIdx(a.get(pos)) > pos) { continue; } occupied = occupied + 1; } // Determine number of elements in the old/current file. long occupiedFile = getOffset(id, a.get(start), a.get(end)); return new Result(occupied, occupiedFile); } }); } try { offsets = executorService.invokeAll(tasks); } catch (InterruptedException notExpectedToHappen) { notExpectedToHappen.printStackTrace(); } assert checkSorted(a, indexer, r) : "Array not fully sorted."; } @Override protected void mergeNewEntries(final RandomAccessFile[] inRAFs, final RandomAccessFile outRAF, final Iterator ignored, final int idx, final long cnt) throws IOException { assert offsets.stream().mapToLong(new ToLongFunction<Future<Result>>() { public long applyAsLong(Future<Result> future) { try { return future.get().getTable(); } catch (InterruptedException notExpectedToHappen) { notExpectedToHappen.printStackTrace(); } catch (ExecutionException notExpectedToHappen) { notExpectedToHappen.printStackTrace(); } return 0L; } }).sum() == insertions : "Missing inserted elements during eviction."; final Collection<Callable<Void>> tasks = new ArrayList<Callable<Void>>(numThreads); // Id = 0 tasks.add(new Callable<Void>() { public Void call() throws Exception { final Result result = offsets.get(0).get(); final Iterator itr = new Iterator(a, result.getTable(), indexer); ConcurrentOffHeapMSBFlusher.super.mergeNewEntries(inRAFs[0], outRAF, itr, 0, 0L); assert outRAF.getFilePointer() == result.getTotal() * FPSet.LongSize && itr.pos == length; return null; } }); // Id > 0 for (int i = 1; i < numThreads; i++) { final int id = i; tasks.add(new Callable<Void>() { public Void call() throws Exception { final RandomAccessFile tmpRAF = new BufferedRandomAccessFile(new File(tmpFilename), "rw"); try { // Sum up the combined number of elements in // lower partitions. long skipTotal = 0L; for (int j = 0; j < id; j++) { skipTotal = skipTotal + offsets.get(j).get().getTotal(); } // Set offsets into the out (tmp) file. final Result result = offsets.get(id).get(); tmpRAF.setLength((skipTotal + result.getTotal()) * FPSet.LongSize); tmpRAF.seek(skipTotal * FPSet.LongSize); // Set offset and the number of elements the // iterator is supposed to return. final long table = result.getTable(); final Iterator itr = new Iterator(a, table, id * length, indexer); final RandomAccessFile inRAF = inRAFs[id]; // Calculate the where the index entries start and // end. final int idx = (int) Math.floor(skipTotal / NumEntriesPerPage); final long cnt = NumEntriesPerPage - (skipTotal - (idx * NumEntriesPerPage)); ConcurrentOffHeapMSBFlusher.super.mergeNewEntries(inRAF, tmpRAF, itr, idx + 1, cnt); // TODO figure out how to calculate the position of // itr for the last partition when it wrapped. assert tmpRAF.getFilePointer() == (skipTotal + result.getTotal()) * FPSet.LongSize && itr.pos == (id == numThreads - 1 ? itr.pos : (id + 1) * length); } finally { tmpRAF.close(); } return null; } }); } // Combine the callable results. try { executorService.invokeAll(tasks); } catch (InterruptedException notExpectedToHappen) { notExpectedToHappen.printStackTrace(); } finally { executorService.shutdown(); } assert checkTable(a) && checkIndex(index); } private class Result { private final long occupiedTable; private final long occupiedDisk; public Result(long occupiedTable, long occupiedDisk) { this.occupiedTable = occupiedTable; this.occupiedDisk = occupiedDisk; } public long getTable() { return occupiedTable; } public long getTotal() { return occupiedDisk + occupiedTable; } } } public class OffHeapMSBFlusher extends Flusher { protected final int r; protected final LongArray a; public OffHeapMSBFlusher(LongArray array, int reprobe) { a = array; r = reprobe; } /* (non-Javadoc) * @see tlc2.tool.fp.DiskFPSet.Flusher#prepareTable() */ protected void prepareTable() { super.prepareTable(); // Sort with a single thread. LongArrays.sort(a, 0, a.size() - 1L + r, getLongComparator()); } /* (non-Javadoc) * @see tlc2.tool.fp.MSBDiskFPSet#mergeNewEntries(java.io.RandomAccessFile, java.io.RandomAccessFile) */ @Override protected void mergeNewEntries(RandomAccessFile[] inRAFs, RandomAccessFile outRAF) throws IOException { final long buffLen = tblCnt.sum(); final Iterator itr = new Iterator(array, buffLen, indexer); final int indexLen = calculateIndexLen(buffLen); index = new long[indexLen]; mergeNewEntries(inRAFs, outRAF, itr, 0, 0L); // maintain object invariants fileCnt += buffLen; } protected void mergeNewEntries(RandomAccessFile[] inRAFs, RandomAccessFile outRAF, Iterator itr, int currIndex, long counter) throws IOException { inRAFs[0].seek(0); mergeNewEntries(inRAFs[0], outRAF, itr, currIndex, counter); } protected void mergeNewEntries(RandomAccessFile inRAF, RandomAccessFile outRAF, final Iterator itr, final int idx, final long cnt) throws IOException { int currIndex = idx; long counter = cnt; // initialize positions in "buff" and "inRAF" long value = 0L; // initialize only to make compiler happy boolean eof = false; if (fileCnt > 0) { try { value = inRAF.readLong(); } catch (EOFException e) { eof = true; } } else { eof = true; } // merge while both lists still have elements remaining boolean eol = false; long fp = itr.next(); while (!eof || !eol) { if ((value < fp || eol) && !eof) { outRAF.writeLong(value); diskWriteCnt.increment(); // update in-memory index file if (counter == 0) { index[currIndex++] = value; counter = NumEntriesPerPage; } counter try { value = inRAF.readLong(); } catch (EOFException e) { eof = true; } } else { // prevent converting every long to String when assertion holds (this is expensive) if (value == fp) { //MAK: Commented cause a duplicate does not pose a risk for correctness. // It merely indicates a bug somewhere. //Assert.check(false, EC.TLC_FP_VALUE_ALREADY_ON_DISK, // String.valueOf(value)); MP.printWarning(EC.TLC_FP_VALUE_ALREADY_ON_DISK, String.valueOf(value)); } assert fp > EMPTY : "Wrote an invalid fingerprint to disk."; outRAF.writeLong(fp); diskWriteCnt.increment(); // update in-memory index file if (counter == 0) { index[currIndex++] = fp; counter = NumEntriesPerPage; } counter // we used one fp up, thus move to next one if (itr.hasNext()) { fp = itr.next(); } else { eol = true; } } } // both sets used up completely Assert.check(eof && eol, EC.GENERAL); if (currIndex == index.length - 1) { // Update the last element in index with the large one of the // current largest element of itr and the previous largest element. index[index.length - 1] = fp; } } } /** * A non-thread safe Iterator whose next method returns the next largest * element. */ public static class Iterator { private enum WRAP { ALLOWED, FORBIDDEN; }; private final long elements; private final LongArray array; private final Indexer indexer; private final WRAP canWrap; private long pos = 0; private long elementsRead = 0L; public Iterator(final LongArray array, final long elements, final Indexer indexer) { this(array, elements, 0L, indexer, WRAP.ALLOWED); } public Iterator(final LongArray array, final long elements, final long start, final Indexer indexer) { this(array, elements, start, indexer, WRAP.FORBIDDEN); } public Iterator(final LongArray array, final long elements, final long start, final Indexer indexer, final WRAP canWrap) { this.array = array; this.elements = elements; this.indexer = indexer; this.pos = start; this.canWrap = canWrap; } /** * Returns the next element in the iteration that is not EMPTY nor * marked evicted. * <p> * THIS IS NOT SIDEEFFECT FREE. AFTERWARDS, THE ELEMENT WILL BE MARKED * EVICTED. * * @return the next element in the iteration that is not EMPTY nor * marked evicted. * @exception NoSuchElementException * iteration has no more elements. */ public long next() { long elem = EMPTY; do { long position = pos % array.size(); elem = array.get(position); pos = pos + 1L; if (elem <= EMPTY) { continue; } final long baseIdx = indexer.getIdx(elem); if (baseIdx > pos) { // This branch should only be active for thread with id 0. assert canWrap == WRAP.ALLOWED; continue; } // mark elem in array as being evicted. array.set(position, elem | MARK_FLUSHED); elementsRead = elementsRead + 1L; return elem; } while (hasNext()); throw new NoSuchElementException(); } /** * Returns <tt>true</tt> if the iteration has more elements. (In other * words, returns <tt>true</tt> if <tt>next</tt> would return an element * rather than throwing an exception.) * * @return <tt>true</tt> if the iterator has more elements. */ public boolean hasNext() { return elementsRead < elements; } } private static boolean checkSorted(final LongArray array, final Indexer indexer, final int reprobe) { long e = 0L; for (long pos = 1; pos < array.size() + reprobe; pos++) { final long tmp = array.get(pos % array.size()); if (tmp <= EMPTY) { continue; } final long idx = indexer.getIdx(tmp); if (idx > pos ) { continue; } if (idx + reprobe < pos) { continue; } if (e == 0L) { // Initialize e with the first element that is not <=EMPTY // or has wrapped. e = tmp; continue; } if (e >= tmp) { return false; } e = tmp; } return true; } private static boolean checkTable(LongArray array) { for (long i = 0L; i < array.size(); i++) { if (array.get(i) > EMPTY) { return false; } } return true; } private static boolean checkIndex(final long[] idx) { for (int i = 1; i < idx.length; i++) { if (idx[i - 1] >= idx[i]) { return false; } } return true; } }
package com.iluwatar; /** * Callback pattern is more native for functional languages where function is treated as first-class citizen. * Prior to Java8 can be simulated using simple (alike command) interfaces. */ public class App { public static void main(String[] args) { Task task = new SimpleTask(); Callback callback = new Callback() { @Override public void call() { System.out.println("I'm done now."); } }; task.executeWith(callback); } }
package collagecreator; import java.awt.Color; import java.awt.Container; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class CollageCreator { public static String portraitDirectoryName; public static String landscapeDirectoryName; //Methods for resizing photo and adding to a panel public static void createLandscapeLabel (String filename, JPanel panel) { try { Image pic = ImageIO.read(new File (landscapeDirectoryName+"/"+filename)); Image resizedpic = pic.getScaledInstance(800,600,Image.SCALE_SMOOTH); JLabel label = new JLabel(new ImageIcon(resizedpic)); panel.add(label); } catch (IOException e) { e.printStackTrace(); } } public static void createPortraitLabel (String filename, JPanel panel) { try { Image pic = ImageIO.read(new File(portraitDirectoryName+"/"+filename)); Image resizedpic = pic.getScaledInstance(600,800,Image.SCALE_SMOOTH); JLabel label = new JLabel(new ImageIcon(resizedpic)); panel.add(label); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { //Setting directory names landscapeDirectoryName = args[0]; portraitDirectoryName = args[1]; //Creating containers JFrame frame = new JFrame(); frame.setSize(3900,2622); frame.setLayout(new GridBagLayout()); frame.getContentPane().setBackground(Color.WHITE); JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(); JPanel panel4 = new JPanel(); JPanel panel5 = new JPanel(); panel1.setLayout(new BoxLayout(panel1, BoxLayout.PAGE_AXIS)); panel2.setLayout(new BoxLayout(panel2, BoxLayout.PAGE_AXIS)); panel3.setLayout(new BoxLayout(panel3, BoxLayout.PAGE_AXIS)); panel4.setLayout(new BoxLayout(panel4, BoxLayout.PAGE_AXIS)); panel5.setLayout(new BoxLayout(panel5, BoxLayout.PAGE_AXIS)); //Creating lists of files to use File landscapeDirectory = new File(landscapeDirectoryName); File portraitDirectory = new File(portraitDirectoryName); ArrayList<String> landscapeList = new ArrayList(Arrays.asList(landscapeDirectory.list())); ArrayList<String> portraitList = new ArrayList(Arrays.asList(portraitDirectory.list())); //Randomising the file order Collections.shuffle(portraitList); Collections.shuffle(landscapeList); //Adding photos to panels for (int i=0; i<18; i++) { if (i<4) { createLandscapeLabel(landscapeList.get(i), panel1); } else if (i<7) { createPortraitLabel(portraitList.get(i-4), panel2); } else if (i<11) { createLandscapeLabel(landscapeList.get(i-3), panel3); } else if (i<14) { createPortraitLabel(portraitList.get(i-8), panel4); } else { createLandscapeLabel(landscapeList.get(i-6), panel5); } } //Adding panels to frame frame.add(panel1); frame.add(panel2); frame.add(panel3); frame.add(panel4); frame.add(panel5); frame.setVisible(true); //Saving contents of frame as file Container content = frame.getContentPane(); BufferedImage img = new BufferedImage(content.getWidth(), content.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); content.printAll(g2d); g2d.dispose(); try { ImageIO.write(img, "jpg", new File("collage.jpg")); } catch (IOException e) { e.printStackTrace(); } System.exit(0); } }
package com.thoughtworks.acceptance; import java.math.BigDecimal; import java.math.BigInteger; public class BasicTypesTest extends AbstractAcceptanceTest { public void testPrimitiveNumbers() { assertBothWays(new Integer(99), "<int>99</int>"); assertBothWays(new Integer(-99), "<int>-99</int>"); assertBothWays(new Integer(0), "<int>0</int>"); assertBothWays(new Float(-123.45f), "<float>-123.45</float>"); assertBothWays(new Double(-1234567890.12345), "<double>-1.23456789012345E9</double>"); assertBothWays(new Long(123456789123456L), "<long>123456789123456</long>"); assertBothWays(new Short((short) 123), "<short>123</short>"); } public void testDifferentBaseIntegers() { assertEquals(new Integer(255), xstream.fromXML("<int>0xFF</int>")); assertEquals(new Integer(8), xstream.fromXML("<int>010</int>")); } public void testNegativeIntegersInHex() { assertEquals(new Byte((byte)-1), xstream.fromXML("<byte>0xFF</byte>")); assertEquals(new Short((short)-1), xstream.fromXML("<short>0xFFFF</short>")); assertEquals(new Integer(-1), xstream.fromXML("<int>0xFFFFFFFF</int>")); assertEquals(new Long(Long.MAX_VALUE), xstream.fromXML("<long>0x7FFFFFFFFFFFFFFF</long>")); } public void testNegativeIntegersInOctal() { assertEquals(new Byte((byte)-1), xstream.fromXML("<byte>0377</byte>")); assertEquals(new Short((short)-1), xstream.fromXML("<short>0177777</short>")); assertEquals(new Integer(-1), xstream.fromXML("<int>037777777777</int>")); assertEquals(new Long(Long.MAX_VALUE), xstream.fromXML("<long>0777777777777777777777</long>")); } public void testOtherPrimitives() { assertBothWays(new Character('z'), "<char>z</char>"); assertBothWays(Boolean.TRUE, "<boolean>true</boolean>"); assertBothWays(Boolean.FALSE, "<boolean>false</boolean>"); assertBothWays(new Byte((byte) 44), "<byte>44</byte>"); } public void testNullCharacter() { assertEquals(new Character('\0'), xstream.fromXML("<char null=\"true\"/>")); // pre XStream 1.3 assertBothWays(new Character('\0'), "<char></char>"); } public void testNonUnicodelCharacter() { assertBothWays(new Character('\uffff'), "<char>&#xffff;</char>"); } public void testStrings() { assertBothWays("hello world", "<string>hello world</string>"); } public void testStringBuffer() { StringBuffer buffer = new StringBuffer(); buffer.append("woo"); String xml = xstream.toXML(buffer); assertEquals(xml, "<string-buffer>woo</string-buffer>"); StringBuffer out = (StringBuffer) xstream.fromXML(xml); assertEquals("woo", out.toString()); } public void testBigInteger() { BigInteger bigInteger = new BigInteger("1234567890123456"); assertBothWays(bigInteger, "<big-int>1234567890123456</big-int>"); } public void testBigDecimal() { BigDecimal bigDecimal = new BigDecimal("1234567890123456.987654321"); assertBothWays(bigDecimal, "<big-decimal>1234567890123456.987654321</big-decimal>"); } public void testNull() { assertBothWays(null, "<null/>"); } public void testNumberFormats() { assertEquals(1.0, ((Double)xstream.fromXML("<double>1</double>")).doubleValue(), 0.001); assertEquals(1.0f, ((Float)xstream.fromXML("<float>1</float>")).floatValue(), 0.001); } }
import java.util.*; public class Factorize { // returns map: prime_divisor -> power public static TreeMap<Long, Integer> factorize(long n) { TreeMap<Long, Integer> factors = new TreeMap<>(); for (long divisor = 2; n > 1; ) { int power = 0; while (n % divisor == 0) { ++power; n /= divisor; } if (power > 0) { factors.put(divisor, power); } ++divisor; if (divisor * divisor > n) { divisor = n; } } return factors; } public static int[] getAllDivisors(int n) { List<Integer> list = new ArrayList<>(); for (int divisor = 1; divisor * divisor <= n; divisor++) if (n % divisor == 0) { list.add(divisor); if (divisor * divisor != n) list.add(n / divisor); } int[] res = new int[list.size()]; for (int i = 0; i < res.length; i++) res[i] = list.get(i); Arrays.sort(res); return res; } // Usage example public static void main(String[] args) { TreeMap<Long, Integer> f = factorize(24); System.out.println(f); System.out.println(Arrays.toString(getAllDivisors(16))); } }
package jade.domain; import java.io.StringReader; import java.io.StringWriter; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.FileWriter; import java.net.InetAddress; import jade.util.leap.Iterator; import jade.util.leap.List; import jade.util.leap.ArrayList; import jade.util.leap.Set; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.core.*; import jade.core.behaviours.*; import jade.core.event.PlatformEvent; import jade.core.event.MTPEvent; import jade.domain.FIPAAgentManagement.*; import jade.domain.JADEAgentManagement.*; import jade.domain.introspection.*; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.lang.Codec; import jade.lang.sl.SL0Codec; import jade.onto.Ontology; import jade.onto.OntologyException; import jade.onto.Frame; import jade.onto.basic.Action; import jade.onto.basic.BasicOntology; import jade.onto.basic.ResultPredicate; import jade.onto.basic.DonePredicate; import jade.onto.basic.TrueProposition; import jade.mtp.MTPException; import jade.proto.FipaRequestResponderBehaviour; /** Standard <em>Agent Management System</em> agent. This class implements <em><b>FIPA</b></em> <em>AMS</em> agent. <b>JADE</b> applications cannot use this class directly, but interact with it through <em>ACL</em> message passing. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class ams extends Agent implements AgentManager.Listener { private abstract class AMSBehaviour extends FipaRequestResponderBehaviour.ActionHandler implements FipaRequestResponderBehaviour.Factory { protected AMSBehaviour(ACLMessage req) { super(ams.this,req); } /** * Create the content for the AGREE message * @param a is the action that has been agreed to perform * @return a String with the content ready to be set into the message **/ protected String createAgreeContent(Action a) { ACLMessage temp = new ACLMessage(ACLMessage.AGREE); temp.setLanguage(getRequest().getLanguage()); temp.setOntology(getRequest().getOntology()); List l = new ArrayList(2); if (a == null) { a = new Action(); a.set_0(getAID()); a.set_1("UnknownAction"); } l.add(a); l.add(new TrueProposition()); try { fillMsgContent(temp,l); } catch (Exception ee) { // in any case try to return some good content return "( true )"; } return temp.getContent(); } /** * Create the content for a so-called "exceptional" message, i.e. * one of NOT_UNDERSTOOD, FAILURE, REFUSE message * @param a is the Action that generated the exception * @param e is the generated Exception * @return a String containing the content to be sent back in the reply * message; in case an exception is thrown somewhere, the method * try to return anyway a valid content with a best-effort strategy **/ protected String createExceptionalMsgContent(Action a, String ontoName, FIPAException e) { ACLMessage temp = new ACLMessage(ACLMessage.NOT_UNDERSTOOD); temp.setLanguage(SL0Codec.NAME); temp.setOntology(ontoName); List l = new ArrayList(2); if (a == null) { a = new Action(); a.set_0(getAID()); a.set_1("UnknownAction"); } l.add(a); l.add(e); try { fillMsgContent(temp,l); } catch (Exception ee) { // in any case try to return some good content return e.getMessage(); } return temp.getContent(); } // Each concrete subclass will implement this deferred method to // do action-specific work protected abstract void processAction(Action a) throws FIPAException; public void action() { Action a = null; try { ACLMessage msg = getRequest(); List l = myAgent.extractMsgContent(msg); a = (Action)l.get(0); // Do real action, deferred to subclasses processAction(a); } catch(FIPAException fe) { String ontoName = getRequest().getOntology(); sendReply((fe instanceof FailureException?ACLMessage.FAILURE:ACLMessage.REFUSE),createExceptionalMsgContent(a, ontoName, fe)); } } /** Writes the <code>Done</code> predicate for the specific action into the result <code>String</code> object, encoded in SL0. */ protected String doneAction(Action a) throws FIPAException { try { Ontology o = lookupOntology(getRequest().getOntology()); DonePredicate dp = new DonePredicate(); dp.set_0(a); Frame f = o.createFrame(dp, BasicOntology.DONE); List l = new ArrayList(1); l.add(f); Codec c = lookupLanguage(SL0Codec.NAME); String result = c.encode(l, o); return result; } catch(OntologyException oe) { oe.printStackTrace(); throw new FIPAException("Internal error in building Done predicate."); } } public boolean done() { return true; } public void reset() { } } // End of AMSBehaviour class // These four concrete classes serve both as a Factory and as an // Action: when seen as Factory they can spawn a new // Behaviour to process a given request, and when seen as // Action they process their request and terminate. private class RegBehaviour extends AMSBehaviour { public RegBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new RegBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Register r = (Register)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)r.get_0(); // waiting for an 'inform' message. Recover the buffered // message from the Map and send it back. ACLMessage informCreator = (ACLMessage)pendingInforms.remove(amsd.getName()); //The message in pendingInforms can be registered with only the localName //without the platformID if(informCreator == null) { String name = amsd.getName().getName(); int atPos = name.lastIndexOf('@'); if(atPos > 0) { name = name.substring(0, atPos); informCreator = (ACLMessage)pendingInforms.remove(name); } } try { // Write new agent data in AMS Agent Table AMSRegister(amsd); sendReply(ACLMessage.AGREE,createAgreeContent(a)); sendReply(ACLMessage.INFORM, doneAction(a)); // Inform agent creator that registration was successful. if(informCreator != null) { send(informCreator); } } catch(AlreadyRegistered are) { sendReply(ACLMessage.AGREE, createAgreeContent(a)); String ontoName = getRequest().getOntology(); sendReply(ACLMessage.FAILURE,createExceptionalMsgContent(a, ontoName, are)); // Inform agent creator that registration failed. if(informCreator != null) { informCreator.setPerformative(ACLMessage.FAILURE); informCreator.setContent(createExceptionalMsgContent(a, ontoName, are)); send(informCreator); } } } } // End of RegBehaviour class private class DeregBehaviour extends AMSBehaviour { public DeregBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new DeregBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Deregister d = (Deregister)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)d.get_0(); AMSDeregister(amsd); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM,doneAction(a)); } } // End of DeregBehaviour class private class ModBehaviour extends AMSBehaviour { public ModBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new ModBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Modify m = (Modify)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)m.get_0(); AMSModify(amsd); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM,doneAction(a)); } } // End of ModBehaviour class private class SrchBehaviour extends AMSBehaviour { public SrchBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new SrchBehaviour(msg); } protected void processAction(Action a) throws FIPAException { Search s = (Search)a.getAction(); AMSAgentDescription amsd = (AMSAgentDescription)s.get_0(); SearchConstraints constraints = s.get_1(); List l = AMSSearch(amsd, constraints, getReply()); sendReply(ACLMessage.AGREE,createAgreeContent(a)); ACLMessage msg = getRequest().createReply(); msg.setPerformative(ACLMessage.INFORM); ResultPredicate r = new ResultPredicate(); r.set_0(a); for (int i=0; i<l.size(); i++) r.add_1(l.get(i)); l.clear(); l.add(r); fillMsgContent(msg,l); send(msg); } } // End of SrchBehaviour class private class GetDescriptionBehaviour extends AMSBehaviour { public GetDescriptionBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new GetDescriptionBehaviour(msg); } protected void processAction(Action a) throws FIPAException { sendReply(ACLMessage.AGREE, createAgreeContent(a)); ACLMessage reply = getReply(); reply.setPerformative(ACLMessage.INFORM); List l = new ArrayList(1); ResultPredicate rp = new ResultPredicate(); rp.set_0(a); rp.add_1(theProfile); ArrayList list = new ArrayList(1); list.add(rp); fillMsgContent(reply,list); send(reply); } } // End of GetDescriptionBehaviour class // These Behaviours handle interactions with platform tools. private class RegisterToolBehaviour extends CyclicBehaviour { private MessageTemplate subscriptionTemplate; RegisterToolBehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage(SL0Codec.NAME); MessageTemplate mt2 = MessageTemplate.MatchOntology(JADEIntrospectionOntology.NAME); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("tool-subscription"); mt2 = MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE); subscriptionTemplate = MessageTemplate.and(mt1, mt2); subscriptionTemplate = MessageTemplate.and(subscriptionTemplate, mt12); } public void action() { // Receive 'subscribe' ACL messages. ACLMessage current = receive(subscriptionTemplate); if(current != null) { // FIXME: Should parse 'iota ?x ...' // Get new tool name from subscription message AID newTool = current.getSender(); try { // Send back the whole container list. ContainerID[] ids = myPlatform.containerIDs(); for(int i = 0; i < ids.length; i++) { ContainerID cid = ids[i]; AddedContainer ac = new AddedContainer(); ac.setContainer(cid); EventRecord er = new EventRecord(ac, here()); Occurred o = new Occurred(); o.set_0(er); List l = new ArrayList(1); l.add(o); toolNotification.clearAllReceiver(); toolNotification.addReceiver(newTool); fillMsgContent(toolNotification, l); send(toolNotification); } // Send all agent names, along with their container name. AID[] agents = myPlatform.agentNames(); for(int i = 0; i < agents.length; i++) { AID agentName = agents[i]; ContainerID cid = myPlatform.getContainerID(agentName); BornAgent ba = new BornAgent(); ba.setAgent(agentName); ba.setWhere(cid); EventRecord er = new EventRecord(ba, here()); Occurred o = new Occurred(); o.set_0(er); List l = new ArrayList(1); l.add(o); toolNotification.clearAllReceiver(); toolNotification.addReceiver(newTool); fillMsgContent(toolNotification, l); send(toolNotification); } // Send the list of the installed MTPs String[] addresses = myPlatform.platformAddresses(); for(int i = 0; i < addresses.length; i++) { AddedMTP amtp = new AddedMTP(); amtp.setAddress(addresses[i]); amtp.setWhere(new ContainerID(AgentManager.MAIN_CONTAINER_NAME, null)); // FIXME: should use AgentManager to know the container EventRecord er = new EventRecord(amtp, here()); Occurred o = new Occurred(); o.set_0(er); List l = new ArrayList(1); l.add(o); toolNotification.clearAllReceiver(); toolNotification.addReceiver(newTool); fillMsgContent(toolNotification, l); send(toolNotification); } //Notification to the RMA of the APDescription PlatformDescription ap = new PlatformDescription(); ap.setPlatform(theProfile); EventRecord er = new EventRecord(ap,here()); Occurred o = new Occurred(); o.set_0(er); List l = new ArrayList(1); l.add(o); toolNotification.clearAllReceiver(); toolNotification.addReceiver(newTool); fillMsgContent(toolNotification, l); send(toolNotification); // Add the new tool to tools list. tools.add(newTool); } catch(NotFoundException nfe) { nfe.printStackTrace(); } catch(FIPAException fe) { fe.printStackTrace(); } } else block(); } } // End of RegisterToolBehaviour class private class DeregisterToolBehaviour extends CyclicBehaviour { private MessageTemplate cancellationTemplate; DeregisterToolBehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage(SL0Codec.NAME); MessageTemplate mt2 = MessageTemplate.MatchOntology(JADEIntrospectionOntology.NAME); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("tool-cancellation"); mt2 = MessageTemplate.MatchPerformative(ACLMessage.CANCEL); cancellationTemplate = MessageTemplate.and(mt1, mt2); cancellationTemplate = MessageTemplate.and(cancellationTemplate, mt12); } public void action() { // Receive 'cancel' ACL messages. ACLMessage current = receive(cancellationTemplate); if(current != null) { // FIXME: Should parse the content // Remove this tool to tools agent group. tools.remove(current.getSender()); } else block(); } } // End of DeregisterToolBehaviour class private class NotifyToolsBehaviour extends CyclicBehaviour { public void action() { synchronized(ams.this) { // Mutual exclusion with handleXXX() methods // Look into the event buffer Iterator it = eventQueue.iterator(); Occurred o = new Occurred(); while(it.hasNext()) { // Write the event into the notification message EventRecord er = (EventRecord)it.next(); o.set_0(er); List l = new ArrayList(1); l.add(o); try { fillMsgContent(toolNotification, l); } catch(FIPAException fe) { fe.printStackTrace(); } // Put all tools in the receiver list toolNotification.clearAllReceiver(); Iterator toolIt = tools.iterator(); while(toolIt.hasNext()) { AID tool = (AID)toolIt.next(); toolNotification.addReceiver(tool); } send(toolNotification); it.remove(); } } block(); } } // End of NotifyToolsBehaviour class private class KillContainerBehaviour extends AMSBehaviour { public KillContainerBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new KillContainerBehaviour(msg); } protected void processAction(Action a) throws FIPAException { KillContainer kc = (KillContainer)a.get_1(); ContainerID cid = kc.getContainer(); myPlatform.killContainer(cid); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM,doneAction(a)); } } // End of KillContainerBehaviour class private class CreateBehaviour extends AMSBehaviour { public CreateBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new CreateBehaviour(msg); } protected void processAction(Action a) throws FIPAException { CreateAgent ca = (CreateAgent)a.get_1(); String agentName = ca.getAgentName(); String className = ca.getClassName(); ContainerID container = ca.getContainer(); Iterator arg = ca.getAllArguments(); //return an iterator of all arguments //create the array of string ArrayList listArg = new ArrayList(); while(arg.hasNext()) listArg.add(arg.next().toString()); String[] arguments = new String[listArg.size()]; for(int n = 0; n< listArg.size(); n++) arguments[n] = (String)listArg.get(n); sendReply(ACLMessage.AGREE, createAgreeContent(a)); try { myPlatform.create(agentName, className, arguments, container); // An 'inform Done' message will be sent to the requester only // when the newly created agent will register itself with the // AMS. The new agent's name will be used as the key in the map. ACLMessage reply = getReply(); reply = (ACLMessage)reply.clone(); reply.setPerformative(ACLMessage.INFORM); reply.setContent(doneAction(a)); pendingInforms.put(agentName, reply); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError(ue.getMessage()); } } } // End of CreateBehaviour class private class KillBehaviour extends AMSBehaviour { public KillBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new KillBehaviour(msg); } protected void processAction(Action a) throws FIPAException { // Kill an agent KillAgent ka = (KillAgent)a.get_1(); AID agentID = ka.getAgent(); String password = ka.getPassword(); try { myPlatform.kill(agentID, password); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM, doneAction(a)); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } } // End of KillBehaviour class private class SniffAgentOnBehaviour extends AMSBehaviour { public SniffAgentOnBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new SniffAgentOnBehaviour(msg); } protected void processAction(Action a) throws FIPAException { SniffOn so = (SniffOn)a.get_1(); try { myPlatform.sniffOn(so.getSniffer(), so.getCloneOfSniffedAgents()); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM, doneAction(a)); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } } // End of SniffAgentOnBehaviour class private class SniffAgentOffBehaviour extends AMSBehaviour { public SniffAgentOffBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new SniffAgentOffBehaviour(msg); } protected void processAction(Action a) throws FIPAException { SniffOff so = (SniffOff)a.get_1(); try { myPlatform.sniffOff(so.getSniffer(), so.getCloneOfSniffedAgents()); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM,doneAction(a)); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } } // End of SniffAgentOffBehaviour class private class DebugAgentOnBehaviour extends AMSBehaviour { public DebugAgentOnBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new DebugAgentOnBehaviour(msg); } protected void processAction(Action a) throws FIPAException { DebugOn dbgOn = (DebugOn)a.get_1(); try { myPlatform.debugOn(dbgOn.getDebugger(), dbgOn.getCloneOfDebuggedAgents()); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM, doneAction(a)); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } } // End of DebugAgentOnBehaviour class private class DebugAgentOffBehaviour extends AMSBehaviour { public DebugAgentOffBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new DebugAgentOffBehaviour(msg); } protected void processAction(Action a) throws FIPAException { DebugOff dbgOff = (DebugOff)a.get_1(); try { myPlatform.debugOff(dbgOff.getDebugger(), dbgOff.getCloneOfDebuggedAgents()); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM, doneAction(a)); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } } // End of DebugAgentOffBehaviour class private class InstallMTPBehaviour extends AMSBehaviour { public InstallMTPBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new InstallMTPBehaviour(msg); } protected void processAction(Action a) throws FIPAException { InstallMTP imtp = (InstallMTP)a.get_1(); try { myPlatform.installMTP(imtp.getAddress(), imtp.getContainer(), imtp.getClassName()); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM, doneAction(a)); } catch(NotFoundException nfe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", nfe.getMessage()); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError(ue.getMessage()); } catch(MTPException mtpe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", mtpe.getMessage()); } } } // End of InstallMTPBehaviour class private class UninstallMTPBehaviour extends AMSBehaviour { public UninstallMTPBehaviour(ACLMessage msg) { super(msg); } public FipaRequestResponderBehaviour.ActionHandler create(ACLMessage msg) { return new UninstallMTPBehaviour(msg); } protected void processAction(Action a) throws FIPAException { UninstallMTP umtp = (UninstallMTP)a.get_1(); try { myPlatform.uninstallMTP(umtp.getAddress(), umtp.getContainer()); sendReply(ACLMessage.AGREE, createAgreeContent(a)); sendReply(ACLMessage.INFORM, doneAction(a)); } catch(NotFoundException nfe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", nfe.getMessage()); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError(ue.getMessage()); } catch(MTPException mtpe) { throw new jade.domain.FIPAAgentManagement.UnrecognisedParameterValue("MTP", mtpe.getMessage()); } } } // End of UninstallMTPBehaviour class // The AgentPlatform where information about agents is stored /** @serial */ private AgentManager myPlatform; // Maintains an association between action names and behaviours to // handle 'fipa-agent-management' actions /** @serial */ private FipaRequestResponderBehaviour dispatcher; // Maintains an association between action names and behaviours to // handle 'jade-agent-management' actions /** @serial */ private FipaRequestResponderBehaviour extensionsDispatcher; // Contains a main Behaviour and some utilities to handle JADE mobility /** @serial */ private MobilityManager mobilityMgr; // Behaviour to listen to incoming 'subscribe' messages from tools. /** @serial */ private RegisterToolBehaviour registerTool; // Behaviour to broadcats AgentPlatform notifications to each // registered tool. /** @serial */ private NotifyToolsBehaviour notifyTools; // Behaviour to listen to incoming 'cancel' messages from tools. /** @serial */ private DeregisterToolBehaviour deregisterTool; // Group of tools registered with this AMS /** @serial */ private List tools; // ACL Message to use for tool notification /** @serial */ private ACLMessage toolNotification = new ACLMessage(ACLMessage.INFORM); // Buffer for AgentPlatform notifications /** @serial */ private List eventQueue = new ArrayList(10); /** @serial */ private Map pendingInforms = new HashMap(); /** @serial */ private APDescription theProfile = new APDescription(); /** This constructor creates a new <em>AMS</em> agent. Since a direct reference to an Agent Platform implementation must be passed to it, this constructor cannot be called from application code. Therefore, no other <em>AMS</em> agent can be created beyond the default one. */ public ams(AgentManager ap) { // Fill Agent Platform Profile with data. theProfile.setDynamic(new Boolean(false)); theProfile.setMobility(new Boolean(false)); APTransportDescription mtps = new APTransportDescription(); theProfile.setTransportProfile(mtps); myPlatform = ap; myPlatform.addListener(this); MessageTemplate mtFIPA = MessageTemplate.and(MessageTemplate.MatchLanguage(SL0Codec.NAME), MessageTemplate.MatchOntology(FIPAAgentManagementOntology.NAME)); dispatcher = new FipaRequestResponderBehaviour(this, mtFIPA); MessageTemplate mtJADE = MessageTemplate.and(MessageTemplate.MatchLanguage(SL0Codec.NAME), MessageTemplate.MatchOntology(JADEAgentManagementOntology.NAME)); extensionsDispatcher = new FipaRequestResponderBehaviour(this, mtJADE); mobilityMgr = new MobilityManager(this); registerTool = new RegisterToolBehaviour(); deregisterTool = new DeregisterToolBehaviour(); notifyTools = new NotifyToolsBehaviour(); tools = new ArrayList(); toolNotification.setSender(new AID()); toolNotification.setLanguage(SL0Codec.NAME); toolNotification.setOntology(JADEIntrospectionOntology.NAME); toolNotification.setInReplyTo("tool-subscription"); // Associate each AMS action name with the behaviour to execute // when the action is requested in a 'request' ACL message dispatcher.registerFactory(FIPAAgentManagementOntology.REGISTER, new RegBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.DEREGISTER, new DeregBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.MODIFY, new ModBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.SEARCH, new SrchBehaviour(null)); dispatcher.registerFactory(FIPAAgentManagementOntology.GETDESCRIPTION, new GetDescriptionBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.CREATEAGENT, new CreateBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.KILLAGENT, new KillBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.KILLCONTAINER, new KillContainerBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.SNIFFON, new SniffAgentOnBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.DEBUGOFF, new DebugAgentOffBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.DEBUGON, new DebugAgentOnBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.SNIFFOFF, new SniffAgentOffBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.INSTALLMTP, new InstallMTPBehaviour(null)); extensionsDispatcher.registerFactory(JADEAgentManagementOntology.UNINSTALLMTP, new UninstallMTPBehaviour(null)); } /** This method starts the <em>AMS</em> behaviours to allow the agent to carry on its duties within <em><b>JADE</b></em> agent platform. */ protected void setup() { // Fill the ':name' slot of the Agent Platform Profile with the Platform ID. theProfile.setName("\"" + getHap() + "\""); writeAPDescription(); // Register the supported ontologies registerOntology(FIPAAgentManagementOntology.NAME, FIPAAgentManagementOntology.instance()); registerOntology(JADEAgentManagementOntology.NAME, JADEAgentManagementOntology.instance()); registerOntology(JADEIntrospectionOntology.NAME, JADEIntrospectionOntology.instance()); registerOntology(MobilityOntology.NAME, MobilityOntology.instance()); // register the supported languages registerLanguage(SL0Codec.NAME, new SL0Codec()); // Add a dispatcher Behaviour for all ams actions following from a // 'fipa-request' interaction with 'fipa-agent-management' ontology. addBehaviour(dispatcher); // Add a dispatcher Behaviour for all ams actions following from a // 'fipa-request' interaction with 'jade-agent-management' ontology. addBehaviour(extensionsDispatcher); // Add a main behaviour to manage mobility related messages addBehaviour(mobilityMgr.getMain()); // Add a Behaviour to accept incoming tool registrations and a // Behaviour to broadcast events to registered tools. addBehaviour(registerTool); addBehaviour(deregisterTool); addBehaviour(notifyTools); } /** * checks that all the mandatory slots for a register/modify/deregister action * are present. * @param actionName is the name of the action (one of * <code>FIPAAgentManagementOntology.REGISTER</code>, * <code>FIPAAgentManagementOntology.MODIFY</code>, * <code>FIPAAgentManagementOntology.DEREGISTER</code>) * @param amsd is the AMSAgentDescription to be checked for * @throws MissingParameter if one of the mandatory slots is missing **/ private void checkMandatorySlots(String actionName, AMSAgentDescription amsd) throws MissingParameter { try { AID name = amsd.getName(); if ((name == null)||(name.getName().length() == 0)) throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "name"); } catch (Exception e) { e.printStackTrace(); throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "name"); } if (!actionName.equalsIgnoreCase(FIPAAgentManagementOntology.DEREGISTER)) try { String state = amsd.getState(); if((state == null)||(state.length() == 0)) throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "state"); } catch (Exception e) { e.printStackTrace(); throw new MissingParameter(FIPAAgentManagementOntology.AMSAGENTDESCRIPTION, "state"); } } /** @serial */ private KB agentDescriptions = new KBAbstractImpl() { protected boolean match(Object template, Object fact) { try { AMSAgentDescription templateDesc = (AMSAgentDescription)template; AMSAgentDescription factDesc = (AMSAgentDescription)fact; String o1 = templateDesc.getOwnership(); if(o1 != null) { String o2 = factDesc.getOwnership(); if((o2 == null) || (!o1.equalsIgnoreCase(o2))) return false; } String s1 = templateDesc.getState(); if(s1 != null) { String s2 = factDesc.getState(); if((s2 == null) || (!s1.equalsIgnoreCase(s2))) return false; } AID id1 = templateDesc.getName(); if(id1 != null) { AID id2 = factDesc.getName(); if((id2 == null) || (!matchAID(id1, id2))) return false; } return true; } catch(ClassCastException cce) { return false; } } }; /** it is called also by Agent.java **/ public void AMSRegister(AMSAgentDescription amsd) throws FIPAException { checkMandatorySlots(FIPAAgentManagementOntology.REGISTER, amsd); String[] addresses = myPlatform.platformAddresses(); AID id = amsd.getName(); for(int i = 0; i < addresses.length; i++) id.addAddresses(addresses[i]); Object old = agentDescriptions.register(amsd.getName(), amsd); if(old != null) throw new AlreadyRegistered(); } /** it is called also by Agent.java **/ public void AMSDeregister(AMSAgentDescription amsd) throws FIPAException { checkMandatorySlots(FIPAAgentManagementOntology.DEREGISTER, amsd); Object old = agentDescriptions.deregister(amsd.getName()); if(old == null) throw new NotRegistered(); } private void AMSModify(AMSAgentDescription amsd) throws FIPAException { checkMandatorySlots(FIPAAgentManagementOntology.MODIFY, amsd); Object old = agentDescriptions.deregister(amsd.getName()); if(old == null) throw new NotRegistered(); agentDescriptions.register(amsd.getName(), amsd); } private List AMSSearch(AMSAgentDescription amsd, SearchConstraints constraints, ACLMessage reply) throws FIPAException { // Search has no mandatory slots return agentDescriptions.search(amsd); } // This one is called in response to a 'move-agent' action void AMSMoveAgent(AID agentID, Location where) throws FIPAException { try { myPlatform.move(agentID, where, ""); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } // This one is called in response to a 'clone-agent' action void AMSCloneAgent(AID agentID, Location where, String newName) throws FIPAException { try { myPlatform.copy(agentID, where, newName, ""); } catch(UnreachableException ue) { throw new jade.domain.FIPAAgentManagement.InternalError("The container is not reachable"); } catch(NotFoundException nfe) { throw new NotRegistered(); } } // This one is called in response to a 'where-is-agent' action Location AMSWhereIsAgent(AID agentID) throws FIPAException { try { ContainerID cid = myPlatform.getContainerID(agentID); String containerName = cid.getName(); return mobilityMgr.getLocation(containerName); } catch(NotFoundException nfe) { nfe.printStackTrace(); throw new NotRegistered(); } } // This one is called in response to a 'query-platform-locations' action Iterator AMSGetPlatformLocations() { return mobilityMgr.getLocations(); } // Methods to be called from AgentPlatform to notify AMS of special events /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void addedContainer(PlatformEvent ev) { ContainerID cid = ev.getContainer(); String name = cid.getName(); // Add a new location to the locations list mobilityMgr.addLocation(name, cid); // Fire an 'added container' event AddedContainer ac = new AddedContainer(); ac.setContainer(cid); EventRecord er = new EventRecord(ac, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void removedContainer(PlatformEvent ev) { ContainerID cid = ev.getContainer(); String name = cid.getName(); // Remove the location from the location list mobilityMgr.removeLocation(name); // Fire a 'container is dead' event RemovedContainer rc = new RemovedContainer(); rc.setContainer(cid); EventRecord er = new EventRecord(rc, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void bornAgent(PlatformEvent ev) { ContainerID cid = ev.getContainer(); AID agentID = ev.getAgent(); BornAgent ba = new BornAgent(); ba.setAgent(agentID); ba.setWhere(cid); EventRecord er = new EventRecord(ba, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void deadAgent(PlatformEvent ev) { ContainerID cid = ev.getContainer(); AID agentID = ev.getAgent(); // Deregister the agent, if it's still there. try { AMSAgentDescription amsd = new AMSAgentDescription(); amsd.setName(agentID); List l = AMSSearch(amsd, null, null); if(!l.isEmpty()) AMSDeregister(amsd); } catch(FIPAException fe) { fe.printStackTrace(); } DeadAgent da = new DeadAgent(); da.setAgent(agentID); da.setWhere(cid); EventRecord er = new EventRecord(da, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void suspendedAgent(PlatformEvent ev) { ContainerID cid = ev.getContainer(); AID agentID = ev.getAgent(); // Registry needs an update here! SuspendedAgent sa = new SuspendedAgent(); sa.setAgent(agentID); sa.setWhere(cid); EventRecord er = new EventRecord(sa, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void resumedAgent(PlatformEvent ev) { ContainerID cid = ev.getContainer(); AID agentID = ev.getAgent(); // Registry needs an update here! SuspendedAgent ra = new SuspendedAgent(); ra.setAgent(agentID); ra.setWhere(cid); EventRecord er = new EventRecord(ra, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void movedAgent(PlatformEvent ev) { ContainerID from = ev.getContainer(); ContainerID to = ev.getNewContainer(); AID agentID = ev.getAgent(); MovedAgent ma = new MovedAgent(); ma.setAgent(agentID); ma.setFrom(from); ma.setTo(to); EventRecord er = new EventRecord(ma, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void addedMTP(MTPEvent ev) { Channel ch = ev.getChannel(); ContainerID cid = ev.getPlace(); String address = ch.getAddress(); // Add the new address to the platform profile APTransportDescription mtps = theProfile.getTransportProfile(); MTPDescription desc = new MTPDescription(); int colonPos = address.indexOf(':'); if(colonPos != -1) desc.setMtpName(address.substring(0, colonPos)); desc.addAddresses(address); mtps.addAvailableMtps(desc); //Update the APDescription file. if(getState() != AP_INITIATED) writeAPDescription(); // Retrieve all agent descriptors AMSAgentDescription amsd = new AMSAgentDescription(); List l = agentDescriptions.search(amsd); // Add the new address to all the agent descriptors Iterator it = l.iterator(); while(it.hasNext()) { AMSAgentDescription ad = (AMSAgentDescription)it.next(); AID name = ad.getName(); name.addAddresses(address); } // Generate a suitable AMS event AddedMTP amtp = new AddedMTP(); amtp.setAddress(address); amtp.setWhere(cid); EventRecord er = new EventRecord(amtp, here()); er.setWhen(ev.getTime()); eventQueue.add(er); //Notify the update of the APDescription... PlatformDescription ap = new PlatformDescription(); ap.setPlatform(theProfile); er = new EventRecord(ap, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } /** Post an event to the AMS agent. This method must not be used by application agents. */ public synchronized void removedMTP(MTPEvent ev) { Channel ch = ev.getChannel(); ContainerID cid = ev.getPlace(); String address = ch.getAddress(); // Remove the dead address from the platform profile APTransportDescription mtps = theProfile.getTransportProfile(); Iterator it = mtps.getAllAvailableMtps(); while(it.hasNext()) { MTPDescription desc = (MTPDescription)it.next(); Iterator addresses = desc.getAllAddresses(); while(addresses.hasNext()) { // Remove all MTPs that have the 'address' String in their // address list. String nextAddr = (String)addresses.next(); if(nextAddr.equalsIgnoreCase(address)) it.remove(); } } //update the APDescription file writeAPDescription(); // Remove the dead address from all the registered agents AID[] agents = myPlatform.agentNames(); AMSAgentDescription amsd = new AMSAgentDescription(); for(int i = 0; i < agents.length; i++) { amsd.setName(agents[i]); List l = agentDescriptions.search(amsd); AMSAgentDescription desc = (AMSAgentDescription)l.get(0); AID name = desc.getName(); name.removeAddresses(address); } // Generate a suitable AMS event RemovedMTP rmtp = new RemovedMTP(); rmtp.setAddress(address); rmtp.setWhere(cid); EventRecord er = new EventRecord(rmtp, here()); er.setWhen(ev.getTime()); eventQueue.add(er); //Notify the update of the APDescription... PlatformDescription ap = new PlatformDescription(); ap.setPlatform(theProfile); er = new EventRecord(ap, here()); er.setWhen(ev.getTime()); eventQueue.add(er); doWake(); } public void messageIn(MTPEvent ev) { System.out.println("Message In."); } public void messageOut(MTPEvent ev) { System.out.println("Message Out."); } private void writeAPDescription() { //Write the APDescription file. try{ FileWriter f = new FileWriter("APDescription.txt"); f.write(theProfile.toString()); //f.write(s, 0, s.length()); f.write('\n'); f.flush(); f.close(); }catch(java.io.IOException ioe){ioe.printStackTrace();} } } // End of class ams
package falgout.backup.guice; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; import org.jukito.JukitoModule; import org.jukito.JukitoRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import com.google.inject.CreationException; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; @RunWith(JukitoRunner.class) public class BackupModuleTest { public static class A extends JukitoModule { @Override protected void configureTest() { bindMock(Properties.class); } } @Inject private Properties properties; private BackupModule module; @Before public void init() { module = new BackupModule(properties); } @Test(expected = CreationException.class) public void ErrorIfNoLocation() { when(properties.propertyNames()).then(returnKeys()); Injector i = Guice.createInjector(module); i.getProvider(BackupModule.LOCATION); } private Answer<Enumeration<String>> returnKeys(final String... keys) { return new Answer<Enumeration<String>>() { @Override public Enumeration<String> answer(InvocationOnMock invocation) throws Throwable { return Collections.enumeration(Arrays.asList(keys)); } }; } @Test public void InjectsLocationForBackupLocation() { Path location = Paths.get(System.getProperty("user.dir")).resolve("foo"); when(properties.propertyNames()).then(returnKeys("location")); when(properties.getProperty("location")).thenReturn(location.toString()); Injector i = Guice.createInjector(module); assertEquals(location, i.getInstance(Key.get(Path.class, BackupLocation.class))); } }
package com.gallatinsystems.framework.dao; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import net.sf.jsr107cache.CacheException; import org.akvo.flow.domain.SecuredObject; import com.google.appengine.datanucleus.query.JDOCursorHelper; import org.datanucleus.exceptions.NucleusObjectNotFoundException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import com.gallatinsystems.common.Constants; import com.gallatinsystems.framework.domain.BaseDomain; import com.gallatinsystems.framework.servlet.PersistenceFilter; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.SurveyGroup; import com.gallatinsystems.user.dao.UserAuthorizationDAO; import com.gallatinsystems.user.dao.UserDao; import com.gallatinsystems.user.domain.User; import com.gallatinsystems.user.domain.UserAuthorization; import com.google.appengine.api.datastore.Cursor; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; /** * This is a reusable data access object that supports basic operations (save, find by property, * list). * * @author Christopher Fagiani * @param <T> a persistent class that extends BaseDomain */ public class BaseDAO<T extends BaseDomain> { public static final int DEFAULT_RESULT_COUNT = 20; protected static final int RETRY_INTERVAL_MILLIS = 200; protected static final String STRING_TYPE = "String"; protected static final String NOT_EQ_OP = "!="; protected static final String EQ_OP = " == "; protected static final String GTE_OP = " >= "; protected static final String LTE_OP = " <= "; protected static final String LT_OP = "<"; private static final int MAX_ALLOWED_FILTERED_ITEMS = 30; private Class<T> concreteClass; protected Logger log; public enum CURSOR_TYPE { all }; public BaseDAO(Class<T> e) { setDomainClass(e); log = Logger.getLogger(this.getClass().getName()); } /** * Injected version of the actual Class to pass for the persistentClass in the query creation. * This must be set before using this implementation class or any derived class. * * @param e an instance of the type of object to use for this instance of the DAO * implementation. */ public void setDomainClass(Class<T> e) { this.concreteClass = e; } /** * saves an object to the data store. This method will set the lastUpdateDateTime on the domain * object prior to saving and will set the createdDateTime (if it is null). * * @param <E> * @param obj * @return */ public <E extends BaseDomain> E save(E obj) { PersistenceManager pm = PersistenceFilter.getManager(); Long who = 0L; if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null ) { final Object credentials = SecurityContextHolder.getContext() .getAuthentication().getCredentials(); if (credentials instanceof Long) { who = (Long) credentials; } } obj.setLastUpdateDateTime(new Date()); obj.setLastUpdateUserId(who); if (obj.getCreatedDateTime() == null) { obj.setCreatedDateTime(obj.getLastUpdateDateTime()); obj.setCreateUserId(who); } obj = pm.makePersistent(obj); return obj; } /** * saves all instances contained within the collection passed in. This will set the * lastUpdateDateTime for the objects prior to saving. * * @param <E> * @param objList * @return */ public <E extends BaseDomain> Collection<E> save(Collection<E> objList) { if (objList != null) { Long who = 0L; if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null ) { final Object credentials = SecurityContextHolder.getContext() .getAuthentication().getCredentials(); if (credentials instanceof Long) { who = (Long) credentials; } } for (E item : objList) { item.setLastUpdateDateTime(new Date()); item.setLastUpdateUserId(who); if (item.getCreatedDateTime() == null) { item.setCreatedDateTime(item.getLastUpdateDateTime()); item.setCreateUserId(who); } } PersistenceManager pm = PersistenceFilter.getManager(); objList = pm.makePersistentAll(objList); } return objList; } /** * gets the core persistent object for the dao concrete class using the string key (obtained * from KeyFactory.stringFromKey()) * * @param keyString * @return */ public T getByKey(String keyString) { return getByKey(keyString, concreteClass); } /** * gets an object by key * * @param key * @return */ public T getByKey(Key key) { return getByKey(key, concreteClass); } /** * convenience method to allow loading of other persistent objects by key from this dao * * @param keyString * @return */ public <E extends BaseDomain> E getByKey(String keyString, Class<E> clazz) { PersistenceManager pm = PersistenceFilter.getManager(); E result = null; Key k = KeyFactory.stringToKey(keyString); try { result = pm.getObjectById(clazz, k); } catch (JDOObjectNotFoundException nfe) { log.warning("No " + clazz.getCanonicalName() + " found with key: " + k); } return result; } /** * gets a single object identified by the key passed in. * * @param <E> * @param key * @param clazz * @return the object corresponding to the key (or null if not found) */ public <E extends BaseDomain> E getByKey(Key key, Class<E> clazz) { PersistenceManager pm = PersistenceFilter.getManager(); E result = null; try { result = pm.getObjectById(clazz, key); } catch (JDOObjectNotFoundException nfe) { log.warning("No " + clazz.getCanonicalName() + " found with key: " + key); } return result; } /** * gets a single object by key where the key is represented as a Long * * @param id * @return */ public T getByKey(Long id) { return getByKey(id, concreteClass); } /** * gets a single object by key where the key is represented as a Long and the type is the class * passed in via clazz * * @param <E> * @param id * @param clazz * @return */ public <E extends BaseDomain> E getByKey(Long id, Class<E> clazz) { PersistenceManager pm = PersistenceFilter.getManager(); String itemKey = KeyFactory.createKeyString(clazz.getSimpleName(), id); E result = null; try { result = pm.getObjectById(clazz, itemKey); } catch (JDOObjectNotFoundException nfe) { log.warning("No " + clazz.getCanonicalName() + " found with id: " + id); } return result; } /** * lists all of the concreteClass instances in the datastore, using a page size. * * @return */ public List<T> list(String cursorString, Integer pageSize) { return list(concreteClass, cursorString, pageSize); } /** * lists all of the concreteClass instances in the datastore. if we think we'll use this on * large tables, we should use Extents * * @return */ public List<T> list(String cursorString) { return list(concreteClass, cursorString); } /** * Lists all of the concreteClass instances in the datastore */ public <E extends BaseDomain> List<E> list(Class<E> c, String cursorString) { return list(c, cursorString, null); } /** * lists all of the type passed in. if we think we'll use this on large tables, we should use * Extents * * @return */ @SuppressWarnings("unchecked") public <E extends BaseDomain> List<E> list(Class<E> c, String cursorString, Integer pageSize) { PersistenceManager pm = PersistenceFilter.getManager(); javax.jdo.Query query = pm.newQuery(c); if (cursorString != null && !cursorString.trim().toLowerCase() .equals(Constants.ALL_RESULTS)) { Cursor cursor = Cursor.fromWebSafeString(cursorString); Map<String, Object> extensionMap = new HashMap<String, Object>(); extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor); query.setExtensions(extensionMap); } List<E> results = null; if (pageSize == null) { this.prepareCursor(cursorString, query); } else { this.prepareCursor(cursorString, pageSize, query); } results = (List<E>) query.execute(); return results; } /** * Return a list of survey groups or surveys that are accessible by the current user, filtered * by object ids * * @return */ public <E extends BaseDomain> List<E> filterByUserAuthorizationObjectId(List<E> allObjectsList, Long userId) { if (!concreteClass.isAssignableFrom(SurveyGroup.class) && !concreteClass.isAssignableFrom(Survey.class)) { throw new UnsupportedOperationException("Cannot filter " + concreteClass.getSimpleName()); } UserDao userDAO = new UserDao(); User user = userDAO.getByKey(userId); if (user.isSuperAdmin()) { return allObjectsList; } UserAuthorizationDAO userAuthorizationDAO = new UserAuthorizationDAO(); List<UserAuthorization> userAuthorizationList = userAuthorizationDAO.listByUser(userId); if (userAuthorizationList.isEmpty()) { return Collections.emptyList(); } Set<Long> securedObjectIds = new HashSet<>(); for (UserAuthorization auth : userAuthorizationList) { if (auth.getSecuredObjectId() != null) { securedObjectIds.add(auth.getSecuredObjectId()); } } // Set of all ancestor ids of secured objects Set<Long> securedAncestorIds = new HashSet<>(); for (Object obj : allObjectsList) { SecuredObject securedObject = (SecuredObject) obj; if (securedObjectIds.contains(securedObject.getObjectId())) { securedAncestorIds.addAll(securedObject.listAncestorIds()); } } Set<E> authorizedSet = new HashSet<>(); if (concreteClass.isAssignableFrom(SurveyGroup.class)) { for (E obj : allObjectsList) { SurveyGroup sg = (SurveyGroup) obj; Long sgId = sg.getKey().getId(); if (hasAuthorizedAncestors(sg.getAncestorIds(), securedObjectIds) || securedObjectIds.contains(sgId) || securedAncestorIds.contains(sgId)) { authorizedSet.add(obj); } } } else { for (E obj : allObjectsList) { Survey s = (Survey) obj; List<Long> ancestorIds = s.getAncestorIds(); if (hasAuthorizedAncestors(ancestorIds, securedObjectIds)) { authorizedSet.add(obj); } } } List<E> authorizedList = new ArrayList<>(); authorizedList.addAll(authorizedSet); return authorizedList; } public <E extends BaseDomain> List<E> filterByUserAuthorizationObjectId(List<E> allObjectsList) { final Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); final Long userId = (Long) authentication.getCredentials(); return filterByUserAuthorizationObjectId(allObjectsList, userId); } /** * Check whether one or more items in the list of an entity's ancestor ids is present in the * list of authorized objects for a user. Return true if this is the case * * @param ancestorIds * @param securedObjectIds * @return */ private boolean hasAuthorizedAncestors(List<Long> ancestorIds, Set<Long> securedObjectIds) { // use new List object to prevent side effects on SurveyGroup.ancestorIds property List<Long> idsList = new ArrayList<Long>(ancestorIds); return idsList != null && idsList.removeAll(securedObjectIds); } /** * returns a single object based on the property value * * @param propertyName * @param propertyValue * @param propertyType * @return */ protected T findByProperty(String propertyName, Object propertyValue, String propertyType) { T result = null; List<T> results = listByProperty(propertyName, propertyValue, propertyType); if (results.size() > 0) { result = results.get(0); } return result; } /** * gets a List of object by key where the key is represented as a Long * * @param ids Array of Long representing the keys of objects * @return null if ids is null, otherwise a list of objects */ public List<T> listByKeys(Long[] ids) { if (ids == null) { return null; } return listByKeys(Arrays.asList(ids)); } /** * Retrieves a List of objects by key where the keys are represented by a Collection of Longs * * @param ids List of Long representing the keys of objects * @return empty list if ids is null, otherwise a list of objects */ public List<T> listByKeys(List<Long> ids) { return listByKeys(ids, concreteClass); } /* * Retrieve a list of datastore entities by the keys provided */ public List<T> listByKeys(List<Long> idsList, Class<T> clazz){ if (idsList == null || idsList.isEmpty()) { return Collections.emptyList(); } PersistenceManager pm = PersistenceFilter.getManager(); List<Object> datastoreKeysList = new ArrayList<>(); for (Long id : idsList) { Key key = KeyFactory.createKey(clazz.getSimpleName(), id); Object objectId = pm.newObjectIdInstance(clazz, key); datastoreKeysList.add(objectId); } final List<T> resultsList = new ArrayList<>(); try { resultsList.addAll(pm.getObjectsById(datastoreKeysList)); } catch (NucleusObjectNotFoundException nfe) { log.warning(nfe.getMessage()); return listByKeysIndividually(idsList); } catch (ArrayIndexOutOfBoundsException exception) { /* when some of the entities are missing, we encounter an ArrayIndexOutOfBoundsException * the exception happens within the com.google.appengine.datanucleus.EntityUtils.getEntitiesFromDatastore() * function which we dont have access to. We catch the exception and run the fall back * function. */ log.warning("Some entities were not found"); return listByKeysIndividually(idsList); } return resultsList; } /* * Takes a list of IDs and retrieve the items on the list individually. * This is only a fall back method for when there may be some elements * missing when attempting to batch retrieve with `listByKeys()` * */ private List<T> listByKeysIndividually(List<Long> idsList) { List<T> resultsList = new ArrayList<>(); for (Long id : idsList) { T item = getByKey(id); if (item != null) { resultsList.add(item); } } return resultsList; } /** * lists all the objects of the same type as the concreteClass with property equal to the value * passed in since using this requires the caller know the persistence data type of the field * and the field name, this method is protected so that it can only be used by subclass DAOs. We * don't want those details to leak into higher layers of the code. * * @param propertyName * @param propertyValue * @param propertyType * @return */ protected List<T> listByProperty(String propertyName, Object propertyValue, String propertyType) { return listByProperty(propertyName, propertyValue, propertyType, null, null, EQ_OP, concreteClass); } /** * lists all objects of type class that have the property name/value passed in * * @param <E> * @param propertyName * @param propertyValue * @param propertyType * @param clazz * @return */ protected <E extends BaseDomain> List<E> listByProperty( String propertyName, Object propertyValue, String propertyType, Class<E> clazz) { return listByProperty(propertyName, propertyValue, propertyType, null, null, EQ_OP, clazz); } /** * lists all instances of type clazz that have the property equal to the value passed in and * orders the results by the field specified. NOTE: for this to work on the datastore, you may * need to have an index defined. * * @param <E> * @param propertyName * @param propertyValue * @param propertyType * @param orderBy * @param clazz * @return */ protected <E extends BaseDomain> List<E> listByProperty( String propertyName, Object propertyValue, String propertyType, String orderBy, Class<E> clazz) { return listByProperty(propertyName, propertyValue, propertyType, orderBy, null, EQ_OP, clazz); } /** * lists all instances that have the property name/value matching those passed in optionally * sorted by the order by column and direction. NOTE: depending on the sort being done, you may * need an index in the datastore for this to work. * * @param propertyName * @param propertyValue * @param propertyType * @param orderByCol * @param orderByDir * @return */ protected List<T> listByProperty(String propertyName, Object propertyValue, String propertyType, String orderByCol, String orderByDir) { return listByProperty(propertyName, propertyValue, propertyType, orderByCol, orderByDir, EQ_OP, concreteClass); } /** * lists all instances that have the property name/value matching those passed in optionally * sorted by the order by column. NOTE: depending on the sort being done, you may need an index * in the datastore for this to work. * * @param propertyName * @param propertyValue * @param propertyType * @param orderByCol * @return */ protected List<T> listByProperty(String propertyName, Object propertyValue, String propertyType, String orderByCol) { return listByProperty(propertyName, propertyValue, propertyType, orderByCol, null, EQ_OP, concreteClass); } /** * convenience method to list all instances of the type passed in that match the property since * using this requires the caller know the persistence data type of the field and the field * name, this method is protected so that it can only be used by subclass DAOs. We don't want * those details to leak into higher layers of the code. * * @param propertyName * @param propertyValue * @param propertyType * @return */ @SuppressWarnings("unchecked") protected <E extends BaseDomain> List<E> listByProperty( String propertyName, Object propertyValue, String propertyType, String orderByField, String orderByDir, String operator, Class<E> clazz) { PersistenceManager pm = PersistenceFilter.getManager(); List<E> results = null; String paramName = propertyName + "Param"; if (paramName.contains(".")) { paramName = paramName.substring(paramName.indexOf(".") + 1); } javax.jdo.Query query = pm.newQuery(clazz); query.setFilter(propertyName + " " + operator + " " + paramName); if (orderByField != null) { query.setOrdering(orderByField + (orderByDir != null ? " " + orderByDir : "")); } query.declareParameters(propertyType + " " + paramName); if (propertyValue instanceof Date) { query.declareImports("import java.util.Date"); } results = (List<E>) query.execute(propertyValue); return results; } /** * deletes an object from the db * * @param <E> * @param obj */ public <E extends BaseDomain> void delete(E obj) { PersistenceManager pm = PersistenceFilter.getManager(); pm.deletePersistent(obj); } /** * deletes a list of objects in a single datastore interaction */ public <E extends BaseDomain> void delete(Collection<E> obj) { PersistenceManager pm = PersistenceFilter.getManager(); pm.deletePersistentAll(obj); } /** * deletes an object from the db, by key * * @param <E> * @param obj */ public <E extends BaseDomain> void deleteByKey(Key k) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.delete(k); } /** * deletes a list of objects, by key, in a single datastore interaction */ public <E extends BaseDomain> void deleteByKeys(Collection<Key> kList) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.delete(kList); } /** * utility method to form a hash map of query parameters using an equality operator * * @param paramName - name of object property * @param filter - in/out stringBuilder of query filters * @param param -in/out stringBuilder of param names * @param type - data type of field * @param value - value to bind to param * @param paramMap - in/out parameter map */ protected void appendNonNullParam(String paramName, StringBuilder filter, StringBuilder param, String type, Object value, Map<String, Object> paramMap) { appendNonNullParam(paramName, filter, param, type, value, paramMap, EQ_OP); } /** * utility method to form a hash map of query parameters * * @param paramName - name of object property * @param filter - in/out stringBuilder of query filters * @param param -in/out stringBuilder of param names * @param type - data type of field * @param value - value to bind to param * @param paramMap - in/out parameter map * @param operator - operator to use */ protected void appendNonNullParam(String paramName, StringBuilder filter, StringBuilder param, String type, Object value, Map<String, Object> paramMap, String operator) { if (value != null) { if (paramMap.keySet().size() > 0) { filter.append(" && "); param.append(", "); } String paramValName = paramName + "Param" + paramMap.keySet().size(); filter.append(paramName).append(" ").append(operator).append(" ") .append(paramValName); param.append(type).append(" ").append(paramValName); paramMap.put(paramValName, value); } } /** * gets a GAE datastore cursor based on the results list passed in. The list must be a non-null * list of persistent entities (entites retrived from the datastore in the same session). * * @param results * @return */ @SuppressWarnings("rawtypes") public static String getCursor(List results) { if (results != null && results.size() > 0) { Cursor cursor = JDOCursorHelper.getCursor(results); if (cursor != null) { return cursor.toWebSafeString(); } else { return null; } } return null; } /** * sets up the cursor with the given page size (or no page size if the cursor string is set to * the ALL_RESULTS constant) * * @param cursorString * @param pageSize * @param query */ protected void prepareCursor(String cursorString, Integer pageSize, javax.jdo.Query query) { if (cursorString != null && !cursorString.trim().toLowerCase() .equals(Constants.ALL_RESULTS)) { Cursor cursor = Cursor.fromWebSafeString(cursorString); Map<String, Object> extensionMap = new HashMap<String, Object>(); extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor); query.setExtensions(extensionMap); } if (cursorString == null || !cursorString.equals(Constants.ALL_RESULTS)) { if (pageSize == null) { query.setRange(0, DEFAULT_RESULT_COUNT); } else { query.setRange(0, pageSize); } } } /** * this method should only be used when running a lot of datastore operations in a single * request to a task queue and or backend (regular online requests can't accumulate enough data * to require a flush without timing out). */ public void flushBatch() { PersistenceManager pm = PersistenceFilter.getManager(); pm.flush(); } /** * sets up the cursor using the default page size * * @param cursorString * @param query */ protected void prepareCursor(String cursorString, javax.jdo.Query query) { prepareCursor(cursorString, DEFAULT_RESULT_COUNT, query); } /** * method used to sleep in the event of a retry */ protected static void sleep() { try { Thread.sleep(RETRY_INTERVAL_MILLIS); } catch (InterruptedException e) { // no-op } } /** * Default format for cache key string * * @param object * @return * @throws CacheException */ public String getCacheKey(BaseDomain object) throws CacheException { if (object.getKey() == null) { throw new CacheException("Trying to get cache key from an unsaved object"); } return object.getClass().getSimpleName() + "-" + object.getKey().getId(); } /** * Default format for cache key string * * @param objectId * @return * @throws CacheException */ public String getCacheKey(String objectId) throws CacheException { if (objectId == null) { throw new CacheException("Trying to get cache key from an unsaved object"); } return concreteClass.getSimpleName() + "-" + objectId; } public List<T> fetchItemsByIdBatches(List<Long> idsList, String fieldName) { if (idsList == null || idsList.isEmpty()) { return Collections.emptyList(); } List<T> fetchedItems = new ArrayList<>(); int idsListSize = idsList.size(); int start = 0; int end = Math.min(MAX_ALLOWED_FILTERED_ITEMS, idsListSize); int numberOfQueryRounds = (int) Math .ceil((double) idsListSize / MAX_ALLOWED_FILTERED_ITEMS); for (int i = 0; i < numberOfQueryRounds; i++) { List<Long> idsToRetrieve = idsList.subList(start, end); fetchedItems.addAll(listValuesByIdsList(idsToRetrieve, fieldName)); start = end; end = Math.min(end + MAX_ALLOWED_FILTERED_ITEMS, idsListSize); } return fetchedItems; } private List<T> listValuesByIdsList(List<Long> idsList, final String fieldName) { if (idsList == null || idsList.isEmpty()) { return Collections.emptyList(); } PersistenceManager pm = PersistenceFilter.getManager(); String queryString = ":p1.contains(" + fieldName + ")"; javax.jdo.Query query = pm.newQuery(concreteClass, queryString); @SuppressWarnings("unchecked") List<T> results = (List<T>) query.execute(idsList); return results; } }
package com.gallatinsystems.survey.domain; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class WebForm { public static Set<String> unsupportedQuestionTypes() { Set<String> unsupportedTypes = new HashSet<String>(); unsupportedTypes.add(Question.Type.GEOSHAPE.toString()); unsupportedTypes.add(Question.Type.SIGNATURE.toString()); unsupportedTypes.add(Question.Type.CADDISFLY.toString()); return unsupportedTypes; } public static boolean validQuestionGroups(final Survey survey) { return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable()).collect(Collectors.toList()).size() == 0; } public static boolean validForm(final Survey survey, final SurveyGroup surveyGroup) { return surveyGroup.getNewLocaleSurveyId() != null && surveyGroup.getNewLocaleSurveyId().equals(survey.getKey().getId()); } public static boolean validWebForm(final SurveyGroup surveyGroup, final Survey survey, final List<Question> questions) { boolean validQuestionGroups = validQuestionGroups(survey); if (!validQuestionGroups) { return false; } boolean validSurveyGroup = validForm(survey, surveyGroup); if (!validSurveyGroup) { return false; } List<Question> validQuestions = questions.stream().filter(i -> !unsupportedQuestionTypes().contains(i.getType().toString())).collect(Collectors.toList()); return validQuestions.size() == questions.size(); } }
package com.hello; import java.util.*; /** * Hello world! */ public class BestHotel { public static void main(String[] args) { System.out.println("Hello Best Hotel!"); best_hotels(); } static void best_hotels() { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); HashMap<Long, Hotel> idScoresMap = new HashMap<Long, Hotel>(); while (n long id = sc.nextLong(); int score = sc.nextInt(); Hotel scores = idScoresMap.get(id); if (scores == null) { scores = new Hotel(id); idScoresMap.put(id, scores); } scores.addScore(score); } sc.close(); Hotel[] hotels = new Hotel[idScoresMap.size()]; idScoresMap.values().toArray(hotels); Arrays.sort(hotels, new HotelComparator()); for (Hotel hotel : hotels) { System.out.println(hotel.getId()); } } private static class Hotel { private long id = 0; private ArrayList<Integer> scoreList = new ArrayList<Integer>(); private int totalScore = 0; public Hotel(long id) { this.id = id; } public long getId() { return id; } public void addScore(int score) { this.scoreList.add(score); this.totalScore += score; } public double getAverageScore() { if (scoreList.size() <= 0) { return 0; } return (double) totalScore / scoreList.size(); } } public static class HotelComparator implements Comparator<Hotel> { // @Override public int compare(Hotel o1, Hotel o2) { int ret = ((Double)o2.getAverageScore()).compareTo(o1.getAverageScore()); if (ret == 0) { ret = (int) (o1.getId() - o2.getId()); } return ret; } } }
package com.mygdx.states; import com.mygdx.handlers.AssetManager; import com.mygdx.handlers.GameStateManager; import com.mygdx.UI.MyStage; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.mygdx.game.MyGame; import com.mygdx.handlers.NetworkManager; public class WinState extends GameState { private MyStage stage; private TextButton backtostart; private TextButton endlessReplay; private Batch batch; private BitmapFont font; public WinState(GameStateManager gameStateManager, NetworkManager networkManager){ super(gameStateManager,networkManager); stage = new MyStage(); Gdx.input.setInputProcessor(stage); Skin skin = new Skin(Gdx.files.internal("UiData/uiskin.json")); //Stop all game music and game sounds AssetManager.dispose(); //Load and Start End Music AssetManager.loadMusic(3); //AssetManager.music.play(); //AssetManager.music.setLooping(true); backtostart = new TextButton("Return to Menu",skin); backtostart.setSize(200,60); backtostart.setPosition(game.V_WIDTH/2-backtostart.getWidth()/2, game.V_HEIGHT/2-backtostart.getHeight()/2); backtostart.addListener(new ClickListener()); endlessReplay = new TextButton("Endless Mode.",skin); endlessReplay.setSize(200,60); endlessReplay.setPosition(game.V_WIDTH/2-backtostart.getWidth()/2, backtostart.getY() - 65); endlessReplay.addListener(new ClickListener()); font = new BitmapFont(); font.setColor(Color.WHITE); font.scale(.5f); stage.addActor(backtostart); stage.addActor(endlessReplay); } @Override public void update(float delta) { stage.act(delta); if(backtostart.isChecked()){ gameStateManager.setState(GameStateManager.MENU, 0); } if(endlessReplay.isChecked()){ gameStateManager.popState(); } } @Override public void show() { } @Override public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 2); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); update(delta); stage.draw(); batch = stage.getBatch(); batch.begin(); font.draw(batch, "Congrats a Winner is you.", MyGame.V_WIDTH / 2 - 64, MyGame.V_HEIGHT - 50); batch.end(); //((OrthographicCamera)stage.getCamera()).zoom += .01; } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } }
package org.ggp.base.util.match; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.ggp.base.util.crypto.SignableJSON; import org.ggp.base.util.crypto.BaseCryptography.EncodedKeyPair; import org.ggp.base.util.game.Game; import org.ggp.base.util.game.RemoteGameRepository; import org.ggp.base.util.gdl.factory.GdlFactory; import org.ggp.base.util.gdl.factory.exceptions.GdlFormatException; import org.ggp.base.util.gdl.grammar.GdlSentence; import org.ggp.base.util.gdl.grammar.GdlTerm; import org.ggp.base.util.gdl.scrambler.GdlScrambler; import org.ggp.base.util.gdl.scrambler.NoOpGdlScrambler; import org.ggp.base.util.statemachine.Move; import org.ggp.base.util.statemachine.Role; import org.ggp.base.util.symbol.factory.SymbolFactory; import org.ggp.base.util.symbol.factory.exceptions.SymbolFormatException; import org.ggp.base.util.symbol.grammar.SymbolList; import external.JSON.JSONArray; import external.JSON.JSONException; import external.JSON.JSONObject; public final class Match { private final String matchId; private final String randomToken; private final String spectatorAuthToken; private final int playClock; private final int startClock; private final int analysisClock; private final Date startTime; private final Game theGame; private final List<List<GdlTerm>> moveHistory; private final List<Set<GdlSentence>> stateHistory; private final List<List<String>> errorHistory; private final List<Date> stateTimeHistory; private boolean isCompleted; private final List<Integer> goalValues; private final int numRoles; private EncodedKeyPair theCryptographicKeys; private List<String> thePlayerNamesFromHost; private List<Boolean> isPlayerHuman; private GdlScrambler theGdlScrambler = new NoOpGdlScrambler(); public Match(String matchId, int analysisClock, int startClock, int playClock, Game theGame) { this.matchId = matchId; this.analysisClock = analysisClock; this.startClock = startClock; this.playClock = playClock; this.theGame = theGame; this.startTime = new Date(); this.randomToken = getRandomString(32); this.spectatorAuthToken = getRandomString(12); this.isCompleted = false; this.numRoles = Role.computeRoles(theGame.getRules()).size(); this.moveHistory = new ArrayList<List<GdlTerm>>(); this.stateHistory = new ArrayList<Set<GdlSentence>>(); this.stateTimeHistory = new ArrayList<Date>(); this.errorHistory = new ArrayList<List<String>>(); this.goalValues = new ArrayList<Integer>(); } public Match(String theJSON, Game theGame, String authToken) throws JSONException, SymbolFormatException, GdlFormatException { JSONObject theMatchObject = new JSONObject(theJSON); this.matchId = theMatchObject.getString("matchId"); this.startClock = theMatchObject.getInt("startClock"); this.playClock = theMatchObject.getInt("playClock"); if (theGame == null) { this.theGame = RemoteGameRepository.loadSingleGame(theMatchObject.getString("gameMetaURL")); if (this.theGame == null) { throw new RuntimeException("Could not find metadata for game referenced in Match object: " + theMatchObject.getString("gameMetaURL")); } } else { this.theGame = theGame; } if (theMatchObject.has("analysisClock")) { this.analysisClock = theMatchObject.getInt("analysisClock"); } else { this.analysisClock = -1; } this.startTime = new Date(theMatchObject.getLong("startTime")); this.randomToken = theMatchObject.getString("randomToken"); this.spectatorAuthToken = authToken; this.isCompleted = theMatchObject.getBoolean("isCompleted"); this.numRoles = Role.computeRoles(theGame.getRules()).size(); this.moveHistory = new ArrayList<List<GdlTerm>>(); this.stateHistory = new ArrayList<Set<GdlSentence>>(); this.stateTimeHistory = new ArrayList<Date>(); this.errorHistory = new ArrayList<List<String>>(); JSONArray theMoves = theMatchObject.getJSONArray("moves"); for (int i = 0; i < theMoves.length(); i++) { List<GdlTerm> theMove = new ArrayList<GdlTerm>(); JSONArray moveElements = theMoves.getJSONArray(i); for (int j = 0; j < moveElements.length(); j++) { theMove.add(GdlFactory.createTerm(moveElements.getString(j))); } moveHistory.add(theMove); } JSONArray theStates = theMatchObject.getJSONArray("states"); for (int i = 0; i < theStates.length(); i++) { Set<GdlSentence> theState = new HashSet<GdlSentence>(); SymbolList stateElements = (SymbolList) SymbolFactory.create(theStates.getString(i)); for (int j = 0; j < stateElements.size(); j++) { theState.add((GdlSentence)GdlFactory.create("( true " + stateElements.get(j).toString() + " )")); } stateHistory.add(theState); } JSONArray theStateTimes = theMatchObject.getJSONArray("stateTimes"); for (int i = 0; i < theStateTimes.length(); i++) { this.stateTimeHistory.add(new Date(theStateTimes.getLong(i))); } if (theMatchObject.has("errors")) { JSONArray theErrors = theMatchObject.getJSONArray("errors"); for (int i = 0; i < theErrors.length(); i++) { List<String> theMoveErrors = new ArrayList<String>(); JSONArray errorElements = theErrors.getJSONArray(i); for (int j = 0; j < errorElements.length(); j++) { theMoveErrors.add(errorElements.getString(j)); } errorHistory.add(theMoveErrors); } } this.goalValues = new ArrayList<Integer>(); try { JSONArray theGoalValues = theMatchObject.getJSONArray("goalValues"); for (int i = 0; i < theGoalValues.length(); i++) { this.goalValues.add(theGoalValues.getInt(i)); } } catch (JSONException e) {} // TODO: Add a way to recover cryptographic public keys and signatures. // Or, perhaps loading a match into memory for editing should strip those? if (theMatchObject.has("playerNamesFromHost")) { thePlayerNamesFromHost = new ArrayList<String>(); JSONArray thePlayerNames = theMatchObject.getJSONArray("playerNamesFromHost"); for (int i = 0; i < thePlayerNames.length(); i++) { thePlayerNamesFromHost.add(thePlayerNames.getString(i)); } } if (theMatchObject.has("isPlayerHuman")) { isPlayerHuman = new ArrayList<Boolean>(); JSONArray isPlayerHumanArray = theMatchObject.getJSONArray("isPlayerHuman"); for (int i = 0; i < isPlayerHumanArray.length(); i++) { isPlayerHuman.add(isPlayerHumanArray.getBoolean(i)); } } } /* Mutators */ public void setCryptographicKeys(EncodedKeyPair k) { this.theCryptographicKeys = k; } public void setGdlScrambler(GdlScrambler gs) { this.theGdlScrambler = gs; } public void setPlayerNamesFromHost(List<String> thePlayerNames) { this.thePlayerNamesFromHost = thePlayerNames; } public void setWhichPlayersAreHuman(List<Boolean> isPlayerHuman) { this.isPlayerHuman = isPlayerHuman; } public void appendMoves(List<GdlTerm> moves) { moveHistory.add(moves); } public void appendMoves2(List<Move> moves) { // NOTE: This is appendMoves2 because it Java can't handle two // appendMove methods that both take List objects with different // templatized parameters. List<GdlTerm> theMoves = new ArrayList<GdlTerm>(); for(Move m : moves) { theMoves.add(m.getContents()); } appendMoves(theMoves); } public void appendState(Set<GdlSentence> state) { stateHistory.add(state); stateTimeHistory.add(new Date()); } public void appendErrors(List<String> errors) { errorHistory.add(errors); } public void appendNoErrors() { List<String> theNoErrors = new ArrayList<String>(); for (int i = 0; i < this.numRoles; i++) { theNoErrors.add(""); } errorHistory.add(theNoErrors); } public void markCompleted(List<Integer> theGoalValues) { this.isCompleted = true; if (theGoalValues != null) { this.goalValues.addAll(theGoalValues); } } /* Complex accessors */ public String toJSON() { JSONObject theJSON = new JSONObject(); try { theJSON.put("matchId", matchId); theJSON.put("randomToken", randomToken); theJSON.put("startTime", startTime.getTime()); theJSON.put("gameMetaURL", getGameRepositoryURL()); theJSON.put("isCompleted", isCompleted); theJSON.put("states", new JSONArray(renderArrayAsJSON(renderStateHistory(stateHistory), true))); theJSON.put("moves", new JSONArray(renderArrayAsJSON(renderMoveHistory(moveHistory), false))); theJSON.put("stateTimes", new JSONArray(renderArrayAsJSON(stateTimeHistory, false))); if (errorHistory.size() > 0) { theJSON.put("errors", new JSONArray(renderArrayAsJSON(renderErrorHistory(errorHistory), false))); } if (goalValues.size() > 0) { theJSON.put("goalValues", goalValues); } theJSON.put("analysisClock", analysisClock); theJSON.put("startClock", startClock); theJSON.put("playClock", playClock); if (thePlayerNamesFromHost != null) { theJSON.put("playerNamesFromHost", thePlayerNamesFromHost); } if (isPlayerHuman != null) { theJSON.put("isPlayerHuman", isPlayerHuman); } theJSON.put("scrambled", theGdlScrambler != null ? theGdlScrambler.scrambles() : false); } catch (JSONException e) { return null; } if (theCryptographicKeys != null) { try { SignableJSON.signJSON(theJSON, theCryptographicKeys.thePublicKey, theCryptographicKeys.thePrivateKey); if (!SignableJSON.isSignedJSON(theJSON)) { throw new Exception("Could not recognize signed match: " + theJSON); } if (!SignableJSON.verifySignedJSON(theJSON)) { throw new Exception("Could not verify signed match: " + theJSON); } } catch (Exception e) { System.err.println(e); theJSON.remove("matchHostPK"); theJSON.remove("matchHostSignature"); } } return theJSON.toString(); } public List<GdlTerm> getMostRecentMoves() { if (moveHistory.size() == 0) return null; return moveHistory.get(moveHistory.size()-1); } public Set<GdlSentence> getMostRecentState() { if (stateHistory.size() == 0) return null; return stateHistory.get(stateHistory.size()-1); } public String getGameRepositoryURL() { return getGame().getRepositoryURL(); } public String toString() { return toJSON(); } /* Simple accessors */ public String getMatchId() { return matchId; } public String getRandomToken() { return randomToken; } public String getSpectatorAuthToken() { return spectatorAuthToken; } public Game getGame() { return theGame; } public List<List<GdlTerm>> getMoveHistory() { return moveHistory; } public List<Set<GdlSentence>> getStateHistory() { return stateHistory; } public List<Date> getStateTimeHistory() { return stateTimeHistory; } public List<List<String>> getErrorHistory() { return errorHistory; } public int getAnalysisClock() { return analysisClock; } public int getPlayClock() { return playClock; } public int getStartClock() { return startClock; } public Date getStartTime() { return startTime; } public boolean isCompleted() { return isCompleted; } public List<Integer> getGoalValues() { return goalValues; } public GdlScrambler getGdlScrambler() { return theGdlScrambler; } /* Static methods */ public static String getRandomString(int nLength) { Random theGenerator = new Random(); String theString = ""; for (int i = 0; i < nLength; i++) { int nVal = theGenerator.nextInt(62); if (nVal < 26) theString += (char)('a' + nVal); else if (nVal < 52) theString += (char)('A' + (nVal-26)); else if (nVal < 62) theString += (char)('0' + (nVal-52)); } return theString; } private static String renderArrayAsJSON(List<?> theList, boolean useQuotes) { String s = "["; for (int i = 0; i < theList.size(); i++) { Object o = theList.get(i); // AppEngine-specific, not needed yet: if (o instanceof Text) o = ((Text)o).getValue(); if (o instanceof Date) o = ((Date)o).getTime(); if (useQuotes) s += "\""; s += o.toString(); if (useQuotes) s += "\""; if (i < theList.size() - 1) s += ", "; } return s + "]"; } private static List<String> renderStateHistory(List<Set<GdlSentence>> stateHistory) { List<String> renderedStates = new ArrayList<String>(); for (Set<GdlSentence> aState : stateHistory) { renderedStates.add(renderStateAsSymbolList(aState)); } return renderedStates; } private static List<String> renderMoveHistory(List<List<GdlTerm>> moveHistory) { List<String> renderedMoves = new ArrayList<String>(); for (List<GdlTerm> aMove : moveHistory) { renderedMoves.add(renderArrayAsJSON(aMove, true)); } return renderedMoves; } private static List<String> renderErrorHistory(List<List<String>> errorHistory) { List<String> renderedErrors = new ArrayList<String>(); for (List<String> anError : errorHistory) { renderedErrors.add(renderArrayAsJSON(anError, true)); } return renderedErrors; } private static String renderStateAsSymbolList(Set<GdlSentence> theState) { // Strip out the TRUE proposition, since those are implied for states. String s = "( "; for (GdlSentence sent : theState) { String sentString = sent.toString(); s += sentString.substring(6, sentString.length()-2).trim() + " "; } return s + ")"; } }
package com.commonliabray.jpush; import java.util.Iterator; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import com.commonliabray.activity.demo.MainActivity; import com.commonliabray.asynchttp.activity.LoginActivity; import com.commonliabray.asynchttp.manager.UserManager; import com.commonliabray.model.PushMessage; import com.loopj.android.http.commonhttp.ResponseEntityToModule; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import cn.jpush.android.api.JPushInterface; /** * @author vision * @function */ public class JPushReceiver extends BroadcastReceiver { private static final String TAG = "JPush"; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Log.d(TAG, "[JPushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle)); if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID); Log.d(TAG, "[JPushReceiver] ID: " + notifactionId); } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { PushMessage pushMessage = (PushMessage) ResponseEntityToModule .parseJsonToModule(bundle.getString(JPushInterface.EXTRA_EXTRA), PushMessage.class); if (getCurrentTask(context)) { Intent pushIntent = new Intent(); pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pushIntent.putExtra("pushMessage", pushMessage); if (pushMessage.messageType != null && pushMessage.messageType.equals("2") && !UserManager.getInstance().hasLogined()) { pushIntent.setClass(context, LoginActivity.class); pushIntent.putExtra("fromPush", true); } else { /** * Case */ if (UserManager.getInstance().getUser() != null) { Log.e("has logined:", UserManager.getInstance().getUser().data.name + " "); } pushIntent.setClass(context, JPushTestActivity.class); } context.startActivity(pushIntent); } else { /** * switch--case */ Intent mainIntent = new Intent(context, MainActivity.class); mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (pushMessage.messageType != null && pushMessage.messageType.equals("2")) { Intent loginIntent = new Intent(); loginIntent.setClass(context, LoginActivity.class); loginIntent.putExtra("fromPush", true); loginIntent.putExtra("pushMessage", pushMessage); context.startActivities(new Intent[] { mainIntent, loginIntent }); } else { Intent pushIntent = new Intent(context, JPushTestActivity.class); pushIntent.putExtra("pushMessage", pushMessage); context.startActivities(new Intent[] { mainIntent, pushIntent }); } } } } // intent extra private static String printBundle(Bundle bundle) { StringBuilder sb = new StringBuilder(); for (String key : bundle.keySet()) { if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) { sb.append("\nkey:" + key + ", value:" + bundle.getInt(key)); } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) { sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key)); } else if (key.equals(JPushInterface.EXTRA_EXTRA)) { if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) { Log.i(TAG, "This message has no Extra data"); continue; } try { /** * JSON */ JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA)); Iterator<String> it = json.keys(); while (it.hasNext()) { String myKey = it.next().toString(); sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]"); } } catch (JSONException e) { Log.e(TAG, "Get message extra JSON error!"); } } else { sb.append("\nkey:" + key + ", value:" + bundle.getString(key)); } } return sb.toString(); } /** * () * * @return */ @SuppressWarnings("deprecation") private boolean getCurrentTask(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> appProcessInfos = activityManager.getRunningTasks(50); for (RunningTaskInfo process : appProcessInfos) { if (process.baseActivity.getPackageName().equals(context.getPackageName()) || process.topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; } }
package espe.edu.ec.educat.model; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Alejandro Torres */ @Entity @Table(name = "programa") @NamedQueries({ @NamedQuery(name = "Programa.findAll", query = "SELECT p FROM Programa p")}) public class Programa implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 8) @Column(name = "COD_PROGRAMA", nullable = false, length = 8) /* * llave primaria de 8 caracteres que identifica al programa que ofrece el * instituto */ private String codPrograma; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "NOMBRE", nullable = false, length = 100) /* * atributo que almacena el nombre del programa que ofrece el instituto */ private String nombre; @Size(max = 4000) @Column(name = "DESCRIPCION", length = 4000) /* * atributo que almacena una breve descripcion del programa */ private String descripcion; @Basic(optional = false) @NotNull @Column(name = "DURACION", nullable = false) /* * atributo que almacena la duracion del programa en horas */ private short duracion; @Column(name = "FECHA_INICIO") @Temporal(TemporalType.DATE) /* * Atributo que almacena la informacion de la fecha en la que inicio el * programa */ private Date fechaInicio; @Column(name = "FECHA_FIN") @Temporal(TemporalType.DATE) /* * Atributo que almacena la fecha en la que el programa ha terminado */ private Date fechaFin; @OneToMany(cascade = CascadeType.ALL, mappedBy = "programa") private List<ProgramaCurso> programaCursoList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "programa") private List<ProgramaAlumno> programaAlumnoList; public Programa() { } public Programa(String codPrograma) { this.codPrograma = codPrograma; } public Programa(String codPrograma, String nombre, short duracion) { this.codPrograma = codPrograma; this.nombre = nombre; this.duracion = duracion; } public String getCodPrograma() { return codPrograma; } public void setCodPrograma(String codPrograma) { this.codPrograma = codPrograma; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public short getDuracion() { return duracion; } public void setDuracion(short duracion) { this.duracion = duracion; } public Date getFechaInicio() { return fechaInicio; } public void setFechaInicio(Date fechaInicio) { this.fechaInicio = fechaInicio; } public Date getFechaFin() { return fechaFin; } public void setFechaFin(Date fechaFin) { this.fechaFin = fechaFin; } public List<ProgramaCurso> getProgramaCursoList() { return programaCursoList; } public void setProgramaCursoList(List<ProgramaCurso> programaCursoList) { this.programaCursoList = programaCursoList; } public List<ProgramaAlumno> getProgramaAlumnoList() { return programaAlumnoList; } public void setProgramaAlumnoList(List<ProgramaAlumno> programaAlumnoList) { this.programaAlumnoList = programaAlumnoList; } @Override public int hashCode() { int hash = 0; hash += (codPrograma != null ? codPrograma.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Programa)) { return false; } Programa other = (Programa) object; if ((this.codPrograma == null && other.codPrograma != null) || (this.codPrograma != null && !this.codPrograma.equals(other.codPrograma))) { return false; } return true; } @Override public String toString() { return "ec.edu.espe.edu.conjunta.model.Programa[ codPrograma=" + codPrograma + " ]"; } }
package com.intellij.extapi.psi; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiInvalidElementAccessException; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.CompositeElement; import com.intellij.psi.impl.source.tree.SharedImplUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; /** * @author max */ public class ASTWrapperPsiElement extends PsiElementBase { private ASTNode myNode; public ASTWrapperPsiElement(final ASTNode node) { myNode = node; } public PsiManager getManager() { final PsiElement parent = getParent(); if (parent == null) throw new PsiInvalidElementAccessException(this); return parent.getManager(); } @NotNull public PsiElement[] getChildren() { final PsiElement psiChild = getFirstChild(); if (psiChild == null) return EMPTY_ARRAY; List<PsiElement> result = new ArrayList<PsiElement>(); ASTNode child = psiChild.getNode(); while (child != null) { if (child instanceof CompositeElement) { result.add(child.getPsi()); } child = child.getTreeNext(); } return result.toArray(new PsiElement[result.size()]); } public void acceptChildren(PsiElementVisitor visitor) { final PsiElement psiChild = getFirstChild(); if (psiChild == null) return; ASTNode child = psiChild.getNode(); while (child != null) { child.getPsi().accept(visitor); child = child.getTreeNext(); } } public PsiElement getParent() { return SharedImplUtil.getParent(myNode); } public PsiElement getFirstChild() { return SharedImplUtil.getFirstChild(myNode); } public PsiElement getLastChild() { return SharedImplUtil.getLastChild(myNode); } public PsiElement getNextSibling() { return SharedImplUtil.getNextSibling(myNode); } public PsiElement getPrevSibling() { return SharedImplUtil.getPrevSibling(myNode); } public TextRange getTextRange() { return myNode.getTextRange(); } public int getStartOffsetInParent() { return myNode.getStartOffset() - myNode.getTreeParent().getStartOffset(); } public int getTextLength() { return myNode.getTextLength(); } public PsiElement findElementAt(int offset) { ASTNode treeElement = myNode.findLeafElementAt(offset); return SourceTreeToPsiMap.treeElementToPsi(treeElement); } public int getTextOffset() { return myNode.getStartOffset(); } public String getText() { return myNode.getText(); } @NotNull public char[] textToCharArray() { return myNode.getText().toCharArray(); } public boolean textContains(char c) { return myNode.textContains(c); } public <T> T getCopyableUserData(Key<T> key) { return myNode.getCopyableUserData(key); } public <T> void putCopyableUserData(Key<T> key, T value) { myNode.putCopyableUserData(key, value); } public ASTNode getNode() { return myNode; } @NotNull public Language getLanguage() { return myNode.getElementType().getLanguage(); } }
package org.unitime.timetable.action; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.Locale; import java.util.TreeSet; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.unitime.commons.Debug; import org.unitime.commons.web.Web; import org.unitime.commons.web.WebTable; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.form.SolutionReportForm; import org.unitime.timetable.model.PreferenceLevel; import org.unitime.timetable.model.RoomType; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.dao.RoomTypeDAO; import org.unitime.timetable.solver.SolverProxy; import org.unitime.timetable.solver.WebSolver; import org.unitime.timetable.solver.interactive.ClassAssignmentDetails; import org.unitime.timetable.solver.ui.DeptBalancingReport; import org.unitime.timetable.solver.ui.DiscouragedInstructorBtbReport; import org.unitime.timetable.solver.ui.JenrlInfo; import org.unitime.timetable.solver.ui.PerturbationReport; import org.unitime.timetable.solver.ui.RoomReport; import org.unitime.timetable.solver.ui.SameSubpartBalancingReport; import org.unitime.timetable.solver.ui.StudentConflictsReport; import org.unitime.timetable.solver.ui.ViolatedDistrPreferencesReport; import org.unitime.timetable.util.Constants; import org.unitime.timetable.util.PdfEventHandler; import org.unitime.timetable.webutil.PdfWebTable; import com.lowagie.text.Document; import com.lowagie.text.FontFactory; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; /** * @author Tomas Muller */ public class SolutionReportAction extends Action { private static java.text.DecimalFormat sDoubleFormat = new java.text.DecimalFormat("0.00",new java.text.DecimalFormatSymbols(Locale.US)); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SolutionReportForm myForm = (SolutionReportForm) form; // Check Access if (!Web.isLoggedIn( request.getSession() )) { throw new Exception ("Access Denied."); } // Read operation to be performed String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op")); Session session = Session.getCurrentAcadSession(Web.getUser(request.getSession())); Calendar sessionStart = Calendar.getInstance(Locale.US); sessionStart.setTime(session.getSessionBeginDateTime()); while (sessionStart.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY) sessionStart.add(Calendar.DAY_OF_YEAR, -1); int startDay = session.getDayOfYear(sessionStart.get(Calendar.DAY_OF_MONTH), sessionStart.get(Calendar.MONTH)) - session.getDayOfYear(1, session.getStartMonth() - 3); Calendar sessionEnd = Calendar.getInstance(Locale.US); sessionEnd.setTime(session.getSessionEndDateTime()); sessionEnd.add(Calendar.WEEK_OF_YEAR, -1); while (sessionEnd.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) sessionEnd.add(Calendar.DAY_OF_YEAR, 1); int endDay = session.getDayOfYear(sessionEnd.get(Calendar.DAY_OF_MONTH), sessionEnd.get(Calendar.MONTH)) - session.getDayOfYear(1, session.getStartMonth() - 3); SolverProxy solver = WebSolver.getSolver(request.getSession()); if (solver==null) { request.setAttribute("SolutionReport.message","Neither a solver is started nor solution is loaded."); } else { try { for (RoomType type : RoomType.findAll()) { RoomReport roomReport = solver.getRoomReport(startDay, endDay, session.getNrWeeks(), type.getUniqueId()); if (roomReport!=null && !roomReport.getGroups().isEmpty()) { WebTable t = getRoomReportTable(request, roomReport, false, type.getUniqueId()); if (t!=null) request.setAttribute("SolutionReport.roomReportTable."+type.getReference(), t.printTable(WebTable.getOrder(request.getSession(),"solutionReports.roomReport.ord"))); } } RoomReport roomReport = solver.getRoomReport(startDay, endDay, session.getNrWeeks(), null); if (roomReport!=null && !roomReport.getGroups().isEmpty()) { WebTable t = getRoomReportTable(request, roomReport, false, null); if (t!=null) request.setAttribute("SolutionReport.roomReportTable.nonUniv", t.printTable(WebTable.getOrder(request.getSession(),"solutionReports.roomReport.ord"))); } DeptBalancingReport deptBalancingReport = solver.getDeptBalancingReport(); if (deptBalancingReport!=null && !deptBalancingReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.deptBalancingReportTable", getDeptBalancingReportTable(request, deptBalancingReport, false).printTable(WebTable.getOrder(request.getSession(),"solutionReports.deptBalancingReport.ord"))); ViolatedDistrPreferencesReport violatedDistrPreferencesReport = solver.getViolatedDistrPreferencesReport(); if (violatedDistrPreferencesReport!=null && !violatedDistrPreferencesReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.violatedDistrPreferencesReportTable", getViolatedDistrPreferencesReportTable(request, violatedDistrPreferencesReport, false).printTable(WebTable.getOrder(request.getSession(),"solutionReports.violDistPrefReport.ord"))); DiscouragedInstructorBtbReport discouragedInstructorBtbReportReport = solver.getDiscouragedInstructorBtbReport(); if (discouragedInstructorBtbReportReport!=null && !discouragedInstructorBtbReportReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.discouragedInstructorBtbReportReportTable", getDiscouragedInstructorBtbReportReportTable(request, discouragedInstructorBtbReportReport, false).printTable(WebTable.getOrder(request.getSession(),"solutionReports.violInstBtb.ord"))); StudentConflictsReport studentConflictsReport = solver.getStudentConflictsReport(); if (studentConflictsReport!=null && !studentConflictsReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.studentConflictsReportTable", getStudentConflictsReportTable(request, studentConflictsReport, false).printTable(WebTable.getOrder(request.getSession(),"solutionReports.studConf.ord"))); SameSubpartBalancingReport sameSubpartBalancingReport = solver.getSameSubpartBalancingReport(); if (sameSubpartBalancingReport!=null && !sameSubpartBalancingReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.sameSubpartBalancingReportTable", getSameSubpartBalancingReportTable(request, sameSubpartBalancingReport, false).printTable(PdfWebTable.getOrder(request.getSession(),"solutionReports.sectBalancingReport.ord"))); PerturbationReport perturbationReport = solver.getPerturbationReport(); if (perturbationReport!=null && !perturbationReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.perturbationReportTable", getPerturbationReportTable(request, perturbationReport, false).printTable(WebTable.getOrder(request.getSession(),"solutionReports.pert.ord"))); } catch (Exception e) { e.printStackTrace(); } } if ("Export PDF".equals(op)) { FileOutputStream out = null; try { File file = ApplicationProperties.getTempFile("report", "pdf"); Document doc = new Document(new Rectangle(60f + PageSize.LETTER.height(), 60f + 0.75f * PageSize.LETTER.height()),30,30,30,30); out = new FileOutputStream(file); PdfWriter iWriter = PdfWriter.getInstance(doc, out); iWriter.setPageEvent(new PdfEventHandler()); doc.open(); boolean atLeastOneRoomReport = false; for (RoomType type : RoomType.findAll()) { RoomReport roomReport = solver.getRoomReport(startDay, endDay, session.getNrWeeks(), type.getUniqueId()); if (roomReport==null || roomReport.getGroups().isEmpty()) continue; PdfWebTable table = getRoomReportTable(request, roomReport, true, type.getUniqueId()); if (table==null) continue; PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.roomReport.ord")); if (!atLeastOneRoomReport) { doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); } doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); atLeastOneRoomReport = true; } RoomReport roomReport = solver.getRoomReport(startDay, endDay, session.getNrWeeks(), null); if (roomReport!=null && !roomReport.getGroups().isEmpty()) { PdfWebTable table = getRoomReportTable(request, roomReport, true, null); if (table!=null) { PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.roomReport.ord")); if (!atLeastOneRoomReport) { doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); } doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); atLeastOneRoomReport = true; } } if (atLeastOneRoomReport) { PdfPTable pdfTable = new PdfPTable(new float[] {10f,100f}); pdfTable.setWidthPercentage(100); pdfTable.getDefaultCell().setPadding(3); pdfTable.getDefaultCell().setBorderWidth(0); pdfTable.setSplitRows(false); pdfTable.addCell("Group"); pdfTable.addCell("group size <minimum, maximum)"); pdfTable.addCell("Size"); pdfTable.addCell("actual group size (size of the smallest and the biggest room in the group)"); pdfTable.addCell("NrRooms"); pdfTable.addCell("number of rooms in the group"); pdfTable.addCell("ClUse"); pdfTable.addCell("number of classes that are using a room from the group (actual solution)"); pdfTable.addCell("ClShould"); pdfTable.addCell("number of classes that \"should\" use a room of the group (smallest available room of a class is in this group)"); pdfTable.addCell("ClMust"); pdfTable.addCell("number of classes that must use a room of the group (all available rooms of a class are in this group)"); pdfTable.addCell("HrUse"); pdfTable.addCell("average hours a room of the group is used (actual solution)"); pdfTable.addCell("HrShould"); pdfTable.addCell("average hours a room of the group should be used (smallest available room of a class is in this group)"); pdfTable.addCell("HrMust"); pdfTable.addCell("average hours a room of this group must be used (all available rooms of a class are in this group)"); pdfTable.addCell(""); pdfTable.addCell("*) cumulative numbers (group minimum ... inf) are displayed in parentheses."); doc.add(pdfTable); } DiscouragedInstructorBtbReport discouragedInstructorBtbReportReport = solver.getDiscouragedInstructorBtbReport(); if (discouragedInstructorBtbReportReport!=null && !discouragedInstructorBtbReportReport.getGroups().isEmpty()) { PdfWebTable table = getDiscouragedInstructorBtbReportReportTable(request, discouragedInstructorBtbReportReport, true); PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.violInstBtb.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); } ViolatedDistrPreferencesReport violatedDistrPreferencesReport = solver.getViolatedDistrPreferencesReport(); if (violatedDistrPreferencesReport!=null && !violatedDistrPreferencesReport.getGroups().isEmpty()) { PdfWebTable table = getViolatedDistrPreferencesReportTable(request, violatedDistrPreferencesReport, true); PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.violDistPrefReport.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); } StudentConflictsReport studentConflictsReport = solver.getStudentConflictsReport(); if (studentConflictsReport!=null && !studentConflictsReport.getGroups().isEmpty()) { PdfWebTable table = getStudentConflictsReportTable(request, studentConflictsReport, true); PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.studConf.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); } SameSubpartBalancingReport sameSubpartBalancingReport = solver.getSameSubpartBalancingReport(); if (sameSubpartBalancingReport!=null && !sameSubpartBalancingReport.getGroups().isEmpty()) { PdfWebTable table = getSameSubpartBalancingReportTable(request, sameSubpartBalancingReport, true); PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.sectBalancingReport.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); } DeptBalancingReport deptBalancingReport = solver.getDeptBalancingReport(); if (deptBalancingReport!=null && !deptBalancingReport.getGroups().isEmpty()) { PdfWebTable table = getDeptBalancingReportTable(request, deptBalancingReport, true); PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.deptBalancingReport.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); } PerturbationReport perturbationReport = solver.getPerturbationReport(); if (perturbationReport!=null && !perturbationReport.getGroups().isEmpty()) { PdfWebTable table = getPerturbationReportTable(request, perturbationReport, true); PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"solutionReports.pert.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); pdfTable = new PdfPTable(new float[] {5f,100f}); pdfTable.setWidthPercentage(100); pdfTable.getDefaultCell().setPadding(3); pdfTable.getDefaultCell().setBorderWidth(0); pdfTable.setSplitRows(false); pdfTable.addCell("Class"); pdfTable.addCell("Class name"); pdfTable.addCell("Time"); pdfTable.addCell("Time (initial -> assigned)"); pdfTable.addCell("Room"); pdfTable.addCell("Room (initial -> assigned)"); pdfTable.addCell("Dist"); pdfTable.addCell("Distance between assignments (if different are used buildings)"); pdfTable.addCell("St"); pdfTable.addCell("Number of affected students"); pdfTable.addCell("StT"); pdfTable.addCell("Number of affected students by time change"); pdfTable.addCell("StR"); pdfTable.addCell("Number of affected students by room change"); pdfTable.addCell("StB"); pdfTable.addCell("Number of affected students by building change"); pdfTable.addCell("Ins"); pdfTable.addCell("Number of affected instructors"); pdfTable.addCell("InsT"); pdfTable.addCell("Number of affected instructors by time change"); pdfTable.addCell("InsR"); pdfTable.addCell("Number of affected instructors by room change"); pdfTable.addCell("InsB"); pdfTable.addCell("Number of affected instructors by building change"); pdfTable.addCell("Rm"); pdfTable.addCell("Number of rooms changed"); pdfTable.addCell("Bld"); pdfTable.addCell("Number of buildings changed"); pdfTable.addCell("Tm"); pdfTable.addCell("Number of times changed"); pdfTable.addCell("Day"); pdfTable.addCell("Number of days changed"); pdfTable.addCell("Hr"); pdfTable.addCell("Number of hours changed"); pdfTable.addCell("TFSt"); pdfTable.addCell("Assigned building too far for instructor (from the initial one)"); pdfTable.addCell("TFIns"); pdfTable.addCell("Assigned building too far for students (from the initial one)"); pdfTable.addCell("DStC"); pdfTable.addCell("Difference in student conflicts"); pdfTable.addCell("NStC"); pdfTable.addCell("Number of new student conflicts"); pdfTable.addCell("DTPr"); pdfTable.addCell("Difference in time preferences"); pdfTable.addCell("DRPr"); pdfTable.addCell("Difference in room preferences"); pdfTable.addCell("DInsB"); pdfTable.addCell("Difference in back-to-back instructor preferences"); doc.add(pdfTable); } doc.close(); request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/"+file.getName()); //response.sendRedirect("temp/"+file.getName()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out!=null) out.close(); } catch (IOException e) {} } } return mapping.findForward("showSolutionReport"); } public PdfWebTable getRoomReportTable(HttpServletRequest request, RoomReport report, boolean noHtml, Long type) { WebTable.setOrder(request.getSession(),"solutionReports.roomReport.ord",request.getParameter("room_ord"),-1); String name = "Room Allocation - "+(type==null?"Non University Locations":RoomTypeDAO.getInstance().get(type).getLabel()); PdfWebTable webTable = new PdfWebTable( 9, name, "solutionReport.do?room_ord=%%", new String[] {"Group", "Size", "NrRooms*", "ClUse", "ClShould", "ClMust*", "HrUse", "HrShould", "HrMust*"}, new String[] {"center", "center", "left","left","left","left","left","left","left"}, null); webTable.setRowStyle("white-space:nowrap"); int nrLines = 0; try { int idx = 0; int nrAllRooms = 0, nrAllLectureUse = 0, nrAllLectureShouldUse = 0; double allSlotsUse = 0.0, allSlotsShouldUse = 0.0; TreeSet groups = new TreeSet(new Comparator() { public int compare(Object o1, Object o2) { RoomReport.RoomAllocationGroup g1 = (RoomReport.RoomAllocationGroup)o1; RoomReport.RoomAllocationGroup g2 = (RoomReport.RoomAllocationGroup)o2; return -Double.compare(g1.getMinRoomSize(),g2.getMinRoomSize()); } }); groups.addAll(report.getGroups()); for (Iterator i=groups.iterator();i.hasNext();idx++) { RoomReport.RoomAllocationGroup g = (RoomReport.RoomAllocationGroup)i.next(); if (g.getNrRooms()==0) continue; double factor = ((double)Constants.SLOT_LENGTH_MIN) / 60.0; nrAllRooms+=g.getNrRooms(); allSlotsUse+=g.getSlotsUse(); allSlotsShouldUse+=g.getSlotsShouldUse(); nrAllLectureUse+=g.getLecturesUse(); nrAllLectureShouldUse+=g.getLecturesShouldUse(); nrLines++; webTable.addLine(null, new String[] { g.getMinRoomSize()+" ... "+(g.getMaxRoomSize()==Integer.MAX_VALUE?(noHtml?"inf":"<i>inf</i>"):String.valueOf(g.getMaxRoomSize())), g.getActualMinRoomSize()+" ... "+g.getActualMaxRoomSize(), g.getNrRooms()+" ("+g.getNrRoomsThisSizeOrBigger()+")", //""+g.getLecturesCanUse(), ""+g.getLecturesUse()+" ("+nrAllLectureUse+")", ""+g.getLecturesShouldUse()+" ("+nrAllLectureShouldUse+")", g.getLecturesMustUse()+" ("+g.getLecturesMustUseThisSizeOrBigger()+")", //sDoubleFormat.format(factor*g.getSlotsCanUse()/g.getNrRooms()), sDoubleFormat.format(factor*g.getSlotsUse()/g.getNrRooms())+" ("+sDoubleFormat.format(factor*allSlotsUse/nrAllRooms)+")", sDoubleFormat.format(factor*g.getSlotsShouldUse()/g.getNrRooms())+" ("+sDoubleFormat.format(factor*allSlotsShouldUse/nrAllRooms)+")", sDoubleFormat.format(factor*g.getSlotsMustUse()/g.getNrRooms())+" ("+sDoubleFormat.format(factor*g.getSlotsMustUseThisSizeOrBigger()/g.getNrRoomsThisSizeOrBigger())+")" }, new Comparable[] { new Integer(g.getMinRoomSize()), new Integer(g.getActualMinRoomSize()), new Integer(g.getNrRooms()), //new Integer(g.getLecturesCanUse()), new Integer(g.getLecturesUse()), new Integer(g.getLecturesShouldUse()), new Integer(g.getLecturesMustUse()), //new Double(factor*g.getSlotsCanUse()/g.getNrRooms()), new Double(factor*g.getSlotsUse()/g.getNrRooms()), new Double(factor*g.getSlotsShouldUse()/g.getNrRooms()), new Double(factor*g.getSlotsMustUse()/g.getNrRooms()) }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); nrLines++; } if (nrLines==0) return null; return webTable; } public PdfWebTable getDeptBalancingReportTable(HttpServletRequest request, DeptBalancingReport deptBalancingReport, boolean noHtml) { WebTable.setOrder(request.getSession(),"solutionReports.deptBalancingReport.ord",request.getParameter("dept_ord"),1); String[] header = new String[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; String[] pos = new String[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; header[0]="Department"; pos[0]="left"; header[1]="Penalty"; pos[1]="center"; for (int i=0;i<Constants.SLOTS_PER_DAY_NO_EVENINGS/6;i++) { header[i+2]=Constants.slot2str(Constants.DAY_SLOTS_FIRST + i*6); pos[i+2]="center"; } PdfWebTable webTable = new PdfWebTable( header.length, "Departmental Balancing", "solutionReport.do?dept_ord=%%", header, pos, null); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Iterator it=deptBalancingReport.getGroups().iterator();it.hasNext();idx++) { DeptBalancingReport.DeptBalancingGroup g = (DeptBalancingReport.DeptBalancingGroup)it.next(); String[] line = new String[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; Comparable[] cmp = new Comparable[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; line[0]=g.getDepartmentName(); cmp[0]=g.getDepartmentName(); int penalty = 0; for (int i=0;i<Constants.SLOTS_PER_DAY_NO_EVENINGS/6;i++) { int slot = Constants.DAY_SLOTS_FIRST + i*6; int usage = g.getUsage(slot); int limit = g.getLimit(slot); if (usage>limit) penalty += g.getExcess(slot); Vector classes = new Vector(g.getClasses(slot)); Collections.sort(classes); StringBuffer sb = new StringBuffer(); StringBuffer toolTip = new StringBuffer(); int u = 0; boolean over = false; for (Enumeration e=classes.elements();e.hasMoreElements();) { ClassAssignmentDetails ca = (ClassAssignmentDetails)e.nextElement(); int nrMeetings = 0; for (int j=0;j<Constants.NR_DAYS_WEEK;j++) if ((Constants.DAY_CODES[j]&ca.getTime().getDays())!=0) nrMeetings++; u+=nrMeetings; if (u>limit && !over) { over=true; sb.append("<hr>"); } sb.append(noHtml?ca.getClazz().getName():ca.getClazz().toHtml(true,true));//+" ("+nrMeetings+"x"+ca.getTime().getMin()+")"); if (e.hasMoreElements()) sb.append(noHtml?"\n":"<br>"); toolTip.append(ca.getClassName()); if (e.hasMoreElements()) toolTip.append(", "); } if (noHtml) { line[i+2]=usage+" / "+limit; line[i+2]+=(classes.isEmpty()?"":"\n"+sb.toString()); } else { line[i+2]="<a title='"+toolTip+"'>"+(limit==0?"":(usage>limit?"<font color='red'>":"")+usage+" / "+limit+(usage>limit?"</font>":""))+"</a>"; line[i+2]+=(classes.isEmpty()?"":"<br>"+sb.toString()); } cmp[i+2]=new Integer(usage*1000+limit); } line[1]=(noHtml?""+penalty:(penalty==0?"":"<font color='red'>+"+penalty+"</font>")); cmp[1]=new Integer(penalty); webTable.addLine(null,line,cmp); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable; } public PdfWebTable getViolatedDistrPreferencesReportTable(HttpServletRequest request, ViolatedDistrPreferencesReport report, boolean noHtml) { WebTable.setOrder(request.getSession(),"solutionReports.violDistPrefReport.ord",request.getParameter("vdist_ord"),1); PdfWebTable webTable = new PdfWebTable( 5, "Violated Distribution Preferences", "solutionReport.do?vdist_ord=%%", new String[] {"Type", "Preference", "Class", "Time", "Room"}, new String[] {"left", "left", "left", "left", "left"}, null); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Iterator i=report.getGroups().iterator();i.hasNext();idx++) { ViolatedDistrPreferencesReport.ViolatedDistrPreference g = (ViolatedDistrPreferencesReport.ViolatedDistrPreference)i.next(); StringBuffer cSB = new StringBuffer(); MultiComparable ord = new MultiComparable(); StringBuffer tSB = new StringBuffer(); StringBuffer rSB = new StringBuffer(); for (Enumeration e=g.getClasses().elements();e.hasMoreElements();) { ClassAssignmentDetails ca = (ClassAssignmentDetails)e.nextElement(); if (noHtml) { cSB.append(ca.getClazz().getName()); tSB.append(ca.getTime().getDaysName()+" "+ca.getTime().getStartTime()+" - "+ca.getTime().getEndTime()); for (int j=0;j<ca.getRoom().length;j++) rSB.append((j>0?", ":"")+ca.getRoom()[j].getName()); } else { cSB.append(ca.getClazz().toHtml(true,true)); tSB.append(ca.getTime().toHtml(false,false,true)); for (int j=0;j<ca.getRoom().length;j++) rSB.append((j>0?", ":"")+ca.getRoom()[j].toHtml(false,false)); } ord.add(ca); if (e.hasMoreElements()) { if (noHtml) { cSB.append("\n");tSB.append("\n");rSB.append("\n"); } else { cSB.append("<BR>");tSB.append("<BR>");rSB.append("<BR>"); } } } webTable.addLine(null, new String[] { g.getName(), (noHtml?"":"<font color='"+PreferenceLevel.int2color(g.getPreference())+"'>")+ PreferenceLevel.getPreferenceLevel(PreferenceLevel.int2prolog(g.getPreference())).getPrefName()+ (noHtml?"":"</font>"), cSB.toString(), tSB.toString(), rSB.toString() }, new Comparable[] { g.getName(), new Integer(g.getPreference()), ord, null, null }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable; } public PdfWebTable getDiscouragedInstructorBtbReportReportTable(HttpServletRequest request, DiscouragedInstructorBtbReport report, boolean noHtml) { WebTable.setOrder(request.getSession(),"solutionReports.violInstBtb.ord",request.getParameter("vinbtb_ord"),1); PdfWebTable webTable = new PdfWebTable( 6, "Instructor Back-to-Back Preferences", "solutionReport.do?vinbtb_ord=%%", new String[] {"Instructor", "Preference", "Distance", "Class", "Time", "Room"}, new String[] {"left", "left", "left", "left", "left", "left"}, null); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Iterator i=report.getGroups().iterator();i.hasNext();idx++) { DiscouragedInstructorBtbReport.DiscouragedBtb g = (DiscouragedInstructorBtbReport.DiscouragedBtb)i.next(); StringBuffer rSB = new StringBuffer(); for (int j=0;j<g.getFirst().getRoom().length;j++) rSB.append((j>0?", ":"")+(noHtml?g.getFirst().getRoom()[j].getName():g.getFirst().getRoom()[j].toHtml(false,false))); rSB.append(noHtml?"\n":"<BR>"); for (int j=0;j<g.getSecond().getRoom().length;j++) rSB.append((j>0?", ":"")+(noHtml?g.getSecond().getRoom()[j].getName():g.getSecond().getRoom()[j].toHtml(false,false))); webTable.addLine(null, new String[] { g.getInstructorName(), (noHtml?"":"<font color='"+PreferenceLevel.prolog2color(g.getPreference())+"'>")+ PreferenceLevel.getPreferenceLevel(g.getPreference()).getPrefName()+ (noHtml?"":"</font>"), String.valueOf(Math.round(g.getDistance()*10.0))+"m", (noHtml?g.getFirst().getClazz().getName()+"\n"+g.getSecond().getClazz().getName(): g.getFirst().getClazz().toHtml(true,true)+"<BR>"+g.getSecond().getClazz().toHtml(true,true)), (noHtml?g.getFirst().getTime().getName(true)+"\n"+g.getSecond().getTime().getName(true): g.getFirst().getTime().toHtml(false,false,true)+"<BR>"+g.getSecond().getTime().toHtml(false,false,true)), rSB.toString() }, new Comparable[] { g.getInstructorName(), g.getPreference(), new Double(g.getDistance()), new DuoComparable(g.getFirst(),g.getSecond()), null, null }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable; } public PdfWebTable getStudentConflictsReportTable(HttpServletRequest request, StudentConflictsReport report, boolean noHtml) { WebTable.setOrder(request.getSession(),"solutionReports.studConf.ord",request.getParameter("studconf_ord"),-1); PdfWebTable webTable = new PdfWebTable( 8, "Student Conflicts", "solutionReport.do?studconf_ord=%%", new String[] {"NrConflicts", "Class", "Time", "Room", "Hard", "Distance", "Fixed", "Commited"}, new String[] {"left", "left", "left", "left", "left", "left","left","left"}, null); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Iterator i=report.getGroups().iterator();i.hasNext();idx++) { JenrlInfo g = (JenrlInfo)i.next(); StringBuffer rSB = new StringBuffer(); for (int j=0;j<g.getFirst().getRoom().length;j++) rSB.append((j>0?", ":"")+(noHtml?g.getFirst().getRoom()[j].getName():g.getFirst().getRoom()[j].toHtml(false,false))); rSB.append(noHtml?"\n":"<BR>"); for (int j=0;j<g.getSecond().getRoom().length;j++) rSB.append((j>0?", ":"")+(noHtml?g.getSecond().getRoom()[j].getName():g.getSecond().getRoom()[j].toHtml(false,false))); webTable.addLine(null, new String[] { String.valueOf(Math.round(g.getJenrl())), (noHtml?g.getFirst().getClazz().getName()+"\n"+g.getSecond().getClazz().getName(): g.getFirst().getClazz().toHtml(true,true)+"<BR>"+g.getSecond().getClazz().toHtml(!g.isCommited(),true)), (noHtml?g.getFirst().getTime().getName(true)+"\n"+g.getSecond().getTime().getName(true): g.getFirst().getTime().toHtml(false,false,true)+"<BR>"+g.getSecond().getTime().toHtml(false,false,true)), rSB.toString(), (noHtml?(g.isHard()?"true":""):g.isHard()?"<img src='images/checkmark.gif' border='0'/>":""), (g.isDistance()?String.valueOf(Math.round(10.0*g.getDistance()))+"m":""), (noHtml?(g.isFixed()?"true":""):g.isFixed()?"<img src='images/checkmark.gif' border='0'/>":""), (noHtml?(g.isCommited()?"true":""):g.isCommited()?"<img src='images/checkmark.gif' border='0'/>":"") }, new Comparable[] { new Double(g.getJenrl()), new DuoComparable(g.getFirst(),g.getSecond()), null, null, new Integer(g.isHard()?1:0), new Double(g.getDistance()), new Integer(g.isFixed()?1:0), new Integer(g.isCommited()?1:0) }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable; } public PdfWebTable getSameSubpartBalancingReportTable(HttpServletRequest request, SameSubpartBalancingReport report, boolean noHtml) { WebTable.setOrder(request.getSession(),"solutionReports.sectBalancingReport.ord",request.getParameter("sect_ord"),1); String[] header = new String[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; String[] pos = new String[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; header[0]="Department"; pos[0]="left"; header[1]="Penalty"; pos[1]="center"; for (int i=0;i<Constants.SLOTS_PER_DAY_NO_EVENINGS/6;i++) { header[i+2]=Constants.slot2str(Constants.DAY_SLOTS_FIRST + i*6); pos[i+2]="center"; } PdfWebTable webTable = new PdfWebTable( header.length, "Section Balancing", "solutionReport.do?sect_ord=%%", header, pos, null); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Iterator it=report.getGroups().iterator();it.hasNext();idx++) { SameSubpartBalancingReport.SameSubpartBalancingGroup g = (SameSubpartBalancingReport.SameSubpartBalancingGroup)it.next(); String[] line = new String[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; Comparable[] cmp = new Comparable[2+Constants.SLOTS_PER_DAY_NO_EVENINGS/6]; line[0]=g.getName(); cmp[0]=g.getName(); int penalty = 0; for (int i=0;i<Constants.SLOTS_PER_DAY_NO_EVENINGS/6;i++) { int slot = Constants.DAY_SLOTS_FIRST + i*6; int usage = g.getUsage(slot); int limit = g.getLimit(slot); if (usage>limit) penalty += g.getExcess(slot); Vector classes = new Vector(g.getClasses(slot)); Collections.sort(classes); StringBuffer sb = new StringBuffer(); StringBuffer toolTip = new StringBuffer(); int u = 0; boolean over = false; for (Enumeration e=classes.elements();e.hasMoreElements();) { ClassAssignmentDetails ca = (ClassAssignmentDetails)e.nextElement(); int nrMeetings = 0; for (int j=0;j<Constants.NR_DAYS_WEEK;j++) if ((Constants.DAY_CODES[j]&ca.getTime().getDays())!=0) nrMeetings++; u+=nrMeetings; if (u>limit && !over) { over=true; sb.append(noHtml?"\n":"<hr>"); } sb.append(noHtml?ca.getClazz().getName():ca.getClazz().toHtml(true,true));//+" ("+nrMeetings+"x"+ca.getTime().getMin()+")"); if (e.hasMoreElements()) sb.append(noHtml?"\n":"<br>"); toolTip.append(ca.getClassName()); if (e.hasMoreElements()) toolTip.append(", "); } if (noHtml) { line[i+2]=usage+" / "+limit; line[i+2]+=(classes.isEmpty()?"":"\n"+sb.toString()); } else { line[i+2]="<a title='"+toolTip+"'>"+(limit==0?"":(usage>limit?"<font color='red'>":"")+usage+" / "+limit+(usage>limit?"</font>":""))+"</a>"; line[i+2]+=(classes.isEmpty()?"":"<br>"+sb.toString()); } cmp[i+2]=new Integer(usage*1000+limit); } line[1]=(noHtml?""+penalty:(penalty==0?"":"<font color='red'>+"+penalty+"</font>")); cmp[1]=new Integer(penalty); webTable.addLine(null,line,cmp); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable; } private String disp(long value, boolean noHtml) { if (value==0) return ""; return (noHtml?ClassAssignmentDetails.dispNumberNoHtml(value):ClassAssignmentDetails.dispNumber(value)); //return String.valueOf(value); } private String disp(double value, boolean noHtml) { if (value==0) return ""; return (noHtml?ClassAssignmentDetails.dispNumberNoHtml(value):ClassAssignmentDetails.dispNumber(value)); //return sDoubleFormat.format(value); } public PdfWebTable getPerturbationReportTable(HttpServletRequest request, PerturbationReport report, boolean noHtml) { WebTable.setOrder(request.getSession(),"solutionReports.pert.ord",request.getParameter("pert_ord"),1); PdfWebTable webTable = new PdfWebTable( 24, "Perturbations", "solutionReport.do?pert_ord=%%", new String[] {"Class", "Time", "Room", "Dist", "St", "StT", "StR", "StB", "Ins", "InsT", "InsR", "InsB", "Rm", "Bld", "Tm", "Day", "Hr", "TFSt", "TFIns", "DStC", "NStC", "DTPr", "DRPr", "DInsB"}, new String[] {"left", "left", "left", "left", "left", "left","left","left","left", "left", "left", "left", "left", "left","left","left","left", "left", "left", "left", "left", "left","left","left"}, null); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Iterator i=report.getGroups().iterator();i.hasNext();idx++) { PerturbationReport.PerturbationGroup g = (PerturbationReport.PerturbationGroup)i.next(); webTable.addLine(null, new String[] { (noHtml?g.getClazz().getClazz().getName():g.getClazz().getClazz().toHtml(true, true)), (noHtml?g.getClazz().getTimeNoHtml():g.getClazz().getTimeHtml()), (noHtml?g.getClazz().getRoomNoHtml():g.getClazz().getRoomHtml()), (Math.round(10.0*g.distance)>0?Math.round(10.0*g.distance)+"m":""), disp(g.affectedStudents, noHtml), disp(g.affectedStudentsByTime, noHtml), disp(g.affectedStudentsByRoom, noHtml), disp(g.affectedStudentsByBldg, noHtml), disp(g.affectedInstructors, noHtml), disp(g.affectedInstructorsByTime, noHtml), disp(g.affectedInstructorsByRoom, noHtml), disp(g.affectedInstructorsByBldg, noHtml), disp(g.differentRoom, noHtml), disp(g.differentBuilding, noHtml), disp(g.differentTime, noHtml), disp(g.differentDay, noHtml), disp(g.differentHour, noHtml), disp(g.tooFarForStudents, noHtml), disp(g.tooFarForInstructors, noHtml), disp(g.deltaStudentConflicts, noHtml), disp(g.newStudentConflicts, noHtml), disp(Math.round(g.deltaTimePreferences), noHtml), disp(g.deltaRoomPreferences, noHtml), disp(g.deltaInstructorDistancePreferences, noHtml) }, new Comparable[] { g.getClazz(), g.getClazz().getTimeName(), g.getClazz().getRoomName(), new Double(g.distance), new Long(g.affectedStudents), new Long(g.affectedStudentsByTime), new Long(g.affectedStudentsByRoom), new Long(g.affectedStudentsByBldg), new Integer(g.affectedInstructors), new Integer(g.affectedInstructorsByTime), new Integer(g.affectedInstructorsByRoom), new Integer(g.affectedInstructorsByBldg), new Integer(g.differentRoom), new Integer(g.differentBuilding), new Integer(g.differentTime), new Integer(g.differentDay), new Integer(g.differentHour), new Integer(g.tooFarForStudents), new Integer(g.tooFarForInstructors), new Integer(g.deltaStudentConflicts), new Integer(g.newStudentConflicts), new Double(g.deltaTimePreferences), new Integer(g.deltaRoomPreferences), new Integer(g.deltaInstructorDistancePreferences) }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable; } public static class DuoComparable implements Comparable { private Comparable iA = null, iB = null; public DuoComparable(Comparable a, Comparable b) { iA = a; iB = b; } public int compareTo(Object o) { if (o==null || !(o instanceof DuoComparable)) return -1; DuoComparable d = (DuoComparable)o; int cmp = iA.compareTo(d.iA); if (cmp!=0) return cmp; return iB.compareTo(d.iB); } } public static class MultiComparable implements Comparable { private Vector iX = new Vector(); public MultiComparable() {} public void add(Comparable x) { iX.addElement(x); } public int compareTo(Object o) { if (o==null || !(o instanceof MultiComparable)) return -1; MultiComparable m = (MultiComparable)o; Enumeration e1 = iX.elements(); Enumeration e2 = m.iX.elements(); while (e1.hasMoreElements() && e2.hasMoreElements()) { int cmp = ((Comparable)e1.nextElement()).compareTo((Comparable)e2.nextElement()); if (cmp!=0) return cmp; } return Double.compare(e1.hasMoreElements()?1:0,e2.hasMoreElements()?1:0); } } }
// JSON.java package ed.js; import java.util.*; import org.mozilla.javascript.*; import ed.js.func.*; import ed.js.engine.*; public class JSON { static Set<String> IGNORE_NAMES = new HashSet<String>(); static { IGNORE_NAMES.add( "_save" ); IGNORE_NAMES.add( "_update" ); IGNORE_NAMES.add( "_ns" ); } public static void init( Scope s ){ s.put( "tojson" , new JSFunctionCalls1(){ public Object call( Scope s , Object o , Object foo[] ){ return serialize( o , true ); } } , true ); s.put( "tojson_u" , new JSFunctionCalls1(){ public Object call( Scope s , Object o , Object foo[] ){ return serialize( o , false ); } } , true ); s.put( "fromjson" , new JSFunctionCalls1(){ public Object call( Scope s , Object o , Object foo[] ){ return parse( o.toString() ); } } , true ); } public static String serialize( Object o ){ // Backwards compatibility return serialize( o, true ); } public static String serialize( Object o , boolean trusted ){ return serialize( o , trusted , "\n" ); } public static String serialize( Object o , boolean trusted , String nl ){ StringBuilder buf = new StringBuilder(); try { serialize( buf , o , trusted , nl ); } catch ( java.io.IOException e ){ throw new RuntimeException( e ); } return buf.toString(); } public static void serialize( Appendable a , Object o , boolean trusted ) throws java.io.IOException { serialize( a , o , trusted , "\n" ); } public static void serialize( Appendable a , Object o , boolean trusted , String nl ) throws java.io.IOException { Serializer.go( a , o , trusted , 0 , nl ); } static class Serializer { static Map<Integer,String> _indents = new HashMap<Integer,String>(); static String _i( final int i ){ String s = _indents.get( i ); if ( s == null ){ s = ""; for ( int j=0; j<i; j++ ) s += " "; _indents.put( i , s ); } return s; } static void string( Appendable a , String s ) throws java.io.IOException { a.append("\""); for(int i = 0; i < s.length(); ++i){ char c = s.charAt(i); if(c == '\\') a.append("\\\\"); else if(c == '"') a.append("\\\""); else if(c == '\n') a.append("\\n"); else if(c == '\r') a.append("\\r"); else if(c == '\t') a.append("\\t"); else a.append(c); } a.append("\""); } static void go( Appendable a , Object something , boolean trusted , int indent , String nl ) throws java.io.IOException { if ( nl.length() > 0 ){ if ( a instanceof StringBuilder ){ StringBuilder sb = (StringBuilder)a; int lastNL = sb.lastIndexOf( nl ); if ( sb.length() - lastNL > 60 ){ a.append( nl ); } } } if ( something == null ){ a.append( "null" ); return; } if ( something instanceof Number || something instanceof Boolean || something instanceof JSRegex ){ a.append( something.toString() ); return; } if ( something instanceof JSDate ){ if ( trusted ) { a.append( "new Date( " + ((JSDate)something)._time + " ) " ); return; } else { a.append( new Long(((JSDate)something)._time).toString() ); return; } } if ( something instanceof JSString || something instanceof String ){ string( a , something.toString() ); return; } if ( something instanceof JSFunction ){ if ( trusted ) { a.append( something.toString() ); return; } throw new java.io.IOException("can't serialize functions in untrusted mode"); } if ( something instanceof ed.db.ObjectId ){ if ( trusted ) { a.append( "ObjectId( \"" + something + "\" )" ); return; } else { string( a , something.toString() ); return; } } if ( ! ( something instanceof JSObject ) ){ a.append( something.toString() ); return; } if ( something instanceof JSArray ){ JSArray arr = (JSArray)something; a.append( "[ " ); for ( int i=0; i<arr._array.size(); i++ ){ if ( i > 0 ) a.append( " , " ); go( a , arr._array.get( i ) , trusted, indent , nl ); } a.append( " ]" ); return; } JSObject o = (JSObject)something; { Object foo = o.get( "tojson" ); if ( foo != null && foo instanceof JSFunction ){ a.append( ((JSFunction)foo).call( Scope.GLOBAL ).toString() ); return; } } a.append( _i( indent ) ); a.append( "{" ); boolean first = true; for ( String s : o.keySet() ){ if ( IGNORE_NAMES.contains( s ) ) continue; Object val = o.get( s ); if ( val instanceof JSObjectBase ){ ((JSObjectBase)val).prefunc(); if ( o.get( s ) == null ) continue; } if ( first ) first = false; else a.append( " ," ); a.append( _i( indent + 1 ) ); string( a , s ); a.append( " : " ); go( a , val , trusted , indent + 1 , nl ); } a.append( _i( indent + 1 ) ); a.append( " }\n" ); } } public static Object parse( String s ){ CompilerEnvirons ce = new CompilerEnvirons(); Parser p = new Parser( ce , ce.getErrorReporter() ); s = "return " + s.trim() + ";"; ScriptOrFnNode theNode = p.parse( s , "foo" , 0 ); Node ret = theNode.getFirstChild(); Convert._assertType( ret , Token.RETURN ); Convert._assertOne( ret ); Node lit = ret.getFirstChild(); if ( lit.getType() != Token.OBJECTLIT && lit.getType() != Token.ARRAYLIT ){ Debug.printTree( lit , 0 ); throw new JSException( "not a literal" ); } return build( lit ); } private static Object build( Node n ){ if ( n == null ) return null; Node c; switch ( n.getType() ){ case Token.OBJECTLIT: JSObject o = new JSObjectBase(); Object[] names = (Object[])n.getProp( Node.OBJECT_IDS_PROP ); int i=0; c = n.getFirstChild(); while ( c != null ){ o.set( names[i++].toString() , build( c ) ); c = c.getNext(); } return o; case Token.ARRAYLIT: JSArray a = new JSArray(); c = n.getFirstChild(); while ( c != null ){ a.add( build( c ) ); c = c.getNext(); } return a; case Token.NUMBER: double d = n.getDouble(); if ( JSNumericFunctions.couldBeInt( d ) ) return (int)d; return d; case Token.STRING: return new JSString( n.getString() ); } Debug.printTree( n , 0 ); throw new RuntimeException( "what: " + n.getType() ); } }
package common; import java.math.BigInteger; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.ArrayList; import java.util.Collection; /** * <p>Generates combinations of the elements in a given combination supplied to the constructor.</p> * @author fiveham * @author fiveham * * @param <T> the type of the elements in the combinations that this * @param <T> the type of the elements in the combinations that this @param <T> the type of the * @param <T> the type of the elements in the combinations that this elements in the combinations * @param <T> the type of the elements in the combinations that this that this class produces */ public class ComboGen<T> implements Iterable<List<T>>{ /** * <p>The minimum possible size ({@value}) of a combination.</p> */ public static final int MIN_COMBO_SIZE = 0; /** * <p>The internal list from which elements are chosen for the combinations this class * produces.</p> */ private final List<T> source; private final int minSize; private final int maxSize; /** * <p>Constructs a ComboGen that produces combinations of elements from {@code source} that have * a size at least {@value #MIN_COMBO_SIZE} and at most {@code source.size()}.</p> * @param source a collection of elements combinations of which are produced by this ComboGen */ public ComboGen(Collection<? extends T> source, int minSize, int maxSize){ this.source = new ArrayList<>(source); if(minSize < 0){ throw new IllegalArgumentException("minSize " + minSize + " < 0"); } else if(maxSize < 0){ throw new IllegalArgumentException("maxSize " + maxSize + " < 0"); } this.minSize = minSize < MIN_COMBO_SIZE ? MIN_COMBO_SIZE : minSize; this.maxSize = maxSize > this.source.size() ? this.source.size() : maxSize; } public ComboGen(Collection<? extends T> source, int minSize){ this(source, minSize, source.size()); } public ComboGen(Collection<? extends T> source){ this(source, MIN_COMBO_SIZE, source.size()); } /** * <p>Returns an IsoIterator wrapping this ComboGen's normal iterator, allowing elements from * the underlying element pool to be excluded from combos produced by subsequent calls to * {@code next()}.</p> * @return an IsoIterator wrapping this ComboGen's normal iterator */ @Override public IsoIterator<T> iterator(){ return new IsoIterator<>(new ComboIterator()); } /** * <p>A combination-navigating iterator for this ComboGen's underlying collection.</p> * <p>Produces collections of varying sizes from this ComboGen's underlying collection, starting * from a size of minMag and increasing to maxMag.</p> */ private class ComboIterator implements Iterator<List<T>>{ private int size; private BigInteger combo; private ComboIterator(){ this.size = minSize; if(sizeInRange()){ this.combo = firstCombo(size); } } @Override public boolean hasNext(){ return sizeInRange(); } private boolean sizeInRange(){ return minSize <= size && size <= maxSize; } @Override public List<T> next(){ if(!sizeInRange()){ throw new NoSuchElementException(); } List<T> result = genComboList(combo); updatePosition(); return result; } private List<T> genComboList(BigInteger combo){ List<T> result = new ArrayList<>(size); for(int i=0; i<source.size(); ++i){ if(combo.testBit(i)){ result.add(source.get(i)); } } return result; } private void updatePosition(){ if(finalCombo(size).equals(combo)){ //maximum lateral position at this height size++; //move to next height if(size <= maxSize){ combo = firstCombo(size); } } else{ //nonmaximum lateral position. proceed to next lateral position combo = comboAfter(combo); } } /** * <p>Returns a BigInteger {@link #genComboList(BigInteger) pointing} to the first * {@code size} elements from {@code list}.</p> * @param size the size of the combo whose backing bitstring is returned * @return a BigInteger {@link #genComboList(BigInteger) pointing} to the first {@code size} * elements from {@code list} */ private BigInteger finalCombo(int size){ return leastCombo(size); } private BigInteger leastCombo(int size){ if(leastComboCache.containsKey(size)){ return leastComboCache.get(size); } BigInteger result = BigInteger.ZERO; for(int i=0; i < size; ++i){ result = result.setBit(i); } leastComboCache.put(size, result); return result; } private final Map<Integer,BigInteger> leastComboCache = new HashMap<>(); /** * <p>Returns a BigInteger {@link #genComboList(BigInteger) pointing} to the last * {@code size} elements from {@code list}.</p> * @param size the size of the combo whose backing bitstring is returned * @return a BigInteger {@link #genComboList(BigInteger) pointing} to the last {@code size} * elements from {@code list} */ private BigInteger firstCombo(int size){ return greatestCombo(size); } /** * </p>Returns a BigInteger having the greatest numerical value of any BigInteger * {@link #genComboList(BigInteger) pointing} to a combination of the current size. The * value returned is equal to {@code (2^(size+1) - 1) * 2^(source.size() - size)}, which * equals {@code 2^(source.size()+1) - 2^(source.size() - size)}.</p> * @param size the number of set bits in the BigIteger returned * @return a BigInteger having the greatest numerical value of any BigInteger * {@link #genComboList(BigInteger) pointing} to a combination of the current size */ private BigInteger greatestCombo(int size){ if(greatestComboCache.containsKey(size)){ return greatestComboCache.get(size); } BigInteger result = BigInteger.ZERO; for(int i=source.size()-size; i < source.size(); ++i){ result = result.setBit(i); } greatestComboCache.put(size, result); return result; } private final Map<Integer,BigInteger> greatestComboCache = new HashMap<>(); /** * <p>This implementation, which pulls ones down to lower indices, is tied to the fact that the * first combo is the greatest value and the final combo is the least value. If that * relationship between combo precedence and the numerical size of the combo ever changes, this * method needs to be adapted to the new relationship.</p> * <p>The combo after a given combo is determined by moving the lowest-indexed movable set bit * to an index lower by 1. A set bit is movable if the bit at index 1 lower than the movable bit * is 0.</p> * @param combo a BigInteger whose bits encode a combination of the elements pertaining to this * ComboGen * @return a BigInteger encoding the combination after {@code combo} */ private BigInteger comboAfter(BigInteger combo){ int swapIndex = lowerableOne(combo); int onesBelow = bitsSetToTheRight(swapIndex, combo); //swap the 1 with the 0 to the right of it BigInteger result = combo.clearBit(swapIndex); swapIndex result = result.setBit(swapIndex); swapIndex //move all the 1s from the right of the swapped 0 to a position immediately to the right of //the swapped 0's initial position for(int onesSet = 0; onesSet < onesBelow; ++onesSet){ result = result.setBit(swapIndex); swapIndex } //fill the space between the rightmost moved 1 and the ones' place of the BigInteger with 0s while(swapIndex >= 0){ result = result.clearBit(swapIndex); swapIndex } return result; } /** * <p>Returns the lowest index in {@code combo} of a {@link BigInteger#testBit(int) 1} such * that the bit at the next lower index is 0. If no such bit exists in {@code combo}, then * {@code source.size()} is returned.</p> * @param combo the combo whose lowest-index 1 with a 0 immediately below it (in terms of * index) is returned * @return the lowest index in {@code combo} of a {@link BigInteger#testBit(int) 1} such * that the bit at the next lower index is 0, or {@code source.size()} if no such bit exists * in {@code combo} */ private int lowerableOne(BigInteger combo){ int i = 0; for(; i < source.size() - 1; ++i){ if(!combo.testBit(i) && combo.testBit(i + 1)){ break; } } return i + 1; } /** * <p>Returns the number of 1s in {@code combo} at indices less than {@code swapIndex}.</p> * @param swapIndex the index in {@code combo} below which 1s are counted * @param combo the BigInteger from which 1s are counted * @return the number of 1s in {@code combo} at indices less than */ private int bitsSetToTheRight(int swapIndex, BigInteger combo){ int result = 0; for(int i=swapIndex - 1; i >= 0; --i){ if(combo.testBit(i)){ ++result; } } return result; } } }
package info.justaway; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.text.Editable; import android.text.TextWatcher; import android.util.TypedValue; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import butterknife.OnItemClick; import butterknife.OnLongClick; import de.greenrobot.event.EventBus; import info.justaway.adapter.UserSearchAdapter; import info.justaway.adapter.main.AccessTokenAdapter; import info.justaway.adapter.main.MainPagerAdapter; import info.justaway.event.AlertDialogEvent; import info.justaway.event.NewRecordEvent; import info.justaway.event.action.AccountChangeEvent; import info.justaway.event.action.GoToTopEvent; import info.justaway.event.action.OpenEditorEvent; import info.justaway.event.action.PostAccountChangeEvent; import info.justaway.event.connection.StreamingConnectionEvent; import info.justaway.fragment.main.StreamingSwitchDialogFragment; import info.justaway.fragment.main.tab.BaseFragment; import info.justaway.fragment.main.tab.DirectMessagesFragment; import info.justaway.fragment.main.tab.InteractionsFragment; import info.justaway.fragment.main.tab.TimelineFragment; import info.justaway.fragment.main.tab.UserListFragment; import info.justaway.task.SendDirectMessageTask; import info.justaway.task.UpdateStatusTask; import info.justaway.util.TwitterUtil; import info.justaway.widget.AutoCompleteEditText; import info.justaway.widget.JustawayButton; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterException; import twitter4j.auth.AccessToken; @SuppressLint("InflateParams") @SuppressWarnings("MagicConstant") public class MainActivity extends FragmentActivity { private static final int REQUEST_ACCOUNT_SETTING = 200; private static final int REQUEST_SETTINGS = 300; private static final int REQUEST_TAB_SETTINGS = 400; private static final int ERROR_CODE_DUPLICATE_STATUS = 187; private static final long TAB_ID_TIMELINE = -1L; private static final long TAB_ID_INTERACTIONS = -2L; private static final long TAB_ID_DIRECT_MESSAGE = -3L; private static final Pattern USER_LIST_PATTERN = Pattern.compile("^(@[a-zA-Z0-9_]+)/(.*)$"); private JustawayApplication mApplication; private MainPagerAdapter mMainPagerAdapter; private ViewPager mViewPager; private Status mInReplyToStatus; private ActionBarDrawerToggle mDrawerToggle; private Activity mActivity; private AccessTokenAdapter mAccessTokenAdapter; private AccessToken mSwitchAccessToken; private boolean mFirstBoot = true; private UserSearchAdapter mUserSearchAdapter; private int mDefaultTextColor; private int mDisabledTextColor; private ActionBarHolder mActionBarHolder; @InjectView(R.id.drawer_layout) DrawerLayout mDrawerLayout; @InjectView(R.id.quick_tweet_layout) LinearLayout mQuickTweetLayout; @InjectView(R.id.tab_menus) LinearLayout mTabMenus; @InjectView(R.id.main) LinearLayout mContainer; @InjectView(R.id.account_list) ListView mDrawerList; @InjectView(R.id.send_button) TextView mSendButton; @InjectView(R.id.post_button) Button mPostButton; @InjectView(R.id.quick_tweet_edit) EditText mQuickTweetEdit; /** * ButterKnife for ActionBar */ class ActionBarHolder { @InjectView(R.id.action_bar_title) TextView title; @InjectView(R.id.action_bar_sub_title) TextView subTitle; @InjectView(R.id.action_bar_normal_layout) LinearLayout normalLayout; @InjectView(R.id.action_bar_search_layout) FrameLayout searchLayout; @InjectView(R.id.action_bar_search_text) AutoCompleteEditText searchText; @InjectView(R.id.action_bar_search_button) TextView searchButton; @InjectView(R.id.action_bar_search_cancel) TextView cancelButton; @InjectView(R.id.action_bar_streaming_button) TextView streamingButton; @OnClick(R.id.action_bar_search_button) void actionBarSearchButton() { startSearch(); } @OnClick(R.id.action_bar_search_cancel) void actionBarCancelButton() { cancelSearch(); } @OnClick(R.id.action_bar_streaming_button) void actionBarToggleStreaming() { final boolean turnOn = !mApplication.getStreamingMode(); DialogFragment dialog = StreamingSwitchDialogFragment.newInstance(turnOn); dialog.show(getSupportFragmentManager(), "dialog"); } public ActionBarHolder(View view) { ButterKnife.inject(this, view); } } /** * ButterKnife for Drawer */ class DrawerHolder { @OnClick(R.id.account_settings) void openAccountSettings() { Intent intent = new Intent(MainActivity.this, AccountSettingActivity.class); startActivityForResult(intent, REQUEST_ACCOUNT_SETTING); } public DrawerHolder(View view) { ButterKnife.inject(this, view); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApplication = JustawayApplication.getApplication(); mApplication.setTheme(this); mActivity = this; if (!mApplication.hasAccessToken()) { Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); finish(); return; } mDefaultTextColor = mApplication.getThemeTextColor(this, R.attr.menu_text_color); mDisabledTextColor = mApplication.getThemeTextColor(this, R.attr.menu_text_color_disabled); /** * ActionBar */ ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); int options = actionBar.getDisplayOptions(); if ((options & ActionBar.DISPLAY_SHOW_CUSTOM) == ActionBar.DISPLAY_SHOW_CUSTOM) { actionBar.setDisplayOptions(options ^ ActionBar.DISPLAY_SHOW_CUSTOM); } else { actionBar.setDisplayOptions(options | ActionBar.DISPLAY_SHOW_CUSTOM); if (actionBar.getCustomView() == null) { actionBar.setCustomView(R.layout.action_bar_main); mActionBarHolder = new ActionBarHolder(actionBar.getCustomView()); mUserSearchAdapter = new UserSearchAdapter(this, R.layout.row_auto_complete); mActionBarHolder.searchText.setThreshold(0); mActionBarHolder.searchText.setAdapter(mUserSearchAdapter); mActionBarHolder.searchText.setOnItemClickListener(getActionBarAutoCompleteOnClickListener()); } } } setContentView(R.layout.activity_main); ButterKnife.inject(this); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); mContainer.requestFocus(); mAccessTokenAdapter = new AccessTokenAdapter(this, R.layout.row_switch_account, mApplication.getThemeTextColor(mActivity, R.attr.holo_blue), mApplication.getThemeTextColor(mActivity, R.attr.text_color)); View drawerFooterView = getLayoutInflater().inflate(R.layout.drawer_menu, null, false); new DrawerHolder(drawerFooterView); mDrawerList.addFooterView(drawerFooterView, null, true); mDrawerList.setAdapter(mAccessTokenAdapter); mDrawerToggle = getActionBarDrawerToggle(); mDrawerLayout.setDrawerListener(mDrawerToggle); setup(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } @Override protected void onStart() { super.onStart(); MyUncaughtExceptionHandler.showBugReportDialogIfExist(this); if (mApplication.getKeepScreenOn()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_TAB_SETTINGS: if (resultCode == RESULT_OK) { setupTab(); } break; case REQUEST_ACCOUNT_SETTING: if (resultCode == RESULT_OK) { mSwitchAccessToken = (AccessToken) data.getSerializableExtra("accessToken"); } if (mAccessTokenAdapter != null) { mAccessTokenAdapter.clear(); for (AccessToken accessToken : mApplication.getAccessTokens()) { mAccessTokenAdapter.add(accessToken); } } break; case REQUEST_SETTINGS: if (resultCode == RESULT_OK) { mApplication.resetDisplaySettings(); finish(); startActivity(new Intent(this, this.getClass())); } break; default: break; } } @Override protected void onResume() { super.onResume(); EventBus.getDefault().register(this); } @Override protected void onPostResume() { super.onPostResume(); if (mFirstBoot) { mFirstBoot = false; return; } mApplication.resetDisplaySettings(); mApplication.resetNotification(); new Handler().postDelayed(new Runnable() { @Override public void run() { // fav/RT try { mMainPagerAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } }, 1000); if (mSwitchAccessToken != null) { mApplication.switchAccessToken(mSwitchAccessToken); mSwitchAccessToken = null; } mApplication.resumeStreaming(); if (mApplication.getTwitterStreamConnected()) { mApplication.setThemeTextColor(this, mActionBarHolder.streamingButton, R.attr.holo_green); } else { if (mApplication.getStreamingMode()) { mApplication.setThemeTextColor(this, mActionBarHolder.streamingButton, R.attr.holo_red); } else { mActionBarHolder.streamingButton.setTextColor(Color.WHITE); } } } @Override protected void onPause() { mApplication.pauseStreaming(); EventBus.getDefault().unregister(this); super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); } /** * finish * moveTaskToBack */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (mQuickTweetEdit.getText() != null && mQuickTweetEdit.getText().length() > 0) { mQuickTweetEdit.setText(""); mInReplyToStatus = null; return false; } finish(); } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } Intent intent; switch (itemId) { case android.R.id.home: cancelSearch(); break; case R.id.profile: intent = new Intent(this, ProfileActivity.class); intent.putExtra("userId", mApplication.getUserId()); startActivity(intent); break; case R.id.tab_settings: intent = new Intent(this, TabSettingsActivity.class); startActivityForResult(intent, REQUEST_TAB_SETTINGS); break; case R.id.action_bar_search_button: intent = new Intent(this, SearchActivity.class); startActivity(intent); break; case R.id.settings: intent = new Intent(this, SettingsActivity.class); startActivityForResult(intent, REQUEST_SETTINGS); break; case R.id.official_website: intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.official_website))); startActivity(intent); break; case R.id.feedback: EventBus.getDefault().post(new OpenEditorEvent(" #justaway", null, null, null)); break; } return true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("signalButtonColor", mActionBarHolder.streamingButton.getCurrentTextColor()); LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); int count = tab_menus.getChildCount(); final int tabColors[] = new int[count]; for (int i = 0; i < count; i++) { Button button = (Button) tab_menus.getChildAt(i); if (button == null) { continue; } tabColors[i] = button.getCurrentTextColor(); } outState.putIntArray("tabColors", tabColors); } @SuppressWarnings("NullableProblems") @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mActionBarHolder.streamingButton.setTextColor(savedInstanceState.getInt("signalButtonColor")); final int[] tabColors = savedInstanceState.getIntArray("tabColors"); assert tabColors != null; LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); int count = Math.min(tab_menus.getChildCount(), tabColors.length); for (int i = 0; i < count; i++) { Button button = (Button) tab_menus.getChildAt(i); if (button == null) { continue; } button.setTextColor(tabColors[i]); } } /** * ActionBarCustomView */ @Override public void setTitle(CharSequence title) { if (mActionBarHolder.title != null) { Matcher matcher = USER_LIST_PATTERN.matcher(title); if (matcher.find()) { mActionBarHolder.title.setText(matcher.group(2)); mActionBarHolder.subTitle.setText(matcher.group(1)); } else { mActionBarHolder.title.setText(title); mActionBarHolder.subTitle.setText("@" + mApplication.getScreenName()); } } } @Override public void setTitle(int titleId) { setTitle(getString(titleId)); } public void showQuickPanel() { mQuickTweetLayout.setVisibility(View.VISIBLE); mQuickTweetEdit.setFocusable(true); mQuickTweetEdit.setFocusableInTouchMode(true); mQuickTweetEdit.setEnabled(true); mApplication.setQuickMod(true); } public void hideQuickPanel() { mQuickTweetEdit.setFocusable(false); mQuickTweetEdit.setFocusableInTouchMode(false); mQuickTweetEdit.setEnabled(false); mQuickTweetEdit.clearFocus(); mQuickTweetLayout.setVisibility(View.GONE); mInReplyToStatus = null; mApplication.setQuickMod(false); } public void setupTab() { ArrayList<JustawayApplication.Tab> tabs = mApplication.loadTabs(); if (tabs.size() > 0) { TypedValue outValueTextColor = new TypedValue(); TypedValue outValueBackground = new TypedValue(); Resources.Theme theme = getTheme(); if (theme != null) { theme.resolveAttribute(R.attr.menu_text_color, outValueTextColor, true); theme.resolveAttribute(R.attr.button_stateful, outValueBackground, true); } mTabMenus.removeAllViews(); mMainPagerAdapter.clearTab(); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( (int) (60 * getResources().getDisplayMetrics().density + 0.5f), LinearLayout.LayoutParams.WRAP_CONTENT); int position = 0; for (JustawayApplication.Tab tab : tabs) { Button button = new JustawayButton(this); button.setLayoutParams(layoutParams); button.setText(tab.getIcon()); button.setTextSize(22); button.setTextColor(outValueTextColor.data); button.setBackgroundResource(outValueBackground.resourceId); button.setTag(position++); button.setOnClickListener(mMenuOnClickListener); button.setOnLongClickListener(mMenuOnLongClickListener); mTabMenus.addView(button); if (tab.id == TAB_ID_TIMELINE) { mMainPagerAdapter.addTab(TimelineFragment.class, null, tab.getName(), tab.id); } else if (tab.id == TAB_ID_INTERACTIONS) { mMainPagerAdapter.addTab(InteractionsFragment.class, null, tab.getName(), tab.id); } else if (tab.id == TAB_ID_DIRECT_MESSAGE) { mMainPagerAdapter.addTab(DirectMessagesFragment.class, null, tab.getName(), tab.id); } else { Bundle args = new Bundle(); args.putLong("userListId", tab.id); mMainPagerAdapter.addTab(UserListFragment.class, args, tab.getName(), tab.id); } } mMainPagerAdapter.notifyDataSetChanged(); int currentPosition = mViewPager.getCurrentItem(); Button button = (Button) mTabMenus.getChildAt(currentPosition); if (button != null) { button.setSelected(true); } setTitle(mMainPagerAdapter.getPageTitle(currentPosition)); } } private View.OnClickListener mMenuOnClickListener = new View.OnClickListener() { @Override public void onClick(View view) { int position = (Integer) view.getTag(); BaseFragment f = mMainPagerAdapter.findFragmentByPosition(position); if (f == null) { return; } int id = mViewPager.getCurrentItem(); if (id != position) { mViewPager.setCurrentItem(position); if (f.isTop()) { showTopView(); } } else { if (f.goToTop()) { showTopView(); } } } }; private View.OnLongClickListener mMenuOnLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { int position = (Integer) view.getTag(); BaseFragment f = mMainPagerAdapter.findFragmentByPosition(position); if (f == null) { return false; } f.reload(); return true; } }; private void setup() { mViewPager = (ViewPager) findViewById(R.id.pager); mMainPagerAdapter = new MainPagerAdapter(this, mViewPager); setupTab(); findViewById(R.id.footer).setVisibility(View.VISIBLE); /** * View * * 1 */ mViewPager.setOffscreenPageLimit(10); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { BaseFragment f = mMainPagerAdapter.findFragmentByPosition(position); if (f.isTop()) { showTopView(); } LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); int count = tab_menus.getChildCount(); for (int i = 0; i < count; i++) { Button button = (Button) tab_menus.getChildAt(i); if (button == null) { continue; } if (i == position) { button.setSelected(true); } else { button.setSelected(false); } } setTitle(mMainPagerAdapter.getPageTitle(position)); } }); mQuickTweetEdit.addTextChangedListener(mQuickTweetTextWatcher); if (mApplication.getQuickMode()) { showQuickPanel(); } if (mApplication.getStreamingMode()) { mApplication.startStreaming(); } } public void showTopView() { LinearLayout tab_menus = (LinearLayout) findViewById(R.id.tab_menus); Button button = (Button) tab_menus.getChildAt(mViewPager.getCurrentItem()); if (button != null) { mApplication.setThemeTextColor(this, button, R.attr.menu_text_color); } } private void startSearch() { mDrawerToggle.setDrawerIndicatorEnabled(false); mActionBarHolder.normalLayout.setVisibility(View.GONE); mActionBarHolder.searchLayout.setVisibility(View.VISIBLE); mActionBarHolder.searchText.showDropDown(); mActionBarHolder.searchText.setText(""); mApplication.showKeyboard(mActionBarHolder.searchText); } private void cancelSearch() { mActionBarHolder.searchText.setText(""); mApplication.hideKeyboard(mActionBarHolder.searchText); mActionBarHolder.searchLayout.setVisibility(View.GONE); mActionBarHolder.normalLayout.setVisibility(View.VISIBLE); mDrawerToggle.setDrawerIndicatorEnabled(true); } @OnItemClick(R.id.account_list) void selectAccount(int position) { if (mAccessTokenAdapter.getCount() <= position) { return; } AccessToken accessToken = mAccessTokenAdapter.getItem(position); if (mApplication.getUserId() != accessToken.getUserId()) { mApplication.switchAccessToken(accessToken); mAccessTokenAdapter.notifyDataSetChanged(); } mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer)); } @OnClick(R.id.send_button) void send() { String msg = mQuickTweetEdit.getText() != null ? mQuickTweetEdit.getText().toString() : null; if (msg != null && msg.length() > 0) { JustawayApplication.showProgressDialog(this, getString(R.string.progress_sending)); if (msg.startsWith("D ")) { SendDirectMessageTask task = new SendDirectMessageTask(null) { @Override protected void onPostExecute(TwitterException e) { JustawayApplication.dismissProgressDialog(); if (e == null) { mQuickTweetEdit.setText(""); } else { JustawayApplication.showToast(R.string.toast_update_status_failure); } } }; task.execute(msg); } else { StatusUpdate statusUpdate = new StatusUpdate(msg); if (mInReplyToStatus != null) { statusUpdate.setInReplyToStatusId(mInReplyToStatus.getId()); mInReplyToStatus = null; } UpdateStatusTask task = new UpdateStatusTask(null) { @Override protected void onPostExecute(TwitterException e) { JustawayApplication.dismissProgressDialog(); if (e == null) { mQuickTweetEdit.setText(""); } else if (e.getErrorCode() == ERROR_CODE_DUPLICATE_STATUS) { JustawayApplication.showToast(getString(R.string.toast_update_status_already)); } else { JustawayApplication.showToast(R.string.toast_update_status_failure); } } }; task.execute(statusUpdate); } } } @OnClick(R.id.post_button) void openPost() { Intent intent = new Intent(this, PostActivity.class); if (mQuickTweetLayout.getVisibility() == View.VISIBLE) { EditText status = (EditText) findViewById(R.id.quick_tweet_edit); if (status == null) { return; } String msg = status.getText() != null ? status.getText().toString() : null; if (msg != null && msg.length() > 0) { intent.putExtra("status", msg); intent.putExtra("selection", msg.length()); if (mInReplyToStatus != null) { intent.putExtra("inReplyToStatus", mInReplyToStatus); } status.setText(""); status.clearFocus(); } } startActivity(intent); } @OnLongClick(R.id.post_button) boolean toggleQuickTweet() { if (mQuickTweetLayout.getVisibility() == View.VISIBLE) { hideQuickPanel(); } else { showQuickPanel(); } return true; } private TextWatcher mQuickTweetTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { int textColor; int length = TwitterUtil.count(charSequence.toString()); // 140 if (length < 0) { textColor = Color.RED; } else if (length == 140) { textColor = mDisabledTextColor; } else { textColor = mDefaultTextColor; } TextView count = ((TextView) findViewById(R.id.count)); count.setTextColor(textColor); count.setText(String.valueOf(length)); if (length < 0 || length == 140) { // 0140 mSendButton.setEnabled(false); } else { mSendButton.setEnabled(true); } } @Override public void afterTextChanged(Editable editable) { } }; private ActionBarDrawerToggle getActionBarDrawerToggle() { int drawer = mApplication.getThemeName().equals("black") ? R.drawable.ic_dark_drawer : R.drawable.ic_dark_drawer; return new ActionBarDrawerToggle( this, mDrawerLayout, drawer, R.string.open, R.string.close) { public void onDrawerClosed(View view) { invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { invalidateOptionsMenu(); } }; } private AdapterView.OnItemClickListener getActionBarAutoCompleteOnClickListener() { return new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (mActionBarHolder.searchText.getText() == null) { return; } Intent intent = null; String searchWord = mActionBarHolder.searchText.getText().toString(); mApplication.hideKeyboard(mActionBarHolder.searchText); if (mUserSearchAdapter.isSavedMode()) { intent = new Intent(mActivity, SearchActivity.class); intent.putExtra("query", searchWord); startActivity(intent); return; } switch (i) { case 0: intent = new Intent(mActivity, SearchActivity.class); intent.putExtra("query", searchWord); break; case 1: intent = new Intent(mActivity, UserSearchActivity.class); intent.putExtra("query", searchWord); break; case 2: intent = new Intent(mActivity, ProfileActivity.class); intent.putExtra("screenName", searchWord); break; } startActivity(intent); } }; } public void onEventMainThread(AlertDialogEvent event) { event.getDialogFragment().show(getSupportFragmentManager(), "dialog"); } @SuppressWarnings("UnusedDeclaration") public void onEventMainThread(GoToTopEvent event) { showTopView(); } /** * PostActivity */ public void onEventMainThread(OpenEditorEvent event) { View singleLineTweet = findViewById(R.id.quick_tweet_layout); if (singleLineTweet != null && singleLineTweet.getVisibility() == View.VISIBLE) { mQuickTweetEdit.setText(event.getText()); if (event.getSelectionStart() != null) { if (event.getSelectionStop() != null) { mQuickTweetEdit.setSelection(event.getSelectionStart(), event.getSelectionStop()); } else { mQuickTweetEdit.setSelection(event.getSelectionStart()); } } mInReplyToStatus = event.getInReplyToStatus(); mApplication.showKeyboard(mQuickTweetEdit); } else { Intent intent = new Intent(this, PostActivity.class); intent.putExtra("status", event.getText()); if (event.getSelectionStart() != null) { intent.putExtra("selection", event.getSelectionStart()); } if (event.getSelectionStop() != null) { intent.putExtra("selection_stop", event.getSelectionStop()); } if (event.getInReplyToStatus() != null) { intent.putExtra("inReplyToStatus", event.getInReplyToStatus()); } startActivity(intent); } } /** * API */ public void onEventMainThread(StreamingConnectionEvent event) { if (mApplication.getStreamingMode()) { switch (event.getStatus()) { case STREAMING_CONNECT: mApplication.setThemeTextColor(this, mActionBarHolder.streamingButton, R.attr.holo_green); break; case STREAMING_CLEANUP: mApplication.setThemeTextColor(this, mActionBarHolder.streamingButton, R.attr.holo_orange); break; case STREAMING_DISCONNECT: mApplication.setThemeTextColor(this, mActionBarHolder.streamingButton, R.attr.holo_red); break; } } else { mActionBarHolder.streamingButton.setTextColor(Color.WHITE); } } @SuppressWarnings("UnusedDeclaration") public void onEventMainThread(AccountChangeEvent event) { if (mAccessTokenAdapter != null) { mAccessTokenAdapter.notifyDataSetChanged(); } setupTab(); mViewPager.setCurrentItem(0); EventBus.getDefault().post(new PostAccountChangeEvent(mMainPagerAdapter.getItemId(mViewPager.getCurrentItem()))); } public void onEventMainThread(NewRecordEvent event) { int position = mMainPagerAdapter.findPositionById(event.getTabId()); if (position < 0) { return; } Button button = (Button) mTabMenus.getChildAt(position); if (button == null) { return; } if (mViewPager.getCurrentItem() == position && event.getAutoScroll()) { mApplication.setThemeTextColor(this, button, R.attr.menu_text_color); } else { mApplication.setThemeTextColor(this, button, R.attr.holo_blue); } } }
// RMG - Reaction Mechanism Generator // RMG Team (rmg_dev@mit.edu) // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. package jing.rxnSys; import jing.rxn.*; import jing.chem.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import jing.chem.Species; import jing.rxn.Reaction; import jing.rxn.Structure; import jing.rxn.TROEReaction; import jing.rxn.ThirdBodyReaction; import jing.param.Global; import jing.param.Pressure; import jing.param.Temperature; import jing.param.ParameterInfor; //## package jing::rxnSys // jing\rxnSys\JDASPK.java //## class JDASPK public class JDASPK extends JDAS { private JDASPK() { super(); } public JDASPK(double p_rtol, double p_atol, int p_parameterInfor, InitialStatus p_initialStatus, int p_index, ValidityTester p_vt, boolean p_autoflag) { super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, p_vt, p_autoflag); } //6/25/08 gmagoon: defined alternate constructor for use with sensitivity analysis (lacks autoflag and validityTester parameters) //6/25/08 gmagoon: set autoflag to be false with this constructor (not used for sensitivity analysis) public JDASPK(double p_rtol, double p_atol, int p_parameterInfor, InitialStatus p_initialStatus, int p_index) { super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, null, false); } //## operation generateSensitivityStatus(ReactionModel,double [],double [],int) private double [] generateSensitivityStatus(ReactionModel p_reactionModel, double [] p_y, double [] p_yprime, int p_paraNum) { //#[ operation generateSensitivityStatus(ReactionModel,double [],double [],int) int neq = p_reactionModel.getSpeciesNumber()*(p_paraNum+1); if (p_y.length != neq) throw new DynamicSimulatorException(); if (p_yprime.length != neq) throw new DynamicSimulatorException(); double [] senStatus = new double[nParameter*nState]; for (int i = p_reactionModel.getSpeciesNumber();i<neq;i++){ double sens = p_y[i]; int index = i-p_reactionModel.getSpeciesNumber(); senStatus[index] = p_y[i]; } return senStatus; // } //## operation solve(boolean,ReactionModel,boolean,SystemSnapshot,ReactionTime,ReactionTime,Temperature,Pressure,boolean) public SystemSnapshot solve(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt, int p_iterationNum) { // set up the input file setupInputFile(); //outputString = new StringBuilder(); //first generate an id for all the species Iterator spe_iter = p_reactionModel.getSpecies(); while (spe_iter.hasNext()){ Species spe = (Species)spe_iter.next(); int id = getRealID(spe); } double startTime = System.currentTimeMillis(); ReactionTime rt = p_beginStatus.getTime(); if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException(); double tBegin = p_beginTime.getStandardTime(); double tEnd = p_endTime.getStandardTime(); double T = p_temperature.getK(); double P = p_pressure.getAtm(); LinkedList initialSpecies = new LinkedList(); // set reaction set if (p_initialization || p_reactionChanged || p_conditionChanged) { nState = p_reactionModel.getSpeciesNumber(); // troeString is a combination of a integer and a real array //real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements) //int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements) troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); // tbrString is a combination of a integer and a real array //real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements) //int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements) tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); lindemannString = generateLindemannReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); //rString is a combination of a integer and a real array //real array format: rate, A, n, Ea, Keq //int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0) rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); nParameter = 0; if (parameterInfor != 0) { nParameter = rList.size() + thirdBodyList.size() + troeList.size() + lindemannList.size() + p_reactionModel.getSpeciesNumber(); } neq = nState*(nParameter + 1); initializeWorkSpace(); initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies); } //6/25/08 gmagoon: (next two lines) for autoflag, get binary 0 or 1 corresponding to boolean false/true int af = 0; if (autoflag) af = 1; try{ if (tt instanceof ConversionTT){ SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0); bw.write(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t 1" +"\t"+ af + "\t0\n"); //6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe; 080509 gmagoon: added sensitivity flag = 0 bw.write(conversionSet[p_iterationNum]+"\n"); } else{ bw.write(nState + "\t" + neq + "\t" + -1 + "\t" +1+"\t"+ af + "\t0\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe; 080509 gmagoon: added sensitivity flag = 0 bw.write(0+"\n"); } bw.write( tBegin+" "+tEnd+"\n" ); for (int i=0; i<nState; i++) bw.write(y[i]+" "); bw.write("\n"); for (int i=0; i<nState; i++) bw.write(yprime[i]+" "); bw.write("\n"); for (int i=0; i<30; i++) bw.write(info[i]+" "); bw.write("\n"+ rtol + " "+atol); bw.write("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n" + lindemannList.size() + "\n" + lindemannString.toString() + "\n"); } catch (IOException e) { System.err.println("Problem writing Solver Input File!"); e.printStackTrace(); } ///4/30/08 gmagoon: code for providing edge reaction info to DASPK in cases if the automatic time stepping flag is set to true if (autoflag) getAutoEdgeReactionInfo((CoreEdgeReactionModel) p_reactionModel, p_temperature, p_pressure); // Add flags that specify whether the concentrations are constant or not getConcentractionFlags(p_reactionModel); //this should be the end of the input file try{ bw.flush(); bw.close(); fw.close(); } catch (IOException e) { System.err.println("Problem closing Solver Input File!"); e.printStackTrace(); } int idid=0; LinkedHashMap speStatus = new LinkedHashMap(); double [] senStatus = new double[nParameter*nState]; int temp = 1; Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60; startTime = System.currentTimeMillis(); //idid = solveDAE(p_initialization, reactionList, p_reactionChanged, thirdBodyReactionList, troeReactionList, nState, y, yprime, tBegin, tEnd, this.rtol, this.atol, T, P); idid = solveDAE(); if (idid !=1 && idid != 2 && idid != 3) { System.out.println("The idid from DASPK was "+idid ); throw new DynamicSimulatorException("DASPK: SA off."); } System.out.println("After ODE: from " + String.valueOf(tBegin) + " SEC to " + String.valueOf(endTime) + "SEC"); Global.solvertime = Global.solvertime + (System.currentTimeMillis() - startTime)/1000/60; startTime = System.currentTimeMillis(); speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, 0); Global.speciesStatusGenerator = Global.speciesStatusGenerator + (System.currentTimeMillis() - startTime)/1000/60; SystemSnapshot sss = new SystemSnapshot(new ReactionTime(endTime, "sec"), speStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure()); //sss.inertGas = p_beginStatus.inertGas; //gmagoon 6/23/09: copy inertGas information from initialStatus sss.inertGas = null;//zero out the inert gas info (in principal, this should already be null, but this is done "just-in-case") //total the concentrations of non-inert species double totalNonInertConc = totalNonInertConcentrations(); //calculate the scale factor needed to account for volume change double inertScaleFactor = 1; if(p_beginStatus.inertGas != null){//8/5/09 gmagoon: make sure inert gas is defined; otherwise, we will have issues with getTotalInertGas() when we start from non-zero time, as jdmo encountered (null-pointer exception) if(p_beginStatus.getTotalInertGas() > 0){//this check will ensure we don't try to divide by zero; otherwise, we will end up setting new concentration to be 0.0*Infinity=NaN inertScaleFactor = (p_beginStatus.getTotalMole()- totalNonInertConc)/p_beginStatus.getTotalInertGas(); } //scale the initial concentrations of the inertGas to account for volume change for (Iterator iter = p_beginStatus.getInertGas(); iter.hasNext(); ) { String inertName = (String)iter.next(); double originalInertConc = p_beginStatus.getInertGas(inertName); sss.putInertGas(inertName, originalInertConc*inertScaleFactor); } } LinkedList reactionList = new LinkedList(); reactionList.addAll(rList); reactionList.addAll(duplicates); reactionList.addAll(thirdBodyList); reactionList.addAll(troeList); reactionList.addAll(lindemannList); sss.setReactionList(reactionList); sss.setReactionFlux(reactionFlux); return sss; // } private int solveDAE() { String workingDirectory = System.getProperty("RMG.workingDirectory"); // write the input file // File SolverInput = new File("ODESolver/SolverInput.dat"); // try { // FileWriter fw = new FileWriter(SolverInput); // fw.write(outputString.toString()); // fw.close(); // } catch (IOException e) { // System.err.println("Problem writing Solver Input File!"); // e.printStackTrace(); // Rename RWORK and IWORK files if they exist renameIntermediateFilesBeforeRun(); //run the solver on the input file boolean error = false; try { String[] command = {workingDirectory + "/software/ODESolver/daspkAUTO.exe"};//5/5/08 gmagoon: changed to call dasslAUTO.exe File runningDir = new File("ODESolver"); Process solver = Runtime.getRuntime().exec(command, null, runningDir); InputStream is = solver.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) { line = line.trim(); if (!(line.contains("ODESOLVER SUCCESSFUL"))) { System.err.println("Error running the ODESolver: "+line); error = true; } } int exitValue = solver.waitFor(); } catch (Exception e) { String err = "Error in running ODESolver \n"; err += e.toString(); e.printStackTrace(); System.exit(0); } //11/1/07 gmagoon: renaming RWORK and IWORK files renameIntermediateFilesAfterRun(); return readOutputFile("ODESolver/SolverOutput.dat"); } private void renameIntermediateFilesBeforeRun(){ File f = new File("ODESolver/RWORK_"+index+".DAT"); File newFile = new File("ODESolver/RWORK.DAT"); boolean renameSuccess = false; if(f.exists()){ if(newFile.exists()) newFile.delete(); renameSuccess = f.renameTo(newFile); if (!renameSuccess) { System.out.println("Renaming of RWORK file(s) failed."); System.exit(0); } } f = new File("ODESolver/IWORK_"+index+".DAT"); newFile = new File("ODESolver/IWORK.DAT"); if(f.exists()){ if(newFile.exists()) newFile.delete(); renameSuccess = f.renameTo(newFile); if (!renameSuccess) { System.out.println("Renaming of IWORK file(s) failed."); System.exit(0); } } f = new File("ODESolver/variables_"+index+".dat"); newFile = new File("ODESolver/variables.dat"); if(f.exists()){ if(newFile.exists()) newFile.delete(); renameSuccess = f.renameTo(newFile); if (!renameSuccess) { System.out.println("Renaming of variables.dat file(s) failed."); System.exit(0); } } } private void renameIntermediateFilesAfterRun() { File f = new File("ODESolver/RWORK.DAT"); File newFile = new File("ODESolver/RWORK_"+index+".DAT"); if(newFile.exists()) newFile.delete(); boolean renameSuccess = f.renameTo(newFile); if (!renameSuccess) { System.out.println("Renaming of RWORK file(s) failed. (renameIntermediateFiles())"); System.exit(0); } f = new File("ODESolver/IWORK.DAT"); newFile = new File("ODESolver/IWORK_"+index+".DAT"); if(newFile.exists()) newFile.delete(); renameSuccess = f.renameTo(newFile); if (!renameSuccess) { System.out.println("Renaming of IWORK file(s) failed. (renameIntermediateFiles())"); System.exit(0); } f = new File("ODESolver/variables.dat"); newFile = new File("ODESolver/variables_"+index+".dat"); if(newFile.exists()) newFile.delete(); renameSuccess = f.renameTo(newFile); if (!renameSuccess) { System.out.println("Renaming of variables.dat file(s) failed. (renameIntermediateFiles())"); System.exit(0); } } public int readOutputFile(String path) { //read the result File SolverOutput = new File(path); try { FileReader fr = new FileReader(SolverOutput); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); //StringTokenizer st = new StringTokenizer(line); Global.solverIterations = Integer.parseInt(line.trim()); line = br.readLine(); if (Double.parseDouble(line.trim()) != neq) { System.out.println("ODESolver didnt generate all species result"); System.exit(0); } endTime = Double.parseDouble(br.readLine().trim()); for (int i=0; i<nParameter+1; i++){ for (int j=0; j<nState; j++) { line = br.readLine(); y[i*nState + j] = Double.parseDouble(line.trim()); } line = br.readLine(); } for (int i=0; i<nParameter+1; i++){ for (int j=0; j<nState; j++) { line = br.readLine(); yprime[i*nState + j] = Double.parseDouble(line.trim()); } line = br.readLine(); } reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size()]; for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size(); i++){ line = br.readLine(); reactionFlux[i] = Double.parseDouble(line.trim()); } for (int i=0; i<30; i++){ line = br.readLine(); info[i] = Integer.parseInt(line.trim()); } } catch (IOException e) { String err = "Error in reading Solver Output File! \n"; err += e.toString(); e.printStackTrace(); System.exit(0); } return 1; } public LinkedList solveSEN(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt) { setupInputFile(); // outputString = new StringBuilder(); Iterator spe_iter = p_reactionModel.getSpecies(); while (spe_iter.hasNext()){ Species spe = (Species)spe_iter.next(); int id = getRealID(spe); } double startTime = System.currentTimeMillis(); ReactionTime rt = p_beginStatus.getTime(); if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException(); double tBegin = p_beginTime.getStandardTime(); double tEnd = p_endTime.getStandardTime(); double T = p_temperature.getK(); double P = p_pressure.getAtm(); LinkedList initialSpecies = new LinkedList(); // set reaction set //if (p_initialization || p_reactionChanged || p_conditionChanged) { nState = p_reactionModel.getSpeciesNumber(); // troeString is a combination of a integer and a real array //real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements) //int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements) troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); // tbrString is a combination of a integer and a real array //real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements) //int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements) tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); lindemannString = generateLindemannReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); //rString is a combination of a integer and a real array //real array format: rate, A, n, Ea, Keq //int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0) rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure); nParameter = 0; if (parameterInfor != 0) { nParameter = rList.size() + thirdBodyList.size() + troeList.size() + lindemannList.size() + p_reactionModel.getSpeciesNumber(); } neq = nState*(nParameter + 1); initializeWorkSpace(); initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies); int iterNum = 0; try{ if (tt instanceof ConversionTT){ SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0); iterNum = conversionSet.length; bw.write(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t" +conversionSet.length+ "\t0\t1\n");//gmagoon 080509: added autoflag=0; later: added sensflag=1 for (int i=0; i<conversionSet.length; i++){ bw.write(conversionSet[i] + " "); } bw.write("\n"); } else{ LinkedList timeSteps = ((ReactionTimeTT)tt).timeStep; iterNum = timeSteps.size(); bw.write(nState + "\t" + neq + "\t" + -1 + "\t" +timeSteps.size()+"\t0\t1\n"); for (int i=0; i<timeSteps.size(); i++){ bw.write(((ReactionTime)timeSteps.get(i)).time + " "); } bw.write("\n"); } bw.write( tBegin+" "+tEnd+ "\n"); for (int i=0; i<nState; i++) bw.write(y[i]+" "); bw.write("\n"); for (int i=0; i<nState; i++) bw.write(yprime[i]+" "); bw.write("\n"); for (int i=0; i<30; i++) bw.write(info[i]+" "); bw.write("\n"+ rtol + " "+atol); bw.write("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n" + lindemannList.size() + "\n" + lindemannString.toString() + "\n"); // Add list of flags for constantConcentration // one for each species, and a final one for the volume // if 1: will not change the number of moles of that species (or the volume) // if 0: will integrate the ODE as normal // eg. liquid phase calculations with a constant concentration of O2 (the solubility limit - replenished from the gas phase) // for normal use, this will be a sequence of '0 's getConcentractionFlags(p_reactionModel); } catch (IOException e) { System.err.println("Problem writing Solver Input File!"); e.printStackTrace(); } //this should be the end of the input file try{ bw.close(); } catch (IOException e) { System.err.println("Problem closing Solver Input File!"); e.printStackTrace(); } int idid=0; int temp = 1; Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60; LinkedList systemSnapshotList = callSolverSEN(iterNum, p_reactionModel, p_beginStatus); return systemSnapshotList; // } private LinkedList callSolverSEN(int p_numSteps, ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) { double startTime = System.currentTimeMillis(); String workingDirectory = System.getProperty("RMG.workingDirectory"); LinkedList systemSnapshotList = new LinkedList(); ReactionTime beginT = new ReactionTime(0.0, "sec"); ReactionTime endT; //write the input file // File SolverInput = new File("ODESolver/SolverInput.dat"); // try { // FileWriter fw = new FileWriter(SolverInput); // fw.write(outputString.toString()); // fw.close(); // } catch (IOException e) { // System.err.println("Problem writing Solver Input File!"); // e.printStackTrace(); Global.writeSolverFile +=(System.currentTimeMillis()-startTime)/1000/60; //run the solver on the input file boolean error = false; try { // system call for therfit String[] command = {workingDirectory + "/software/ODESolver/daspkAUTO.exe"}; File runningDir = new File("ODESolver"); Process ODESolver = Runtime.getRuntime().exec(command, null, runningDir); InputStream is = ODESolver.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) { //System.out.println(line); line = line.trim(); //if (!(line.contains("ODESOLVER SUCCESSFUL"))) { System.out.println(line); //error = true; } int exitValue = 4; exitValue = ODESolver.waitFor(); //System.out.println(br.readLine() + exitValue); } catch (Exception e) { String err = "Error in running ODESolver \n"; err += e.toString(); e.printStackTrace(); System.exit(0); } startTime = System.currentTimeMillis(); //read the result File SolverOutput = new File("ODESolver/SolverOutput.dat"); try { FileReader fr = new FileReader(SolverOutput); BufferedReader br = new BufferedReader(fr); String line ; double presentTime = 0; for (int k=0; k<p_numSteps; k++){ line = br.readLine(); if (Double.parseDouble(line.trim()) != neq) { System.out.println("ODESolver didnt generate all species result"); System.exit(0); } presentTime = Double.parseDouble(br.readLine().trim()); endT = new ReactionTime(presentTime, "sec"); for (int i=0; i<nParameter+1; i++){ for (int j=0; j<nState; j++) { line = br.readLine(); y[i*nState + j] = Double.parseDouble(line.trim()); } line = br.readLine(); } for (int i=0; i<nParameter+1; i++){ for (int j=0; j<nState; j++) { line = br.readLine(); yprime[i*nState + j] = Double.parseDouble(line.trim()); } line = br.readLine(); } reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size()]; for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size(); i++){ line = br.readLine(); reactionFlux[i] = Double.parseDouble(line.trim()); } LinkedHashMap speStatus = new LinkedHashMap(); double [] senStatus = new double[nParameter*nState]; System.out.println("After ODE: from " + String.valueOf(beginT.time) + " SEC to " + String.valueOf(endT.time) + "SEC"); speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, nParameter); senStatus = generateSensitivityStatus(p_reactionModel,y,yprime,nParameter); SystemSnapshot sss = new SystemSnapshot(endT, speStatus, senStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure()); // sss.inertGas = p_beginStatus.inertGas; //gmagoon 6/23/09: copy inertGas information from initialStatus sss.inertGas = new LinkedHashMap();//zero out the inert gas info (in principal, this should already be null, but this is done "just-in-case") //total the concentrations of non-inert species double totalNonInertConc = totalNonInertConcentrations(); //calculate the scale factor needed to account for volume change double inertScaleFactor = 1; if(p_beginStatus.inertGas != null){//8/4/09 gmagoon: make sure inert gas is defined; otherwise, we will have issues with getTotalInertGas() when we start from non-zero time, as jdmo encountered (null-pointer exception) if(p_beginStatus.getTotalInertGas() > 0){//this check will ensure we don't try to divide by zero; otherwise, we will end up setting new concentration to be 0.0*Infinity=NaN inertScaleFactor = (p_beginStatus.getTotalMole()- totalNonInertConc)/p_beginStatus.getTotalInertGas(); } //scale the initial concentrations of the inertGas to account for volume change for (Iterator iter = p_beginStatus.getInertGas(); iter.hasNext(); ) { String inertName = (String)iter.next(); double originalInertConc = p_beginStatus.getInertGas(inertName); sss.putInertGas(inertName, originalInertConc*inertScaleFactor); } } sss.setIDTranslator(IDTranslator); LinkedList reactionList = new LinkedList(); reactionList.addAll(rList); reactionList.addAll(duplicates); reactionList.addAll(thirdBodyList); reactionList.addAll(troeList); reactionList.addAll(lindemannList); sss.setReactionList(reactionList); systemSnapshotList.add(sss); sss.setReactionFlux(reactionFlux); beginT = endT; //tEnd = tEnd.add(tStep); } } catch (IOException e) { String err = "Error in reading Solver Output File! \n"; err += e.toString(); e.printStackTrace(); System.exit(0); } Global.readSolverFile += (System.currentTimeMillis() - startTime)/1000/60; return systemSnapshotList; } @Override protected void initializeWorkSpace() { super.initializeWorkSpace(); info[4] = 1; //use analytical jacobian if (nParameter != 0) { info[18] = nParameter; //the number of parameters info[19] = 2; //perform senstivity analysis info[24] = 1;//staggered corrector method is used } } @Override protected void initializeConcentrations(SystemSnapshot p_beginStatus, ReactionModel p_reactionModel, ReactionTime p_beginTime, ReactionTime p_endTime, LinkedList initialSpecies) { super.initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies); if (nParameter != 0){//svp double [] sensitivityStatus = new double[nState*nParameter]; int speciesNumber = p_reactionModel.getSpeciesNumber(); for (int i=0; i<nParameter*speciesNumber;i++){ sensitivityStatus[i] = 0; } p_beginStatus.addSensitivity(sensitivityStatus); } } }
package Mapper; import Mapper.NativeLib; import Mapper.PropertyValue; import Mapper.TimeTag; import Mapper.Db.*; public class Monitor { /*! Bit flags for coordinating monitor metadata subscriptions. */ public static final int SUB_NONE = 0x00; public static final int SUB_DEVICE = 0x01; public static final int SUB_DEVICE_INPUTS = 0x03; public static final int SUB_DEVICE_OUTPUTS = 0x05; public static final int SUB_DEVICE_SIGNALS = 0x07; public static final int SUB_DEVICE_LINKS = 0x09; public static final int SUB_DEVICE_CONNECTIONS_IN = 0x21; public static final int SUB_DEVICE_CONNECTIONS_OUT = 0x41; public static final int SUB_DEVICE_CONNECTIONS = 0x61; public static final int SUB_DEVICE_ALL = 0xFF; public Monitor(int autosubscribeFlags) { _monitor = mmon_new(autosubscribeFlags); Db = this.new Db(mmon_get_db(_monitor)); } public Monitor() { _monitor = mmon_new(0); Db = this.new Db(mmon_get_db(_monitor)); } public void free() { if (_monitor!=0) mmon_free(_monitor); _monitor = 0; } public int poll(int timeout) { return mmon_poll(_monitor, timeout); } public class Db { /*! The set of possible actions on a db entity. */ public static final int MODIFIED = 0; public static final int NEW = 1; public static final int REMOVED = 2; private Db(long d) { _db = d; _device_cb = null; _signal_cb = null; _link_cb = null; _connection_cb = null; } private void checkMonitor() { if (_monitor._monitor == 0) throw new NullPointerException( "Db object associated with invalid Monitor"); } public boolean valid() { return _monitor._monitor != 0; } // Callbacks public void addDeviceCallback(Mapper.Db.DeviceListener handler) { if (handler != _device_cb) mdb_remove_device_callback(_db, _device_cb); mdb_add_device_callback(_db, handler); _device_cb = handler; } private native void mdb_add_device_callback(long db, Mapper.Db.DeviceListener handler); public void removeDeviceCallback(Mapper.Db.DeviceListener handler) { mdb_remove_device_callback(_db, handler); } private native void mdb_remove_device_callback(long db, Mapper.Db.DeviceListener handler); public void addSignalCallback(Mapper.Db.SignalListener handler) { if (handler != _signal_cb) mdb_remove_signal_callback(_db, _signal_cb); mdb_add_signal_callback(_db, handler); _signal_cb = handler; } private native void mdb_add_signal_callback(long db, Mapper.Db.SignalListener handler); public void removeSignalCallback(Mapper.Db.SignalListener handler) { mdb_remove_signal_callback(_db, handler); } private native void mdb_remove_signal_callback(long db, Mapper.Db.SignalListener handler); public void addLinkCallback(Mapper.Db.LinkListener handler) { if (handler != _link_cb) mdb_remove_link_callback(_db, _link_cb); mdb_add_link_callback(_db, handler); _link_cb = handler; } private native void mdb_add_link_callback(long _p, Mapper.Db.LinkListener handler); public void removeLinkCallback(Mapper.Db.LinkListener handler) { mdb_remove_link_callback(_db, handler); } private native void mdb_remove_link_callback(long db, Mapper.Db.LinkListener handler); public void addConnectionCallback(Mapper.Db.ConnectionListener handler) { if (handler != _connection_cb) mdb_remove_connection_callback(_db, _connection_cb); mdb_add_connection_callback(_db, handler); _connection_cb = handler; } private native void mdb_add_connection_callback(long db, Mapper.Db.ConnectionListener handler); public void removeConnectionCallback(Mapper.Db.ConnectionListener handler) { mdb_remove_connection_callback(_db, handler); } private native void mdb_remove_connection_callback(long db, Mapper.Db.ConnectionListener handler); // Db.Device public native Mapper.Db.DeviceCollection devices(); public native Mapper.Db.Device get_device(String deviceName); public native Mapper.Db.DeviceCollection match_devices(String pattern); // Db.Input public native Mapper.Db.Signal getInput(String deviceName, String signalName); private native long mdb_inputs(long db, String deviceName); public Mapper.Db.SignalCollection inputs() { long _s = mdb_inputs(_db, null); return (_s == 0) ? null : new Mapper.Db.SignalCollection(_s); } public Mapper.Db.SignalCollection inputs(String deviceName) { long _s = mdb_inputs(_db, deviceName); return (_s == 0) ? null : new Mapper.Db.SignalCollection(_s); } public native Mapper.Db.SignalCollection matchInputs(String deviceName, String signalPattern); // Db.Output public native Mapper.Db.Signal getOutput(String deviceName, String signalName); private native long mdb_outputs(long db, String deviceName); public Mapper.Db.SignalCollection outputs() { long _s = mdb_outputs(_db, null); return (_s == 0) ? null : new Mapper.Db.SignalCollection(_s); } public Mapper.Db.SignalCollection outputs(String deviceName) { long _s = mdb_outputs(_db, deviceName); return (_s == 0) ? null : new Mapper.Db.SignalCollection(_s); } public native Mapper.Db.SignalCollection matchOutputs(String deviceName, String signalPattern); // Db.Link public native Mapper.Db.Link getLink(String srcName, String destName); private native Mapper.Db.LinkCollection mdb_links(long db, String deviceName); public Mapper.Db.LinkCollection links(String deviceName) { return mdb_links(_db, deviceName); } public Mapper.Db.LinkCollection links() { return mdb_links(_db, null); } public native Mapper.Db.LinkCollection links(Mapper.Db.DeviceCollection src, Mapper.Db.DeviceCollection dest); public native Mapper.Db.LinkCollection linksBySrc(String deviceName); public native Mapper.Db.LinkCollection linksByDest(String deviceName); // Db.Connection private native Mapper.Db.ConnectionCollection mdb_connections( long db, String deviceName); public Mapper.Db.ConnectionCollection connections(String deviceName) { return mdb_connections(_db, deviceName); } public Mapper.Db.ConnectionCollection connections() { return mdb_connections(_db, null); } public native Mapper.Db.ConnectionCollection connections( Mapper.Db.SignalCollection src, Mapper.Db.SignalCollection dest); private native Mapper.Db.ConnectionCollection mdb_connections_by_src( long db, String deviceName, String signalName); public Mapper.Db.ConnectionCollection connectionsBySrc(String signalName) { return mdb_connections_by_src(_db, null, signalName); } public Mapper.Db.ConnectionCollection connectionsBySrc(String deviceName, String signalName) { return mdb_connections_by_src(_db, deviceName, signalName); } private native Mapper.Db.ConnectionCollection mdb_connections_by_dest( long db, String deviceName, String signalName); public Mapper.Db.ConnectionCollection connectionsByDest(String signalName) { return mdb_connections_by_dest(_db, null, signalName); } public Mapper.Db.ConnectionCollection connectionsByDest(String deviceName, String signalName) { return mdb_connections_by_dest(_db, deviceName, signalName); } public native Mapper.Db.Connection connectionBySignals(String srcName, String destName); public native Mapper.Db.ConnectionCollection connectionsByDevices( String srcDevice, String destDevice); private long _db; private Monitor _monitor; // TODO: enable multiple listeners private Mapper.Db.DeviceListener _device_cb; private Mapper.Db.SignalListener _signal_cb; private Mapper.Db.LinkListener _link_cb; private Mapper.Db.ConnectionListener _connection_cb; }; public void subscribe(String deviceName, int subscribeFlags, int timeout) { mmon_subscribe(_monitor, deviceName, subscribeFlags, timeout); } public void unsubscribe(String deviceName) { mmon_unsubscribe(_monitor, deviceName); } public void link(String sourceDevice, String destDevice, Mapper.Db.Link props) { mmon_link(_monitor, sourceDevice, destDevice, props); } public void unlink(String sourceDevice, String destDevice) { mmon_unlink(_monitor, sourceDevice, destDevice); } public void connect(String sourceSignal, String destSignal, Mapper.Db.Connection props) { mmon_connect_or_mod(_monitor, sourceSignal, destSignal, props, 0); } public void disconnect(String sourceSignal, String destSignal) { mmon_disconnect(_monitor, sourceSignal, destSignal); } public void modifyConnection(String sourceSignal, String destSignal, Mapper.Db.Connection props) { mmon_connect_or_mod(_monitor, sourceSignal, destSignal, props, 1); } public void autosubscribe(int autosubscribeFlags) { mmon_autosubscribe(_monitor, autosubscribeFlags); } public TimeTag now() { return mmon_now(_monitor); } // Note: this is _not_ guaranteed to run, the user should still // call free() explicitly when the monitor is no longer needed. protected void finalize() throws Throwable { try { free(); } finally { super.finalize(); } } private native long mmon_new(int autosubscribe_flags); private native long mmon_get_db(long db); private native void mmon_free(long db); private native int mmon_poll(long db, int timeout); private native void mmon_subscribe(long db, String device_name, int subscribe_flags, int timeout); private native void mmon_unsubscribe(long db, String device_name); private native void mmon_link(long db, String source_device, String dest_device, Mapper.Db.Link props); private native void mmon_unlink(long db, String source_device, String dest_device); private native void mmon_connect_or_mod(long db, String source_signal, String dest_signal, Mapper.Db.Connection props, int modify); private native void mmon_disconnect(long db, String source_signal, String dest_signal); private native void mmon_autosubscribe(long db, int autosubscribe_flags); private native TimeTag mmon_now(long db); private long _monitor; public Mapper.Monitor.Db Db; public boolean valid() { return _monitor != 0; } static { System.loadLibrary(NativeLib.name); } }
package hex.glrm; import hex.*; import water.DKV; import water.H2O; import water.Key; import water.MRTask; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.util.ArrayUtils; import java.util.Random; public class GLRMModel extends Model<GLRMModel,GLRMModel.GLRMParameters,GLRMModel.GLRMOutput> { public static class GLRMParameters extends Model.Parameters { public DataInfo.TransformType _transform = DataInfo.TransformType.NONE; // Data transformation (demean to compare with PCA) public int _k = 1; // Rank of resulting XY matrix public Loss _loss = Loss.L2; // Loss function for numeric cols public MultiLoss _multi_loss = MultiLoss.Categorical; // Loss function for categorical cols public int _period = 1; // Length of the period when _loss = Periodic public Regularizer _regularization_x = Regularizer.None; // Regularization function for X matrix public Regularizer _regularization_y = Regularizer.None; // Regularization function for Y matrix public double _gamma_x = 0; // Regularization weight on X matrix public double _gamma_y = 0; // Regularization weight on Y matrix public int _max_iterations = 1000; // Max iterations public double _init_step_size = 1.0; // Initial step size (decrease until we hit min_step_size) public double _min_step_size = 1e-4; // Min step size public long _seed = System.nanoTime(); // RNG seed public GLRM.Initialization _init = GLRM.Initialization.PlusPlus; // Initialization of Y matrix public Key<Frame> _user_points; // User-specified Y matrix (for _init = User) public Key<Frame> _loading_key; // Key to save X matrix public boolean _recover_svd = false; // Recover singular values and eigenvectors of XY at the end? public enum Loss { L2, L1, Huber, Poisson, Hinge, Logistic, Periodic } public enum MultiLoss { Categorical, Ordinal } // Non-negative matrix factorization (NNMF): r_x = r_y = NonNegative // Orthogonal NNMF: r_x = OneSparse, r_y = NonNegative // K-means clustering: r_x = UnitOneSparse, r_y = 0 (\gamma_y = 0) // Quadratic mixture: r_x = Simplex, r_y = 0 (\gamma_y = 0) public enum Regularizer { None, L2, L1, NonNegative, OneSparse, UnitOneSparse, Simplex } public final boolean hasClosedForm() { return (_loss == GLRMParameters.Loss.L2 && (_gamma_x == 0 || _regularization_x == Regularizer.None || _regularization_x == GLRMParameters.Regularizer.L2) && (_gamma_y == 0 || _regularization_y == Regularizer.None || _regularization_y == GLRMParameters.Regularizer.L2)); } // L(u,a): Loss function public final double loss(double u, double a) { switch(_loss) { case L2: return (u-a)*(u-a); case L1: return Math.abs(u - a); case Huber: return Math.abs(u-a) <= 1 ? 0.5*(u-a)*(u-a) : Math.abs(u-a)-0.5; case Poisson: return Math.exp(u) - a*u + a*Math.log(a) - a; case Hinge: return Math.max(1-a*u,0); case Logistic: return Math.log(1 + Math.exp(-a * u)); case Periodic: return 1-Math.cos((a-u)*(2*Math.PI)/_period); default: throw new RuntimeException("Unknown loss function " + _loss); } } // \grad_u L(u,a): Gradient of loss function with respect to u public final double lgrad(double u, double a) { switch(_loss) { case L2: return 2*(u-a); case L1: return Math.signum(u - a); case Huber: return Math.abs(u-a) <= 1 ? u-a : Math.signum(u-a); case Poisson: return Math.exp(u)-a; case Hinge: return a*u <= 1 ? -a : 0; case Logistic: return -a/(1+Math.exp(a*u)); case Periodic: return ((2*Math.PI)/_period) * Math.sin((a - u) * (2 * Math.PI) / _period); default: throw new RuntimeException("Unknown loss function " + _loss); } } // L(u,a): Multidimensional loss function public final double mloss(double[] u, int a) { if(a < 0 || a > u.length-1) throw new IllegalArgumentException("Index must be between 0 and " + String.valueOf(u.length-1)); double sum = 0; switch(_multi_loss) { case Categorical: for (int i = 0; i < u.length; i++) sum += Math.max(1 + u[i], 0); sum += Math.max(1 - u[a], 0) - Math.max(1 + u[a], 0); return sum; case Ordinal: for (int i = 0; i < u.length-1; i++) sum += Math.max(a>i ? 1-u[i]:1, 0); return sum; default: throw new RuntimeException("Unknown multidimensional loss function " + _multi_loss); } } // \grad_u L(u,a): Gradient of multidimensional loss function with respect to u public final double[] mlgrad(double[] u, int a) { if(a < 0 || a > u.length-1) throw new IllegalArgumentException("Index must be between 0 and " + String.valueOf(u.length-1)); double[] grad = new double[u.length]; switch(_multi_loss) { case Categorical: for (int i = 0; i < u.length; i++) grad[i] = (1+u[i] > 0) ? 1:0; grad[a] = (1-u[a] > 0) ? -1:0; return grad; case Ordinal: for (int i = 0; i < u.length-1; i++) grad[i] = (a>i && 1-u[i] > 0) ? -1:0; return grad; default: throw new RuntimeException("Unknown multidimensional loss function " + _multi_loss); } } // r_i(x_i): Regularization function for single row x_i public final double regularize_x(double[] u) { return regularize(u, _regularization_x); } public final double regularize_y(double[] u) { return regularize(u, _regularization_y); } public final double regularize(double[] u, Regularizer regularization) { if(u == null) return 0; double ureg = 0; switch(regularization) { case None: return 0; case L2: for(int i = 0; i < u.length; i++) ureg += u[i] * u[i]; return ureg; case L1: for(int i = 0; i < u.length; i++) ureg += Math.abs(u[i]); return ureg; case NonNegative: for(int i = 0; i < u.length; i++) { if(u[i] < 0) return Double.POSITIVE_INFINITY; } return 0; case OneSparse: int card = 0; for(int i = 0; i < u.length; i++) { if(u[i] < 0) return Double.POSITIVE_INFINITY; else if(u[i] > 0) card++; } return card == 1 ? 0 : Double.POSITIVE_INFINITY; case UnitOneSparse: int ones = 0, zeros = 0; for(int i = 0; i < u.length; i++) { if(u[i] == 1) ones++; else if(u[i] == 0) zeros++; else return Double.POSITIVE_INFINITY; } return ones == 1 && zeros == u.length-1 ? 0 : Double.POSITIVE_INFINITY; case Simplex: double sum = 0; for(int i = 0; i < u.length; i++) { if(u[i] < 0) return Double.POSITIVE_INFINITY; else sum += u[i]; } return sum == 1 ? 0 : Double.POSITIVE_INFINITY; default: throw new RuntimeException("Unknown regularization function " + regularization); } } // \sum_i r_i(x_i): Sum of regularization function for all entries of X public final double regularize_x(double[][] u) { return regularize(u, _regularization_x); } public final double regularize_y(double[][] u) { return regularize(u, _regularization_y); } public final double regularize(double[][] u, Regularizer regularization) { if(u == null || regularization == Regularizer.None) return 0; double ureg = 0; for(int i = 0; i < u.length; i++) { ureg += regularize(u[i], regularization); if(Double.isInfinite(ureg)) return ureg; } return ureg; } // \prox_{\alpha_k*r}(u): Proximal gradient of (step size) * (regularization function) evaluated at vector u public final double[] rproxgrad_x(double[] u, double alpha, Random rand) { return rproxgrad(u, alpha, _gamma_x, _regularization_x, rand); } public final double[] rproxgrad_y(double[] u, double alpha, Random rand) { return rproxgrad(u, alpha, _gamma_y, _regularization_y, rand); } // public final double[] rproxgrad_x(double[] u, double alpha) { return rproxgrad(u, alpha, _gamma_x, _regularization_x, RandomUtils.getRNG(_seed)); } // public final double[] rproxgrad_y(double[] u, double alpha) { return rproxgrad(u, alpha, _gamma_y, _regularization_y, RandomUtils.getRNG(_seed)); } public final double[] rproxgrad(double[] u, double alpha, double gamma, Regularizer regularization, Random rand) { if(u == null || alpha == 0 || gamma == 0) return u; double[] v = new double[u.length]; switch(regularization) { case None: return u; case L2: for(int i = 0; i < u.length; i++) v[i] = u[i]/(1+2*alpha*gamma); return v; case L1: for(int i = 0; i < u.length; i++) v[i] = Math.max(u[i]-alpha*gamma,0) + Math.min(u[i]+alpha*gamma,0); return v; case NonNegative: for(int i = 0; i < u.length; i++) v[i] = Math.max(u[i],0); return v; case OneSparse: int idx = ArrayUtils.maxIndex(u, rand); v[idx] = u[idx] > 0 ? u[idx] : 1e-6; return v; case UnitOneSparse: idx = ArrayUtils.maxIndex(u, rand); v[idx] = 1; return v; case Simplex: // 1) Sort input vector u in ascending order: u[1] <= ... <= u[n] int n = u.length; int[] idxs = new int[n]; for(int i = 0; i < n; i++) idxs[i] = i; ArrayUtils.sort(idxs, u); // 2) Calculate cumulative sum of u in descending order // cumsum(u) = (..., u[n-2]+u[n-1]+u[n], u[n-1]+u[n], u[n]) double[] ucsum = new double[n]; ucsum[n-1] = u[idxs[n-1]]; for(int i = n-2; i >= 0; i ucsum[i] = ucsum[i+1] + u[idxs[i]]; // 3) Let t_i = (\sum_{j=i+1}^n u[j] - 1)/(n - i) // For i = n-1,...,1, set optimal t* to first t_i >= u[i] double t = (ucsum[0] - 1)/n; // Default t* = (\sum_{j=1}^n u[j] - 1)/n for(int i = n-1; i >= 1; i double tmp = (ucsum[i] - 1)/(n - i); if(tmp >= u[idxs[i-1]]) { t = tmp; break; } } // 4) Return max(u - t*, 0) as projection of u onto simplex double[] x = new double[u.length]; for(int i = 0; i < u.length; i++) x[i] = Math.max(u[i] - t, 0); return x; default: throw new RuntimeException("Unknown regularization function " + regularization); } } // Project X,Y matrices into appropriate subspace so regularizer is finite. Used during initialization. public final double[] project_x(double[] u, Random rand) { return project(u, _regularization_x, rand); } public final double[] project_y(double[] u, Random rand) { return project(u, _regularization_y, rand); } public final double[] project(double[] u, Regularizer regularization, Random rand) { if(u == null) return u; switch(regularization) { // Domain is all real numbers case None: case L2: case L1: return u; // Proximal operator of indicator function for a set C is (Euclidean) projection onto C case NonNegative: case OneSparse: case UnitOneSparse: return rproxgrad(u, 1, 1, regularization, rand); case Simplex: double reg = regularize(u, regularization); // Check if inside simplex before projecting since algo is complicated if (reg == 0) return u; return rproxgrad(u, 1, 1, regularization, rand); default: throw new RuntimeException("Unknown regularization function " + regularization); } } // \hat A_{i,j} = \argmin_a L_{i,j}(x_iy_j, a): Data imputation for real numeric values public final double impute(double u) { switch(_loss) { case L2: case L1: case Huber: case Periodic: return u; case Poisson: return Math.exp(u)-1; case Hinge: return 1/u; case Logistic: if (u == 0) return 0; // Any finite real number is minimizer if u = 0 return (u > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY); default: throw new RuntimeException("Unknown loss function " + _loss); } } // \hat A_{i,j} = \argmin_a L_{i,j}(x_iy_j, a): Data imputation for categorical values {0,1,2,...} // TODO: Is there a faster way to find the loss minimizer? public final int mimpute(double[] u) { switch(_multi_loss) { case Categorical: case Ordinal: double[] cand = new double[u.length]; for (int a = 0; a < cand.length; a++) cand[a] = mloss(u, a); return ArrayUtils.minIndex(cand); default: throw new RuntimeException("Unknown multidimensional loss function " + _multi_loss); } } } public static class GLRMOutput extends Model.Output { // Iterations executed public int _iterations; // Current value of objective function public double _objective; // Average change in objective function this iteration public double _avg_change_obj; // Mapping from training data to lower dimensional k-space (Y') public double[/*feature*/][/*k*/] _archetypes; public GLRM.Archetypes _archetypes_full; // Needed for indexing into Y' for scoring // Final step size public double _step_size; // SVD of output XY public double[/*feature*/][/*k*/] _eigenvectors; public double[] _singular_vals; // Frame key of X matrix public Key<Frame> _loading_key; // Number of categorical and numeric columns public int _ncats; public int _nnums; // Number of good rows in training frame (not skipped) public long _nobs; // Categorical offset vector public int[] _catOffsets; // If standardized, mean of each numeric data column public double[] _normSub; // If standardized, one over standard deviation of each numeric data column public double[] _normMul; // Permutation matrix mapping training col indices to adaptedFrame public int[] _permutation; // Expanded column names of adapted training frame public String[] _names_expanded; public GLRMOutput(GLRM b) { super(b); } /** Override because base class implements ncols-1 for features with the * last column as a response variable; for GLRM all the columns are features. */ @Override public int nfeatures() { return _names.length; } @Override public ModelCategory getModelCategory() { return ModelCategory.DimReduction; } } public GLRMModel(Key selfKey, GLRMParameters parms, GLRMOutput output) { super(selfKey, parms, output); } // GLRM scoring is data imputation based on feature domains using reconstructed XY (see Udell (2015), Section 5.3) @Override protected Frame predictScoreImpl(Frame orig, Frame adaptedFr, String destination_key) { final int ncols = _output._names.length; assert ncols == adaptedFr.numCols(); String prefix = "reconstr_"; // Need [A,X,P] where A = adaptedFr, X = loading frame, P = imputed frame // Note: A is adapted to original training frame, P has columns shuffled so cats come before nums! Frame fullFrm = new Frame(adaptedFr); Frame loadingFrm = DKV.get(_output._loading_key).get(); fullFrm.add(loadingFrm); String[][] adaptedDomme = adaptedFr.domains(); for(int i = 0; i < ncols; i++) { Vec v = fullFrm.anyVec().makeZero(); v.setDomain(adaptedDomme[i]); fullFrm.add(prefix + _output._names[i], v); } GLRMScore gs = new GLRMScore(null, ncols, _parms._k, true).doAll(fullFrm); // Return the imputed training frame int x = ncols + _parms._k, y = fullFrm.numCols(); Frame f = fullFrm.extractFrame(x, y); // this will call vec_impl() and we cannot call the delete() below just yet f = new Frame((null == destination_key ? Key.make() : Key.make(destination_key)), f.names(), f.vecs()); DKV.put(f); gs._mb.makeModelMetrics(GLRMModel.this, adaptedFr); // save error metrics based on imputed data return f; } private class GLRMScore extends MRTask<GLRMScore> { final String[] _domain; final int _ncolA; // Number of cols in original data A final int _ncolX; // Number of cols in X (rank k) final boolean _save_imputed; // Save imputed data into new vecs? ModelMetrics.MetricBuilder _mb; GLRMScore( String[] domain, int ncolA, int ncolX, boolean save_imputed ) { _domain = domain; _ncolA = ncolA; _ncolX = ncolX; _save_imputed = save_imputed; } @Override public void map( Chunk chks[] ) { float atmp [] = new float[_ncolA]; double xtmp [] = new double[_ncolX]; double preds[] = new double[_ncolA]; _mb = GLRMModel.this.makeMetricBuilder(null); if (_save_imputed) { for (int row = 0; row < chks[0]._len; row++) { double p[] = impute_data(chks, row, xtmp, preds); compute_metrics(chks, row, atmp, p); for (int c = 0; c < preds.length; c++) chks[_ncolA + _ncolX + c].set(row, p[c]); } } else { for (int row = 0; row < chks[0]._len; row++) { double p[] = impute_data(chks, row, xtmp, preds); compute_metrics(chks, row, atmp, p); } } } @Override public void reduce( GLRMScore other ) { if(_mb != null) _mb.reduce(other._mb); } @Override protected void postGlobal() { if(_mb != null) _mb.postGlobal(); } private float[] compute_metrics(Chunk[] chks, int row_in_chunk, float[] tmp, double[] preds) { for( int i=0; i<tmp.length; i++) tmp[i] = (float)chks[i].atd(row_in_chunk); _mb.perRow(preds, tmp, GLRMModel.this); return tmp; } private double[] impute_data(Chunk[] chks, int row_in_chunk, double[] tmp, double[] preds) { for( int i=0; i<tmp.length; i++ ) tmp[i] = chks[_ncolA+i].atd(row_in_chunk); impute_data(tmp, preds); return preds; } private double[] impute_data(double[] tmp, double[] preds) { assert preds.length == _output._nnums + _output._ncats; // Categorical columns for (int d = 0; d < _output._ncats; d++) { double[] xyblock = _output._archetypes_full.lmulCatBlock(tmp,d); preds[_output._permutation[d]] = _parms.mimpute(xyblock); } // Numeric columns for (int d = _output._ncats; d < preds.length; d++) { int ds = d - _output._ncats; double xy = _output._archetypes_full.lmulNumCol(tmp, ds); preds[_output._permutation[d]] = _parms.impute(xy); } return preds; } } @Override protected double[] score0(double[] data, double[] preds) { throw H2O.unimpl(); } public ModelMetricsGLRM scoreMetricsOnly(Frame frame) { final int ncols = _output._names.length; // Need [A,X] where A = adapted test frame, X = loading frame // Note: A is adapted to original training frame Frame adaptedFr = new Frame(frame); adaptTestForTrain(adaptedFr, true, false); assert ncols == adaptedFr.numCols(); // Append loading frame X for calculating XY Frame fullFrm = new Frame(adaptedFr); Frame loadingFrm = DKV.get(_output._loading_key).get(); fullFrm.add(loadingFrm); GLRMScore gs = new GLRMScore(null, ncols, _parms._k, false).doAll(fullFrm); ModelMetrics mm = gs._mb.makeModelMetrics(GLRMModel.this, adaptedFr); // save error metrics based on imputed data return (ModelMetricsGLRM) mm; } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { return new ModelMetricsGLRM.GLRMModelMetrics(_parms._k, _output._permutation); } }
import java.util.Arrays; public class PlayerSkeleton { public static boolean DEBUG = false; public static boolean PRINT_UTILITY = false; public static boolean PRINT_LINES_CLEARED = true; // Make copies of static variables public static final int ORIENT = State.ORIENT; public static final int SLOT = State.SLOT; public static final int COLS = State.COLS; public static final int ROWS = State.ROWS; public static final int N_PIECES = State.N_PIECES; public static final int[][][] pTop = State.getpTop(); public static final int[][][] pBottom = State.getpBottom(); public static final int[][] pWidth = State.getpWidth(); public static final int[][] pHeight = State.getpHeight(); // Factor for scaling reward against utility private static final double REWARD_FACTOR = 1; // Waiting time between consecutive moves private static final long WAITING_TIME = 50; // Total number of games to be played private static int NO_OF_GAMES = 10; // Weights private static double constant_weight; private static double[] absoulte_column_height_weight; private static double[] relative_column_height_weight; private static double highest_column_height_weight; private static double holes_weight; // Record the utility and reward values of all moves for printing // 22 feature values followed by reward value private static double[][] features; // Record number of board state printed static int number_of_board_states = 1; static int MAX_BOARD_STATE = 2000; // Implement this function to have a working system public int pickMove(State s, int[][] legalMoves) { // initialize value array for all moves features = new double[legalMoves.length][23]; // Record the move that produces max utility and reward int moveWithMaxUtilityAndReward = 0; double maxUtilityAndReward = -9999; int[][] currentField = deepCopy2D(s.getField()); int[] currentColumnHeights = deepCopy(s.getTop()); int[][] simulatedNextField; int[] simulatedColumnHeights; for (int i = 0; i < legalMoves.length; i++) { simulatedNextField = deepCopy2D(currentField); simulatedColumnHeights = deepCopy(currentColumnHeights); int rowRemoved = tryMakeMove(legalMoves[i][ORIENT], legalMoves[i][SLOT], s, simulatedNextField, simulatedColumnHeights); // The move does not result in end game, we proceed to evaluate if (rowRemoved != -1) { double reward = rowRemoved * REWARD_FACTOR; // Update constant and reward value for the move for printing features[i][0] = 1; features[i][22] = rowRemoved; double utility = evalUtility(i, simulatedNextField, simulatedColumnHeights); utility += constant_weight; if (DEBUG) { System.out.println("Eval: Move: " + i + ", Reward: " + reward + ", Utility:" + utility); } if (reward + utility > maxUtilityAndReward) { maxUtilityAndReward = reward + utility; moveWithMaxUtilityAndReward = i; } } } // In the case where all moves lead to losing, it will choose the first // move with index 0 if (DEBUG) { System.out.println(); System.out.println("Choice: " + "Move: " + moveWithMaxUtilityAndReward + ", Reward+Utility:" + maxUtilityAndReward); System.out.println(); } int pick = moveWithMaxUtilityAndReward; // Print the feature and reward values for interfacing with learner // Do not print the last state if (PRINT_UTILITY && features[pick][0] != 0 && number_of_board_states < MAX_BOARD_STATE) { number_of_board_states++; for (int i = 0; i < features[pick].length; i++) { System.out.print(features[pick][i]); System.out.print(' '); } System.out.println(); } return pick; } private double evalUtility(int move, int[][] field, int[] columnHeights) { double utility = 0.0; double utility_to_be_added = 0.0; // Add utility for absolute column heights // The more rows left for each column, the higher the utility for (int i = 0; i < columnHeights.length; i++) { utility_to_be_added = absoulte_column_height_weight[i] * columnHeights[i]; // Update index 1 to 10 features[move][i + 1] = columnHeights[i]; utility += utility_to_be_added; } // Add utility for relative heights for neighboring columns int height_diff = 0; for (int i = 0; i < columnHeights.length - 1; i++) { height_diff = Math.abs(columnHeights[i] - columnHeights[i + 1]); utility_to_be_added = relative_column_height_weight[i] * height_diff; // Update index 11 to 19 features[move][i + 11] = height_diff; utility += utility_to_be_added; } // Add utility for max height of column int highest = 0; for (int i = 0; i < columnHeights.length; i++) { if (columnHeights[i] > highest) { highest = columnHeights[i]; } } utility_to_be_added = highest_column_height_weight * highest; // update index 20 features[move][20] = highest; utility += utility_to_be_added; // Add utility for holes int no_of_holes = getNumberOfHoles(field); utility_to_be_added = holes_weight * no_of_holes; if (DEBUG) { System.out.println("Move: " + move + ", No of holes: " + no_of_holes + ", utility added for holes:" + utility_to_be_added); } // Update index 21 features[move][21] = no_of_holes; utility += utility_to_be_added; return utility; } private int getNumberOfHoles(int[][] field) { int count = 0; for (int i = 0; i < field.length; i++) { for (int j = 0; j < field[i].length; j++) { if (isHole(i, j, field)) { count++; } } } return count; } private boolean isHole(int i, int j, int[][] field) { if (field[i][j] != 0) { return false; } int cur_row = i + 1; while (cur_row < ROWS) { if (field[cur_row][j] != 0) { return true; } cur_row += 1; } return false; } /** * Simulate the effect of making a specific move * * Modifies simulated next field and height of each column for further * evaluation * * @param orient * @param slot * @param s * @return number of rows removed, -1 if lost */ public int tryMakeMove(int orient, int slot, State s, int[][] field, int[] top) { // Initialize state-related variables int nextPiece = s.getNextPiece(); int turn = s.getTurnNumber() + 1; // Height if the first column makes contact int height = top[slot] - pBottom[nextPiece][orient][0]; // For each column beyond the first in the piece for (int c = 1; c < pWidth[nextPiece][orient]; c++) { height = Math.max(height, top[slot + c] - pBottom[nextPiece][orient][c]); } // Check if game ended if (height + pHeight[nextPiece][orient] >= ROWS) { return -1; } // For each column in the piece - fill in the appropriate blocks for (int i = 0; i < pWidth[nextPiece][orient]; i++) { // From bottom to top of brick for (int h = height + pBottom[nextPiece][orient][i]; h < height + pTop[nextPiece][orient][i]; h++) { field[h][i + slot] = turn; } } // adjust top for (int c = 0; c < pWidth[nextPiece][orient]; c++) { top[slot + c] = height + pTop[nextPiece][orient][c]; } int rowsCleared = 0; // check for full rows - starting at the top for (int r = height + pHeight[nextPiece][orient] - 1; r >= height; r // check all columns in the row boolean full = true; for (int c = 0; c < COLS; c++) { if (field[r][c] == 0) { full = false; break; } } // if the row was full - remove it and slide above stuff down if (full) { rowsCleared++; // for each column for (int c = 0; c < COLS; c++) { // slide down all bricks for (int i = r; i < top[c]; i++) { field[i][c] = field[i + 1][c]; } // lower the top top[c] while (top[c] >= 1 && field[top[c] - 1][c] == 0) top[c] } } } return rowsCleared; } public static void main(String[] args) { if (args.length == 23) { // Take in weights from the command line if present NO_OF_GAMES = Integer.parseInt(args[0]); initializeWeights(args); } else { // Use default weights if arguments are not present initializeWeights(); } State s; TFrame t; for (int i = 0; i < NO_OF_GAMES; i++) { s = new State(); t = new TFrame(s); PlayerSkeleton p = new PlayerSkeleton(); while(!s.hasLost()) { s.makeMove(p.pickMove(s, s.legalMoves())); s.draw(); s.drawNext(0, 0); try { Thread.sleep(WAITING_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } // Remove the windows as we finish the game if (i < NO_OF_GAMES) { t.dispose(); } // Print signal for next game if (i != 0) { System.out.println(" } number_of_board_states = 1; if (PRINT_LINES_CLEARED) { System.out.println("You have completed " + s.getRowsCleared() + " rows."); } } } private static void initializeWeights(String[] args) { // args[1] for constant constant_weight = Double.parseDouble(args[1]); // args[2] to args[11] for absolute column heights absoulte_column_height_weight = new double[COLS]; for (int i1 = 0; i1 < absoulte_column_height_weight.length; i1++) { absoulte_column_height_weight[i1] = Double .parseDouble(args[2 + i1]); } // args[12] to args[20] for relative column heights relative_column_height_weight = new double[COLS - 1]; for (int i1 = 0; i1 < relative_column_height_weight.length; i1++) { relative_column_height_weight[i1] = Double .parseDouble(args[12 + i1]); } // args[21] for relative column heights highest_column_height_weight = Double.parseDouble(args[21]); // args[22] for relative column heights holes_weight = Double.parseDouble(args[22]); assert (absoulte_column_height_weight.length == 10); assert (relative_column_height_weight.length == 9); } private static void initializeWeights() { constant_weight = 1.0; absoulte_column_height_weight = new double[COLS]; for (int i1 = 0; i1 < absoulte_column_height_weight.length; i1++) { absoulte_column_height_weight[i1] = -0.05; } relative_column_height_weight = new double[COLS - 1]; for (int i1 = 0; i1 < relative_column_height_weight.length; i1++) { relative_column_height_weight[i1] = -0.5; } highest_column_height_weight = -0.5; holes_weight = -1.0; assert (absoulte_column_height_weight.length == 10); assert (relative_column_height_weight.length == 9); } public static int[][] deepCopy2D(int[][] original) { if (original == null) { return null; } final int[][] result = new int[original.length][]; for (int i = 0; i < original.length; i++) { result[i] = Arrays.copyOf(original[i], original[i].length); } return result; } public static int[] deepCopy(int[] original) { if (original == null) { return null; } int[] result = new int[original.length]; result = Arrays.copyOf(original, original.length); return result; } }
package bramble.networking; import java.io.IOException; import java.io.InputStream; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import org.nustaq.serialization.FSTObjectInput; public class ListenerServer extends ServerSocket { public ListenerServer(int port) throws IOException, BindException { super(port); } synchronized public Message listen() throws Exception { Socket socket = this.accept(); InputStream inputStream = socket.getInputStream(); FSTObjectInput objectInputStream = new FSTObjectInput(inputStream); Message output = null; while(output == null){ output = (Message) objectInputStream.readObject(); } objectInputStream.close(); inputStream.close(); socket.close(); return output; } }
package UI; import Layers.FrontDotLayer; import Layers.GridLayer; import Layers.Layer; import Layers.LinesLayer; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseButton; import javafx.scene.paint.Color; import static UI.Main.*; import static UI.UIValues.WINDOW_HEIGHT; import static UI.UIValues.WINDOW_WIDTH; public class ConfigLayer { public static boolean dot_dragged = false; public static void ConfigLinesLayer(LinesLayer lines, FrontDotLayer front, GridLayer gridLayer){ SettingAnchor(lines); ContextMenu popup_lines = new ContextMenu(); MenuItem cat_dot = new MenuItem(""); MenuItem quit_cat = new MenuItem(""); MenuItem remove_dot = new MenuItem(""); MenuItem move_dot = new MenuItem(""); cat_dot.setOnAction(event -> { for(final Dot p : CurrentLayerData.getDotSet()){ if(Math.abs(p.getX() - x) < 5){ if(Math.abs(p.getY() - y) < 5){ if(!p.isSelected()){ CurrentLayerData.connect(selecting_dot, p).Draw(lines, 0.5, Color.BLACK); selecting_dot.UnSelect(); SwitchFrontLayer(front); break; } } } } }); cat_dot.setDisable(true); quit_cat.setOnAction(event -> { selecting_dot.UnSelect(); SwitchFrontLayer(front); }); remove_dot.setOnAction(event -> { selecting_dot.Erase(front); CurrentLayerData.RemoveDot(selecting_dot); lines.getGraphicsContext().clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); CurrentLayerData.DrawAllLines(lines); Main.SwitchFrontLayer(front); }); move_dot.setOnAction(event -> { Dot update_dot; if(gridLayer.isEnableComplete()) { update_dot = new Dot(x, y, gridLayer.getInterval()); }else{ update_dot = new Dot(x, y); } selecting_dot.Erase(front); CurrentLayerData.MoveDot(selecting_dot, update_dot); lines.getGraphicsContext().clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); CurrentLayerData.DrawAllLines(lines); update_dot.Draw(front, Color.RED); }); popup_lines.getItems().addAll(cat_dot, move_dot, remove_dot, quit_cat); lines.getCanvas().setOnContextMenuRequested(event -> { popup_lines.show(lines.getCanvas(), event.getScreenX(), event.getScreenY()); }); lines.getCanvas().setOnMouseClicked(event -> { if (event.getButton() == MouseButton.PRIMARY) { popup_lines.hide(); } else if (event.getButton() == MouseButton.SECONDARY){ x = (int)event.getX(); y = (int)event.getY(); } }); lines.getCanvas().setOnMouseMoved(event -> { for(Dot p : CurrentLayerData.getDotSet()){ if(p.isSelected()) continue; if(Math.abs(p.getX() - event.getX()) < 5){ if(Math.abs(p.getY() - event.getY()) < 5){ cat_dot.setDisable(false); p.Draw(front, Color.RED); break; }else{ p.Draw(front, Color.BLACK); cat_dot.setDisable(true); } }else{ p.Draw(front, Color.BLACK); cat_dot.setDisable(true); } } footer.PutText(String.valueOf((int)event.getX()) + ":" + String.valueOf((int)event.getY()), WINDOW_WIDTH - 80); }); lines.getCanvas().setOnMouseDragged(event -> { if(!dot_dragged) return; Dot update_dot; if(gridLayer.isEnableComplete()) { update_dot = new Dot((int)event.getX(), (int)event.getY(), gridLayer.getInterval()); }else{ update_dot = new Dot((int)event.getX(), (int)event.getY()); } selecting_dot.Erase(front); CurrentLayerData.MoveDot(selecting_dot, update_dot); lines.getGraphicsContext().clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); CurrentLayerData.DrawAllLines(lines); selecting_dot = update_dot; selecting_dot.Select(); update_dot.Draw(front, Color.RED); }); lines.getCanvas().setOnMousePressed(event -> { if(Math.abs(selecting_dot.getX() - event.getX()) < 5){ if(Math.abs(selecting_dot.getY() - event.getY()) < 5) { dot_dragged = true; } } }); lines.getCanvas().setOnMouseReleased(event -> dot_dragged = false); } public static void ConfigNormalFrontLayer(FrontDotLayer front, LinesLayer lines, GridLayer gridLayer, LayersTree layersTree){ SettingAnchor(front); ContextMenu popup = new ContextMenu(); MenuItem choose = new MenuItem(""); choose.setOnAction(event -> { for(final Dot p : CurrentLayerData.getDotSet()){ if(Math.abs(p.getX() - x) < 5){ if(Math.abs(p.getY() - y) < 5){ p.Select(); selecting_dot = p; selecting_dot.Select(); selecting_dot.Draw(front, Color.RED); SwitchFrontLayer(lines); break; } } } }); popup.getItems().addAll(choose); front.getCanvas().setOnContextMenuRequested(event -> { if(CurrentLayerData == null){ return; } popup.show(front.getCanvas(), event.getScreenX(), event.getScreenY()); }); front.getCanvas().setOnMouseClicked(event -> { popup.hide(); x = (int)event.getX(); y = (int)event.getY(); if(keyTable.isPressed(KeyCode.D)){ putDot(layersTree, gridLayer, front); }else if(keyTable.isPressed(KeyCode.C)){ if(!front.isLastEmpty()) { Dot dot = front.getLast(); putDot(layersTree, gridLayer, front); CurrentLayerData.connect(dot, front.getLast()).Draw(lines, 0.5, Color.BLACK); } } }); front.getCanvas().setOnMouseMoved(event -> { if(CurrentLayerData == null){ return; } CurrentLayerData.getPolygons().forEach(polygon -> { polygon.DrawDots(front); }); Dot dot; for(Polygon polygon : CurrentLayerData.getPolygons()){ if((dot = polygon.isOverlaps(new Point2i((int)event.getX(), (int)event.getY()))) != null){ selecting_dot = dot; break; } } footer.PutText(String.valueOf((int)event.getX()) + ":" + String.valueOf((int)event.getY()), WINDOW_WIDTH - 80); }); front.getCanvas().setOnMouseDragged(event -> { if(!ConfigLayer.dot_dragged) return; Dot update_dot; if(gridLayer.isEnableComplete()) { update_dot = new Dot((int)event.getX(), (int)event.getY(), gridLayer.getInterval()); }else{ update_dot = new Dot((int)event.getX(), (int)event.getY()); } selecting_dot.Erase(front); for(Polygon polygon : CurrentLayerData.getPolygons()){ polygon.MoveDot(selecting_dot, update_dot); } CurrentLayerData.getLineList().forEach(line -> line.exchange(selecting_dot, update_dot)); lines.getGraphicsContext().clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); CurrentLayerData.DrawAllLines(lines); selecting_dot = update_dot; selecting_dot.Draw(front, Color.RED); }); front.getCanvas().setOnMousePressed(event -> { for(Polygon polygon : CurrentLayerData.getPolygons()){ if(polygon.isOverlaps(new Point2i((int)event.getX(), (int)event.getY())) != null){ ConfigLayer.dot_dragged = true; break; } } }); front.getCanvas().setOnMouseReleased(event -> ConfigLayer.dot_dragged = false); choose.setDisable(true); } }
package com.jjdltc.cordova.plugin.sftp; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; public class JJsftp extends CordovaPlugin { private AsyncTask<Void, Integer, Boolean> staticAsync = null; private enum ACTIONS { download , upload , cancel }; /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false if not. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { boolean result = true; JSONObject hostData = this.setHostData(args); JSONArray actionArr = this.setActionArr(args); if((hostData==null || action == null) && action!="cancel"){ this.processResponse(callbackContext, false, "Some parameters were missed - hostData or actionArr not found-"); return false; } switch (ACTIONS.valueOf(action)) { case download: this.download(hostData, actionArr); this.processResponse(callbackContext, true, "Download is added to to list"); break; case upload: this.upload(hostData, actionArr); this.processResponse(callbackContext, true, "upload is added to to list"); break; case cancel: boolean cancellSuccess = this.cancelStaticAsync(); String msg = (cancellSuccess)?"Cancellation request sent":"Cancellation request sent but we are unable to execute (may not be such a process or is already cancelled)"; this.processResponse(callbackContext, cancellSuccess, msg); break; default: this.processResponse(callbackContext, false, "Some parameters were missed - action not found -"); result = false; break; } return result; } /** * * @param ctx The plugin CallbackContext * @param success Boolean that define if the JS plugin should fire the success or error function * @param msg The String msg to by sended * @throws JSONException */ private void processResponse(CallbackContext ctx, boolean success, String msg) throws JSONException{ JSONObject response = new JSONObject(); response.put("success", success); response.put("message", msg); if(success){ ctx.success(response); } else{ ctx.error(response); } } /** * Use an custom AsyncTask 'asyncSFTPAction' to execute the download * * @param hostData JSONObject with the host data to connect (processed by 'setHostData' function) * @param actionArr JSONArray with the action list to execute (processed by 'setActionArr' function) */ private void download(JSONObject hostData, JSONArray actionArr){ this.staticAsync = new asyncSFTPAction(hostData, actionArr, "download", this.webView); this.staticAsync.execute(); } private void upload(JSONObject hostData, JSONArray actionArr){ this.staticAsync = new asyncSFTPAction(hostData, actionArr, "upload", this.webView); this.staticAsync.execute(); } /** * Validate if the options sent by user are not null or empty and also if accomplish the base structure * * @param arguments The arguments passed by user with the JSONObject that has the host options * @return A valid 'hostData' JSONObject with its inner host options to connect * @throws JSONException */ private JSONObject setHostData(JSONArray arguments) throws JSONException{ JSONObject hostData = arguments.optJSONObject(0); boolean validArgs = true; String[] keys = new String[]{ "host" , "user" , "pswd" }; if(hostData==null){ return null; } if(hostData.opt("port")==null){ hostData.put("port", 22); } for (int i = 0; i < keys.length; i++) { if(hostData.opt(keys[i])==null){ validArgs = false; break; } } return (validArgs)?hostData:null; } /** * Validate if the options sent by user are not null or empty and also if accomplish the base structure * * @param arguments The arguments passed by user with the JSONArray of JSONObject with the local and remote path of the files * @return A valid 'actionArr' JSONArray with its inner JSONObject paths */ private JSONArray setActionArr(JSONArray arguments){ JSONArray actionArr = arguments.optJSONArray(1); boolean validArr = true; if(actionArr==null){ return null; } for (int i = 0; i < actionArr.length(); i++) { JSONObject tempActionObj = actionArr.optJSONObject(i); if(tempActionObj==null){ validArr = false; } else{ validArr = (tempActionObj.opt("remote")==null || tempActionObj.opt("local")==null)?false:validArr; } if(!validArr){ break; } } return (validArr)?actionArr:null; } private boolean cancelStaticAsync(){ return (this.staticAsync!=null)?this.staticAsync.cancel(true):false; } }
import java.io.File; import java.io.IOException; import java.net.URL; import org.apache.commons.io.FileUtils; public class Crawler2 { private static final String MAIN_PATH = "C:\\Users\\Dilip\\Desktop\\Download2\\"; public static void main(String[] args) throws Exception { try { File file; URL url; //i represents page number to crawl. Logic should change based on URL for (int i = 1; i < 37; i++) { file = FileUtils.getFile(MAIN_PATH + i + ".tif"); if(i<10) url = new URL("http://ia902702.us.archive.org/BookReader/BookReaderImages.php?zip=/0/items/lifeandworksirj00geddgoog/lifeandworksirj00geddgoog_tif.zip&file=lifeandworksirj00geddgoog_tif/lifeandworksirj00geddgoog_000" + i + ".tif&scale=1.3101604278074865&rotate=0"); else if (i<100) url = new URL("http://ia902702.us.archive.org/BookReader/BookReaderImages.php?zip=/0/items/lifeandworksirj00geddgoog/lifeandworksirj00geddgoog_tif.zip&file=lifeandworksirj00geddgoog_tif/lifeandworksirj00geddgoog_00" + i + ".tif&scale=1.3101604278074865&rotate=0"); else url = new URL("http://ia902702.us.archive.org/BookReader/BookReaderImages.php?zip=/0/items/lifeandworksirj00geddgoog/lifeandworksirj00geddgoog_tif.zip&file=lifeandworksirj00geddgoog_tif/lifeandworksirj00geddgoog_0" + i + ".tif&scale=1.3101604278074865&rotate=0"); // Copy bytes from the URL to the destination file. System.out.println(url); FileUtils.copyURLToFile(url, file); //Thread.sleep(5000); } } catch (IOException e) { e.printStackTrace(); } } }
package pylos.view; import pylos.Pylos; import pylos.controller.Controller; import pylos.model.Ball; import pylos.model.Model; import pylos.model.Position; import pylos.view.ball.HighlightBallGraphics; import pylos.view.ball.PositionBallGraphics; import com.jme3.app.SimpleApplication; import com.jme3.asset.plugins.FileLocator; import com.jme3.input.ChaseCamera; import com.jme3.input.MouseInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.scene.Node; import com.jme3.system.AppSettings; public class View extends SimpleApplication implements ActionListener { static final int CheckTargetsEveryFrames = 30; public Model model; public Controller controller; public BoardGraphics board; ChaseCamera chaseCam; CameraTarget cameraTarget; Node targets = new Node("Targets"); Node ballsOnBoard = new Node("Balls on Board"); Node positionBalls = new Node("Position Balls"); Node visible = new Node("Visible"); HighlightBallGraphics highlightBall = new HighlightBallGraphics(); public View(Model model) { super(); this.model = model; showSettings = false; settings = new AppSettings(true); settings.setResolution(800, 600); settings.setTitle("Pylos"); } @Override public void simpleInitApp() { assetManager.registerLocator(Pylos.rootPath + "/assets", FileLocator.class); rootNode.attachChild(visible); cameraTarget = new CameraTarget(this); rootNode.attachChild(cameraTarget.geometry); board = new BoardGraphics(this); rootNode.attachChild(board.getSpatial()); // You must add a light to make the model visible new Lights(this); initFlyCam(); initBalls(); initKeys(); controller.initTurn(); highlightBall.create(this); } @Override public void simpleUpdate(float tpf) { if ((int) (tpf) % CheckTargetsEveryFrames == 0) { Collisions collisions = new Collisions(this); if (collisions.any()) { Position position = collisions.getPosition(); board.place(highlightBall, position); visible.attachChild(highlightBall); } else { visible.detachChild(highlightBall); } } } private void initKeys() { inputManager.addMapping("PickBall", new MouseButtonTrigger(0)); // left-button click inputManager.addListener(this, "PickBall"); } public void initBalls() { for (Ball ball : Model.balls) { ball.graphics.create(this); rootNode.attachChild(ball.graphics); } board.drawBalls(); } public void initFlyCam() { flyCam.setEnabled(false); chaseCam = new ChaseCamera(cam, cameraTarget.geometry, inputManager); chaseCam.setInvertVerticalAxis(true); chaseCam.setToggleRotationTrigger(new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); } public void show() { start(); } public void placePositionBalls() { for (Position position : model.getPositionsToPlaceBallOnBoard()) { PositionBallGraphics graphics = new PositionBallGraphics(position); board.place(graphics, position); positionBalls.attachChild(graphics); } targets.attachChild(positionBalls); } public void onAction(String name, boolean isPressed, float tpf) { if (name.equals("PickBall") && !isPressed) { Collisions collisions = new Collisions(Pylos.view); if (collisions.any()) { controller.placePlayerBall(collisions.getPosition()); } } } }
import java.util.NoSuchElementException; public class TwoProbeHashTable<Key, Value> extends SeparateChainingHashTable<Key, Value> { public static void main(String[] args) { TwoProbeHashTable<String, Integer> table = new TwoProbeHashTable<>(); table.put("one", 1); table.put("two", 2); table.put("three", 3); table.put("four", 4); table.put("five", 5); table.put("six", 6); System.out.println(table.size()); System.out.println(table.isEmpty()); System.out.println(table.get("one")); table.erase("two"); System.out.println(table.size()); table.erase("one"); table.erase("three"); table.erase("four"); System.out.println(table.get("six")); } public void put(Key key, Value value) { int first = _firstHash(key); for (Node node = _nodes[first]; node != null; node = node.next) { if (node.key.equals(key)) { node.value = value; return; } } int second = _secondHash(first); for (Node node = _nodes[second]; node != null; node = node.next) { if (node.key.equals(key)) { node.value = value; return; } } int hash = (_sizes[first] > _sizes[second]) ? second : first; _nodes[hash] = new Node(key, value, _nodes[hash]); ++_sizes[hash]; if (++_size == _capacity) _resize(); } public Value get(Key key) { int first = _firstHash(key); for (Node node = _nodes[first]; node != null; node = node.next) { if (node.key.equals(key)) return (Value) node.value; } int second = _secondHash(first); for (Node node = _nodes[second]; node != null; node = node.next) { if (node.key.equals(key)) return (Value) node.value; } return null; } public void erase(Key key) { int first = _firstHash(key); Node node = _nodes[first], previous = null; for ( ; node != null; node = node.next) { if (node.key.equals(key)) { if (previous != null) { previous.next = node.next; } node = null; --_sizes[first]; if (--_size == _capacity/4) _resize(); return; } } int second = _secondHash(first); node = _nodes[second]; previous = null; for ( ; node != null; node = node.next) { if (node.key.equals(key)) { if (previous != null) { previous.next = node.next; } node = null; --_sizes[second]; if (--_size == _capacity/4) _resize(); return; } } throw new NoSuchElementException("No such element '" + key.toString() + "'!"); } private int _firstHash(Key key) { return super._hash(key); } private int _secondHash(int first) { return first ^ (first << 1) % _nodes.length; } protected void _resize() { super._resize(); int[] old = _sizes; _sizes = new int[_nodes.length]; for (int i = 0; i < _size; ++i) { _sizes[i] = old[i]; } } private int[] _sizes = new int[MINIMUM_CAPACITY]; }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.core; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hbase.async.Bytes; import org.hbase.async.HBaseException; import org.hbase.async.KeyValue; import org.hbase.async.Scanner; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import static org.hbase.async.Bytes.ByteMap; import net.opentsdb.stats.Histogram; import net.opentsdb.uid.NoSuchUniqueId; import net.opentsdb.uid.NoSuchUniqueName; import net.opentsdb.uid.UniqueId; /** * Non-synchronized implementation of {@link Query}. */ final class TsdbQuery implements Query { private static final Logger LOG = LoggerFactory.getLogger(TsdbQuery.class); /** Used whenever there are no results. */ private static final DataPoints[] NO_RESULT = new DataPoints[0]; /** * Keep track of the latency we perceive when doing Scans on HBase. * We want buckets up to 16s, with 2 ms interval between each bucket up to * 100 ms after we which we switch to exponential buckets. */ static final Histogram scanlatency = new Histogram(16000, (short) 2, 100); /** * Charset to use with our server-side row-filter. * We use this one because it preserves every possible byte unchanged. */ private static final Charset CHARSET = Charset.forName("ISO-8859-1"); /** The TSDB we belong to. */ private final TSDB tsdb; /** Value used for timestamps that are uninitialized. */ private static final int UNSET = -1; /** Start time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */ private long start_time = UNSET; /** End time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */ private long end_time = UNSET; /** ID of the metric being looked up. */ private byte[] metric; /** * Tags of the metrics being looked up. * Each tag is a byte array holding the ID of both the name and value * of the tag. * Invariant: an element cannot be both in this array and in group_bys. */ private ArrayList<byte[]> tags; /** * Tags by which we must group the results. * Each element is a tag ID. * Invariant: an element cannot be both in this array and in {@code tags}. */ private ArrayList<byte[]> group_bys; /** * Values we may be grouping on. * For certain elements in {@code group_bys}, we may have a specific list of * values IDs we're looking for. Those IDs are stored in this map. The key * is an element of {@code group_bys} (so a tag name ID) and the values are * tag value IDs (at least two). */ private ByteMap<byte[][]> group_by_values; /** If true, use rate of change instead of actual values. */ private boolean rate; /** Specifies the various options for rate calculations */ private RateOptions rate_options; /** Aggregator function to use. */ private Aggregator aggregator; /** * Downsampling function to use, if any (can be {@code null}). * If this is non-null, {@code sample_interval} must be strictly positive. */ private Aggregator downsampler; /** Minimum time interval (in seconds) wanted between each data point. */ private int sample_interval; /** Optional list of TSUIDs to fetch and aggregate instead of a metric */ private List<String> tsuids; /** Constructor. */ public TsdbQuery(final TSDB tsdb) { this.tsdb = tsdb; } public void setStartTime(final long timestamp) { if ((timestamp & Const.SECOND_MASK) != 0 && (timestamp < 1000000000000L || timestamp > 9999999999999L)) { throw new IllegalArgumentException("Invalid timestamp: " + timestamp); } else if (end_time != UNSET && timestamp >= getEndTime()) { throw new IllegalArgumentException("new start time (" + timestamp + ") is greater than or equal to end time: " + getEndTime()); } start_time = timestamp; } public long getStartTime() { if (start_time == UNSET) { throw new IllegalStateException("setStartTime was never called!"); } return start_time; } public void setEndTime(final long timestamp) { if ((timestamp & Const.SECOND_MASK) != 0 && (timestamp < 1000000000000L || timestamp > 9999999999999L)) { throw new IllegalArgumentException("Invalid timestamp: " + timestamp); } else if (start_time != UNSET && timestamp <= getStartTime()) { throw new IllegalArgumentException("new end time (" + timestamp + ") is less than or equal to start time: " + getStartTime()); } end_time = timestamp; } /** @return the configured end time. If the end time hasn't been set, the * current system time will be stored and returned. */ public long getEndTime() { if (end_time == UNSET) { setEndTime(System.currentTimeMillis()); } return end_time; } public void setTimeSeries(final String metric, final Map<String, String> tags, final Aggregator function, final boolean rate) throws NoSuchUniqueName { setTimeSeries(metric, tags, function, rate, new RateOptions()); } public void setTimeSeries(final String metric, final Map<String, String> tags, final Aggregator function, final boolean rate, final RateOptions rate_options) throws NoSuchUniqueName { findGroupBys(tags); this.metric = tsdb.metrics.getId(metric); this.tags = Tags.resolveAll(tsdb, tags); aggregator = function; this.rate = rate; this.rate_options = rate_options; } public void setTimeSeries(final List<String> tsuids, final Aggregator function, final boolean rate) { setTimeSeries(tsuids, function, rate, new RateOptions()); } public void setTimeSeries(final List<String> tsuids, final Aggregator function, final boolean rate, final RateOptions rate_options) { if (tsuids == null || tsuids.isEmpty()) { throw new IllegalArgumentException( "Empty or missing TSUID list not allowed"); } String first_metric = ""; for (final String tsuid : tsuids) { if (first_metric.isEmpty()) { first_metric = tsuid.substring(0, TSDB.metrics_width() * 2) .toUpperCase(); continue; } final String metric = tsuid.substring(0, TSDB.metrics_width() * 2) .toUpperCase(); if (!first_metric.equals(metric)) { throw new IllegalArgumentException( "One or more TSUIDs did not share the same metric"); } } // the metric will be set with the scanner is configured this.tsuids = tsuids; aggregator = function; this.rate = rate; this.rate_options = rate_options; } public void downsample(final int interval, final Aggregator downsampler) { if (downsampler == null) { throw new NullPointerException("downsampler"); } else if (interval <= 0) { throw new IllegalArgumentException("interval not > 0: " + interval); } this.downsampler = downsampler; this.sample_interval = interval; } /** * Extracts all the tags we must use to group results. * <ul> * <li>If a tag has the form {@code name=*} then we'll create one * group per value we find for that tag.</li> * <li>If a tag has the form {@code name={v1,v2,..,vN}} then we'll * create {@code N} groups.</li> * </ul> * In the both cases above, {@code name} will be stored in the * {@code group_bys} attribute. In the second case specifically, * the {@code N} values would be stored in {@code group_by_values}, * the key in this map being {@code name}. * @param tags The tags from which to extract the 'GROUP BY's. * Each tag that represents a 'GROUP BY' will be removed from the map * passed in argument. */ private void findGroupBys(final Map<String, String> tags) { final Iterator<Map.Entry<String, String>> i = tags.entrySet().iterator(); while (i.hasNext()) { final Map.Entry<String, String> tag = i.next(); final String tagvalue = tag.getValue(); if (tagvalue.equals("*") // 'GROUP BY' with any value. || tagvalue.indexOf('|', 1) >= 0) { // Multiple possible values. if (group_bys == null) { group_bys = new ArrayList<byte[]>(); } group_bys.add(tsdb.tag_names.getId(tag.getKey())); i.remove(); if (tagvalue.charAt(0) == '*') { continue; // For a 'GROUP BY' with any value, we're done. } // 'GROUP BY' with specific values. Need to split the values // to group on and store their IDs in group_by_values. final String[] values = Tags.splitString(tagvalue, '|'); if (group_by_values == null) { group_by_values = new ByteMap<byte[][]>(); } final short value_width = tsdb.tag_values.width(); final byte[][] value_ids = new byte[values.length][value_width]; group_by_values.put(tsdb.tag_names.getId(tag.getKey()), value_ids); for (int j = 0; j < values.length; j++) { final byte[] value_id = tsdb.tag_values.getId(values[j]); System.arraycopy(value_id, 0, value_ids[j], 0, value_width); } } } } /** * Executes the query * @return An array of data points with one time series per array value */ public DataPoints[] run() throws HBaseException { try { return runAsync().joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } } public Deferred<DataPoints[]> runAsync() throws HBaseException { return findSpans().addCallback(new GroupByAndAggregateCB()); } private Deferred<TreeMap<byte[], Span>> findSpans() throws HBaseException { final short metric_width = tsdb.metrics.width(); final TreeMap<byte[], Span> spans = // The key is a row key from HBase. new TreeMap<byte[], Span>(new SpanCmp(metric_width)); final Scanner scanner = getScanner(); final Deferred<TreeMap<byte[], Span>> results = new Deferred<TreeMap<byte[], Span>>(); /** * Scanner callback executed recursively each time we get a set of data * from storage. This is responsible for determining what columns are * returned and issuing requests to load leaf objects. * When the scanner returns a null set of rows, the method initiates the * final callback. */ final class ScannerCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { int nrows = 0; int hbase_time = 0; // milliseconds. long starttime = System.nanoTime(); /** * Starts the scanner and is called recursively to fetch the next set of * rows from the scanner. * @return The map of spans if loaded successfully, null if no data was * found */ public Object scan() { starttime = System.nanoTime(); return scanner.nextRows().addCallback(this); } /** * Loops through each row of the scanner results and parses out data * points and optional meta data * @return null if no rows were found, otherwise the TreeMap with spans */ @Override public Object call(final ArrayList<ArrayList<KeyValue>> rows) throws Exception { hbase_time += (System.nanoTime() - starttime) / 1000000; try { if (rows == null) { hbase_time += (System.nanoTime() - starttime) / 1000000; scanlatency.add(hbase_time); LOG.info(TsdbQuery.this + " matched " + nrows + " rows in " + spans.size() + " spans"); if (nrows < 1) { results.callback(null); } else { results.callback(spans); } scanner.close(); return null; } for (final ArrayList<KeyValue> row : rows) { final byte[] key = row.get(0).key(); if (Bytes.memcmp(metric, key, 0, metric_width) != 0) { scanner.close(); throw new IllegalDataException( "HBase returned a row that doesn't match" + " our scanner (" + scanner + ")! " + row + " does not start" + " with " + Arrays.toString(metric)); } Span datapoints = spans.get(key); if (datapoints == null) { datapoints = new Span(tsdb); spans.put(key, datapoints); } final KeyValue compacted = tsdb.compact(row, datapoints.getAnnotations()); if (compacted != null) { // Can be null if we ignored all KVs. datapoints.addRow(compacted); nrows++; } } return scan(); } catch (Exception e) { scanner.close(); results.callback(e); return null; } } } new ScannerCB().scan(); return results; } /** * Callback that should be attached the the output of * {@link TsdbQuery#findSpans} to group and sort the results. */ private class GroupByAndAggregateCB implements Callback<DataPoints[], TreeMap<byte[], Span>>{ /** * Creates the {@link SpanGroup}s to form the final results of this query. * @param spans The {@link Span}s found for this query ({@link #findSpans}). * Can be {@code null}, in which case the array returned will be empty. * @return A possibly empty array of {@link SpanGroup}s built according to * any 'GROUP BY' formulated in this query. */ public DataPoints[] call(final TreeMap<byte[], Span> spans) throws Exception { if (spans == null || spans.size() <= 0) { return NO_RESULT; } if (group_bys == null) { // We haven't been asked to find groups, so let's put all the spans // together in the same group. final SpanGroup group = new SpanGroup(tsdb, getScanStartTime(), getScanEndTime(), spans.values(), rate, rate_options, aggregator, sample_interval, downsampler); return new SpanGroup[] { group }; } // Maps group value IDs to the SpanGroup for those values. Say we've // been asked to group by two things: foo=* bar=* Then the keys in this // map will contain all the value IDs combinations we've seen. If the // name IDs for `foo' and `bar' are respectively [0, 0, 7] and [0, 0, 2] // then we'll have group_bys=[[0, 0, 2], [0, 0, 7]] (notice it's sorted // by ID, so bar is first) and say we find foo=LOL bar=OMG as well as // foo=LOL bar=WTF and that the IDs of the tag values are: // LOL=[0, 0, 1] OMG=[0, 0, 4] WTF=[0, 0, 3] // then the map will have two keys: // - one for the LOL-OMG combination: [0, 0, 1, 0, 0, 4] and, // - one for the LOL-WTF combination: [0, 0, 1, 0, 0, 3]. final ByteMap<SpanGroup> groups = new ByteMap<SpanGroup>(); final short value_width = tsdb.tag_values.width(); final byte[] group = new byte[group_bys.size() * value_width]; for (final Map.Entry<byte[], Span> entry : spans.entrySet()) { final byte[] row = entry.getKey(); byte[] value_id = null; int i = 0; // TODO(tsuna): The following loop has a quadratic behavior. We can // make it much better since both the row key and group_bys are sorted. for (final byte[] tag_id : group_bys) { value_id = Tags.getValueId(tsdb, row, tag_id); if (value_id == null) { break; } System.arraycopy(value_id, 0, group, i, value_width); i += value_width; } if (value_id == null) { LOG.error("WTF? Dropping span for row " + Arrays.toString(row) + " as it had no matching tag from the requested groups," + " which is unexpected. Query=" + this); continue; } //LOG.info("Span belongs to group " + Arrays.toString(group) + ": " + Arrays.toString(row)); SpanGroup thegroup = groups.get(group); if (thegroup == null) { thegroup = new SpanGroup(tsdb, getScanStartTime(), getScanEndTime(), null, rate, rate_options, aggregator, sample_interval, downsampler); // Copy the array because we're going to keep `group' and overwrite // its contents. So we want the collection to have an immutable copy. final byte[] group_copy = new byte[group.length]; System.arraycopy(group, 0, group_copy, 0, group.length); groups.put(group_copy, thegroup); } thegroup.add(entry.getValue()); } //for (final Map.Entry<byte[], SpanGroup> entry : groups) { // LOG.info("group for " + Arrays.toString(entry.getKey()) + ": " + entry.getValue()); return groups.values().toArray(new SpanGroup[groups.size()]); } } /** * Returns a scanner set for the given metric (from {@link #metric} or from * the first TSUID in the {@link #tsuids}s list. If one or more tags are * provided, it calls into {@link #createAndSetFilter} to setup a row key * filter. If one or more TSUIDs have been provided, it calls into * {@link #createAndSetTSUIDFilter} to setup a row key filter. * @return A scanner to use for fetching data points */ protected Scanner getScanner() throws HBaseException { final short metric_width = tsdb.metrics.width(); final byte[] start_row = new byte[metric_width + Const.TIMESTAMP_BYTES]; final byte[] end_row = new byte[metric_width + Const.TIMESTAMP_BYTES]; // We search at least one row before and one row after the start & end // time we've been given as it's quite likely that the exact timestamp // we're looking for is in the middle of a row. Plus, a number of things // rely on having a few extra data points before & after the exact start // & end dates in order to do proper rate calculation or downsampling near // the "edges" of the graph. Bytes.setInt(start_row, (int) getScanStartTime(), metric_width); Bytes.setInt(end_row, (end_time == UNSET ? -1 // Will scan until the end (0xFFF...). : (int) getScanEndTime()), metric_width); // set the metric UID based on the TSUIDs if given, or the metric UID if (tsuids != null && !tsuids.isEmpty()) { final String tsuid = tsuids.get(0); final String metric_uid = tsuid.substring(0, TSDB.metrics_width() * 2); metric = UniqueId.stringToUid(metric_uid); System.arraycopy(metric, 0, start_row, 0, metric_width); System.arraycopy(metric, 0, end_row, 0, metric_width); } else { System.arraycopy(metric, 0, start_row, 0, metric_width); System.arraycopy(metric, 0, end_row, 0, metric_width); } final Scanner scanner = tsdb.client.newScanner(tsdb.table); scanner.setStartKey(start_row); scanner.setStopKey(end_row); if (tsuids != null && !tsuids.isEmpty()) { createAndSetTSUIDFilter(scanner); } else if (tags.size() > 0 || group_bys != null) { createAndSetFilter(scanner); } scanner.setFamily(TSDB.FAMILY); return scanner; } /** Returns the UNIX timestamp from which we must start scanning. */ private long getScanStartTime() { // The reason we look before by `MAX_TIMESPAN * 2' seconds is because of // the following. Let's assume MAX_TIMESPAN = 600 (10 minutes) and the // start_time = ... 12:31:00. If we initialize the scanner to look // only 10 minutes before, we'll start scanning at time=12:21, which will // give us the row that starts at 12:30 (remember: rows are always aligned // on MAX_TIMESPAN boundaries -- so in this example, on 10m boundaries). // But we need to start scanning at least 1 row before, so we actually // look back by twice MAX_TIMESPAN. Only when start_time is aligned on a // MAX_TIMESPAN boundary then we'll mistakenly scan back by an extra row, // but this doesn't really matter. // Additionally, in case our sample_interval is large, we need to look // even further before/after, so use that too. long start = getStartTime(); // down cast to seconds if we have a query in ms if ((start & Const.SECOND_MASK) != 0) { start /= 1000; } final long ts = start - Const.MAX_TIMESPAN * 2 - sample_interval; return ts > 0 ? ts : 0; } /** Returns the UNIX timestamp at which we must stop scanning. */ private long getScanEndTime() { // For the end_time, we have a different problem. For instance if our // end_time = ... 12:30:00, we'll stop scanning when we get to 12:40, but // once again we wanna try to look ahead one more row, so to avoid this // problem we always add 1 second to the end_time. Only when the end_time // is of the form HH:59:59 then we will scan ahead an extra row, but once // again that doesn't really matter. // Additionally, in case our sample_interval is large, we need to look // even further before/after, so use that too. long end = getEndTime(); if ((end & Const.SECOND_MASK) != 0) { end /= 1000; } return end + Const.MAX_TIMESPAN + 1 + sample_interval; } /** * Sets the server-side regexp filter on the scanner. * In order to find the rows with the relevant tags, we use a * server-side filter that matches a regular expression on the row key. * @param scanner The scanner on which to add the filter. */ private void createAndSetFilter(final Scanner scanner) { if (group_bys != null) { Collections.sort(group_bys, Bytes.MEMCMP); } final short name_width = tsdb.tag_names.width(); final short value_width = tsdb.tag_values.width(); final short tagsize = (short) (name_width + value_width); // Generate a regexp for our tags. Say we have 2 tags: { 0 0 1 0 0 2 } // and { 4 5 6 9 8 7 }, the regexp will be: // "^.{7}(?:.{6})*\\Q\000\000\001\000\000\002\\E(?:.{6})*\\Q\004\005\006\011\010\007\\E(?:.{6})*$" final StringBuilder buf = new StringBuilder( 15 // "^.{N}" + "(?:.{M})*" + "$" + ((13 + tagsize) // "(?:.{M})*\\Q" + tagsize bytes + "\\E" * (tags.size() + (group_bys == null ? 0 : group_bys.size() * 3)))); // In order to avoid re-allocations, reserve a bit more w/ groups ^^^ // Alright, let's build this regexp. From the beginning... buf.append("(?s)" // Ensure we use the DOTALL flag. + "^.{") // ... start by skipping the metric ID and timestamp. .append(tsdb.metrics.width() + Const.TIMESTAMP_BYTES) .append("}"); final Iterator<byte[]> tags = this.tags.iterator(); final Iterator<byte[]> group_bys = (this.group_bys == null ? new ArrayList<byte[]>(0).iterator() : this.group_bys.iterator()); byte[] tag = tags.hasNext() ? tags.next() : null; byte[] group_by = group_bys.hasNext() ? group_bys.next() : null; // Tags and group_bys are already sorted. We need to put them in the // regexp in order by ID, which means we just merge two sorted lists. do { // Skip any number of tags. buf.append("(?:.{").append(tagsize).append("})*\\Q"); if (isTagNext(name_width, tag, group_by)) { addId(buf, tag); tag = tags.hasNext() ? tags.next() : null; } else { // Add a group_by. addId(buf, group_by); final byte[][] value_ids = (group_by_values == null ? null : group_by_values.get(group_by)); if (value_ids == null) { // We don't want any specific ID... buf.append(".{").append(value_width).append('}'); // Any value ID. } else { // We want specific IDs. List them: /(AAA|BBB|CCC|..)/ buf.append("(?:"); for (final byte[] value_id : value_ids) { buf.append("\\Q"); addId(buf, value_id); buf.append('|'); } // Replace the pipe of the last iteration. buf.setCharAt(buf.length() - 1, ')'); } group_by = group_bys.hasNext() ? group_bys.next() : null; } } while (tag != group_by); // Stop when they both become null. // Skip any number of tags before the end. buf.append("(?:.{").append(tagsize).append("})*$"); scanner.setKeyRegexp(buf.toString(), CHARSET); } /** * Sets the server-side regexp filter on the scanner. * This will compile a list of the tagk/v pairs for the TSUIDs to prevent * storage from returning irrelevant rows. * @param scanner The scanner on which to add the filter. * @since 2.0 */ private void createAndSetTSUIDFilter(final Scanner scanner) { Collections.sort(tsuids); // first, convert the tags to byte arrays and count up the total length // so we can allocate the string builder final short metric_width = tsdb.metrics.width(); int tags_length = 0; final ArrayList<byte[]> uids = new ArrayList<byte[]>(tsuids.size()); for (final String tsuid : tsuids) { final String tags = tsuid.substring(metric_width * 2); final byte[] tag_bytes = UniqueId.stringToUid(tags); tags_length += tag_bytes.length; uids.add(tag_bytes); } // Generate a regexp for our tags based on any metric and timestamp (since // those are handled by the row start/stop) and the list of TSUID tagk/v // pairs. The generated regex will look like: ^.{7}(tags|tags|tags)$ // where each "tags" is similar to \\Q\000\000\001\000\000\002\\E final StringBuilder buf = new StringBuilder( 13 + (tsuids.size() * 11) // "\\Q" + "\\E|" + tags_length); // total # of bytes in tsuids tagk/v pairs // Alright, let's build this regexp. From the beginning... buf.append("(?s)" // Ensure we use the DOTALL flag. + "^.{") // ... start by skipping the metric ID and timestamp. .append(tsdb.metrics.width() + Const.TIMESTAMP_BYTES) .append("}("); for (final byte[] tags : uids) { // quote the bytes buf.append("\\Q"); addId(buf, tags); buf.append('|'); } // Replace the pipe of the last iteration, close and set buf.setCharAt(buf.length() - 1, ')'); buf.append("$"); scanner.setKeyRegexp(buf.toString(), CHARSET); } /** * Helper comparison function to compare tag name IDs. * @param name_width Number of bytes used by a tag name ID. * @param tag A tag (array containing a tag name ID and a tag value ID). * @param group_by A tag name ID. * @return {@code true} number if {@code tag} should be used next (because * it contains a smaller ID), {@code false} otherwise. */ private boolean isTagNext(final short name_width, final byte[] tag, final byte[] group_by) { if (tag == null) { return false; } else if (group_by == null) { return true; } final int cmp = Bytes.memcmp(tag, group_by, 0, name_width); if (cmp == 0) { throw new AssertionError("invariant violation: tag ID " + Arrays.toString(group_by) + " is both in 'tags' and" + " 'group_bys' in " + this); } return cmp < 0; } /** * Appends the given ID to the given buffer, followed by "\\E". */ private static void addId(final StringBuilder buf, final byte[] id) { boolean backslash = false; for (final byte b : id) { buf.append((char) (b & 0xFF)); if (b == 'E' && backslash) { // If we saw a `\' and now we have a `E'. // So we just terminated the quoted section because we just added \E // to `buf'. So let's put a litteral \E now and start quoting again. buf.append("\\\\E\\Q"); } else { backslash = b == '\\'; } } buf.append("\\E"); } public String toString() { final StringBuilder buf = new StringBuilder(); buf.append("TsdbQuery(start_time=") .append(getStartTime()) .append(", end_time=") .append(getEndTime()); if (tsuids != null && !tsuids.isEmpty()) { buf.append(", tsuids="); for (final String tsuid : tsuids) { buf.append(tsuid).append(","); } } else { buf.append(", metric=").append(Arrays.toString(metric)); try { buf.append(" (").append(tsdb.metrics.getName(metric)); } catch (NoSuchUniqueId e) { buf.append(" (<").append(e.getMessage()).append('>'); } try { buf.append("), tags=").append(Tags.resolveIds(tsdb, tags)); } catch (NoSuchUniqueId e) { buf.append("), tags=<").append(e.getMessage()).append('>'); } } buf.append(", rate=").append(rate) .append(", aggregator=").append(aggregator) .append(", group_bys=("); if (group_bys != null) { for (final byte[] tag_id : group_bys) { try { buf.append(tsdb.tag_names.getName(tag_id)); } catch (NoSuchUniqueId e) { buf.append('<').append(e.getMessage()).append('>'); } buf.append(' ') .append(Arrays.toString(tag_id)); if (group_by_values != null) { final byte[][] value_ids = group_by_values.get(tag_id); if (value_ids == null) { continue; } buf.append("={"); for (final byte[] value_id : value_ids) { try { buf.append(tsdb.tag_values.getName(value_id)); } catch (NoSuchUniqueId e) { buf.append('<').append(e.getMessage()).append('>'); } buf.append(' ') .append(Arrays.toString(value_id)) .append(", "); } buf.append('}'); } buf.append(", "); } } buf.append("))"); return buf.toString(); } /** * Comparator that ignores timestamps in row keys. */ private static final class SpanCmp implements Comparator<byte[]> { private final short metric_width; public SpanCmp(final short metric_width) { this.metric_width = metric_width; } public int compare(final byte[] a, final byte[] b) { final int length = Math.min(a.length, b.length); if (a == b) { // Do this after accessing a.length and b.length return 0; // in order to NPE if either a or b is null. } int i; // First compare the metric ID. for (i = 0; i < metric_width; i++) { if (a[i] != b[i]) { return (a[i] & 0xFF) - (b[i] & 0xFF); // "promote" to unsigned. } } // Then skip the timestamp and compare the rest. for (i += Const.TIMESTAMP_BYTES; i < length; i++) { if (a[i] != b[i]) { return (a[i] & 0xFF) - (b[i] & 0xFF); // "promote" to unsigned. } } return a.length - b.length; } } }
package org.reldb.relui.monitors; import java.util.Deque; import java.util.LinkedList; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; public class PercentDisplay extends org.eclipse.swt.widgets.Canvas { private Deque<Integer> percentageHistory; private int middleLimit = 50; private int lowerLimit = 20; private Color goodColor; private Color okColor; private Color badColor; private Color black; private Color lightGray; private int delay = 500; private boolean running = true; private int displayWidth; private String emitText = ""; private final Runnable refresh = new Runnable() { public void run() { if (!isDisposed()) redraw(); } }; private void refresh() { if (isDisposed()) return; getDisplay().asyncExec(refresh); } public void setMiddleLimit(int middleLimit) { if (this.middleLimit < 0 || this.middleLimit > 100) throw new IllegalArgumentException("MiddleLimit must be between 0 and 100, inclusive."); this.middleLimit = middleLimit; refresh(); } public int getMiddleLimit() { return middleLimit; } public void setLowerLimit(int lowerLimit) { if (this.lowerLimit < 0 || this.lowerLimit > 100) throw new IllegalArgumentException("LowerLimit must be between 0 and 100, inclusive."); this.lowerLimit = lowerLimit; refresh(); } public int getLowerLimit() { return lowerLimit; } public void setDelay(int milliseconds) { delay = milliseconds; } public int getDelay() { return delay; } public void dispose() { running = false; goodColor.dispose(); badColor.dispose(); okColor.dispose(); black.dispose(); lightGray.dispose(); super.dispose(); } // Force color value between 0 and 255. private static int cr(int x) { return Math.max(Math.min(x, 255), 0); } // Make a Color redder private static Color redder(Color c) { return new Color(c.getDevice(), cr(c.getRed() + 30), cr(c.getGreen() - 30), cr(c.getBlue() - 30)); } // Make a color yellower private static Color yellower(Color c) { return new Color(c.getDevice(), cr(c.getRed() + 30), cr(c.getGreen() + 30), cr(c.getBlue() - 30)); } // Make a Color greener private static Color greener(Color c) { return new Color(c.getDevice(), cr(c.getRed() - 30), cr(c.getGreen() + 30), cr(c.getBlue() - 30)); } private synchronized Integer[] getPercentages() { return percentageHistory.toArray(new Integer[0]); } private synchronized void addPercentage(int percentValue) { percentageHistory.add(percentValue); while (percentageHistory.size() > displayWidth) percentageHistory.removeFirst(); } public PercentDisplay(Composite parent, int style, String displaytext, PercentSource percent) { super(parent, style); percentageHistory = new LinkedList<Integer>(); goodColor = greener(getBackground()); badColor = redder(getBackground()); okColor = yellower(getBackground()); black = new Color(parent.getDisplay(), 0, 0, 0); lightGray = new Color(parent.getDisplay(), 200, 200, 200); addListener (SWT.Paint, new Listener () { @Override public void handleEvent (Event e) { GC gc = e.gc; Rectangle rect = getClientArea(); displayWidth = rect.width; Integer[] percentages = getPercentages(); int lastX = rect.x; int lastY = rect.y; for (int index=0; index<percentages.length; index++) { int barY = (100 - percentages[index]) * rect.height / 100 + 2; int barX = rect.x + index; gc.setForeground(getBackground()); gc.drawLine(barX, rect.y, barX, barY); if (percentages[index] < lowerLimit) gc.setForeground(badColor); else if (percentages[index] < middleLimit) gc.setForeground(okColor); else gc.setForeground(goodColor); gc.drawLine(barX, rect.height, barX, barY); if (index > 0) { int dontDrawLineBelow = 5; if (lastY < dontDrawLineBelow && barY < dontDrawLineBelow) gc.setForeground(black); else gc.setForeground(lightGray); gc.drawLine(lastX, lastY, barX, barY); } lastX = barX; lastY = barY; } gc.setForeground(black); gc.drawText(emitText, 2, 5, true); } }); Thread painter = new Thread() { public void run() { while (running) { try {sleep(delay);} catch (InterruptedException ie) {} int percentValue = percent.getPercent(); addPercentage(percentValue); emitText = String.format("%3d%% ", percentValue) + displaytext; refresh(); } } }; painter.start(); } }
package data.core; public enum Norm { MEANSD, MINMAX, NULL }
package boundary.Score; import entity.Question; import entity.Score; import java.util.List; import javax.ejb.Stateless; import javax.persistence.CacheStoreMode; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class ScoreResource { @PersistenceContext EntityManager entityManager; /** * Method to find a Score by id * @param id * @return Score */ public Score findById(String id) { return entityManager.find(Score.class, id); } /** * Method to get all the scores by value decreasing order * @return List of Score */ public List<Score> findAll() { return entityManager.createNamedQuery("Score.findAll", Score.class) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); } /** * Method to get all the scores from a Question * @param question * @return List of Score */ public List<Score> findByQuestion(Question question) { return entityManager.createQuery("SELECT s FROM Score s WHERE s.question =: question") .setParameter("question", question) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); } /** * Method that returns the scores with pagination and limit method * * @param offset start at the nth position * @param limit number max of result * @return List of Score */ public List<Score> offsetLimit(int offset, int limit) { return entityManager.createNamedQuery("Score.findAll", Score.class) .setFirstResult(offset) .setMaxResults(limit) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); } /** * Method that inserts a score into the database * @param score to add * @return the score added */ public Score insert(Score score) { score.generateId(); return entityManager.merge(score); } /** * Method to delete a score * @param score the Score to delete */ public void delete(Score score) { entityManager.remove(score); } /** * Method to update a score * @param score * @return the updated score */ public Score update(Score score) { return entityManager.merge(score); } }
//#if ${BugTrack} == "T" or ${Categoria} == "T" or ${Cupom} == "T" or ${Endereco} == "T" or ${FormaPagament} == "T" or ${Mensagem} == "T" or ${Perfil} == "T" or ${Produto} == "T" or ${SituacaoBug} == "T" or ${StatusUsuario} == "T" or ${StatusVenda} == "T" or ${TipoMensagem} == "T" or ${UnidadeMedida} == "T" or ${UsuarioCupom} == "T" or ${UsuarioCupom} == "T" or ${Usuario} == "T" or ${Venda} == "T" or ${VendaProduto} == "T" or ${VendaProdutoEmbbed} == "T" package br.com.webstore.facade; import java.util.List; //#if ${BugTrack} == "T" import br.com.webstore.dao.BugTrackDao; //#endif //#if ${Categoria} == "T" import br.com.webstore.dao.CategoriaDao; //#endif //#if ${Cupom} == "T" import br.com.webstore.dao.CupomDao; //#endif //#if ${Endereco} == "T" import br.com.webstore.dao.EnderecoDao; //#endif //#if ${Faq} == "T" import br.com.webstore.dao.FaqDao; //#endif //#if ${FormaPagamento} == "T" import br.com.webstore.dao.FormaPagamentDao; //#endif //#if ${Mensagem} == "T" import br.com.webstore.dao.MensagemDao; //#endif //#if ${Perfil} == "T" import br.com.webstore.dao.PerfilDao; //#endif //#if ${Produto} == "T" import br.com.webstore.dao.ProdutoDao; //#endif //#if ${SituacaoBug} == "T" import br.com.webstore.dao.SituacaoBugDao; //#endif //#if ${StatusUsuario} == "T" import br.com.webstore.dao.StatusUsuarioDao; //#endif //#if ${StatusVenda} == "T" import br.com.webstore.dao.StatusVendaDao; //#endif //#if ${TipoMensagem} == "T" import br.com.webstore.dao.TipoMensagemDao; //#endif //#if ${UnidadeMedida} == "T" import br.com.webstore.dao.UnidadeMedidaDao; //#endif //#if ${UsuarioCupom} == "T" import br.com.webstore.dao.UsuarioCupomDao; //#endif //#if ${Usuario} == "T" import br.com.webstore.dao.UsuarioDao; //#endif //#if ${Venda} == "T" import br.com.webstore.dao.VendaDao; //#endif //#if ${VendaProduto} == "T" import br.com.webstore.dao.VendaProdutoDao; //#endif //#if ${VendaProdutoEmbbed} == "T" import br.com.webstore.dao.VendaProdutoEmbbedDao; //#endif //#if ${BugTrack} == "T" import br.com.webstore.model.BugTrack; //#endif //#if ${Categoria} == "T" import br.com.webstore.model.Categoria; //#endif //#if ${Cupom} == "T" import br.com.webstore.model.Cupom; //#endif //#if ${Endereco} == "T" import br.com.webstore.model.Endereco; //#endif //#if ${Faq} == "T" import br.com.webstore.model.Faq; //#endif //#if ${FormaPagamento} == "T" import br.com.webstore.model.FormaPagamento; //#endif //#if ${Mensagem} == "T" import br.com.webstore.model.Mensagem; //#endif //#if ${Perfil} == "T" import br.com.webstore.model.Perfil; //#endif //#if ${Produto} == "T" import br.com.webstore.model.Produto; //#endif //#if ${SituacaoBug} == "T" import br.com.webstore.model.SituacaoBug; //#endif //#if ${StatusUsuario} == "T" import br.com.webstore.model.StatusUsuario; //#endif //#if ${StatusVenda} == "T" import br.com.webstore.model.StatusVenda; //#endif //#if ${TipoMensagem} == "T" import br.com.webstore.model.TipoMensagem; //#endif //#if ${UnidadeMedida} == "T" import br.com.webstore.model.UnidadeMedida; //#endif //#if ${Usuario} == "T" import br.com.webstore.model.Usuario; //#endif //#if ${UsuarioCupom} == "T" import br.com.webstore.model.UsuarioCupom; //#endif //#if ${Venda} == "T" import br.com.webstore.model.Venda; //#endif //#if ${VendaProduto} == "T" import br.com.webstore.model.VendaProduto; //#endif //#if ${VendaProdutoEmbbed} == "T" import br.com.webstore.model.VendaProdutoEmbbed; //#endif /** * @author webstore * */ public class GenericFacade { //#if ${BugTrack} == "T" private BugTrackDao bugTrackDao = new BugTrackDao(); public BugTrack insertBugTrack(BugTrack bugTrack) { return bugTrackDao.insert(bugTrack); } public Boolean updateBugTrack(BugTrack bugTrack) {//TODO: remove retornar boolean bugTrackDao.update(bugTrack); return true; } public List<BugTrack> findBugTrack(BugTrack query) { return bugTrackDao.getList(); } public List<BugTrack> findBugTrack(String titulo, SituacaoBug situacao) { return this.bugTrackDao.findByTitulo(titulo, situacao); } public List<BugTrack> findBugTrack(String titulo) { return this.bugTrackDao.findByTitulo(titulo); } public List<BugTrack> findBugTrack() { return bugTrackDao.getList(); } public Boolean removeBugTrack(int id){ //TODO: remove retornar boolean bugTrackDao.remove(id); return true; } public BugTrack getBugTrack(int id) { return bugTrackDao.find(id); } //#endif //#if ${FAQ} == "T" private FaqDao faqDataProvider = new FaqDao(); public Faq insertFaq(Faq faq) { return this.faqDataProvider.insert(faq); } public void updateFaq(Faq faq) { this.faqDataProvider.update(faq); } public List<Faq> findFaq(String descricao) { return this.faqDataProvider.findByNome(descricao); } public Faq getFaqById(int id) { return this.faqDataProvider.find(id); } public void removerFaq(int id) { this.faqDataProvider.remove(id); } //#endif //Categoria //#if ${Categoria} == "T" private CategoriaDao categoriaDataProvider = new CategoriaDao(); public Categoria insertCategoria(Categoria categoria) { return this.categoriaDataProvider.insert(categoria); //replace return categoriaDataProvider.insert(categoria); } public void updateCategoria(Categoria categoria) { //replace categoriaDataProvider.update(categoria); this.categoriaDataProvider.update(categoria); } public List<Categoria> findCategoria(String nome) { //replace public List<Categoria> findCategoria() { // return categoriaDataProvider.getList(); return this.categoriaDataProvider.findByNome(nome); } public Categoria getById(int id) { return this.categoriaDataProvider.find(id); } public void removerCategoria(int id) { this.categoriaDataProvider.remove(id); } public List<Categoria> getListCategoria() { return categoriaDataProvider.getList(); } //#endif //Cupom //#if ${Cupom} == "T" private CupomDao cupomDataProvider = new CupomDao(); public Cupom insertCupom(Cupom cupom) { return cupomDataProvider.insert(cupom); } public void updateCupom(Cupom cupom) { cupomDataProvider.update(cupom); } public List<Cupom> findCupom(Cupom query) { return cupomDataProvider.getList(); } //#endif //Endereco //#if ${Endereco} == "T" private EnderecoDao enderecoDataProvider = new EnderecoDao(); public Endereco insertEndereco(Endereco endereco) { return enderecoDataProvider.insert(endereco); } public void updateEndereco(Endereco endereco) { enderecoDataProvider.update(endereco); } public List<Endereco> findEndereco(Endereco query) { return enderecoDataProvider.getList(); } //#endif //FormaPagamento //#if ${FormaPagamento} == "T" private FormaPagamentDao formaPagamentDataProvider = new FormaPagamentDao(); public FormaPagamento insertFormaPagamento(FormaPagamento formaPagamento) { return formaPagamentDataProvider.insert(formaPagamento); } public void updateFormaPagamento(FormaPagamento formaPagamento) { formaPagamentDataProvider.update(formaPagamento); } public List<FormaPagamento> findFormaPagamento(FormaPagamento query) { return formaPagamentDataProvider.getList(); } //#endif //Mensagem //#if ${Mensagem} == "T" private MensagemDao mensagemDao = new MensagemDao(); public void insert(Mensagem mensagem) { this.mensagemDao.insert(mensagem); } public void update(Mensagem mensagem) { this.mensagemDao.update(mensagem); } public Mensagem find(Integer id) { return this.mensagemDao.find(id); } public List<Mensagem> list(Mensagem query) { return this.mensagemDao.getList(); } //#endif //Perfil //#if ${Perfil} == "T" private PerfilDao perfilDataProvider = new PerfilDao(); public Perfil insertPerfil(Perfil perfil) { return perfilDataProvider.insert(perfil); } public void savePerfil(Perfil perfil) { perfilDataProvider.update(perfil); } public List<Perfil> findPerfil(Perfil query) { return perfilDataProvider.getList(); } //#endif //Produto //#if ${Produto} == "T" private ProdutoDao produtoDataProvider = new ProdutoDao(); public Produto insertProduto(Produto produto) { return this.produtoDataProvider.insert(produto); } public void updateProduto(Produto produto) { this.produtoDataProvider.update(produto); } public List<Produto> findProduto(String nome) { return this.produtoDataProvider.findByNome(nome); } public Produto getProdutoById(int id) { return this.produtoDataProvider.find(id); } public void removerProduto(int id) { this.produtoDataProvider.remove(id); } //#endif //SituacaoBug //#if ${SituacaoBug} == "T" private SituacaoBugDao situacaoBugDataProvider= new SituacaoBugDao(); public SituacaoBug insertSituacaoBug(SituacaoBug situacaoBug) { return situacaoBugDataProvider.insert(situacaoBug); } public void updateSituacaoBug(SituacaoBug situacaoBug) { situacaoBugDataProvider.update(situacaoBug); } public List<SituacaoBug> findSituacaoBug(SituacaoBug query) { return situacaoBugDataProvider.getList(); } public List<SituacaoBug> getListSituacaoBug() { return situacaoBugDataProvider.getList(); } public SituacaoBug findSituacaoBug(int id){ return situacaoBugDataProvider.find(id); } public SituacaoBugDao getDaoSituacaoBug(){ return situacaoBugDataProvider; } //#endif //StatusUsuario //#if ${StatusUsuario} == "T" private StatusUsuarioDao statusUsuarioDataProvider = new StatusUsuarioDao(); public StatusUsuario insertStatusUsuario(StatusUsuario statusUsuario) { return statusUsuarioDataProvider.insert(statusUsuario); } public void updateStatusUsuario(StatusUsuario statusUsuario) { statusUsuarioDataProvider.update(statusUsuario); } public List<StatusUsuario> findStatusUsuario(StatusUsuario query) { return statusUsuarioDataProvider.getList(); } //#endif //StatusVenda //#if ${StatusVenda} == "T" private StatusVendaDao statusVendaDataProvider = new StatusVendaDao(); public StatusVenda insertStatusVenda(StatusVenda statusVenda) { return statusVendaDataProvider.insert(statusVenda); } public void updateStatusVenda(StatusVenda statusVenda) { statusVendaDataProvider.update(statusVenda); } public List<StatusVenda> findStatusVenda(StatusVenda query) { return statusVendaDataProvider.getList(); } //#endif //TipoMensagem //#if ${TipoMensagem} == "T" private TipoMensagemDao tipoMensagemDataProvider = new TipoMensagemDao(); public TipoMensagem findTipoMensagem(Integer id) { return tipoMensagemDataProvider.find(id); } public List<TipoMensagem> listTipoMensagem() { return tipoMensagemDataProvider.getList(); } //#endif //UnidadeMedida //#if ${UnidadeMedida} == "T" private UnidadeMedidaDao unidadeMedidaDao = new UnidadeMedidaDao(); public UnidadeMedida insertUnidadeMedida(UnidadeMedida unidadeMedida) { return unidadeMedidaDao.insert(unidadeMedida); } public void updateUnidadeMedida(UnidadeMedida unidadeMedida) { unidadeMedidaDao.update(unidadeMedida); } public List<UnidadeMedida> findUnidadeMedida(UnidadeMedida unidadeMedida) { return unidadeMedidaDao.getList(); } public List<UnidadeMedida> getListUnidadeMedida() { return unidadeMedidaDao.getList(); } //#endif //UsuarioCupom //#if ${UsuarioCupom} == "T" private UsuarioCupomDao usuarioCupomDao; public UsuarioCupom insertUsuarioCupom(UsuarioCupom usuarioCupom) { return usuarioCupomDao.insert(usuarioCupom); } public void updateUsuarioCupom(UsuarioCupom usuarioCupom) { usuarioCupomDao.update(usuarioCupom); } public List<UsuarioCupom> findUsuarioCupom(UsuarioCupom usuarioCupom) { return usuarioCupomDao.getList(); } //#endif //Usuario //#if ${Usuario} == "T" private UsuarioDao usuarioDao = new UsuarioDao(); public Usuario insertUsuario(Usuario usuario) { return usuarioDao.insert(usuario); } public void updateUsuario(Usuario usuario) { usuarioDao.update(usuario); } public List<Usuario> findUsuario(Usuario usuario) { return usuarioDao.getList(); } public void removeUsuario(Integer id) { usuarioDao.remove(id); } public Usuario getUsuarioById(Integer id) { return usuarioDao.find(id); } public List<Usuario> getUsuarioByLoginSenha(String Login, String Senha) { return usuarioDao.getUsuarioByLoginSenha(Login, Senha); } //#endif //Venda //#if ${Venda} == "T" private VendaDao vendaDao; public Venda insertVenda(Venda venda) { return vendaDao.insert(venda); } public void updateVenda(Venda venda) { vendaDao.update(venda); } public List<Venda> findCategoria(Venda venda) { return vendaDao.getList(); } //#endif //VendaProdutoEmbbed //#if ${VendaProdutoEmbbed} == "T" private VendaProdutoEmbbedDao vendaProdutoEmbbedDao = new VendaProdutoEmbbedDao(); public VendaProdutoEmbbed insertVendaProdutoEmbbed(VendaProdutoEmbbed vendaProdutoEmbbed) { return vendaProdutoEmbbedDao.insert(vendaProdutoEmbbed); } public void updateVendaProdutoEmbbed(VendaProdutoEmbbed vendaProdutoEmbbed) { vendaProdutoEmbbedDao.update(vendaProdutoEmbbed); } public List<VendaProdutoEmbbed> findVendaProdutoEmbbed(VendaProdutoEmbbed vendaProdutoEmbbed) { return vendaProdutoEmbbedDao.getList(); } //#endif //VendaProduto //#if ${VendaProduto} == "T" private VendaProdutoDao vendaProdutoDao = new VendaProdutoDao(); public VendaProduto insertVendaProduto(VendaProduto vendaProduto) { return vendaProdutoDao.insert(vendaProduto); } public void updateVendaProduto(VendaProduto vendaProduto) { vendaProdutoDao.update(vendaProduto); } public List<VendaProduto> findVendaProduto(VendaProduto vendaProduto) { return vendaProdutoDao.getList(); } //#endif } //#endif
package com.jsv; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import com.jsv.hardware.OTH; import com.jsv.command.Command; import com.jsv.hardware.CPUList; import com.jsv.instance.Instance; import com.jsv.instance.ShortestJobTimeInstance; public class Driver { private static final String NEW = "NEW"; private static final String CPU = "CPU"; private static final String OTH = "OTH"; public static int clock = 0; //Start at time 0 public static final int NUM_CPUS = 2; /** Alternate CPU and other call. Always start with CPU. * @throws IOException * */ public static void main(String[] args) throws IOException { // First come first serve // Shortest Job First // Priority // Pick the time of the next CPU call and find // Least other time // Total number of commands // Time slicing // Multiqueue List<Instance> instanceTable = new LinkedList<Instance>(); int pid = 0; StringBuilder filePath = new StringBuilder("src/input.txt"); BufferedReader reader = new BufferedReader(new FileReader(filePath.toString())); String[] commandTime = new String[2]; String line = reader.readLine(); while(line != null) { commandTime = line.split(" "); // Make a new Instance if(commandTime[0].equals(NEW)) { // instanceTable.add(new FCFSInstance(pid, Integer.parseInt(commandTime[1]))); // instanceTable.add(new TotalTimeInstance(pid, Integer.parseInt(commandTime[1]))); instanceTable.add(new ShortestJobTimeInstance(pid, Integer.parseInt(commandTime[1]))); pid++; } // CPU command if(commandTime[0].equals(CPU)) { // Get the last Instance and add a new command instanceTable.get(pid-1).addCommand(new Command(1, Integer.parseInt(commandTime[1]))); } // Other command if(commandTime[0].equals(OTH)) { // Get the last Instance and add a new command instanceTable.get(pid-1).addCommand(new Command(2, Integer.parseInt(commandTime[1]))); } // Read a new line line = reader.readLine(); } //Reads file in // Close the reader reader.close(); Queue<Instance> priority = new PriorityQueue<Instance>(instanceTable); /* for(int i = 0; !priority.isEmpty(); i++) { System.out.println(priority.poll().getPid()); }*/ CPUList slechta = new CPUList(Driver.NUM_CPUS); for(Instance instance : instanceTable) { slechta.add(instance); } /*slechta.printList(); System.out.println("Removing an Instance from CPU 1: " + slechta.pop(1).getPid()); slechta.printList();*/ Queue<OTH> othQueue = new PriorityQueue<OTH>(); ArrayList<Instance> finishedList = new ArrayList<Instance>(); int originalLength = instanceTable.size(); while(finishedList.size() != originalLength) { System.out.println("Hey bro"); finishedList.add(new Instance(0,0)); } } }
package gameutils; import gameutils.util.FastMath; import java.applet.Applet; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; /** * Game is the main class that must be extended by the user. It handles the game loop and certain other functions.<br> * Game extends Applet but also supports being a desktop app.<br> * Remember: if this game will be used as an Applet, a default constructor <strong>MUST</strong> be present.<br> * <br> * It uses a Screen system where only 1 Screen is active at one time.<br> * <br> * A typical game looks like this: <br> * <br> * <code> * public class MyGame extends Game {<br> * &nbsp;&nbsp;&nbsp;&nbsp;public static void main(String args[]) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MyGame game = new MyGame();<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;game.setupFrame("My Game",800,600,true);<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;game.start();<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * <br> * &nbsp;&nbsp;&nbsp;&nbsp;public void initGame() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Initialize the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * <br> * &nbsp;&nbsp;&nbsp;&nbsp;public void update(long deltaTime) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super.update(deltaTime);<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Optional: update the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * <br> * &nbsp;&nbsp;&nbsp;&nbsp;public void paused() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Pause the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void resumed() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Resume the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void resized(int width, int height) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Resize the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void stopGame() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Stop the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void paint(Graphics2D g) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super.paint(g);<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Optional: draw the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * } * </code> * @author Roi Atalla */ public abstract class Game extends Applet implements Runnable { private static final long serialVersionUID = -1870725768768871166L; static { try{ UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch(Exception exc) {} } /** * Initializes and displays the window. * @param title The title of the window * @param width The width of the window * @param height The height of the window * @param resizable If true, the window will be resizable, else it will not be resizable. * @return The JFrame that was initialized by this method. */ protected final JFrame setupFrame(String title, int width, int height, boolean resizable) { final JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setIgnoreRepaint(true); frame.setResizable(resizable); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { synchronized(Game.this) { stopGame(); } System.exit(0); } }); frame.add(this); frame.setVisible(true); isApplet = false; setSize(width,height); init(); ((JPanel)frame.getContentPane()).revalidate(); return frame; } /** * Used to notify the game loop thread to update and render as fast as possible. */ public static final int MAX_FPS = 0; /** * Used to notify the game loop thread to update the maximum number of times before render. */ public static final int MAX_UPDATES = -1; /** * 1 second in nanoseconds, AKA 1,000,000 nanoseconds. */ public static final long ONE_SECOND = (long)1e9; private final Art art; private final Sound sound; private final Map<String,ScreenInfo> screens; private ScreenInfo currentScreen; private final Canvas canvas; private final Input input; private ArrayList<Event> events; private Object quality; private int maxUpdates; private int FPS; private double version; private boolean showFPS; private boolean useYield; private boolean standardKeysEnabled = true; private boolean isApplet = true; private volatile boolean isActive; private volatile boolean isPaused; /** * Default constructor. The defaults are:<br> * - MAX_UPDATES is set * - 60FPS<br> * - Version 1.0<br> * - showFPS = true<br> * - quality = high<br> * - standardKeysEnabled = true */ public Game() { this(60,1.0); } /** * Sets defaults and the FPS and version. * @param FPS The FPS to achieve. * @param version The version of this game. */ public Game(int FPS, double version) { art = new Art(); sound = new Sound(); screens = Collections.synchronizedMap(new HashMap<String,ScreenInfo>()); currentScreen = new ScreenInfo(new Screen() { public void init(Game game) {} public Game getGame() { return null; } public void show() {} public void hide() {} public void paused() {} public void resumed() {} public void resized(int width, int height) {} public void update(long deltaTime) {} public void draw(Graphics2D g) {} }); screens.put("Default", currentScreen); canvas = new Canvas(); input = new Input(canvas); events = new ArrayList<Event>(); this.FPS = FPS; this.version = version; showFPS = true; quality = RenderingHints.VALUE_ANTIALIAS_ON; maxUpdates = MAX_UPDATES; } /** * Returns the current working directory of this game. * @return The current working directory of this game. */ public URL getCodeBase() { if(isApplet()) return super.getCodeBase(); try{ return getClass().getResource("/"); } catch(Exception exc) { exc.printStackTrace(); return null; } } public Graphics getGraphics() { return canvas.getGraphics(); } /** * Returns the appropriate container of this game: this instance if it is an Applet, the JFrame if it is a desktop application. * @return If this game is an Applet, it returns this instance, else it returns the JFrame used to display this game. */ public Container getRootParent() { if(isApplet()) return this; return getParent().getParent().getParent().getParent(); } public int getWidth() { return canvas.getWidth(); } public int getHeight() { return canvas.getHeight(); } /** * @return Returns true if this game is an Applet, false otherwise. */ public boolean isApplet() { return isApplet; } /** * @return Returns true if this game is currently active. */ public boolean isActive() { return isActive; } /** * Manually pauses the game loop. paused() will be called */ public void pause() { if(isActive()) { isPaused = true; paused(); } } /** * Returns true if the game loop is paused. * @return True if the game loop is paused, false otherwise. */ public boolean isPaused() { return isPaused; } /** * Manually resumes the game loop. resumed() will be called right before the game loop resumes. */ public void resume() { if(isActive() && isPaused()) { isPaused = false; resumed(); } } /** * If this game is an applet, it calls the superclass's resize method, else it calls setSize(int,int). * @param width The new width of this game's canvas. * @param height The new height of this game's canvas; */ public void resize(int width, int height) { if(isApplet()) super.resize(width,height); else setSize(width,height); } /** * If this game is an Applet, it calls the superclass's resize method, else it adjusts the JFrame according to the platform specific Insets. * @param width The new width of this game's canvas * @param height The new height of this game's canvas */ public void setSize(int width, int height) { if(isApplet()) super.resize(width,height); else { Insets i = getRootParent().getInsets(); getRootParent().setSize(width+i.right+i.left,height+i.bottom+i.top); ((JFrame)getRootParent()).setLocationRelativeTo(null); } } public void setFullScreen(boolean setFullScreen) { GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); if(setFullScreen) { if(isFullScreen()) throw new IllegalStateException("A full screen window is already open."); JFrame frame = new JFrame(); frame.setResizable(false); frame.setUndecorated(true); frame.setIgnoreRepaint(true); remove(canvas); invalidate(); validate(); frame.add(canvas); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { setFullScreen(false); } }); if(!isApplet()) getRootParent().setVisible(false); gd.setFullScreenWindow(frame); } else { if(!isFullScreen()) return; gd.getFullScreenWindow().dispose(); gd.setFullScreenWindow(null); add(canvas); invalidate(); validate(); if(!isApplet()) getRootParent().setVisible(true); } canvas.requestFocus(); } /** * Returns true if this game is running full screen. * @return True if this game is running full screen, false otherwise. */ public boolean isFullScreen() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getFullScreenWindow() != null; } /** * Game loop. */ public final void run() { if(isActive()) return; Thread.currentThread().setName("Game Loop Thread"); synchronized(Game.this) { initGame(); } Listener listener = new Listener(); canvas.addKeyListener(listener); canvas.addMouseListener(listener); canvas.addMouseMotionListener(listener); canvas.addMouseWheelListener(listener); canvas.createBufferStrategy(2); BufferStrategy strategy = canvas.getBufferStrategy(); Font fpsFont = new Font(Font.SANS_SERIF,Font.TRUETYPE_FONT,10); int frames = 0; int currentFPS = 0; long time = System.nanoTime(); long lastTime = System.nanoTime(); isActive = true; canvas.requestFocus(); while(isActive()) { long diffTime = System.nanoTime()-lastTime; lastTime += diffTime; try{ processEvents(); } catch(Exception exc) { exc.printStackTrace(); } int updateCount = 0; while(diffTime > 0 && (maxUpdates <= 0 || updateCount < maxUpdates) && !isPaused()) { long deltaTime = FPS > 0 ? deltaTime = Math.min(diffTime,ONE_SECOND/FPS) : diffTime; try{ synchronized(Game.this) { update(deltaTime); } } catch(Exception exc) { exc.printStackTrace(); } diffTime -= deltaTime; updateCount++; } try{ do{ do{ Graphics2D g = (Graphics2D)strategy.getDrawGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,quality); try{ synchronized(Game.this) { paint(g); } } catch(Exception exc) { exc.printStackTrace(); } if(showFPS) { g.setColor(Color.black); g.setFont(fpsFont); g.drawString("Version " + version + " " + currentFPS + " FPS",2,getHeight()-2); } g.dispose(); }while(strategy.contentsRestored()); strategy.show(); }while(strategy.contentsLost()); } catch(Exception exc) { exc.printStackTrace(); } frames++; if(System.nanoTime()-time >= ONE_SECOND) { time = System.nanoTime(); currentFPS = frames; frames = 0; } try{ if(FPS > 0) { long sleepTime = FastMath.round((ONE_SECOND/FPS)-(System.nanoTime()-lastTime)); if(sleepTime <= 0) continue; long prevTime = System.nanoTime(); while(System.nanoTime()-prevTime <= sleepTime) { if(useYield) Thread.yield(); else Thread.sleep(1); } } } catch(Exception exc) { exc.printStackTrace(); } } stopGame(); if(!isApplet() && ((JFrame)getRootParent()).getDefaultCloseOperation() == JFrame.EXIT_ON_CLOSE) System.exit(0); } private void processEvents() { synchronized(events) { for(Event e : events) { switch(e.id) { case 0: for(InputListener l : currentScreen.listeners) l.keyTyped((KeyEvent)e.event,getScreen()); break; case 1: for(InputListener l : currentScreen.listeners) l.keyPressed((KeyEvent)e.event,getScreen()); break; case 2: for(InputListener l : currentScreen.listeners) l.keyReleased((KeyEvent)e.event,getScreen()); break; case 3: for(InputListener l : currentScreen.listeners) l.mouseClicked((MouseEvent)e.event,getScreen()); break; case 4: for(InputListener l : currentScreen.listeners) l.mouseEntered((MouseEvent)e.event,getScreen()); break; case 5: for(InputListener l : currentScreen.listeners) l.mouseExited((MouseEvent)e.event,getScreen()); break; case 6: for(InputListener l : currentScreen.listeners) l.mousePressed((MouseEvent)e.event,getScreen()); break; case 7: for(InputListener l : currentScreen.listeners) l.mouseReleased((MouseEvent)e.event,getScreen()); break; case 8: for(InputListener l : currentScreen.listeners) l.mouseDragged((MouseEvent)e.event,getScreen()); break; case 9: for(InputListener l : currentScreen.listeners) l.mouseMoved((MouseEvent)e.event,getScreen()); break; case 10: for(InputListener l : currentScreen.listeners) l.mouseWheelMoved((MouseWheelEvent)e.event,getScreen()); break; case 11: resized(getWidth(),getHeight()); break; case 12: if(isPaused() && isActive()) resume(); break; case 13: if(!isPaused() && isActive()) pause(); break; } } events.clear(); } } public final void init() { setIgnoreRepaint(true); setLayout(new BorderLayout()); add(canvas); canvas.setSize(super.getWidth(),super.getHeight()); canvas.setIgnoreRepaint(true); canvas.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent ce) { synchronized(events) { events.add(new Event(11,ce)); } } }); canvas.addFocusListener(new FocusListener() { public void focusGained(FocusEvent fe) { synchronized(events) { events.add(new Event(12,fe)); } } public void focusLost(FocusEvent fe) { synchronized(events) { events.add(new Event(13,fe)); } } }); } /** * Automatically called if this game is an Applet, otherwise it has to be manually called. */ public final void start() { if(!isActive()) new Thread(this).start(); } /** * Called when this game is stopped. Calling this method stops the game loop. stopGame() is then called. */ public final void stop() { sound.setOn(false); isActive = false; } /** * Called as soon as the game is created. */ protected abstract void initGame(); /** * Called the set FPS times a second. Updates the current screen. * @param deltaTime The time passed since the last call to it. */ protected void update(long deltaTime) { getScreen().update(deltaTime); } /** * Called when this game loses focus. */ protected void paused() { getScreen().paused(); } /** * Called when this game regains focus. */ protected void resumed() { getScreen().resumed(); } /** * called when the game is resized. * @param width The new width. * @param height The new height. */ protected void resized(int width, int height) { getScreen().resized(width, height); } /** * Called when this game is stopped. */ protected abstract void stopGame(); /** * Called the set FPS times a second. Clears the window using the Graphics2D's background color then draws the current screen. * @param g The Graphics context to be used to draw to the canvas. */ protected void paint(Graphics2D g) { g.clearRect(0, 0, getWidth(), getHeight()); getScreen().draw((Graphics2D)g.create()); } /** * Adds a screen to this game. * @param screen The Screen to add. * @param name The name of the screen. */ public synchronized void addScreen(Screen screen, String name) { if(screen == null) throw new IllegalArgumentException("Screen cannot be null."); if(name == null) throw new IllegalArgumentException("Name cannot be null."); screens.put(name,new ScreenInfo(screen)); screen.init(this); } /** * Returns the current screen. * @return The current screen. */ public Screen getScreen() { return currentScreen.screen; } /** * Returns the name of the current screen. This is the same as calling <code>getName(getScreen())</code>. * @return The name of the current screen. */ public String getScreenName() { return getName(getScreen()); } /** * Returns the screen specified * @param name The name of the screen. * @return The screen associated with the specified name. */ public Screen getScreen(String name) { return screens.get(name).screen; } /** * Returns the name of the screen. * @param screen The Screen who's name is returned. * @return The name of the specified screen. */ public synchronized String getName(Screen screen) { for(String s : screens.keySet()) if(screens.get(s).screen == screen) return s; return null; } /** * Adds the screen and sets it as the current screen. * @param screen The Screen to be added and set. * @param name The name assigned to the Screen. */ public synchronized void setScreen(Screen screen, String name) { addScreen(screen,name); setScreen(name); } public void setScreen(Screen screen) { setScreen(getScreenInfo(screen)); } public void setScreen(String name) { ScreenInfo info = screens.get(name); if(info == null) throw new IllegalArgumentException(name + " does not exist."); setScreen(info); } private void setScreen(ScreenInfo screenInfo) { if(screenInfo == null || !screens.containsValue(screenInfo)) throw new IllegalArgumentException("Screen has not been added."); currentScreen.screen.hide(); currentScreen = screenInfo; currentScreen.screen.show(); } private ScreenInfo getScreenInfo(Screen screen) { if(screen == null) return null; for(ScreenInfo s : screens.values()) if(s.screen == screen) return s; return null; } /** * Adds an input listener on the specified screen. * @param screen The Screen to add the listener to. * @param listener The InputListener to be notified of input events on this screen. */ public void addInputListener(Screen screen, InputListener listener) { if(screen == null) throw new IllegalArgumentException("Screen cannot be null."); addInputListener(getScreenInfo(screen),listener); } /** * Adds an input listener on the specified screen. * @param name The name of the screen to add the listener to. * @param listener The InputListener to be notified of input events on this screen. */ public void addInputListener(String name, InputListener listener) { ScreenInfo info = screens.get(name); if(info == null) throw new IllegalArgumentException(name + " does not exist."); addInputListener(screens.get(name),listener); } private synchronized void addInputListener(ScreenInfo screenInfo, InputListener listener) { if(screenInfo == null || !screens.containsValue(screenInfo)) throw new IllegalArgumentException("Screen has not been added."); if(listener == null) throw new IllegalArgumentException("InputListener cannot be null."); screenInfo.listeners.add(listener); } /** * Removes the input listener from the specified screen. * @param screen The Screen to remove the listener from. * @param listener The InputListener reference to remove. */ public void removeInputListener(Screen screen, InputListener listener) { if(screen == null) throw new IllegalArgumentException("Screen cannot be null."); removeInputListener(getScreenInfo(screen),listener); } /** * Removes the input listener from the specified screen. * @param name The name of the screen to remove the listener from. * @param listener The InputListneer reference to remove. */ public void removeInputListener(String name, InputListener listener) { ScreenInfo info = screens.get(name); if(info == null) throw new IllegalArgumentException(name + " does not exist."); removeInputListener(screens.get(name),listener); } private synchronized void removeInputListener(ScreenInfo screenInfo, InputListener listener) { if(screenInfo == null || !screens.containsValue(screenInfo)) throw new IllegalArgumentException("Screen has not been added."); if(listener == null) throw new IllegalArgumentException("InputListener cannot be null."); screenInfo.listeners.remove(listener); } /** * Sets the version of the game. * @param version The current version of the game. */ public void setVersion(double version) { this.version = version; } /** * Returns the version of the game. * @return The current version of the game. */ public double getVersion() { return version; } /** * Sets the showFPS property. * @param showFPS If true, the FPS is updated and displayed every second, else the FPS is not displayed. */ public void showFPS(boolean showFPS) { this.showFPS = showFPS; } /** * Returns the current state of the showFPS property. * @return If true, the FPS is updated and displayed every second, else the FPS is not displayed. */ public boolean isShowingFPS() { return showFPS; } /** * Sets the optimal FPS of this game. * @param FPS Specifies the number of updates and frames shown per second. */ public void setFPS(int FPS) { this.FPS = FPS; } /** * Returns the optimal FPS of this game. * @return The number of udpates and frames shown per second. */ public int getFPS() { return FPS; } /** * Sets whether the game loop should use Thread.yield() or Thread.sleep(1).<br> * Thread.yield() produces a smoother game loop but at the expense of a high CPU usage.<br> * Thread.sleep(1) is less smooth but barely uses any CPU time.<br> * The default is Thread.sleep(1). * @param useYield If true, uses Thread.yield(), otherwise uses Thread.sleep(1). */ public void useYield(boolean useYield) { this.useYield = useYield; } /** * Returns whether the game loop uses Thread.yield() or Thread.sleep(1). The default is Thread.sleep(1). * @return True if the game loop uses Thread.yield(), false if it uses Thread.sleep(1). */ public boolean usesYield() { return useYield; } /** * Sets the quality of this game's graphics. * @param highQuality If true, the graphics are of high quality, else the graphics are of low quality. */ public void setHighQuality(boolean highQuality) { if(highQuality) quality = RenderingHints.VALUE_ANTIALIAS_ON; else quality = RenderingHints.VALUE_ANTIALIAS_OFF; } /** * Returns the current state of the quality property. * @return If true, the graphics are of high quality, else the graphics are of low quality. */ public boolean isHighQuality() { return quality == RenderingHints.VALUE_ANTIALIAS_ON; } /** * The standard keys are M for audio on/off, P for pause/resume, and Q for high/low quality. * @param standardKeysEnabled If true, a key press of the standard keys automatically call the appropriate methods, else this function is disabled. */ public void setStandardKeysEnabled(boolean standardKeysEnabled) { this.standardKeysEnabled = standardKeysEnabled; } /** * Returns the current state of the standardKeysEnabled property. * @return If true, a key press of the standard keys automatically call the appropriate methods, else this function is disabled. */ public boolean isStandardKeysEnabled() { return standardKeysEnabled; } /** * Sets the maximum number of updates before render. * @param maxUpdates The maximum number of updates before render. */ public void setMaximumUpdatesBeforeRender(int maxUpdates) { this.maxUpdates = maxUpdates; } /** * Returns the maximum number of updates before render. * @return The maximum number of updates before render. */ public int getMaximumUpdatesBeforeRender() { return maxUpdates; } /** * Returns a reference to the Art object. * @return A reference to the Art object. */ public Art getArt() { return art; } /** * Returns a reference to the Sound object. * @return A reference to the Sound object. */ public Sound getSound() { return sound; } /** * Returns a reference to the Input object. * @return A reference to the Input object. */ public Input getInput() { return input; } private static class ScreenInfo { private Screen screen; private ArrayList<InputListener> listeners = new ArrayList<InputListener>(); public ScreenInfo(Screen screen) { this.screen = screen; } } private static class Event { int id; AWTEvent event; public Event(int id, AWTEvent event) { this.id = id; this.event = event; } } private class Listener implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener { public void keyTyped(KeyEvent key) { synchronized(events) { events.add(new Event(0,key)); } } public void keyPressed(KeyEvent key) { synchronized(events) { events.add(new Event(1,key)); } if(isStandardKeysEnabled()) { switch(key.getKeyCode()) { case KeyEvent.VK_P: if(isPaused()) resume(); else pause(); break; case KeyEvent.VK_M: sound.setOn(!sound.isOn()); break; case KeyEvent.VK_Q: setHighQuality(!isHighQuality()); break; } } } public void keyReleased(KeyEvent key) { synchronized(events) { events.add(new Event(2,key)); } } public void mouseClicked(MouseEvent me) { synchronized(events) { events.add(new Event(3,me)); } } public void mouseEntered(MouseEvent me) { synchronized(events) { events.add(new Event(4,me)); } } public void mouseExited(MouseEvent me) { synchronized(events) { events.add(new Event(5,me)); } } public void mousePressed(MouseEvent me) { synchronized(events) { events.add(new Event(6,me)); } } public void mouseReleased(MouseEvent me) { synchronized(events) { events.add(new Event(7,me)); } } public void mouseDragged(MouseEvent me) { synchronized(events) { events.add(new Event(8,me)); } } public void mouseMoved(MouseEvent me) { synchronized(events) { events.add(new Event(9,me)); } } public void mouseWheelMoved(MouseWheelEvent mwe) { synchronized(events) { events.add(new Event(10,mwe)); } } } }
package slimpleslickgame; import java.util.concurrent.ConcurrentHashMap; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import util.EventProtocol; import client.ByteMonitor; import client.Client; import client.GameStatsEvents; public class Game extends BasicGameState { public static final int ID = 2; private GameContainer gc; private ByteMonitor bm; private ConcurrentHashMap<Byte, GameInstance> instances; private GameStatsEvents gse; private Vector2f boardSize; private boolean gameStarted; public void addGSM(GameStatsEvents gse, ByteMonitor byteMonitor) { this.bm = byteMonitor; this.gse = gse; } @Override public void init(GameContainer gc, StateBasedGame arg1) throws SlickException { this.gc = gc; this.boardSize = new Vector2f(gc.getWidth()/5, gc.getHeight()); instances = new ConcurrentHashMap<Byte, GameInstance>(); gameStarted = false; } @Override public void render(GameContainer gc, StateBasedGame arg1, Graphics g) throws SlickException { if(gameStarted){ for(Byte b : instances.keySet()){ instances.get(b).render(g); } } else { int th = g.getFont().getLineHeight(); int tw = 100; g.drawString("PRESS ENTER TO START GAME\nPlayers in game: " + instances.size(), (Client.WIDTH/2)-tw, (Client.HEIGHT/2)-th); } } @Override public void update(GameContainer gc, StateBasedGame arg1, int delta) throws SlickException { if(gameStarted){ for(Byte b : instances.keySet()){ instances.get(b).update(delta); } } else { if(gc.getInput().isKeyPressed(Input.KEY_ENTER)){ byte[] bytes = new byte[]{EventProtocol.GAME_STARTED}; bm.putArrayToServer(bytes, (byte) -1); } } } @Override public int getID() { return ID; } public void startGame(){ gameStarted = true; } public void addOpponentPlayer(byte playerId) { addPlayer(new OpponentPlayer(this.gse, playerId)); } public void addLocalPlayer(byte playerId){ addPlayer(new LocalPlayer(gc, bm, playerId)); } private void addPlayer(Player player){ GameInstance gs = new GameInstance(player, this.boardSize); instances.put(player.id, gs); } /** * Closes the connection held by the bytemonitorn. */ public void onClose(){ if(this.bm.isOpen()) this.bm.closeConnection(); } public void removePlayer(byte playerId) { //TODO: remove stuff inside instance? try{ instances.remove(playerId); }catch(Exception e){ //TODO: end game } } public boolean isStarted() { return gameStarted; } }
package com.jetbrains.edu.coursecreator.stepik; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.jetbrains.edu.coursecreator.CCUtils; import com.jetbrains.edu.learning.StudySerializationUtils; import com.jetbrains.edu.learning.StudyTaskManager; import com.jetbrains.edu.learning.core.EduNames; import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder; import com.jetbrains.edu.learning.courseFormat.Course; import com.jetbrains.edu.learning.courseFormat.Lesson; import com.jetbrains.edu.learning.courseFormat.RemoteCourse; import com.jetbrains.edu.learning.courseFormat.tasks.Task; import com.jetbrains.edu.learning.stepic.EduStepicAuthorizedClient; import com.jetbrains.edu.learning.stepic.EduStepicNames; import com.jetbrains.edu.learning.stepic.StepicUser; import com.jetbrains.edu.learning.stepic.StepicWrappers; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.Collections; import java.util.List; public class CCStepicConnector { private static final Logger LOG = Logger.getInstance(CCStepicConnector.class.getName()); private CCStepicConnector() { } public static RemoteCourse getCourseInfo(String courseId) { final String url = EduStepicNames.COURSES + "/" + courseId; try { final StepicWrappers.CoursesContainer coursesContainer = EduStepicAuthorizedClient.getFromStepic(url, StepicWrappers.CoursesContainer.class); return coursesContainer == null ? null : coursesContainer.courses.get(0); } catch (IOException e) { LOG.error(e.getMessage()); } return null; } public static void postCourseWithProgress(final Project project, @NotNull final Course course) { ProgressManager.getInstance().run(new com.intellij.openapi.progress.Task.Modal(project, "Uploading Course", true) { @Override public void run(@NotNull final ProgressIndicator indicator) { postCourse(project, course); } }); } private static void postCourse(final Project project, @NotNull Course course) { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (indicator != null) { indicator.setText("Uploading course to " + EduStepicNames.STEPIC_URL); indicator.setIndeterminate(false); } final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/courses"); final StepicUser currentUser = EduStepicAuthorizedClient.getCurrentUser(); if (currentUser != null) { final List<StepicUser> courseAuthors = course.getAuthors(); for (int i = 0; i < courseAuthors.size(); i++) { if (courseAuthors.size() > i) { final StepicUser courseAuthor = courseAuthors.get(i); currentUser.setFirstName(courseAuthor.getFirstName()); currentUser.setLastName(courseAuthor.getLastName()); } } course.setAuthors(Collections.singletonList(currentUser)); } String requestBody = new Gson().toJson(new StepicWrappers.CourseWrapper(course)); request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) { LOG.warn("Http client is null"); return; } final CloseableHttpResponse response = client.execute(request); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; final StatusLine line = response.getStatusLine(); EntityUtils.consume(responseEntity); if (line.getStatusCode() != HttpStatus.SC_CREATED) { LOG.error("Failed to push " + responseString); return; } final RemoteCourse postedCourse = new Gson().fromJson(responseString, StepicWrappers.CoursesContainer.class).courses.get(0); postedCourse.setLessons(course.getLessons(true)); postedCourse.setAuthors(course.getAuthors()); postedCourse.setCourseMode(CCUtils.COURSE_MODE); postedCourse.setLanguage(course.getLanguageID()); final int sectionId = postModule(postedCourse.getId(), 1, String.valueOf(postedCourse.getName())); int position = 1; for (Lesson lesson : course.getLessons()) { if (indicator != null) { indicator.checkCanceled(); indicator.setText2("Publishing lesson " + lesson.getIndex()); } final int lessonId = postLesson(project, lesson); postUnit(lessonId, position, sectionId); if (indicator != null) { indicator.setFraction((double)lesson.getIndex()/course.getLessons().size()); indicator.checkCanceled(); } position += 1; } ApplicationManager.getApplication().runReadAction(() -> postAdditionalFiles(course, project, postedCourse.getId())); StudyTaskManager.getInstance(project).setCourse(postedCourse); } catch (IOException e) { LOG.error(e.getMessage()); } } private static void postAdditionalFiles(Course course, @NotNull final Project project, int id) { final Lesson lesson = CCUtils.createAdditionalLesson(course, project); if (lesson != null) { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (indicator != null) { indicator.setText2("Publishing additional files"); } final int sectionId = postModule(id, 2, EduNames.PYCHARM_ADDITIONAL); final int lessonId = postLesson(project, lesson); postUnit(lessonId, 1, sectionId); } } public static void postUnit(int lessonId, int position, int sectionId) { final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.UNITS); final StepicWrappers.UnitWrapper unitWrapper = new StepicWrappers.UnitWrapper(); final StepicWrappers.Unit unit = new StepicWrappers.Unit(); unit.setLesson(lessonId); unit.setPosition(position); unit.setSection(sectionId); unitWrapper.setUnit(unit); String requestBody = new Gson().toJson(unitWrapper); request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return; final CloseableHttpResponse response = client.execute(request); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; final StatusLine line = response.getStatusLine(); EntityUtils.consume(responseEntity); if (line.getStatusCode() != HttpStatus.SC_CREATED) { LOG.error("Failed to push " + responseString); } } catch (IOException e) { LOG.error(e.getMessage()); } } private static int postModule(int courseId, int position, @NotNull final String title) { final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/sections"); final StepicWrappers.Section section = new StepicWrappers.Section(); section.setCourse(courseId); section.setTitle(title); section.setPosition(position); final StepicWrappers.SectionWrapper sectionContainer = new StepicWrappers.SectionWrapper(); sectionContainer.setSection(section); String requestBody = new Gson().toJson(sectionContainer); request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return -1; final CloseableHttpResponse response = client.execute(request); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; final StatusLine line = response.getStatusLine(); EntityUtils.consume(responseEntity); if (line.getStatusCode() != HttpStatus.SC_CREATED) { LOG.error("Failed to push " + responseString); return -1; } final StepicWrappers.Section postedSection = new Gson().fromJson(responseString, StepicWrappers.SectionContainer.class).getSections().get(0); return postedSection.getId(); } catch (IOException e) { LOG.error(e.getMessage()); } return -1; } public static int updateTask(@NotNull final Project project, @NotNull final Task task) { final Lesson lesson = task.getLesson(); final int lessonId = lesson.getId(); final HttpPut request = new HttpPut(EduStepicNames.STEPIC_API_URL + "/step-sources/" + String.valueOf(task.getStepId())); final Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation(). registerTypeAdapter(AnswerPlaceholder.class, new StudySerializationUtils.Json.StepicAnswerPlaceholderAdapter()).create(); ApplicationManager.getApplication().invokeLater(() -> { task.addTestsTexts("tests.py", task.getTestsText(project)); final String requestBody = gson.toJson(new StepicWrappers.StepSourceWrapper(project, task, lessonId)); request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return; final CloseableHttpResponse response = client.execute(request); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; EntityUtils.consume(responseEntity); final StatusLine line = response.getStatusLine(); if (line.getStatusCode() != HttpStatus.SC_OK) { LOG.error("Failed to push " + responseString); } } catch (IOException e) { LOG.error(e.getMessage()); } }); return -1; } public static int updateLesson(@NotNull final Project project, @NotNull final Lesson lesson) { final HttpPut request = new HttpPut(EduStepicNames.STEPIC_API_URL + EduStepicNames.LESSONS + String.valueOf(lesson.getId())); String requestBody = new Gson().toJson(new StepicWrappers.LessonWrapper(lesson)); request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return -1; final CloseableHttpResponse response = client.execute(request); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; final StatusLine line = response.getStatusLine(); EntityUtils.consume(responseEntity); if (line.getStatusCode() != HttpStatus.SC_OK) { LOG.error("Failed to push " + responseString); return -1; } final Lesson postedLesson = new Gson().fromJson(responseString, RemoteCourse.class).getLessons().get(0); for (Integer step : postedLesson.steps) { deleteTask(step); } for (Task task : lesson.getTaskList()) { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (indicator != null) { indicator.checkCanceled(); } postTask(project, task, lesson.getId()); } return lesson.getId(); } catch (IOException e) { LOG.error(e.getMessage()); } return -1; } public static int postLesson(@NotNull final Project project, @NotNull final Lesson lesson) { final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/lessons"); String requestBody = new Gson().toJson(new StepicWrappers.LessonWrapper(lesson)); request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return -1; final CloseableHttpResponse response = client.execute(request); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; final StatusLine line = response.getStatusLine(); EntityUtils.consume(responseEntity); if (line.getStatusCode() != HttpStatus.SC_CREATED) { LOG.error("Failed to push " + responseString); return 0; } final Lesson postedLesson = new Gson().fromJson(responseString, RemoteCourse.class).getLessons(true).get(0); lesson.setId(postedLesson.getId()); for (Task task : lesson.getTaskList()) { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (indicator != null) { indicator.checkCanceled(); } postTask(project, task, postedLesson.getId()); } return postedLesson.getId(); } catch (IOException e) { LOG.error(e.getMessage()); } return -1; } public static void deleteTask(@NotNull final Integer task) { final HttpDelete request = new HttpDelete(EduStepicNames.STEPIC_API_URL + EduStepicNames.STEP_SOURCES + task); ApplicationManager.getApplication().invokeLater(() -> { try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return; final CloseableHttpResponse response = client.execute(request); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; EntityUtils.consume(responseEntity); final StatusLine line = response.getStatusLine(); if (line.getStatusCode() != HttpStatus.SC_NO_CONTENT) { LOG.error("Failed to delete task " + responseString); } } catch (IOException e) { LOG.error(e.getMessage()); } }); } public static void postTask(final Project project, @NotNull final Task task, final int lessonId) { final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/step-sources"); final Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation(). registerTypeAdapter(AnswerPlaceholder.class, new StudySerializationUtils.Json.StepicAnswerPlaceholderAdapter()).create(); ApplicationManager.getApplication().invokeLater(() -> { final String requestBody = gson.toJson(new StepicWrappers.StepSourceWrapper(project, task, lessonId)); request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); try { final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(); if (client == null) return; final CloseableHttpResponse response = client.execute(request); final StatusLine line = response.getStatusLine(); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; EntityUtils.consume(responseEntity); if (line.getStatusCode() != HttpStatus.SC_CREATED) { LOG.error("Failed to push " + responseString); return; } final JsonObject postedTask = new Gson().fromJson(responseString, JsonObject.class); final JsonObject stepSource = postedTask.getAsJsonArray("step-sources").get(0).getAsJsonObject(); task.setStepId(stepSource.getAsJsonPrimitive("id").getAsInt()); } catch (IOException e) { LOG.error(e.getMessage()); } }); } }
package com.jukusoft.erp.core.module.base.service; import com.jukusoft.data.entity.User; import com.jukusoft.data.repository.UserRepository; import com.jukusoft.erp.lib.database.InjectRepository; import com.jukusoft.erp.lib.message.ResponseType; import com.jukusoft.erp.lib.message.request.ApiRequest; import com.jukusoft.erp.lib.message.response.ApiResponse; import com.jukusoft.erp.lib.route.Route; import com.jukusoft.erp.lib.service.AbstractService; import com.jukusoft.erp.lib.session.Session; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; public class LoginService extends AbstractService { @InjectRepository protected UserRepository userRepository; @Route(routes = "/try-login") public void tryLogin (Message<ApiRequest> event, ApiRequest req, ApiResponse response, Handler<AsyncResult<ApiResponse>> handler) { //validate username if (!req.getData().has("username")) { getLogger().warn(req.getMessageID(), "failed_login", "username wasnt set."); response.setStatusCode(ResponseType.BAD_REQUEST); handler.handle(Future.succeededFuture(response)); return; } //get username String username = req.getData().getString("username"); //get password if (!req.getData().has("password")) { getLogger().warn(req.getMessageID(), "failed_login", "password wasnt set."); response.setStatusCode(ResponseType.BAD_REQUEST); handler.handle(Future.succeededFuture(response)); return; } //get password String password = req.getData().getString("password"); getLogger().info(req.getMessageID(), "try_login", "try login '" + username + "' (IP: " + req.getIP() + ")."); if (userRepository == null) { throw new NullPointerException("user repository cannot be null."); } //find user by username userRepository.getUserByUsername(username, res -> { if (!res.succeeded()) { generateFailedMessage("Couldnt find user. Maybe its an internal problem, please contact administrator.", response); handler.handle(Future.succeededFuture(response)); return; } //get user User user = res.result(); if (user == null) { getLogger().warn(req.getMessageID(), "try_login", "Couldnt found username '" + username + "'."); generateFailedMessage("User doesnt exists.", response); handler.handle(Future.succeededFuture(response)); return; } getLogger().info(req.getMessageID(), "try_login", "username '" + username + "' was found (userID: " + user.getUserID() + ")."); //check password userRepository.checkPassword(user.getUserID(), password, result -> { if (!result.succeeded()) { getLogger().warn(req.getMessageID(), "try_login", "Exception occurred: " + result.cause()); generateFailedMessage("Internal Server Error! Cannot check password.", response); handler.handle(Future.succeededFuture(response)); return; } boolean value = result.result(); if (value == true) { //login successfully getLogger().info(req.getMessageID(), "login", "Login user successfully: " + username + " (userID: " + user.getUserID() + ")."); //get session Session session = getContext().getSessionManager().getSession(req.getSessionID()); //set logged in state session.login(user.getUserID(), user.getUsername()); //save session session.flush(); generateSuccessMessage("Login successful!", response); handler.handle(Future.succeededFuture(response)); } else { //login failed getLogger().info(req.getMessageID(), "login", "Login failed (wrong password): " + username + " (userID: " + user.getUserID() + ")."); generateFailedMessage("Wrong password!", response); handler.handle(Future.succeededFuture(response)); } }); }); } @Route(routes = "/isloggedin") public void isLoggedIn (Message<ApiRequest> event, ApiRequest req, ApiResponse response, Handler<AsyncResult<ApiResponse>> handler) { //get session Session session = getContext().getSessionManager().getSession(req.getSessionID()); response.getData().put("is-logged-in", session.isLoggedIn()); handler.handle(Future.succeededFuture(response)); } protected void generateFailedMessage (String message, ApiResponse response) { response.setStatusCode(ResponseType.OK); response.getData().put("login_state", "failed"); response.getData().put("login_message", message); } protected void generateSuccessMessage (String message, ApiResponse response) { response.setStatusCode(ResponseType.OK); response.getData().put("login_state", "success"); response.getData().put("login_message", message); } }
package org.fcrepo.integration.api; import static java.util.regex.Pattern.compile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.fcrepo.Transaction; import org.fcrepo.services.TransactionService; import org.fcrepo.test.util.TestHelpers; import org.junit.Test; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.update.GraphStore; public class FedoraTransactionsIT extends AbstractResourceIT { @Test public void testCreateTransaction() throws Exception { /* create a tx */ final HttpPost createTx = new HttpPost(serverAddress + "fcr:tx"); HttpResponse response = execute(createTx); assertEquals(201, response.getStatusLine().getStatusCode()); final String location = response.getFirstHeader("Location").getValue(); logger.info("Got location {}", location); assertTrue( "Expected Location header to send us to root node path within the transaction", compile("tx:[0-9a-f-]+$").matcher(location).find()); } @Test public void testRequestsInTransactionThatDoestExist() throws Exception { /* create a tx */ final HttpPost createTx = new HttpPost(serverAddress + "tx:123/objects"); HttpResponse response = execute(createTx); assertEquals(410, response.getStatusLine().getStatusCode()); } @Test public void testCreateAndTimeoutTransaction() throws Exception { /* create a short-lived tx */ final long testTimeout = Math.min(500, TransactionService.REAP_INTERVAL / 2); System.setProperty(Transaction.TIMEOUT_SYSTEM_PROPERTY, Long .toString(testTimeout)); /* create a tx */ final HttpPost createTx = new HttpPost(serverAddress + "fcr:tx"); HttpResponse response = execute(createTx); assertEquals(201, response.getStatusLine().getStatusCode()); final String location = response.getFirstHeader("Location").getValue(); final HttpGet getWithinTx = new HttpGet(location); HttpResponse resp = execute(getWithinTx); IOUtils.toString(resp.getEntity().getContent()); assertEquals(200, resp.getStatusLine().getStatusCode()); int statusCode = 0; Thread.sleep(TransactionService.REAP_INTERVAL * 2); final HttpGet getWithExpiredTx = new HttpGet(location); resp = execute(getWithExpiredTx); IOUtils.toString(resp.getEntity().getContent()); statusCode = resp.getStatusLine().getStatusCode(); try { assertEquals("Transaction did not expire", 410, statusCode); } finally { System.setProperty(Transaction.TIMEOUT_SYSTEM_PROPERTY, Long .toString(Transaction.DEFAULT_TIMEOUT)); System.clearProperty("fcrepo4.tx.timeout"); } } @Test public void testCreateDoStuffAndRollbackTransaction() throws Exception { /* create a tx */ final HttpPost createTx = new HttpPost(serverAddress + "fcr:tx"); HttpResponse response = execute(createTx); assertEquals(201, response.getStatusLine().getStatusCode()); final String txLocation = response.getFirstHeader("Location").getValue(); /* create a new object inside the tx */ final HttpPost postNew = new HttpPost(txLocation + "/object-in-tx-rollback"); HttpResponse resp = execute(postNew); assertEquals(201, resp.getStatusLine().getStatusCode()); /* fetch the created tx from the endpoint */ final HttpGet getTx = new HttpGet(txLocation + "/object-in-tx-rollback"); resp = execute(getTx); assertEquals( "Expected to find our object within the scope of the transaction", 200, resp.getStatusLine().getStatusCode()); final GraphStore graphStore = TestHelpers.parseTriples(resp.getEntity().getContent()); logger.debug(graphStore.toString()); assertTrue(graphStore.toDataset().asDatasetGraph().contains(Node.ANY, Node.createURI(txLocation + "/object-in-tx-rollback"), Node.ANY, Node.ANY)); /* fetch the created tx from the endpoint */ final HttpGet getObj = new HttpGet(serverAddress + "/object-in-tx-rollback"); resp = execute(getObj); assertEquals( "Expected to not find our object within the scope of the transaction", 404, resp.getStatusLine().getStatusCode()); /* and rollback */ final HttpPost rollbackTx = new HttpPost(txLocation + "/fcr:tx/fcr:rollback"); resp = execute(rollbackTx); assertEquals(204, resp.getStatusLine().getStatusCode()); } @Test public void testCreateDoStuffAndCommitTransaction() throws Exception { /* create a tx */ final HttpPost createTx = new HttpPost(serverAddress + "fcr:tx"); HttpResponse response = execute(createTx); assertEquals(201, response.getStatusLine().getStatusCode()); final String txLocation = response.getFirstHeader("Location").getValue(); /* create a new object inside the tx */ final HttpPost postNew = new HttpPost(txLocation + "/object-in-tx-commit"); HttpResponse resp = execute(postNew); assertEquals(201, resp.getStatusLine().getStatusCode()); /* fetch the created tx from the endpoint */ final HttpGet getTx = new HttpGet(txLocation + "/object-in-tx-commit"); resp = execute(getTx); assertEquals( "Expected to find our object within the scope of the transaction", 200, resp.getStatusLine().getStatusCode()); final GraphStore graphStore = TestHelpers.parseTriples(resp.getEntity().getContent()); logger.debug(graphStore.toString()); assertTrue(graphStore.toDataset().asDatasetGraph().contains(Node.ANY, Node.createURI(txLocation + "/object-in-tx-commit"), Node.ANY, Node.ANY)); /* fetch the object-in-tx outside of the tx */ final HttpGet getObj = new HttpGet(serverAddress + "/object-in-tx-commit"); resp = execute(getObj); assertEquals( "Expected to not find our object within the scope of the transaction", 404, resp.getStatusLine().getStatusCode()); /* and rollback */ final HttpPost commitTx = new HttpPost(txLocation + "/fcr:tx/fcr:commit"); resp = execute(commitTx); assertEquals(204, resp.getStatusLine().getStatusCode()); /* fetch the object-in-tx outside of the tx after it has been committed */ final HttpGet getObjCommitted = new HttpGet(serverAddress + "/object-in-tx-commit"); resp = execute(getObjCommitted); assertEquals( "Expected to find our object after the transaction was committed", 200, resp.getStatusLine().getStatusCode()); } }
package com.foundationdb.sql.pg; import com.foundationdb.junit.SelectedParameterizedRunner; import com.foundationdb.util.RandomRule; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Random; import static org.junit.Assert.assertEquals; /** * Randomly generate 2 queries, then * run Query1 & Query2 and store results * do * SELECT id FROM (Query1) WHERE id IN (Query2) * Manually compute results from stored results, * and compare with whole query. * Also handles NOT IN and EXISTS and NOT EXISTS, could handle more * */ @Ignore("Waiting until this passes most of the time") @RunWith(SelectedParameterizedRunner.class) public class RandomSemiJoinTestDT extends PostgresServerITBase { private static final Logger LOG = LoggerFactory.getLogger(RandomSemiJoinTestDT.class); private static final int DDL_COUNT = 10; private static final int QUERY_COUNT = 30; private static final int TABLE_COUNT = 3; private static final int COLUMN_COUNT = 10; private static final int MAX_ROW_COUNT = 100; private static final int MAX_INDEX_COUNT = 5; private static final int MAX_CONDITION_COUNT = 10; private static final int JOIN_CONSTANT_LIKELYHOOD = 6; private static final int WHERE_CONSTANT_LIKELYHOOD = 4; private static final int MAX_VALUE = MAX_ROW_COUNT * 2; private static final int MIN_VALUE = MAX_ROW_COUNT * -2; private static final int MAX_OUTER_LIMIT = 10; @ClassRule public static final RandomRule randomRule = new RandomRule(); @Rule public final RandomRule testRandom = randomRule; /** * The seed used for individual parameterized tests, so that they can have different DDL & DML */ private Long testSeed; @Parameterized.Parameters(name="Test Seed: {0}") public static List<Object[]> params() throws Exception { Random random = randomRule.reset(); List<Object[]> params = new ArrayList<>(DDL_COUNT); for (int i=0; i< DDL_COUNT; i++) { params.add(new Object[] {random.nextLong()}); } return params; } public RandomSemiJoinTestDT(Long testSeed) { this.testSeed = testSeed; } private static String buildQuery(Random random, boolean useExists, boolean firstQuery) { if (firstQuery && random.nextInt(20) == 0) { return randomTable(random); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT ta0."); stringBuilder.append(firstQuery ? "main" : randomColumn(random)); stringBuilder.append(" FROM "); stringBuilder.append(randomTable(random)); stringBuilder.append(" AS ta0"); int tableAliasCount = 1; switch (random.nextInt(4)) { case 0: // Just the FROM break; case 1: tableAliasCount++; addJoinClause("INNER", stringBuilder, random, tableAliasCount); break; case 2: tableAliasCount++; addJoinClause("LEFT OUTER", stringBuilder, random, tableAliasCount); break; case 3: tableAliasCount++; addJoinClause("RIGHT OUTER", stringBuilder, random, tableAliasCount); break; default: throw new IllegalStateException("not enough cases for random values"); } addWhereClause(stringBuilder, random, tableAliasCount, !firstQuery && useExists); addLimitClause(stringBuilder, random, tableAliasCount); return stringBuilder.toString(); } private static void addLimitClause(StringBuilder stringBuilder, Random random, int tableAliasCount) { if (random.nextInt(10) == 0) { stringBuilder.append(" ORDER BY "); addAliasedSource(stringBuilder, random, random.nextInt(tableAliasCount)); stringBuilder.append(" LIMIT "); stringBuilder.append(random.nextInt(10)+1); } } private static void addWhereClause(StringBuilder stringBuilder, Random random, int tableAliasCount, boolean forceMainEqualsClause) { if (!forceMainEqualsClause && random.nextInt(5) == 0) { return; } stringBuilder.append(" WHERE "); addCondition(stringBuilder, random, tableAliasCount, WHERE_CONSTANT_LIKELYHOOD, forceMainEqualsClause); for (int i=0; i<MAX_CONDITION_COUNT; i++) { if (random.nextInt(5) == 0) { break; } stringBuilder.append(random.nextBoolean() ? " AND " : " OR "); addCondition(stringBuilder, random, tableAliasCount, WHERE_CONSTANT_LIKELYHOOD, false); } } private static void addJoinClause(String type, StringBuilder sb, Random random, int tableAliasCount) { sb.append(" "); sb.append(type); sb.append(" JOIN "); sb.append(randomTable(random)); sb.append(" AS ta"); sb.append(tableAliasCount-1); sb.append(" ON "); // no cross joins right now int conditionCount = random.nextInt(3); for (int i=0; i<conditionCount+1; i++) { if (i > 0) { sb.append(" AND "); } addCondition(sb, random, tableAliasCount, JOIN_CONSTANT_LIKELYHOOD, false); } } private static void addCondition(StringBuilder sb, Random random, int tableAliasCount, int constantBias, boolean forceMainEqualsClause) { int firstTable = random.nextInt(tableAliasCount); int secondTable = random.nextInt(tableAliasCount); if (secondTable == firstTable) { secondTable = (firstTable + 1) % tableAliasCount; } boolean mainIsFirst = false; // 0 => first is constant, 1 => second is constant, else neither int oneIsConstant = random.nextInt(constantBias); if (oneIsConstant == 0) { sb.append(randomValue(random)); } else { mainIsFirst = random.nextBoolean(); if (mainIsFirst && forceMainEqualsClause) { sb.append("%s"); } else { addAliasedSource(sb, random, firstTable); } } int whichComparison = random.nextInt(6); switch (whichComparison) { case 0: sb.append(" < "); break; case 1: sb.append(" > "); break; default: sb.append(" = "); break; } if (oneIsConstant == 1) { sb.append(randomValue(random)); } else { if (mainIsFirst || !forceMainEqualsClause) { addAliasedSource(sb, random, secondTable); } else { sb.append("%s"); } } } private static void addAliasedSource(StringBuilder sb, Random random, int firstTable) { sb.append("ta"); sb.append(firstTable); sb.append("."); sb.append(randomColumn(random)); } private static String randomColumn(Random random) { return "c" + random.nextInt(COLUMN_COUNT); } private static String randomTable(Random random) { return table(random.nextInt(TABLE_COUNT)); } private static String table(int index) { return "table" + index; } private static Integer randomValue(Random random) { int val = random.nextInt(MAX_VALUE-MIN_VALUE) + MIN_VALUE; if (val == MAX_VALUE) { return null; } else { return val; } } private void insertRows(Random random, int tableIndex) { int row_count = random.nextInt(MAX_ROW_COUNT); for (int j=0; j<row_count; j++) { StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO "); sb.append(table(tableIndex)); sb.append(" VALUES ("); sb.append(j); for (int k=0; k<COLUMN_COUNT; k++) { sb.append(","); sb.append(randomValue(random)); } sb.append(")"); sql(sb.toString()); } } private static String createIndexSql(Random random, String indexName) { List<String> columns = new ArrayList<>(); columns.add("main"); for (int i=0; i<COLUMN_COUNT; i++) { columns.add("c" + i); } int columnsInIndex = random.nextInt(COLUMN_COUNT); StringBuilder sb = new StringBuilder("CREATE "); sb.append("INDEX "); sb.append(indexName); sb.append( " ON "); sb.append(randomTable(random)); sb.append("("); sb.append(columns.remove(random.nextInt(COLUMN_COUNT))); while (!columns.isEmpty()) { if (random.nextInt(4) == 0) { break; } sb.append(", "); sb.append(columns.remove(random.nextInt(columns.size()))); } sb.append(")"); return sb.toString(); } @Before public void setup() { // RandomRule is used to generate parameters, so that we have different DDL sets of tests Random random = new Random(testSeed); for (int i=0; i<TABLE_COUNT; i++) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("CREATE TABLE "); stringBuilder.append(table(i)); stringBuilder.append(" (main INT PRIMARY KEY"); for (int j=0; j<COLUMN_COUNT; j++) { stringBuilder.append(", c"); stringBuilder.append(j); stringBuilder.append(" INT"); } stringBuilder.append(")"); sql(stringBuilder.toString()); insertRows(random, i); } int indexCount = random.nextInt(MAX_INDEX_COUNT); for (int k=0; k<indexCount; k++) { sql(createIndexSql(random, "index" + k)); } // TODO create random groups & group indexes } @Test public void Test() { Random random = new Random(testSeed); for (int i=0; i<QUERY_COUNT; i++) { boolean useExists = random.nextBoolean(); int limitOutside = random.nextInt(MAX_OUTER_LIMIT * 10); if (useExists) { testOneQueryExists(buildQuery(random, useExists, true), buildQuery(random, useExists, false), limitOutside); } else { testOneQueryIn(buildQuery(random, useExists, true), buildQuery(random, useExists, false), limitOutside); } } } private void testOneQueryExists(String query1, String query2, int limitOutside) { boolean negative = randomRule.getRandom().nextBoolean(); String existsClause = negative ? "NOT EXISTS" : "EXISTS"; boolean query1IsJustATable = query1.startsWith("table"); LOG.debug("Outer: {}", query1); LOG.debug("Inner: {}", query2); List<List<?>> results = sql(query1IsJustATable ? "SELECT main FROM " + query1 : query1); List<Integer> expected = new ArrayList<>(); for (List<?> outerRow : results) { List<List<?>> innerResults = sql(String.format(query2, outerRow.get(0))); if (negative == (innerResults.size() == 0)) { expected.add((Integer) outerRow.get(0)); } } String q1 = query1IsJustATable ? query1 : "(" + query1 + ")"; String finalQuery = "SELECT main FROM " + q1 + " AS T1 WHERE " + existsClause + " (" + String.format(query2, "T1.main") + ")" + finalQueryLimit(limitOutside); LOG.debug("Final: {}", finalQuery); List<List<?>> sqlResults = sql(finalQuery); List<Integer> actual = new ArrayList<>(); for (List<?> actualRow : sqlResults) { assertEquals("Expected 1 column" + actualRow, 1, actualRow.size()); actual.add((Integer) actualRow.get(0)); } Collections.sort(expected, new NullableIntegerComparator()); Collections.sort(actual, new NullableIntegerComparator()); expected = applyLimit(expected, limitOutside); assertEqualLists("Results different for " + finalQuery, expected, actual); } private void testOneQueryIn(String query1, String query2, int limitOutside) { boolean useIn = randomRule.getRandom().nextBoolean(); String inClause = useIn ? "IN" : "NOT IN"; LOG.debug("Outer: {}", query1); LOG.debug("Inner: {}", query2); boolean query1IsJustATable = query1.startsWith("table"); List<List<?>> results1 = sql(query1IsJustATable ? "SELECT main FROM " + query1 : query1); List<List<?>> results2 = sql(query2); List<Integer> expected = new ArrayList<>(); for (List<?> row : results1) { boolean rowIsInResults2 = false; for (List<?> row2 : results2) { if (nullableEquals(row.get(0), row2.get(0))) { rowIsInResults2 = true; break; } } if (useIn == rowIsInResults2) { expected.add((Integer) row.get(0)); } } String q1 = query1IsJustATable ? query1 : "(" + query1 + ")"; String finalQuery = "SELECT main FROM " + q1 + " AS T1 WHERE main " + inClause + " (" + query2 + ")" + finalQueryLimit(limitOutside); LOG.debug("Final: {}", finalQuery); List<List<?>> sqlResults = sql(finalQuery); List<Object> actual = new ArrayList<>(); for (List<?> actualRow : sqlResults) { assertEquals("Expected 1 column" + actualRow, 1, actualRow.size()); actual.add(actualRow.get(0)); } expected = applyLimit(expected, limitOutside); assertEqualLists("Results different for " + finalQuery, expected, actual); } private List<Integer> applyLimit(List<Integer> expected, int limitOutside) { if (limitOutside < MAX_OUTER_LIMIT) { Collections.sort(expected, new NullableIntegerComparator()); if (limitOutside+1 < expected.size()) { return expected.subList(0, limitOutside + 1); } } return expected; } private String finalQueryLimit(int limitOutside) { if (limitOutside < 10) { return " ORDER BY T1.main LIMIT " + (limitOutside + 1); } else { return ""; } } /** * Object comparison in the same way that SQL does it, i.e. null != null */ private boolean nullableEquals(Object o1, Object o2) { if (o1 == null || o2 == null) { return false; } return o1.equals(o2); } private class NullableIntegerComparator implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { if (Objects.equals(o1, o2)) { return 0; } if (o1 == null) { return Integer.MIN_VALUE; } if (o2 == null) { return Integer.MAX_VALUE; } return o1-o2; } @Override public boolean equals(Object obj) { return obj instanceof NullableIntegerComparator; } } }
package org.fao.fenix.commons.msd.dto.full; import com.fasterxml.jackson.annotation.JsonProperty; import org.fao.fenix.commons.annotations.Description; import org.fao.fenix.commons.annotations.Label; import org.fao.fenix.commons.msd.dto.JSONEntity; import javax.persistence.Embedded; import java.io.Serializable; import java.util.Map; public class SeDatum extends JSONEntity implements Serializable { @JsonProperty @Label(en="Datum") @Description(en= "Identifier of the datum used. Datum description is requested when the coordinate reference system citation is not supplied. A datum could be geodetic, vertical or engineering. A geodetic datum gives the relationship of a coordinate system to the Earth and is used as the basis for two or three dimensional system (in most cases it requires an ellipsoid de nition). A vertical datum gives the relationship of gravity-related heights to a surface known as the geoid. A datum can be engineering if it is neither geodetic not vertical. For geodetic datum it could be useful to report the EPGS (European Petroleum Survey Group) coordinates.") private OjCodeList datum; @JsonProperty @Label(en="Name of datum") @Description(en= "Name of the datum used.") private Map<String, String> datumName; public Map<String, String> getDatumName() { return datumName; } public void setDatumName(Map<String, String> datumName) { this.datumName = datumName; } public OjCodeList getDatum() { return datum; } @Embedded public void setDatum(OjCodeList datum) { this.datum = datum; } }
package net.sf.taverna.t2.workbench.file.impl; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import java.util.WeakHashMap; import java.util.Map.Entry; import javax.swing.filechooser.FileFilter; import net.sf.taverna.t2.lang.observer.MultiCaster; import net.sf.taverna.t2.lang.observer.Observable; import net.sf.taverna.t2.lang.observer.Observer; import net.sf.taverna.t2.lang.ui.ModelMap; import net.sf.taverna.t2.lang.ui.ModelMap.ModelMapEvent; import net.sf.taverna.t2.workbench.ModelMapConstants; import net.sf.taverna.t2.workbench.edits.EditManager; import net.sf.taverna.t2.workbench.edits.EditManager.AbstractDataflowEditEvent; import net.sf.taverna.t2.workbench.edits.EditManager.EditManagerEvent; import net.sf.taverna.t2.workbench.file.DataflowInfo; import net.sf.taverna.t2.workbench.file.DataflowPersistenceHandler; import net.sf.taverna.t2.workbench.file.FileManager; import net.sf.taverna.t2.workbench.file.FileType; import net.sf.taverna.t2.workbench.file.events.ClosedDataflowEvent; import net.sf.taverna.t2.workbench.file.events.ClosingDataflowEvent; import net.sf.taverna.t2.workbench.file.events.FileManagerEvent; import net.sf.taverna.t2.workbench.file.events.OpenedDataflowEvent; import net.sf.taverna.t2.workbench.file.events.SavedDataflowEvent; import net.sf.taverna.t2.workbench.file.events.SetCurrentDataflowEvent; import net.sf.taverna.t2.workbench.file.exceptions.OpenException; import net.sf.taverna.t2.workbench.file.exceptions.OverwriteException; import net.sf.taverna.t2.workbench.file.exceptions.SaveException; import net.sf.taverna.t2.workbench.file.exceptions.UnsavedException; import net.sf.taverna.t2.workflowmodel.Dataflow; import org.apache.log4j.Logger; /** * Implementation of {@link FileManager} * * @author Stian Soiland-Reyes * */ public class FileManagerImpl extends FileManager { private static Logger logger = Logger.getLogger(FileManagerImpl.class); /** * The last blank dataflow created using #newDataflow() until it has been * changed - when this variable will be set to null again. Used to * automatically close unmodified blank dataflows on open. */ private Dataflow blankDataflow = null; private EditManager editManager = EditManager.getInstance(); private EditManagerObserver editManagerObserver = new EditManagerObserver(); private ModelMap modelMap = ModelMap.getInstance(); private ModelMapObserver modelMapObserver = new ModelMapObserver(); protected MultiCaster<FileManagerEvent> observers = new MultiCaster<FileManagerEvent>( this); /** * Ordered list of open dataflows */ private LinkedHashMap<Dataflow, OpenDataflowInfo> openDataflowInfos = new LinkedHashMap<Dataflow, OpenDataflowInfo>(); public DataflowPersistenceHandlerRegistry getPersistanceHandlerRegistry() { // Delay initialization of handlers return DataflowPersistenceHandlerRegistry.getInstance(); } public FileManagerImpl() { editManager.addObserver(editManagerObserver); modelMap.addObserver(modelMapObserver); } /** * Add an observer to be notified of {@link FileManagerEvent}s, such as * {@link OpenedDataflowEvent} and {@link SavedDataflowEvent}. * * {@inheritDoc} */ public void addObserver(Observer<FileManagerEvent> observer) { observers.addObserver(observer); } /** * {@inheritDoc} */ @Override public boolean canSaveWithoutDestination(Dataflow dataflow) { OpenDataflowInfo dataflowInfo = getOpenDataflowInfo(dataflow); if (dataflowInfo.getSource() == null) { return false; } Set<DataflowPersistenceHandler> handlers = getPersistanceHandlerRegistry() .getSaveHandlersForType(dataflowInfo.getFileType(), dataflowInfo.getDataflowInfo().getCanonicalSource() .getClass()); return !handlers.isEmpty(); } /** * {@inheritDoc} */ @Override public boolean closeDataflow(Dataflow dataflow, boolean failOnUnsaved) throws UnsavedException { if (dataflow == null) { throw new NullPointerException("Dataflow can't be null"); } ClosingDataflowEvent message = new ClosingDataflowEvent(dataflow); observers.notify(message); if (message.isAbortClose()) { return false; } if ((failOnUnsaved && getOpenDataflowInfo(dataflow).isChanged())) { throw new UnsavedException(dataflow); } if (dataflow.equals(getCurrentDataflow())) { // We'll need to change current dataflow // Find best candidate to the left or right List<Dataflow> dataflows = getOpenDataflows(); int openIndex = dataflows.indexOf(dataflow); if (openIndex == -1) { throw new IllegalArgumentException("Workflow was not opened " + dataflow); } else if (openIndex > 0) { setCurrentDataflow(dataflows.get(openIndex - 1)); } else if (openIndex == 0 && dataflows.size() > 1) { setCurrentDataflow(dataflows.get(1)); } else { // If it was the last one, start a new, empty dataflow newDataflow(); } } if (dataflow == blankDataflow) { blankDataflow = null; } openDataflowInfos.remove(dataflow); observers.notify(new ClosedDataflowEvent(dataflow)); return true; } /** * {@inheritDoc} */ @Override public Dataflow getCurrentDataflow() { return (Dataflow) modelMap.getModel(ModelMapConstants.CURRENT_DATAFLOW); } @Override public Dataflow getDataflowBySource(Object source) { for (Entry<Dataflow,OpenDataflowInfo> infoEntry : openDataflowInfos.entrySet()) { OpenDataflowInfo info = infoEntry.getValue(); if (source.equals(info.getSource())) { return infoEntry.getKey(); } } // Not found return null; } /** * {@inheritDoc} */ @Override public String getDataflowName(Dataflow dataflow) { Object source = getDataflowSource(dataflow); String name = dataflow.getLocalName(); // Fallback if (source == null) { return name; } if (source instanceof File){ return ((File)source).getAbsolutePath(); } else if (source instanceof URL){ return source.toString(); } else { // Check if it has implemented a toString() method Method toStringMethod = null; Method toStringMethodFromObject = null; try { toStringMethod = source.getClass().getMethod("toString"); toStringMethodFromObject = Object.class.getMethod("toString"); } catch (Exception e) { throw new IllegalStateException("Source did not implement Object.toString() " + source); } if (! toStringMethod.equals(toStringMethodFromObject)) { return source.toString(); } } return name; } /** * {@inheritDoc} */ @Override public Object getDataflowSource(Dataflow dataflow) { return getOpenDataflowInfo(dataflow).getSource(); } /** * {@inheritDoc} */ @Override public FileType getDataflowType(Dataflow dataflow) { return getOpenDataflowInfo(dataflow).getFileType(); } /** * {@inheritDoc} */ public List<Observer<FileManagerEvent>> getObservers() { return observers.getObservers(); } protected synchronized OpenDataflowInfo getOpenDataflowInfo( Dataflow dataflow) { if (dataflow == null) { throw new NullPointerException("Dataflow can't be null"); } OpenDataflowInfo info = openDataflowInfos.get(dataflow); if (info != null) { return info; } else { throw new IllegalArgumentException("Workflow was not opened" + dataflow); } } /** * {@inheritDoc} */ @Override public List<Dataflow> getOpenDataflows() { return new ArrayList<Dataflow>(openDataflowInfos.keySet()); } /** * {@inheritDoc} */ @Override public List<FileFilter> getOpenFileFilters() { List<FileFilter> fileFilters = new ArrayList<FileFilter>(); Set<FileType> fileTypes = getPersistanceHandlerRegistry().getOpenFileTypes(); if (!fileTypes.isEmpty()) { fileFilters.add(new MultipleFileTypes(fileTypes, "All supported workflow types")); } for (FileType fileType : fileTypes) { fileFilters.add(new FileTypeFileFilter(fileType)); } return fileFilters; } /** * {@inheritDoc} */ @Override public List<FileFilter> getOpenFileFilters(Class<?> sourceClass) { List<FileFilter> fileFilters = new ArrayList<FileFilter>(); for (FileType fileType : getPersistanceHandlerRegistry() .getOpenFileTypesFor(sourceClass)) { fileFilters.add(new FileTypeFileFilter(fileType)); } return fileFilters; } /** * {@inheritDoc} */ @Override public List<FileFilter> getSaveFileFilters() { List<FileFilter> fileFilters = new ArrayList<FileFilter>(); for (FileType fileType : getPersistanceHandlerRegistry().getSaveFileTypes()) { fileFilters.add(new FileTypeFileFilter(fileType)); } return fileFilters; } /** * {@inheritDoc} */ @Override public List<FileFilter> getSaveFileFilters(Class<?> destinationClass) { List<FileFilter> fileFilters = new ArrayList<FileFilter>(); for (FileType fileType : getPersistanceHandlerRegistry() .getSaveFileTypesFor(destinationClass)) { fileFilters.add(new FileTypeFileFilter(fileType)); } return fileFilters; } /** * {@inheritDoc} */ @Override public boolean isDataflowChanged(Dataflow dataflow) { return getOpenDataflowInfo(dataflow).isChanged(); } /** * {@inheritDoc} */ @Override public boolean isDataflowOpen(Dataflow dataflow) { return openDataflowInfos.containsKey(dataflow); } /** * {@inheritDoc} */ @Override public Dataflow newDataflow() { Dataflow dataflow = editManager.getEdits().createDataflow(); blankDataflow = null; openDataflowInternal(dataflow); blankDataflow = dataflow; observers.notify(new OpenedDataflowEvent(dataflow)); return dataflow; } /** * {@inheritDoc} */ @Override public void openDataflow(Dataflow dataflow) { openDataflowInternal(dataflow); observers.notify(new OpenedDataflowEvent(dataflow)); } /** * {@inheritDoc} */ @Override public Dataflow openDataflow(FileType fileType, Object source) throws OpenException { DataflowInfo openDataflow = openDataflowSilently(fileType, source); Dataflow dataflow = openDataflow.getDataflow(); openDataflowInternal(dataflow); getOpenDataflowInfo(dataflow).setOpenedFrom(openDataflow); observers.notify(new OpenedDataflowEvent(dataflow)); return dataflow; } @Override public DataflowInfo openDataflowSilently(FileType fileType, Object source) throws OpenException { Set<DataflowPersistenceHandler> handlers; Class<? extends Object> sourceClass = source.getClass(); boolean unknownFileType = (fileType == null); if (unknownFileType) { handlers = getPersistanceHandlerRegistry() .getOpenHandlersFor(sourceClass); } else { handlers = getPersistanceHandlerRegistry().getOpenHandlersFor(fileType, sourceClass); } if (handlers.isEmpty()) { throw new OpenException("Unsupported file type or class " + fileType + " " + sourceClass); } Throwable lastException = null; for (DataflowPersistenceHandler handler : handlers) { Collection<FileType> fileTypes; if (unknownFileType) { fileTypes = handler.getOpenFileTypes(); } else { fileTypes = Collections.singleton(fileType); } for (FileType candidateFileType : fileTypes) { if (unknownFileType && (source instanceof File)) { // If source is file but fileType was not explicitly set from the // open workflow dialog - check the file extension and decide which // handler to use based on that (so that we do not loop though all handlers) File file = (File) source; if (! file.getPath().endsWith(candidateFileType.getExtension())) { continue; } } try { DataflowInfo openDataflow = handler.openDataflow( candidateFileType, source); Dataflow dataflow = openDataflow.getDataflow(); logger.info("Loaded workflow: " + dataflow.getLocalName() + " " + dataflow.getInternalIdentier() + " from " + source + " using " + handler); return openDataflow; } catch (OpenException ex) { logger.warn("Could not open workflow " + source + " using " + handler + " of type " + candidateFileType); lastException = ex; } } } throw new OpenException("Could not open workflow " + source + "\n", lastException); } /** * Mark the dataflow as opened, and close the blank dataflow if needed. * * @param dataflow * Dataflow that has been opened */ protected void openDataflowInternal(Dataflow dataflow) { if (dataflow == null) { throw new NullPointerException("Dataflow can't be null"); } if (isDataflowOpen(dataflow)) { throw new IllegalArgumentException("Workflow is already open: " + dataflow); } openDataflowInfos.put(dataflow, new OpenDataflowInfo()); setCurrentDataflow(dataflow); if (openDataflowInfos.size() == 2 && blankDataflow != null) { // Behave like a word processor and close the blank workflow // when another workflow has been opened try { closeDataflow(blankDataflow, true); } catch (UnsavedException e) { logger.error("Blank workflow was modified " + "and could not be closed"); } } } /** * {@inheritDoc} */ public void removeObserver(Observer<FileManagerEvent> observer) { observers.removeObserver(observer); } /** * {@inheritDoc} */ @Override public void saveDataflow(Dataflow dataflow, boolean failOnOverwrite) throws SaveException { if (dataflow == null) { throw new NullPointerException("Dataflow can't be null"); } OpenDataflowInfo lastSave = getOpenDataflowInfo(dataflow); if (lastSave.getSource() == null) { throw new SaveException("Can't save without source " + dataflow); } saveDataflow(dataflow, lastSave.getFileType(), lastSave.getSource(), failOnOverwrite); } /** * {@inheritDoc} */ @Override public void saveDataflow(Dataflow dataflow, FileType fileType, Object destination, boolean failOnOverwrite) throws SaveException { DataflowInfo savedDataflow = saveDataflowSilently(dataflow, fileType, destination, failOnOverwrite); getOpenDataflowInfo(dataflow).setSavedTo(savedDataflow); observers.notify(new SavedDataflowEvent(dataflow)); } @Override public DataflowInfo saveDataflowSilently(Dataflow dataflow, FileType fileType, Object destination, boolean failOnOverwrite) throws SaveException, OverwriteException { Set<DataflowPersistenceHandler> handlers; Class<? extends Object> destinationClass = destination.getClass(); if (fileType != null) { handlers = getPersistanceHandlerRegistry().getSaveHandlersForType( fileType, destinationClass); } else { handlers = getPersistanceHandlerRegistry() .getSaveHandlersFor(destinationClass); } if (handlers.isEmpty()) { throw new SaveException("Unsupported file type or class " + fileType + " " + destinationClass); } SaveException lastException = null; for (DataflowPersistenceHandler handler : handlers) { if (failOnOverwrite) { OpenDataflowInfo openDataflowInfo = getOpenDataflowInfo(dataflow); if (handler.wouldOverwriteDataflow(dataflow, fileType, destination, openDataflowInfo.getDataflowInfo())) { throw new OverwriteException(destination); } } try { DataflowInfo savedDataflow = handler.saveDataflow(dataflow, fileType, destination); savedDataflow.getDataflow(); logger.info("Saved workflow: " + dataflow.getLocalName() + " " + dataflow.getInternalIdentier() + " to " + savedDataflow.getCanonicalSource() + " using " + handler); return savedDataflow; } catch (SaveException ex) { logger.warn("Could not save to " + destination + " using " + handler); lastException = ex; } } throw new SaveException("Could not save to " + destination, lastException); } /** * {@inheritDoc} */ @Override public void setCurrentDataflow(Dataflow dataflow) { setCurrentDataflow(dataflow, false); } /** * {@inheritDoc} */ @Override public void setCurrentDataflow(Dataflow dataflow, boolean openIfNeeded) { if (!isDataflowOpen(dataflow)) { if (openIfNeeded) { openDataflow(dataflow); return; } else { throw new IllegalArgumentException("Workflow is not open: " + dataflow); } } modelMap.setModel(ModelMapConstants.CURRENT_DATAFLOW, dataflow); } /** * {@inheritDoc} */ @Override public void setDataflowChanged(Dataflow dataflow, boolean isChanged) { getOpenDataflowInfo(dataflow).setIsChanged(isChanged); if (blankDataflow == dataflow) { blankDataflow = null; } } /** * Observe the {@link EditManager} for changes to open dataflows. A change * of an open workflow would set it as changed using * {@link FileManagerImpl#setDataflowChanged(Dataflow, boolean)}. * * @author Stian Soiland-Reyes * */ private final class EditManagerObserver implements Observer<EditManagerEvent> { public void notify(Observable<EditManagerEvent> sender, EditManagerEvent message) throws Exception { if (message instanceof AbstractDataflowEditEvent) { AbstractDataflowEditEvent dataflowEdit = (AbstractDataflowEditEvent) message; Dataflow dataflow = dataflowEdit.getDataFlow(); /** * TODO: on undo/redo - keep last event or similar to determine * if workflow was saved before. See * FileManagerTest#isChangedWithUndo(). */ setDataflowChanged(dataflow, true); } } } /** * Observes the {@link ModelMap} for the ModelMapConstants.CURRENT_DATAFLOW. * Make sure that the dataflow is opened and notifies observers with a * SetCurrentDataflowEvent. * * @author Stian Soiland-Reyes * */ private final class ModelMapObserver implements Observer<ModelMapEvent> { public void notify(Observable<ModelMapEvent> sender, ModelMapEvent message) throws Exception { if (message.getModelName().equals( ModelMapConstants.CURRENT_DATAFLOW)) { Dataflow newModel = (Dataflow) message.getNewModel(); if (newModel != null) { if (!isDataflowOpen(newModel)) { openDataflowInternal(newModel); } } observers.notify(new SetCurrentDataflowEvent(newModel)); } } } }
package org.flymine.dataconversion; import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.LinkedHashMap; import java.util.Collection; import java.util.Arrays; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.File; import java.io.BufferedReader; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.ModelFactory; import org.intermine.xml.full.FullParser; import org.intermine.xml.full.FullRenderer; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.DataTranslatorTestCase; import org.intermine.dataconversion.MockItemReader; import org.intermine.dataconversion.MockItemWriter; /** * Test for translating MAGE data in fulldata Item format conforming to a source OWL definition * to fulldata Item format conforming to InterMine OWL definition. * * @author Wenyan Ji * @author Richard Smith */ public class MageDataTranslatorTest extends DataTranslatorTestCase { private String tgtNs = "http://www.flymine.org/model/genomic private String ns = "http://www.flymine.org/model/mage public void setUp() throws Exception { super.setUp(); } public void testTranslate() throws Exception { Collection srcItems = getSrcItems(); FileWriter writerSrc = new FileWriter(new File("src_items.xml")); writerSrc.write(FullRenderer.render(srcItems)); writerSrc.close(); Map itemMap = writeItems(srcItems); DataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), getOwlModel(), tgtNs); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); FileWriter writer = new FileWriter(new File("exptmp")); writer.write(FullRenderer.render(tgtIw.getItems())); writer.close(); //assertEquals(new HashSet(expectedItems), tgtIw.getItems()); } public void testCreateAuthors() { Item srcItem = createItem(ns + "BibliographicReference", "0_0", ""); srcItem.addAttribute(new Attribute("authors", " William Whitfield; FlyChip Facility")); Item exp1 = createItem(tgtNs + "Author", "-1_1", ""); exp1.addAttribute(new Attribute("name", "William Whitfield")); Item exp2 = createItem(tgtNs + "Author", "-1_2", ""); exp2.addAttribute(new Attribute("name", "FlyChip Facility")); Set expected = new HashSet(Arrays.asList(new Object[] {exp1, exp2})); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(new HashMap()), getOwlModel(), tgtNs); assertEquals(expected, translator.createAuthors(srcItem)); } public void testSetReporterLocationCoords() throws Exception{ Item srcItem = createItem(ns + "FeatureReporterMap", "6_28", ""); srcItem.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"7_29"})))); Item srcItem2=createItem(ns + "FeatureInformation", "7_29", ""); srcItem2. addReference(new Reference("feature", "8_30")); Item srcItem3=createItem(ns + "Feature", "8_30", ""); srcItem3.addReference(new Reference("featureLocation", "9_31")); srcItem3.addReference(new Reference("zone", "10_17")); Item srcItem4 = createItem(ns + "FeatureLocation", "9_31", ""); srcItem4.addAttribute(new Attribute("column", "1")); srcItem4.addAttribute(new Attribute("row", "2")); Item srcItem5 = createItem(ns + "Zone", "10_17", ""); srcItem5.addAttribute(new Attribute("column", "1")); srcItem5.addAttribute(new Attribute("row", "1")); Set srcItems = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem2, srcItem3, srcItem4, srcItem5})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), getOwlModel(), tgtNs); Item tgtItem = createItem(tgtNs + "ReporterLocation", "6_28", ""); tgtItem.addAttribute(new Attribute("localX", "1")); tgtItem.addAttribute(new Attribute("localY", "2")); tgtItem.addAttribute(new Attribute("zoneX", "1")); tgtItem.addAttribute(new Attribute("zoneY", "1")); HashSet expected = new HashSet(Arrays.asList(new Object[]{tgtItem})); assertEquals(expected, translator.translateItem(srcItem)); } public void testCreateFeatureMap() throws Exception { Item srcItem1=createItem(ns + "PhysicalArrayDesign", "0_0", ""); ReferenceList rl1=new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[] {"1_1"}))); srcItem1.addCollection(rl1); Item srcItem2=createItem(ns + "FeatureGroup", "1_1", ""); ReferenceList rl2=new ReferenceList("features", new ArrayList(Arrays.asList(new Object[] {"1_2"}))); srcItem2.addCollection(rl2); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem1, srcItem2})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), getOwlModel(), tgtNs); Item tgtItem = createItem(tgtNs+"MicroArraySlideDesign", "3_1", ""); Map expected = new HashMap(); expected.put("1_2", "3_1"); translator.createFeatureMap(srcItem1, tgtItem); assertEquals(expected, translator.featureToDesign); } //test translate from PhysicalArrayDesign to MicroArraySlideDesign //which includes 3 methods, createFeatureMap, padDescriptions, and changeRefToAttr public void testTranslateMASD() throws Exception { Item srcItem1=createItem(ns + "PhysicalArrayDesign", "1_1", ""); srcItem1.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[] {"1_2", "2_2"} )))); srcItem1.addReference(new Reference("surfaceType","1_11")); srcItem1.addCollection(new ReferenceList("featureGroups", new ArrayList(Arrays.asList(new Object[] {"1_12"})))); Item srcItem2=createItem(ns + "Description", "1_2", ""); srcItem2.addCollection(new ReferenceList("annotations", new ArrayList(Arrays.asList(new Object[] {"1_3", "1_4"})))); Item srcItem2a=createItem(ns + "Description", "2_2", ""); srcItem2a.addCollection(new ReferenceList("annotations", new ArrayList(Arrays.asList(new Object[] {"2_3", "2_4"})))); Item srcItem3=createItem(ns + "OntologyEntry", "1_3", ""); srcItem3.addAttribute(new Attribute("value", "double")); Item srcItem4=createItem(ns + "SurfaceType", "1_11", ""); srcItem4.addAttribute(new Attribute("value", "polylysine")); Item srcItem5=createItem(ns + "FeatureGroup", "1_12", ""); srcItem5.addCollection(new ReferenceList("features", new ArrayList(Arrays.asList(new Object[] {"1_13"})))); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem1, srcItem2, srcItem2a, srcItem3, srcItem4, srcItem5})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), getOwlModel(), tgtNs); //MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); //translator.translate(tgtIw); // expected items // MicroArraySlideDesign 1_1 Item expectedItem=createItem(tgtNs + "MicroArraySlideDesign", "1_1", ""); expectedItem.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[] {"1_3", "1_4", "2_3", "2_4"})))); expectedItem.addAttribute(new Attribute("surfaceType", "polylysine")); HashSet expected = new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem1)); } public void testMicroArrayExperiment()throws Exception { Item srcItem = createItem(ns+"Experiment", "61_748", ""); srcItem.addAttribute(new Attribute("name", "P10005")); srcItem.addCollection(new ReferenceList("bioAssays", new ArrayList(Arrays.asList(new Object[]{"33_603", "57_709", "43_654"})))); srcItem.addCollection(new ReferenceList("descriptions", new ArrayList(Arrays.asList(new Object[]{"12_749", "12_750"})))); Item srcItem1= createItem(ns+"MeasuredBioAssay", "33_603", ""); srcItem1.addReference(new Reference("featureExtraction", "4_2")); Item srcItem2= createItem(ns+"DerivedBioAssay", "57_709", ""); srcItem2.addReference(new Reference("featureExtraction", "4_2")); Item srcItem3= createItem(ns+"PhysicalBioAssay", "43_654", ""); srcItem3.addReference(new Reference("featureExtraction", "4_2")); Item srcItem4= createItem(ns+"Description", "12_749", ""); srcItem4.addAttribute(new Attribute("text", "experiment description")); Item srcItem5= createItem(ns+"Description", "12_750", ""); srcItem5.addCollection(new ReferenceList("bibliographicReferences", new ArrayList(Arrays.asList(new Object[]{"62_751"})))); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3, srcItem4, srcItem5})); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), getOwlModel(), tgtNs); Item expectedItem =createItem(tgtNs+"MicroArrayExperiment", "61_748", ""); expectedItem.addAttribute(new Attribute("name", "P10005")); expectedItem.addAttribute(new Attribute("description", "experiment description")); expectedItem.addReference(new Reference("publication", "62_751")); expectedItem.addCollection(new ReferenceList("assays", new ArrayList(Arrays.asList(new Object[]{"57_709"})))); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem)); } public void testMicroArrayAssay() throws Exception{ Item srcItem= createItem(ns+"DerivedBioAssay", "57_709", ""); srcItem.addCollection(new ReferenceList("derivedBioAssayData", new ArrayList(Arrays.asList(new Object[]{"58_710"})))); Item srcItem1= createItem(ns+"DerivedBioAssayData", "58_710", ""); srcItem1.addReference(new Reference("bioDataValues", "58_739")); Item srcItem2= createItem(ns+"BioDataTuples", "58_739", ""); srcItem2.addCollection(new ReferenceList("bioAssayTupleData", new ArrayList(Arrays.asList(new Object[]{"58_740", "58_744", "58_755"})))); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2})); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), getOwlModel(), tgtNs); Item expectedItem = createItem(tgtNs+"MicroArrayAssay", "57_709", ""); expectedItem.addCollection(new ReferenceList("results", new ArrayList(Arrays.asList(new Object[]{"58_740", "58_744", "58_755"})))); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem)); } public void testMicroArrayExperimentalResult() throws Exception { Item srcItem= createItem(ns+"BioAssayDatum", "58_762", ""); srcItem.addReference(new Reference("quantitationType","40_620")); srcItem.addAttribute(new Attribute("normalised","true")); Item srcItem1= createItem(ns+"Error", "40_620", ""); srcItem1.addAttribute(new Attribute("name", "Signal st dev Cy3")); srcItem1.addReference(new Reference("targetQuantitationType", "38_608")); Item srcItem2= createItem(ns+"MeasuredSignal", "38_608", ""); srcItem2.addAttribute(new Attribute("isBackground", "false")); srcItem2.addReference(new Reference("scale", "1_611")); Item srcItem3= createItem(ns+"OntologyEntry", "1_611", ""); srcItem3.addAttribute(new Attribute("value", "linear_scale")); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3})); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), getOwlModel(), tgtNs); Item expectedItem = createItem(tgtNs+"MicroArrayExperimentalResult", "58_762", ""); expectedItem.addAttribute(new Attribute("normalised","true")); expectedItem.addAttribute(new Attribute("type","Signal st dev Cy3")); expectedItem.addAttribute(new Attribute("scale","linear_scale")); expectedItem.addAttribute(new Attribute("isBackground","false")); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem)); } public void testBioEntity() throws Exception { Item srcItem= createItem(ns+"BioSequence", "0_11", ""); srcItem.addReference(new Reference("type","1_13")); srcItem.addCollection(new ReferenceList("sequenceDatabases", new ArrayList(Arrays.asList(new Object[]{"2_14", "2_15", "2_16", "2_17"})))); Item srcItem1= createItem(ns+"OntologyEntry", "1_13", ""); srcItem1.addAttribute(new Attribute("value", "cDNA_clone")); Item srcItem2= createItem(ns+"DatabaseEntry", "2_14", ""); srcItem2.addAttribute(new Attribute("accession", "FBgn0010173")); srcItem2.addReference(new Reference("database", "3_7")); Item srcItem3= createItem(ns+"DatabaseEntry", "2_15", ""); srcItem3.addAttribute(new Attribute("accession", "AY069331")); srcItem3.addReference(new Reference("database", "3_9")); Item srcItem4= createItem(ns+"DatabaseEntry", "2_16", ""); srcItem4.addAttribute(new Attribute("accession", "AA201663")); srcItem4.addReference(new Reference("database", "3_9")); Item srcItem5= createItem(ns+"DatabaseEntry", "2_17", ""); srcItem5.addAttribute(new Attribute("accession", "AW941561")); srcItem5.addReference(new Reference("database", "3_9")); Item srcItem6= createItem(ns+"Database", "3_7", ""); srcItem6.addAttribute(new Attribute("name", "flybase")); Item srcItem7= createItem(ns+"Database", "3_9", ""); srcItem7.addAttribute(new Attribute("name", "embl")); Set src = new HashSet(Arrays.asList(new Object[]{srcItem, srcItem1, srcItem2, srcItem3, srcItem4, srcItem5, srcItem6, srcItem7 })); Map srcMap = writeItems(src); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(srcMap), getOwlModel(), tgtNs); Item expectedItem = createItem(tgtNs+"CDNAClone", "0_11", ""); expectedItem.addAttribute(new Attribute("identifier","AY069331")); expectedItem.addCollection(new ReferenceList("synonyms", new ArrayList(Arrays.asList(new Object[]{"2_15", "2_16", "2_17"})))); Item expectedItem1 = createItem(tgtNs+"Gene", "-1_1", ""); expectedItem1.addAttribute(new Attribute("organismDbId", "FBgn0010173")); expectedItem1.addCollection(new ReferenceList("synonyms", new ArrayList(Arrays.asList(new Object[]{"3_7"})))); HashSet expected=new HashSet(Arrays.asList(new Object[]{expectedItem})); assertEquals(expected, translator.translateItem(srcItem)); } public void testBioEntity2MAER() throws Exception { Item srcItem= createItem(ns+"Reporter", "12_45", ""); srcItem.addCollection(new ReferenceList("featureReporterMaps", new ArrayList(Arrays.asList(new Object[]{"7_41"})))); srcItem.addCollection(new ReferenceList("immobilizedCharacteristics", new ArrayList(Arrays.asList(new Object[]{"0_3"})))); Item srcItem1= createItem(ns+"FeatureReporterMap", "7_41", ""); srcItem1.addCollection(new ReferenceList("featureInformationSources", new ArrayList(Arrays.asList(new Object[]{"8_42"})))); Item srcItem2= createItem(ns+"FeatureInformation", "8_42", ""); srcItem2.addReference(new Reference("feature", "9_43")); Item srcItem3= createItem(ns+"BioSequence", "0_3", ""); srcItem2.addReference(new Reference("type", "1_5")); Item srcItem4 =createItem(ns+"OntologyEntry", "1_5", ""); srcItem4.addAttribute(new Attribute("value", "cDNA_clone")); Set srcItems = new HashSet(Arrays.asList(new Object[] {srcItem, srcItem1, srcItem2, srcItem3, srcItem4})); Map itemMap = writeItems(srcItems); MageDataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), getOwlModel(), tgtNs); Item tgtItem = createItem(tgtNs+"cDNAClone", "0_3", ""); Map expected = new HashMap(); expected.put("0_3", "9_43 "); translator.setBioEntity2FeatureMap(srcItem,tgtItem); assertEquals(expected, translator.bioEntity2Feature); } protected Collection getSrcItems() throws Exception { BufferedReader srcReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/MageTestData_adf.xml"))); MockItemWriter mockIw = new MockItemWriter(new LinkedHashMap()); MageConverter converter = new MageConverter(mockIw); converter.process(srcReader); //BufferedReader srcReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test/MageTestData_exp.xml"))); //converter = new MageConverter( mockIw); converter.process(srcReader); return mockIw.getItems(); } protected Collection getExpectedItems() throws Exception { Collection srcItems = getSrcItems(); Map itemMap = writeItems(srcItems); DataTranslator translator = new MageDataTranslator(new MockItemReader(itemMap), getOwlModel(), tgtNs); MockItemWriter tgtIw = new MockItemWriter(new LinkedHashMap()); translator.translate(tgtIw); return tgtIw.getItems(); } protected OntModel getOwlModel() { InputStreamReader reader = new InputStreamReader( getClass().getClassLoader().getResourceAsStream("genomic.n3")); OntModel ont = ModelFactory.createOntologyModel(); ont.read(reader, null, "N3"); return ont; } protected String getModelName() { return "genomic"; } private Item createItem(String className, String itemId, String implementation){ Item item=new Item(); item.setIdentifier(itemId); item.setClassName(className); item.setImplementations(implementation); return item; } }
package com.oracle.graal.nodes.calc; import com.oracle.graal.api.meta.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; /** * A {@code FloatConvert} converts between integers and floating point numbers according to Java * semantics. */ public class FloatConvertNode extends ConvertNode implements Canonicalizable, Lowerable, ArithmeticLIRLowerable { public enum FloatConvert { F2I, D2I, F2L, D2L, I2F, L2F, D2F, I2D, L2D, F2D; public FloatConvert reverse() { switch (this) { case D2F: return F2D; case D2I: return I2D; case D2L: return L2D; case F2D: return D2F; case F2I: return I2F; case F2L: return L2F; case I2D: return D2I; case I2F: return F2I; case L2D: return D2L; case L2F: return F2L; default: throw GraalInternalError.shouldNotReachHere(); } } } private final FloatConvert op; public FloatConvertNode(FloatConvert op, ValueNode input) { super(createStamp(op, input), input); this.op = op; } private static Stamp createStamp(FloatConvert op, ValueNode input) { switch (op) { case I2F: case I2D: assert input.stamp() instanceof IntegerStamp && ((IntegerStamp) input.stamp()).getBits() == 32; break; case L2F: case L2D: assert input.stamp() instanceof IntegerStamp && ((IntegerStamp) input.stamp()).getBits() == 64; break; case F2I: case F2L: case F2D: assert input.stamp() instanceof FloatStamp && ((FloatStamp) input.stamp()).getBits() == 32; break; case D2I: case D2L: case D2F: assert input.stamp() instanceof FloatStamp && ((FloatStamp) input.stamp()).getBits() == 64; break; default: throw GraalInternalError.shouldNotReachHere(); } switch (op) { case F2I: case D2I: return StampFactory.forKind(Kind.Int); case F2L: case D2L: return StampFactory.forKind(Kind.Long); case I2F: case L2F: case D2F: return StampFactory.forKind(Kind.Float); case I2D: case L2D: case F2D: return StampFactory.forKind(Kind.Double); default: throw GraalInternalError.shouldNotReachHere(); } } public FloatConvert getOp() { return op; } @Override public boolean inferStamp() { return updateStamp(createStamp(op, getInput())); } private static Constant convert(FloatConvert op, Constant value) { switch (op) { case F2I: return Constant.forInt((int) value.asFloat()); case D2I: return Constant.forInt((int) value.asDouble()); case F2L: return Constant.forLong((long) value.asFloat()); case D2L: return Constant.forLong((long) value.asDouble()); case I2F: return Constant.forFloat(value.asInt()); case L2F: return Constant.forFloat(value.asLong()); case D2F: return Constant.forFloat((float) value.asDouble()); case I2D: return Constant.forDouble(value.asInt()); case L2D: return Constant.forDouble(value.asLong()); case F2D: return Constant.forDouble(value.asFloat()); default: throw GraalInternalError.shouldNotReachHere(); } } @Override public Constant convert(Constant c) { return convert(op, c); } @Override public Constant reverse(Constant c) { return convert(op.reverse(), c); } @Override public boolean isLossless() { switch (op) { case F2D: case I2D: return true; default: return false; } } @Override public Node canonical(CanonicalizerTool tool) { if (getInput().isConstant()) { return ConstantNode.forPrimitive(evalConst(getInput().asConstant()), graph()); } else if (getInput() instanceof FloatConvertNode) { FloatConvertNode other = (FloatConvertNode) getInput(); if (other.isLossless() && other.op == this.op.reverse()) { return other.getInput(); } } return this; } public void lower(LoweringTool tool) { tool.getLowerer().lower(this, tool); } public void generate(ArithmeticLIRGenerator gen) { gen.setResult(this, gen.emitFloatConvert(op, gen.operand(getInput()))); } }
package com.nucleus.scene; import java.util.ArrayList; import com.nucleus.SimpleLogger; import com.nucleus.event.EventManager; import com.nucleus.mmi.MMIEventListener; import com.nucleus.mmi.MMIPointerEvent; import com.nucleus.mmi.ObjectInputListener; import com.nucleus.mmi.core.PointerInputProcessor; import com.nucleus.properties.Property; import com.nucleus.scene.Node.State; /** * Handles pointer input checking on nodes * Takes {@link MMIEventListener} events and checks the registered node tree for pointer hits. * This class must be registred to {@link PointerInputProcessor} for it to get mmi event callbacks. */ public class J2SENodeInputListener implements NodeInputListener, MMIEventListener { private final RootNode root; private float[] down = new float[2]; public J2SENodeInputListener(RootNode root) { this.root = root; } @Override public boolean onInputEvent(ArrayList<Node> nodes, MMIPointerEvent event) { int count = nodes.size() - 1; Node node = null; for (int i = count; i >= 0; i node = nodes.get(i); switch (node.getState()) { case ON: case ACTOR: if (onPointerEvent(node, event)) { return true; } break; default: SimpleLogger.d(getClass(), "Not handling input, node in state: " + node.getState()); // Do nothing } } return false; } /** * Checks this node for pointer event. * This default implementation will check bounds and check {@link #ONCLICK} property and send to * {@link EventManager#post(Node, String, String)} if defined. * TODO Instead of transforming the bounds the inverse matrix should be used. * Will stop when a node is in state {@link State#OFF} or {@link State#RENDER} * * @param event * @return True if the input event was consumed, false otherwise. */ protected boolean onPointerEvent(Node node, MMIPointerEvent event) { float[] position = event.getPointerData().getCurrentPosition(); if (position == null) { return false; } if (node.isInside(position)) { if (node instanceof MMIEventListener) { ((MMIEventListener) node).onInputEvent(event); } ObjectInputListener listener = root.getObjectInputListener(); switch (event.getAction()) { case ACTIVE: down[0] = position[0]; down[1] = position[1]; SimpleLogger.d(getClass(), "HIT: " + node); String onclick = node.getProperty(ONCLICK); if (onclick != null) { Property p = Property.create(onclick); if (p != null) { EventManager.getInstance().post(node, p.getKey(), p.getValue()); } else { SimpleLogger.d(getClass(), "Invalid property for node " + node.getId() + " : " + onclick); } } if (listener != null) { listener.onInputEvent(node, event.getPointerData().getCurrent()); } return true; case INACTIVE: if (listener != null) { listener.onInputEvent(node, event.getPointerData().getCurrent()); } return true; case MOVE: if (listener != null) { listener.onDrag(node, event.getPointerData()); } return true; case ZOOM: break; default: break; } } return false; } /** * Checks children for pointer event, calling {@link #onPointerEvent(MMIPointerEvent)} recursively and stopping when * a child returns true. * * @param event * @return true if one of the children has a match for the pointer event, false otherwise */ protected boolean checkChildren(Node node, MMIPointerEvent event) { State state = node.getState(); if (state == State.ON || state == State.ACTOR) { for (Node n : node.getChildren()) { if (onPointerEvent(n, event)) { return true; } } } return false; } @Override public void onInputEvent(MMIPointerEvent event) { onInputEvent(root.getVisibleNodeList(), event); } }
package android.support.design.widget; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewCompat; public final class TabLayoutUtils { public static TabLayout.Tab setBackground(@NonNull final TabLayout.Tab tab, @Nullable final Drawable background) { ViewCompat.setBackground(tab.mView, background); return tab; } public static TabLayout.Tab setVisibility(@NonNull final TabLayout.Tab tab, final int visibility) { tab.mView.setVisibility(visibility); return tab; } }
package ucar.nc2.geotiff; import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.StringWriter; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Formatter; import java.util.List; import ucar.nc2.util.CompareNetcdf2; /** * Low level read/write geotiff files. * * @author John Caron * @author Yuan Ho */ public class GeoTiff implements Closeable { private static final boolean showBytes = false, debugRead = false, debugReadGeoKey = false; private static final boolean showHeaderBytes = false; private String filename; private RandomAccessFile file; private FileChannel channel; private List<IFDEntry> tags = new ArrayList<>(); private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; private boolean readonly; /** * Constructor. Does not open or create the file. * * @param filename pathname of file */ public GeoTiff(String filename) { this.filename = filename; } /** * Close the Geotiff file. * * @throws java.io.IOException on io error */ public void close() throws IOException { if (channel != null) { if (!readonly) { channel.force(true); channel.truncate(nextOverflowData); } channel.close(); } if (file != null) file.close(); } // writing private int headerSize = 8; private int firstIFD; private int lastIFD; private int startOverflowData; private int nextOverflowData; void addTag(IFDEntry ifd) { tags.add(ifd); } List<IFDEntry> getTags() { return tags; } void deleteTag(IFDEntry ifd) { tags.remove(ifd); } void setTransform(double xStart, double yStart, double xInc, double yInc) { // tie the raster 0, 0 to xStart, yStart addTag(new IFDEntry(Tag.ModelTiepointTag, FieldType.DOUBLE) .setValue(new double[] {0.0, 0.0, 0.0, xStart, yStart, 0.0})); // define the "affine transformation" : requires grid to be regular (!) addTag(new IFDEntry(Tag.ModelPixelScaleTag, FieldType.DOUBLE).setValue(new double[] {xInc, yInc, 0.0})); } private List<GeoKey> geokeys = new ArrayList<>(); void addGeoKey(GeoKey geokey) { geokeys.add(geokey); } private void writeGeoKeys() { if (geokeys.isEmpty()) return; // count extras int extra_chars = 0; int extra_ints = 0; int extra_doubles = 0; for (GeoKey geokey : geokeys) { if (geokey.isDouble) extra_doubles += geokey.count(); else if (geokey.isString) extra_chars += geokey.valueString().length() + 1; else if (geokey.count() > 1) extra_ints += geokey.count(); } int n = (geokeys.size() + 1) * 4; int[] values = new int[n + extra_ints]; double[] dvalues = new double[extra_doubles]; char[] cvalues = new char[extra_chars]; int icounter = n; int dcounter = 0; int ccounter = 0; values[0] = 1; values[1] = 1; values[2] = 0; values[3] = geokeys.size(); int count = 4; for (GeoKey geokey : geokeys) { values[count++] = geokey.tagCode(); if (geokey.isDouble) { values[count++] = Tag.GeoDoubleParamsTag.getCode(); // extra double values here values[count++] = geokey.count(); values[count++] = dcounter; for (int k = 0; k < geokey.count(); k++) dvalues[dcounter++] = geokey.valueD(k); } else if (geokey.isString) { String s = geokey.valueString(); values[count++] = Tag.GeoAsciiParamsTag.getCode(); // extra double values here values[count++] = s.length(); // dont include trailing 0 in the count values[count++] = ccounter; for (int k = 0; k < s.length(); k++) cvalues[ccounter++] = s.charAt(k); cvalues[ccounter++] = (char) 0; } else if (geokey.count() > 1) { // more than one int value values[count++] = Tag.GeoKeyDirectoryTag.getCode(); // extra int values here values[count++] = geokey.count(); values[count++] = icounter; for (int k = 0; k < geokey.count(); k++) values[icounter++] = geokey.value(k); } else { // normal case of one int value values[count++] = 0; values[count++] = 1; values[count++] = geokey.value(); } } // loop over geokeys addTag(new IFDEntry(Tag.GeoKeyDirectoryTag, FieldType.SHORT).setValue(values)); if (extra_doubles > 0) addTag(new IFDEntry(Tag.GeoDoubleParamsTag, FieldType.DOUBLE).setValue(dvalues)); if (extra_chars > 0) addTag(new IFDEntry(Tag.GeoAsciiParamsTag, FieldType.ASCII).setValue(new String(cvalues))); } int writeData(byte[] data, int imageNumber) throws IOException { if (file == null) init(); if (imageNumber == 1) channel.position(headerSize); else channel.position(nextOverflowData); ByteBuffer buffer = ByteBuffer.wrap(data); channel.write(buffer); if (imageNumber == 1) firstIFD = headerSize + data.length; else firstIFD = data.length + nextOverflowData; return nextOverflowData; } int writeData(float[] data, int imageNumber) throws IOException { if (file == null) init(); if (imageNumber == 1) channel.position(headerSize); else channel.position(nextOverflowData); // no way around making a copy ByteBuffer direct = ByteBuffer.allocateDirect(4 * data.length); FloatBuffer buffer = direct.asFloatBuffer(); buffer.put(data); // ((Buffer) buffer).flip(); channel.write(direct); if (imageNumber == 1) firstIFD = headerSize + 4 * data.length; else firstIFD = 4 * data.length + nextOverflowData; return nextOverflowData; } void writeMetadata(int imageNumber) throws IOException { if (file == null) init(); // geokeys all get added at once writeGeoKeys(); // tags gotta be in order Collections.sort(tags); if (imageNumber == 1) { writeHeader(channel); } else { // now this is not the first image we need to fill the Offset of nextIFD channel.position(lastIFD); ByteBuffer buffer = ByteBuffer.allocate(4); if (debugRead) System.out.println("position before writing nextIFD= " + channel.position() + " IFD is " + firstIFD); buffer.putInt(firstIFD); ((Buffer) buffer).flip(); channel.write(buffer); } writeIFD(channel, firstIFD); } private int writeHeader(FileChannel channel) throws IOException { channel.position(0); ByteBuffer buffer = ByteBuffer.allocate(8); buffer.put((byte) 'M'); buffer.put((byte) 'M'); buffer.putShort((short) 42); buffer.putInt(firstIFD); ((Buffer) buffer).flip(); channel.write(buffer); return firstIFD; } public void initTags() { tags = new ArrayList<>(); geokeys = new ArrayList<>(); } private void init() throws IOException { file = new RandomAccessFile(filename, "rw"); channel = file.getChannel(); if (debugRead) System.out.println("Opened file to write: '" + filename + "', size=" + channel.size()); readonly = false; } private void writeIFD(FileChannel channel, int start) throws IOException { channel.position(start); ByteBuffer buffer = ByteBuffer.allocate(2); int n = tags.size(); buffer.putShort((short) n); ((Buffer) buffer).flip(); channel.write(buffer); start += 2; startOverflowData = start + 12 * tags.size() + 4; nextOverflowData = startOverflowData; for (IFDEntry elem : tags) { writeIFDEntry(channel, elem, start); start += 12; } // firstIFD = startOverflowData; // position to where the "next IFD" goes channel.position(startOverflowData - 4); lastIFD = startOverflowData - 4; if (debugRead) System.out.println("pos before writing nextIFD= " + channel.position()); buffer = ByteBuffer.allocate(4); buffer.putInt(0); ((Buffer) buffer).flip(); channel.write(buffer); } private void writeIFDEntry(FileChannel channel, IFDEntry ifd, int start) throws IOException { channel.position(start); ByteBuffer buffer = ByteBuffer.allocate(12); buffer.putShort((short) ifd.tag.getCode()); buffer.putShort((short) ifd.type.code); buffer.putInt(ifd.count); int size = ifd.count * ifd.type.size; if (size <= 4) { int done = writeValues(buffer, ifd); for (int k = 0; k < 4 - done; k++) // fill out to 4 bytes buffer.put((byte) 0); ((Buffer) buffer).flip(); channel.write(buffer); } else { // write offset buffer.putInt(nextOverflowData); ((Buffer) buffer).flip(); channel.write(buffer); // write data channel.position(nextOverflowData); ByteBuffer vbuffer = ByteBuffer.allocate(size); writeValues(vbuffer, ifd); ((Buffer) vbuffer).flip(); channel.write(vbuffer); nextOverflowData += size; } } private int writeValues(ByteBuffer buffer, IFDEntry ifd) { int done = 0; if (ifd.type == FieldType.ASCII) { return writeSValue(buffer, ifd); } else if (ifd.type == FieldType.RATIONAL) { for (int i = 0; i < ifd.count * 2; i++) done += writeIntValue(buffer, ifd, ifd.value[i]); } else if (ifd.type == FieldType.FLOAT) { for (int i = 0; i < ifd.count; i++) buffer.putFloat((float) ifd.valueD[i]); done += ifd.count * 4; } else if (ifd.type == FieldType.DOUBLE) { for (int i = 0; i < ifd.count; i++) buffer.putDouble(ifd.valueD[i]); done += ifd.count * 8; } else { for (int i = 0; i < ifd.count; i++) done += writeIntValue(buffer, ifd, ifd.value[i]); } return done; } private int writeIntValue(ByteBuffer buffer, IFDEntry ifd, int v) { switch (ifd.type.code) { case 1: buffer.put((byte) v); return 1; case 3: buffer.putShort((short) v); return 2; case 4: case 5: buffer.putInt(v); return 4; } return 0; } private int writeSValue(ByteBuffer buffer, IFDEntry ifd) { buffer.put(ifd.valueS.getBytes(StandardCharsets.UTF_8)); int size = ifd.valueS.length(); if ((size & 1) != 0) size++; // check if odd return size; } // reading /** * Read the geotiff file, using the filename passed in the constructor. * * @throws IOException on read error */ public void read() throws IOException { file = new RandomAccessFile(filename, "r"); channel = file.getChannel(); if (debugRead) System.out.println("Opened file to read:'" + filename + "', size=" + channel.size()); readonly = true; int nextOffset = readHeader(channel); while (nextOffset > 0) { nextOffset = readIFD(channel, nextOffset); parseGeoInfo(); } // parseGeoInfo(); } IFDEntry findTag(Tag tag) { if (tag == null) return null; for (IFDEntry ifd : tags) { if (ifd.tag == tag) return ifd; } return null; } private int readHeader(FileChannel channel) throws IOException { channel.position(0); ByteBuffer buffer = ByteBuffer.allocate(8); int n = channel.read(buffer); assert n == 8; ((Buffer) buffer).flip(); if (showHeaderBytes) { printBytes(System.out, "header", buffer, 4); buffer.rewind(); } byte b = buffer.get(); if (b == 73) byteOrder = ByteOrder.LITTLE_ENDIAN; buffer.order(byteOrder); buffer.position(4); int firstIFD = buffer.getInt(); if (debugRead) System.out.println(" firstIFD == " + firstIFD); return firstIFD; } private int readIFD(FileChannel channel, int start) throws IOException { channel.position(start); ByteBuffer buffer = ByteBuffer.allocate(2); buffer.order(byteOrder); int n = channel.read(buffer); assert n == 2; ((Buffer) buffer).flip(); if (showBytes) { printBytes(System.out, "IFD", buffer, 2); buffer.rewind(); } short nentries = buffer.getShort(); if (debugRead) System.out.println(" nentries = " + nentries); start += 2; for (int i = 0; i < nentries; i++) { IFDEntry ifd = readIFDEntry(channel, start); if (debugRead) System.out.println(i + " == " + ifd); tags.add(ifd); start += 12; } if (debugRead) System.out.println(" looking for nextIFD at pos == " + channel.position() + " start = " + start); channel.position(start); buffer = ByteBuffer.allocate(4); buffer.order(byteOrder); assert 4 == channel.read(buffer); ((Buffer) buffer).flip(); int nextIFD = buffer.getInt(); if (debugRead) System.out.println(" nextIFD == " + nextIFD); return nextIFD; } private IFDEntry readIFDEntry(FileChannel channel, int start) throws IOException { if (debugRead) System.out.println("readIFDEntry starting position to " + start); channel.position(start); ByteBuffer buffer = ByteBuffer.allocate(12); buffer.order(byteOrder); int n = channel.read(buffer); assert n == 12; ((Buffer) buffer).flip(); if (showBytes) printBytes(System.out, "IFDEntry bytes", buffer, 12); IFDEntry ifd; buffer.position(0); int code = readUShortValue(buffer); Tag tag = Tag.get(code); if (tag == null) tag = new Tag(code); FieldType type = FieldType.get(readUShortValue(buffer)); int count = buffer.getInt(); ifd = new IFDEntry(tag, type, count); if (ifd.count * ifd.type.size <= 4) { readValues(buffer, ifd); } else { int offset = buffer.getInt(); if (debugRead) System.out.println("position to " + offset); channel.position(offset); ByteBuffer vbuffer = ByteBuffer.allocate(ifd.count * ifd.type.size); vbuffer.order(byteOrder); assert ifd.count * ifd.type.size == channel.read(vbuffer); ((Buffer) vbuffer).flip(); readValues(vbuffer, ifd); } return ifd; } private void readValues(ByteBuffer buffer, IFDEntry ifd) { if (ifd.type == FieldType.ASCII) { ifd.valueS = readSValue(buffer, ifd); } else if (ifd.type == FieldType.RATIONAL) { ifd.value = new int[ifd.count * 2]; for (int i = 0; i < ifd.count * 2; i++) ifd.value[i] = readIntValue(buffer, ifd); } else if (ifd.type == FieldType.FLOAT) { ifd.valueD = new double[ifd.count]; for (int i = 0; i < ifd.count; i++) ifd.valueD[i] = (double) buffer.getFloat(); } else if (ifd.type == FieldType.DOUBLE) { ifd.valueD = new double[ifd.count]; for (int i = 0; i < ifd.count; i++) ifd.valueD[i] = buffer.getDouble(); } else { ifd.value = new int[ifd.count]; for (int i = 0; i < ifd.count; i++) ifd.value[i] = readIntValue(buffer, ifd); } } private int readIntValue(ByteBuffer buffer, IFDEntry ifd) { switch (ifd.type.code) { case 1: case 2: return (int) buffer.get(); case 3: return readUShortValue(buffer); case 4: case 5: return buffer.getInt(); } return 0; } private int readUShortValue(ByteBuffer buffer) { return buffer.getShort() & 0xffff; } private String readSValue(ByteBuffer buffer, IFDEntry ifd) { byte[] dst = new byte[ifd.count]; buffer.get(dst); return new String(dst, StandardCharsets.UTF_8); } private void printBytes(PrintStream ps, String head, ByteBuffer buffer, int n) { ps.print(head + " == "); for (int i = 0; i < n; i++) { byte b = buffer.get(); int ub = (b < 0) ? b + 256 : b; ps.print(ub + "("); ps.write(b); ps.print(") "); } ps.println(); } // geotiff stuff private void parseGeoInfo() { IFDEntry keyDir = findTag(Tag.GeoKeyDirectoryTag); if (null == keyDir) return; int nkeys = keyDir.value[3]; if (debugReadGeoKey) System.out.println("parseGeoInfo nkeys = " + nkeys + " keyDir= " + keyDir); int pos = 4; for (int i = 0; i < nkeys; i++) { int id = keyDir.value[pos++]; int location = keyDir.value[pos++]; int vcount = keyDir.value[pos++]; int offset = keyDir.value[pos++]; GeoKey.Tag tag = GeoKey.Tag.getOrMake(id); GeoKey key = null; if (location == 0) { // simple case key = new GeoKey(id, offset); } else { // more than one, or non short value IFDEntry data = findTag(Tag.get(location)); if (data == null) { System.out.println("********ERROR parseGeoInfo: cant find Tag code = " + location); } else if (data.tag == Tag.GeoDoubleParamsTag) { // double params double[] dvalue = new double[vcount]; System.arraycopy(data.valueD, offset, dvalue, 0, vcount); key = new GeoKey(tag, dvalue); } else if (data.tag == Tag.GeoKeyDirectoryTag) { // int params int[] value = new int[vcount]; System.arraycopy(data.value, offset, value, 0, vcount); key = new GeoKey(tag, value); } else if (data.tag == Tag.GeoAsciiParamsTag) { // ascii params String value = data.valueS.substring(offset, offset + vcount); key = new GeoKey(tag, value); } } if (key != null) { keyDir.addGeoKey(key); if (debugReadGeoKey) System.out.println(" yyy add geokey=" + key); } } } /** * Write the geotiff Tag information to out. */ public void showInfo(PrintWriter out) { out.println("Geotiff file= " + filename); for (int i = 0; i < tags.size(); i++) { IFDEntry ifd = tags.get(i); out.println(i + " IFDEntry == " + ifd); } } /** * Write the geotiff Tag information to a String. */ public String showInfo() { StringWriter sw = new StringWriter(5000); showInfo(new PrintWriter(sw)); return sw.toString(); } /** @deprecated do not use */ @Deprecated public void compare(GeoTiff other, Formatter f) { CompareNetcdf2.compareLists(tags, other.getTags(), f); } // testing only ByteBuffer testReadData(int offset, int size) throws IOException { channel.position(offset); ByteBuffer buffer = ByteBuffer.allocate(size); buffer.order(byteOrder); assert size == channel.read(buffer); ((Buffer) buffer).flip(); return buffer; } }
package krati.cds.impl.array; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.util.List; import org.apache.log4j.Logger; import krati.cds.array.DataArray; import krati.cds.array.LongArray; import krati.cds.impl.array.basic.LongArrayMemoryImpl; import krati.cds.impl.array.basic.LongArrayRecoverableImpl; import krati.cds.impl.array.entry.Entry; import krati.cds.impl.array.entry.EntryFileWriter; import krati.cds.impl.array.entry.EntryPersistAdapter; import krati.cds.impl.array.entry.EntryValue; import krati.cds.impl.segment.AddressFormat; import krati.cds.impl.segment.Segment; import krati.cds.impl.segment.SegmentException; import krati.cds.impl.segment.SegmentManager; import krati.cds.impl.segment.SegmentOverflowException; /** * DataArrayImpl: Simple Persistent DataArray Implementation. * * This class is not thread-safe by design. It is expected that the conditions below hold within one JVM. * <pre> * 1. There is one and only one instance of DataArrayImpl for a given cacheDirectory. * 2. There is one and only one thread is calling setData methods at any given time. * </pre> * * It is expected that this class is used in the case of multiple readers and single writer. * * @author jwu * */ public class DataArrayImpl implements DataArray { private final static Logger _log = Logger.getLogger(DataArrayImpl.class); protected Segment _segment; // current segment to append protected boolean _canTriggerCompaction; // current segment can trigger compaction only once protected volatile LongArray _addressArray; protected volatile SegmentManager _segmentManager; protected DataArrayImplCompactor _compactor; protected final double _segmentCompactFactor; protected final double _segmentCompactTrigger; protected long _segmentCompactTriggerLowerPosition; protected long _segmentCompactTriggerUpperPosition; protected final int _offsetMask; protected final int _segmentMask; protected final int _segmentShift; private long _metaUpdateOnAppendPosition = Segment.dataStartPosition; /** * Constructs a DataArray with Segment Compact Trigger default to 0.1 and Segment Compact Factor default to 0.5. * * @param addressArray Array of addresses (longs) to positions of Segment. * @param segmentManager Segment manager for loading, creating, freeing, maintaining segments. * */ public DataArrayImpl(LongArrayRecoverableImpl addressArray, SegmentManager segmentManager) { this(addressArray, segmentManager, 0.1, 0.5); } /** * Constructs a DataArray. * * @param addressArray Array of addresses (longs) to positions of Segment. * @param segmentManager Segment manager for loading, creating, freeing, maintaining segments. * @param segmentCompactTrigger Percentage of segment capacity, which writes trigger compaction once per segment. * @param segmentCompactFactor Load factor below which a segment is eligible for compaction. Recommended value is 0.5. */ public DataArrayImpl(LongArrayRecoverableImpl addressArray, SegmentManager segmentManager, double segmentCompactTrigger, double segmentCompactFactor) { this._addressArray = addressArray; this._segmentManager = segmentManager; this._segmentCompactFactor = segmentCompactFactor; this._segmentCompactTrigger = segmentCompactTrigger; addressArray.getEntryManager().setEntryPersistListener(new SegmentPersistListener()); AddressFormat f = new AddressFormat(16); this._segmentShift = f.getSegmentShift(); this._segmentMask = f.getSegmentMask(); this._offsetMask = f.getOffsetMask(); this.init(); this._compactor = new DataArrayImplCompactor(this, getSegmentCompactFactor()); this._canTriggerCompaction = true; this.updateCompactTriggerBounds(); this._metaUpdateOnAppendPosition = Segment.dataStartPosition; } protected DataArrayImpl(LongArrayMemoryImpl memAddressArray, SegmentManager segmentManager, List<Segment> segTargetList) { this._addressArray = memAddressArray; this._segmentManager = segmentManager; this._segmentCompactFactor = 0; // No segment will be compacted. this._segmentCompactTrigger = 1; // No compaction will be triggered. AddressFormat f = new AddressFormat(16); this._segmentShift = f.getSegmentShift(); this._segmentMask = f.getSegmentMask(); this._offsetMask = f.getOffsetMask(); this.init(); this._compactor = null; this._canTriggerCompaction = false; this.updateCompactTriggerBounds(); this._metaUpdateOnAppendPosition = Segment.dataStartPosition; // Add current segment to segTargetList segTargetList.add(_segment); } protected long compact(Segment segSource, List<Segment> segTargetList, EntryFileWriter entryWriter) throws IOException { int segTargetCnt = 1; RandomAccessFile raf; Segment segTarget = null; if(segTargetList.size() > 0) { segTarget = segTargetList.get(segTargetList.size() - 1); } else { segTarget = getSegmentManager().nextSegment(); segTargetList.add(segTarget); } int segSourceId = segSource.getSegmentId(); int segTargetId = segTarget.getSegmentId(); // Get read channel raf = new RandomAccessFile(segSource.getSegmentFile(), "r"); FileChannel readChannel = raf.getChannel(); // Get write channel raf = new RandomAccessFile(segTarget.getSegmentFile(), "rw"); FileChannel writeChannel = raf.getChannel(); // Position write channel properly writeChannel.position(segTarget.getAppendPosition()); long sizeLimit = segTarget.getInitialSize(); try { long bytesTransferred = 0; int indexStart = getIndexStart(); long scn = entryWriter.getMinScn(); for(int index = indexStart, cnt = length(); index < cnt; index++) { long oldAddress = getAddress(index); int oldSegPos = (int)(oldAddress & _offsetMask); int oldSegInd = (int)((oldAddress >> _segmentShift) & _segmentMask); if (oldSegInd == segSourceId && oldSegPos >= Segment.dataStartPosition) { int length = segSource.readInt(oldSegPos); int byteCnt = 4 + length; long newSegPos = writeChannel.position(); long newAddress = (((long)segTargetId) << _segmentShift) | newSegPos; if(writeChannel.position() + byteCnt >= sizeLimit) { /* It should never require more than 2 segments. * If it does happen, some kind of data corruption may have occurred. * Should abort data transfer now and try compaction at another time. */ if (segTargetCnt >= 2) { throw new CompactionAbortedException(); } // Update segTarget append position writeChannel.force(true); segTarget.setAppendPosition(writeChannel.position()); segTarget.asReadOnly(); writeChannel.close(); String info = "transfer overflow: segment changed from " + segTarget.getSegmentId(); // Get new segTarget segTarget = getSegmentManager().nextSegment(); segTargetId = segTarget.getSegmentId(); segTargetList.add(segTarget); segTargetCnt++; info = info + " to " + segTarget.getSegmentId(); // Get new write channel raf = new RandomAccessFile(segTarget.getSegmentFile(), "rw"); writeChannel = raf.getChannel(); // Position write channel properly writeChannel.position(segTarget.getAppendPosition()); sizeLimit = segTarget.getInitialSize(); _log.info(info); } // Transfer byte from source to target readChannel.transferTo(oldSegPos, byteCnt, writeChannel); segTarget.incrLoadSize(byteCnt); bytesTransferred += byteCnt; // Update address try { setAddress(index, newAddress, 0); } catch(Exception e) { throw new IOException(e.getCause()); } // Log the original address into compactor entry file. entryWriter.write(index - indexStart, oldAddress, scn); } } // Update segTarget append position segTarget.setAppendPosition(writeChannel.position()); // Close read channel readChannel.close(); readChannel = null; // Close write channel writeChannel.force(true); writeChannel.close(); writeChannel = null; return bytesTransferred; } catch(IOException ioe) { // Update segTarget append position segTarget.setAppendPosition(writeChannel.position()); if(readChannel != null) readChannel.close(); if(writeChannel != null) writeChannel.close(); throw ioe; } } protected void catchup(int index, long addressUpdate, long scnUpdate, List<Segment> segTargetList) throws Exception { long address = getAddress(index); int segPos = (int)(address & _offsetMask); int segInd = (int)((address >> _segmentShift) & _segmentMask); for(Segment segTarget: segTargetList) { if (segInd == segTarget.getSegmentId() && segPos >= Segment.dataStartPosition) { segTarget.decrLoadSize(segTarget.readInt(segPos)); break; } } // Update address in the cloned memory array setAddress(index, addressUpdate, scnUpdate); } protected void wrap(LongArray memAddressArray, SegmentManager segmentManager) throws IOException { try { _segmentManager = segmentManager; ((LongArrayRecoverableImpl)_addressArray).wrap(memAddressArray); _log.info("wrapped array:" + " indexStart=" + memAddressArray.getIndexStart() + " length=" + memAddressArray.length()); } catch(Exception e) { _log.error("failed to wrap array:"+ " indexStart=" + memAddressArray.getIndexStart() + " length=" + memAddressArray.length()); if(e instanceof IOException) { throw (IOException)e; } else { throw new IOException(e); } } } protected void init() { try { _segment = _segmentManager.nextSegment(); } catch(IOException ioe) { _log.error(ioe.getMessage(), ioe); throw new SegmentException("Instantiation failed due to " + ioe.getMessage()); } } protected void updateCompactTriggerBounds() { long size = getCurrentSegment().getInitialSize(); long incr = (long)(size * 0.05); long compactTriggerLowerPosition = (long)(size * getSegmentCompactTrigger()); _segmentCompactTriggerLowerPosition = compactTriggerLowerPosition - incr; _segmentCompactTriggerUpperPosition = compactTriggerLowerPosition + incr; if(_segmentCompactTriggerLowerPosition < Segment.dataStartPosition) { _segmentCompactTriggerLowerPosition = Segment.dataStartPosition; } if(_segmentCompactTriggerUpperPosition > size) { _segmentCompactTriggerUpperPosition = size; } } protected long getAddress(int index) { return _addressArray.getData(index); } protected void setAddress(int index, long value, long scn) throws Exception { _addressArray.setData(index, value, scn); } protected LongArray getAddressArray() { return _addressArray; } protected double getSegmentCompactFactor() { return _segmentCompactFactor; } protected double getSegmentCompactTrigger() { return _segmentCompactTrigger; } protected SegmentManager getSegmentManager() { return _segmentManager; } protected Segment getCurrentSegment() { return _segment; } protected void decrOriginalSegmentLoad(int index) { try { long address = getAddress(index); int segPos = (int)(address & _offsetMask); int segInd = (int)((address >> _segmentShift) & _segmentMask); if (segPos >= Segment.dataStartPosition) { // get data segment Segment seg = _segmentManager.getSegment(segInd); // read data length if(seg != null) seg.decrLoadSize(seg.readInt(segPos)); } } catch(IOException e) {} } private void tryFlowControl() { Segment liveSegment = _segment; if(liveSegment == null) { return; } DataArrayImpl dataArrayCopy = _compactor.getDataArrayCopy(); if(dataArrayCopy == null) { return; } SegmentManager segManagerCopy = dataArrayCopy.getSegmentManager(); if(segManagerCopy == null) { return; } Segment compactSegment = segManagerCopy.getCurrentSegment(); if(compactSegment == null || compactSegment == liveSegment) { return; } /* * Slow down the writer for 0.2 milliseconds so that the compactor has a chance to catch up. */ if(compactSegment.getLoadSize() < liveSegment.getLoadSize()) { try { Thread.sleep(0, 200000); } catch(Exception e) {} } } @Override public int getDataLength(int index) { try { long address = getAddress(index); int segPos = (int)(address & _offsetMask); int segInd = (int)((address >> _segmentShift) & _segmentMask); // no data found if(segPos < Segment.dataStartPosition) return -1; // get data segment Segment seg = _segmentManager.getSegment(segInd); // read data length return seg.readInt(segPos); } catch(Exception e) { return -1; } } @Override public byte[] getData(int index) { try { long address = getAddress(index); int segPos = (int)(address & _offsetMask); int segInd = (int)((address >> _segmentShift) & _segmentMask); // no data found if(segPos < Segment.dataStartPosition) return null; // get data segment Segment seg = _segmentManager.getSegment(segInd); // read data length int len = seg.readInt(segPos); // read data into byte array byte[] data = new byte[len]; if (len > 0) { seg.read(segPos + 4, data); } return data; } catch(Exception e) { return null; } } @Override public int getData(int index, byte[] data) { return getData(index, data, 0); } @Override public int getData(int index, byte[] data, int offset) { try { long address = getAddress(index); int segPos = (int)(address & _offsetMask); int segInd = (int)((address >> _segmentShift) & _segmentMask); // no data found if(segPos < Segment.dataStartPosition) return -1; // get data segment Segment seg = _segmentManager.getSegment(segInd); // read data length int len = seg.readInt(segPos); // read data into byte array if (len > 0) { seg.read(segPos + 4, data, offset, len); } return len; } catch(Exception e) { return -1; } } @Override public int transferTo(int index, WritableByteChannel channel) { try { long address = getAddress(index); int segPos = (int)(address & _offsetMask); int segInd = (int)((address >> _segmentShift) & _segmentMask); // no data found if(segPos < Segment.dataStartPosition) return -1; // get data segment Segment seg = _segmentManager.getSegment(segInd); // read data length int len = seg.readInt(segPos); // transfer data to a writable channel if (len > 0) { seg.transferTo(segPos + 4, len, channel); } return len; } catch(Exception e) { return -1; } } @Override public void setData(int index, byte[] data, long scn) throws Exception { if(data == null) { setData(index, data, 0, 0, scn); } else { setData(index, data, 0, data.length, scn); } } @Override public void setData(int index, byte[] data, int offset, int length, long scn) throws Exception { decrOriginalSegmentLoad(index); // no data if (data == null) { setAddress(index, 0, scn); return; } if (offset > data.length || (offset + length) > data.length) { throw new ArrayIndexOutOfBoundsException(data.length); } while(true) { // get append position long pos = _segment.getAppendPosition(); try { // check append position is in range if ((pos >> _segmentShift) > 0) { throw new SegmentOverflowException(_segment); } // append data size _segment.appendInt(length); // append actual data if (length > 0) { _segment.append(data, offset, length); } // update addressArray long address = (((long)_segment.getSegmentId()) << _segmentShift) | pos; setAddress(index, address, scn); // update segment meta on first write if (pos >= _metaUpdateOnAppendPosition) { _segmentManager.updateMeta(); _metaUpdateOnAppendPosition = _segment.getInitialSize(); } // current segment can trigger compaction once and only once if (_canTriggerCompaction && pos > _segmentCompactTriggerLowerPosition && pos < _segmentCompactTriggerUpperPosition ) { if(!_compactor.isStarted()) { _log.info("Segment " + _segment.getSegmentId() + " triggered compaction"); // persist this data array and apply entry log files persist(); // disable auto-applying entry files if (_addressArray instanceof LongArrayRecoverableImpl) { ((LongArrayRecoverableImpl)_addressArray).getEntryManager().setAutoApplyEntries(false); } // start the compactor _compactor.start(); _canTriggerCompaction = false; } } // Notify the compactor of new address update if(_compactor.isStarted()) { _compactor.addressUpdated(index, address, scn); /* * Flow-control the writer and average-out write latency. * Give the compactor a chance to catch up with the writer. */ tryFlowControl(); } return; } catch(SegmentOverflowException soe) { _log.info("Segment " + _segment.getSegmentId() + " filled"); // update segment meta // _segmentManager.updateMeta(); // wait until compactor is done while(_compactor.isStarted()) { _log.info("wait for compactor"); Thread.sleep(100); } synchronized(this) // synchronize the code below and the compactor { // persist the current segment persist(); // enable auto-applying entry files if (_addressArray instanceof LongArrayRecoverableImpl) { ((LongArrayRecoverableImpl)_addressArray).getEntryManager().setAutoApplyEntries(true); } // get the next segment available for appending _metaUpdateOnAppendPosition = Segment.dataStartPosition; _segment = _segmentManager.nextSegment(_segment); _canTriggerCompaction = true; _log.info("Segment " + _segment.getSegmentId() + " live"); } } catch(Exception e) { // restore append position _segment.setAppendPosition(pos); // enable auto-applying entry files if (_addressArray instanceof LongArrayRecoverableImpl) { ((LongArrayRecoverableImpl)_addressArray).getEntryManager().setAutoApplyEntries(true); } throw e; } } } @Override public int getIndexStart() { return _addressArray.getIndexStart(); } @Override public boolean indexInRange(int index) { return _addressArray.indexInRange(index); } @Override public int length() { return _addressArray.length(); } @Override public long getHWMark() { return _addressArray.getHWMark(); } @Override public long getLWMark() { return _addressArray.getLWMark(); } @Override public void saveHWMark(long endOfPeriod) throws Exception { _addressArray.saveHWMark(endOfPeriod); } @Override public synchronized void sync() throws IOException { /* The "persist" must be synchronized with data array compactor because * the compactor runs in a separate thread and will re-write the address * array file at the end of compaction. */ /* CALLS ORDERED: * Need force _segment first and then persist _addressArray. * During recovery, the _addressArray can always point to addresses * which are valid though may not reflect the most recent address update. */ _segment.force(); _addressArray.sync(); _segmentManager.updateMeta(); } @Override public synchronized void persist() throws IOException { /* The "persist" must be synchronized with data array compactor because * the compactor runs in a separate thread and will re-write the address * array file at the end of compaction. */ /* CALLS ORDERED: * Need force _segment first and then persist _addressArray. * During recovery, the _addressArray can always point to addresses * which are valid though may not reflect the most recent address update. */ _segment.force(); _addressArray.persist(); _segmentManager.updateMeta(); } @Override public synchronized void clear() { _addressArray.clear(); _segmentManager.clear(); } private class SegmentPersistListener extends EntryPersistAdapter { public void priorPersisting(Entry<? extends EntryValue> e) throws IOException { if(_segment != null) { _segment.force(); } } public void afterPersisting(Entry<? extends EntryValue> e) throws IOException { if(_segmentManager != null) { _segmentManager.updateMeta(); } } } }
// RMG - Reaction Mechanism Generator // RMG Team (rmg_dev@mit.edu) // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. package jing.rxn; import jing.chem.*; import jing.chemUtil.Graph; import jing.chemUtil.Node; import java.util.*; import jing.param.*; import jing.rxnSys.Logger; import jing.rxnSys.SystemSnapshot; //## package jing::rxn // jing\rxn\TemplateReaction.java /** Reaction generated from templates. Immutable object. */ //## class TemplateReaction public class TemplateReaction extends Reaction { protected PDepNetwork pDepNetwork; protected ReactionTemplate reactionTemplate; // Constructors //## operation TemplateReaction(Structure,RateConstant,ReactionTemplate) private TemplateReaction(Structure p_structure, Kinetics[] p_kinetics, ReactionTemplate p_template) { //#[ operation TemplateReaction(Structure,RateConstant,ReactionTemplate) structure = p_structure; kinetics = p_kinetics; reactionTemplate = p_template; if (kinetics != null) kineticsFromPrimaryKineticLibrary = p_kinetics[0].isFromPrimaryKineticLibrary(); } public TemplateReaction() { } //## operation calculatePDepRate(Temperature) /* public double calculatePDepRate(Temperature p_temperature) { //#[ operation calculatePDepRate(Temperature) PDepNetwork pdn = getPDepNetwork(); if (pdn != null) { Iterator iter = pdn.getPDepNetReactionList(); while (iter.hasNext()) { PDepNetReaction pdnr = (PDepNetReaction)iter.next(); if (pdnr.getStructure().equals(getStructure())) { double temp = pdnr.getTemperature(); if (temp != p_temperature.getK()) { System.out.println("Different temperature used!"); System.exit(0); } //System.out.println("for reaction " + toString() + "\t using p dep rate:" + String.valueOf(pdnr.getRate())); return pdnr.getRate(); } } iter = pdn.getPDepNonincludedReactionList(); while (iter.hasNext()) { PDepNetReaction pdnr = (PDepNetReaction)iter.next(); if (pdnr.getStructure().equals(getStructure())) { double temp = pdnr.getTemperature(); if (temp != p_temperature.getK()) { System.out.println("Different temperature used!"); System.exit(0); } //System.out.println("for reaction " + toString() + "\t using p dep rate:" + String.valueOf(pdnr.getRate())); return pdnr.getRate(); } } } return calculateRate(p_temperature); //#] }*/ // ## operation calculatePDepRate(Temperature) public double calculateTotalPDepRate(Temperature p_temperature, Pressure p_pressure) { //#[ operation calculatePDepRate(Temperature) PDepNetwork pdn = getPDepNetwork(); if (pdn != null) { ListIterator iter = pdn.getNetReactions().listIterator(); while (iter.hasNext()) { PDepReaction pdnr = (PDepReaction) iter.next(); if (pdnr.getStructure().equals(getStructure())) return pdnr.calculateRate(p_temperature, p_pressure); } iter = pdn.getNonincludedReactions().listIterator(); while (iter.hasNext()) { PDepReaction pdnr = (PDepReaction) iter.next(); if (pdnr.getStructure().equals(getStructure())) return pdnr.calculateRate(p_temperature, p_pressure); } } return calculateTotalRate(p_temperature); // } //## operation generateReverseForBackwardReaction() private TemplateReaction generateReverseForBackwardReaction(Structure fs, Structure fsSp) { //#[ operation generateReverseForBackwardReaction() // we need to only generate reverse reaction for backward reaction, so that we wont be stuck into a self loop. if (!this.isBackward()) { return null; } ReactionTemplate fRT = getReactionTemplate(); ReactionTemplate rRT = null; if (fRT.isForward()) { return null; } else if (fRT.isNeutral()) { rRT = fRT; } else if (fRT.isBackward()) { rRT = fRT.getReverseReactionTemplate(); } else { throw new InvalidReactionTemplateDirectionException(); //Structure fs = getStructure(); } LinkedList freactant = fs.getReactantList(); LinkedList fproduct = fs.getProductList(); Structure rs = new Structure(fproduct, freactant, -1 * this.getDirection()); Structure rsSp = new Structure(fsSp.products, fsSp.reactants, -1 * this.getDirection()); // If it's in the reverse ReactionTemplate.reactionDictionaryByStructure then just return that one. TemplateReaction rr = rRT.getReactionFromStructure(rsSp); if (rr != null) { rr.setReverseReaction(this); return rr; } int rNum = fproduct.size(); Kinetics[] k = rRT.findReverseRateConstant(rs); if (k == null && rRT.name.equals("R_Recombination")) { ChemGraph cg = ((ChemGraph) fproduct.get(0)); Graph g = cg.getGraph(); Node n = (Node) g.getCentralNodeAt(2); if (n == null) { cg = ((ChemGraph) fproduct.get(1)); g = cg.getGraph(); n = (Node) g.getCentralNodeAt(2); } g.clearCentralNode(); g.setCentralNode(1, n); k = rRT.findRateConstant(rs); } else if (k == null && rRT.name.equals("H_Abstraction")) { ChemGraph cg1 = ((ChemGraph) fproduct.get(0)); Graph g1 = cg1.getGraph(); Node n3 = (Node) g1.getCentralNodeAt(3); if (n3 == null) { cg1 = ((ChemGraph) fproduct.get(1)); g1 = cg1.getGraph(); n3 = (Node) g1.getCentralNodeAt(3); Node n2 = (Node) g1.getCentralNodeAt(2); g1.clearCentralNode(); g1.setCentralNode(1, n3); g1.setCentralNode(2, n2); ChemGraph cg2 = ((ChemGraph) fproduct.get(0)); Graph g2 = cg2.getGraph(); Node n1 = (Node) g2.getCentralNodeAt(1); g2.clearCentralNode(); g2.setCentralNode(3, n1); } else { Node n2 = (Node) g1.getCentralNodeAt(2); g1.clearCentralNode(); g1.setCentralNode(1, n3); g1.setCentralNode(2, n2); ChemGraph cg2 = ((ChemGraph) fproduct.get(1)); Graph g2 = cg2.getGraph(); Node n1 = (Node) g2.getCentralNodeAt(1); g2.clearCentralNode(); g2.setCentralNode(3, n1); } k = rRT.findRateConstant(rs); } /* * Added by MRH on 27-Aug-2009 * This hard-coding is necessary for rxn family templates * that are labeled "thermo_consistence". * * After the chemgraphs are mutated, the central nodes for * the products are not correct (see example below). These * hard-coded portions are necessary for RMG to find Kinetics * for the structure. * * Example: CH4 + H * CH4 * 1 *1 C 0 {2,S} {3,S} {4,S} {5,S} * 2 *2 H 0 {1,S} * 3 H 0 {1,S} * 4 H 0 {1,S} * 5 H 0 {1,S} * * H * 1 *3 H 1 * * After RMG has "reactChemGraph" and "mutate" the chemgraphs * of the reactants, the products would look as such: * * prod1 * 1 *1 C 1 {2,S} {3,S} {4,S} * 2 H 0 {1,S} * 3 H 0 {1,S} * 4 H 0 {1,S} * * prod2 * 1 *3 H 0 {2,S} * 2 *2 H 0 {1,S} * * Assuming the reaction as written (CH4+H=CH3+H2) is * endothermic at 298K, RMG will label this structure * as direction=-1 (backward). When attempting to find * Kinetics for the backward reaction, RMG will try * to match the prod1 graph against the generic graphs * X_H and Y_rad_birad. It cannot match Y_rad_birad * (because there is no *3 node) and it cannot match * X_H (because there is no *2 node). Thus, a "null" * Kinetics will be returned from the findReverseRateConstant * call. We then relabel the central nodes on prod1 * and prod2 and attempt to get Kinetics for this * structure. * * I am adding the following bit of code to work with the * new reaction family Aaron Vandeputte is adding to * RMG: "". * */ else if (k == null && rRT.name.equals("intra_substitutionS_isomerization")) { ChemGraph cg1 = ((ChemGraph) fproduct.get(0)); Graph g1 = cg1.getGraph(); Node n1 = (Node) g1.getCentralNodeAt(1); Node n2 = (Node) g1.getCentralNodeAt(2); Node n3 = (Node) g1.getCentralNodeAt(3); Node n4 = (Node) g1.getCentralNodeAt(4); Node n5 = (Node) g1.getCentralNodeAt(5); Node n6 = (Node) g1.getCentralNodeAt(6); Node n7 = (Node) g1.getCentralNodeAt(7); g1.clearCentralNode(); g1.setCentralNode(1, n1); g1.setCentralNode(2, n3); g1.setCentralNode(3, n2); if (n7 != null) { g1.setCentralNode(7, n4); g1.setCentralNode(6, n5); g1.setCentralNode(5, n6); g1.setCentralNode(4, n7); } else if (n6 != null) { g1.setCentralNode(6, n4); g1.setCentralNode(5, n5); g1.setCentralNode(4, n6); } else if (n5 != null) { g1.setCentralNode(5, n4); g1.setCentralNode(4, n5); } else if (n4 != null) g1.setCentralNode(4, n4); k = rRT.findRateConstant(rs); } // Adding another elseif statement for Aaron Vandeputte rxn family // RMG expects to find *1 and *2 in the same ChemGraph (for this rxn family) // but will instead find *1 and *3 in the same ChemGraph (if we've reached this far) // Need to switch *2 and *3 else if (k == null && (rRT.name.equals("substitutionS") || rRT.name.equals("Substitution_O"))) { ChemGraph cg1 = ((ChemGraph) fproduct.get(0)); ChemGraph cg2 = ((ChemGraph) fproduct.get(1)); Graph g1 = cg1.getGraph(); Graph g2 = cg2.getGraph(); Node n3 = (Node) g1.getCentralNodeAt(3); if (n3 == null) { // Switch the identities of cg1/g1 and cg2/g2 cg1 = ((ChemGraph) fproduct.get(1)); g1 = cg1.getGraph(); cg2 = ((ChemGraph) fproduct.get(0)); g2 = cg2.getGraph(); n3 = (Node) g1.getCentralNodeAt(3); } Node n1 = (Node) g1.getCentralNodeAt(1); g1.clearCentralNode(); g1.setCentralNode(2, n3); g1.setCentralNode(1, n1); Node n2 = (Node) g2.getCentralNodeAt(2); g2.clearCentralNode(); g2.setCentralNode(3, n2); k = rRT.findRateConstant(rs); } else if (k == null && rRT.name.equals("intra_H_migration")) { ChemGraph cg = ((ChemGraph) fproduct.get(0)); rr = rRT.calculateForwardRateConstant(cg, rs); if (!rr.isForward()) { String err = "Backward:" + structure.toString() + String.valueOf(structure.calculateKeq(new Temperature(298, "K"))) + '\n'; err = err + "Forward:" + rr.structure.toString() + String.valueOf(rr.structure.calculateKeq(new Temperature(298, "K"))); throw new InvalidReactionDirectionException(err); } rr.setReverseReaction(this); rRT.addReaction(rr); return rr; } if (k == null) { Logger.error("Couldn't find the rate constant for reaction: " + rs.toChemkinString(true) + " with " + rRT.name); //System.exit(0); return null; } rr = new TemplateReaction(rsSp, k, rRT); if (!rr.isForward()) { String err = "Backward:" + structure.toString() + String.valueOf(structure.calculateKeq(new Temperature(298, "K"))) + '\n'; err = err + "Forward:" + rr.structure.toString() + String.valueOf(rr.structure.calculateKeq(new Temperature(298, "K"))); throw new InvalidReactionDirectionException(err); } rr.setReverseReaction(this); rRT.addReaction(rr); return rr; // } /** Requires: Effects: return the type of itsReactionTemplate as the type of this reaction. Modifies: */ //## operation getType() public String getType() { //#[ operation getType() return reactionTemplate.getName(); // } public static TemplateReaction makeTemplateReaction(Structure p_structureSp, Kinetics[] p_kinetics, ReactionTemplate p_template, Structure p_structure) { double PT = System.currentTimeMillis(); // Look for pre-existing reaction in Template's reactionDictionaryByStructure. TemplateReaction reaction = p_template.getReactionFromStructure(p_structureSp); Global.getReacFromStruc = Global.getReacFromStruc + (System.currentTimeMillis() - PT) / 1000 / 60; if (reaction == null){ // Create a new reaction. reaction = new TemplateReaction(p_structureSp, p_kinetics, p_template); if (reaction.isBackward()) { Logger.info("Created new reverse " + p_template.getName() + " reaction: " + reaction.toString()); TemplateReaction reverse = reaction.generateReverseForBackwardReaction(p_structure, p_structureSp); if (reverse == null) return null; reaction.setReverseReaction(reverse); } else { Logger.info("Created new forwards " + p_template.getName() + " reaction: " + reaction.toString()); ReactionTemplate fRT = reaction.getReactionTemplate(); ReactionTemplate rRT = null; if (fRT.isNeutral()) rRT = fRT; else rRT = fRT.getReverseReactionTemplate(); if (rRT != null) { TemplateReaction reverse = new TemplateReaction(p_structureSp.generateReverseStructure(), p_kinetics, rRT); reaction.setReverseReaction(reverse); reverse.setReverseReaction(reaction); rRT.addReaction(reverse); } } p_template.addReaction(reaction); if (!reaction.repOk()) { throw new InvalidTemplateReactionException(); } } Global.makeTR += (System.currentTimeMillis() - PT) / 1000 / 60; return reaction; } //## operation repOk() public boolean repOk() { //#[ operation repOk() return (super.repOk() && reactionTemplate.repOk()); // } //## operation toString() public String toString(Temperature p_temperature) { //#[ operation toString() String totalString = ""; String s = getStructure().toString() + '\t'; Kinetics[] k = getKinetics(); for (int i=0; i<k.length; i++) { totalString += s + k[i].toChemkinString(calculateHrxn(p_temperature), p_temperature, false); if (k.length > 1) totalString += "\n"; } return totalString; // } /* * MRH 24MAR2010: * Commented out toStringWithReverseReaction method as it is never called */ //## operation toStringWithReveseReaction() // public String toStringWithReveseReaction(Temperature p_temperature) { // //#[ operation toStringWithReveseReaction() // TemplateReaction rr = (TemplateReaction)getReverseReaction(); // if (rr == null) return getStructure().toChemkinString(false).toString() + '\t' + getReactionTemplate().getName() + '\t' + getKinetics().toChemkinString(calculateHrxn(p_temperature), p_temperature, true); // else { // TemplateReaction temp = null; // if (isForward()) temp = this; // else if (isBackward()) temp = rr; // else throw new InvalidReactionDirectionException(); // return temp.getStructure().toChemkinString(false).toString() + '\t' + temp.getReactionTemplate().getName() + '\t' + temp.getKinetics().toChemkinString(calculateHrxn(p_temperature), p_temperature, true); // // public PDepNetwork getPDepNetwork() { return pDepNetwork; } public ReactionTemplate getReactionTemplate() { return reactionTemplate; } }
package de.huberlin.wbi.hiway.app.am; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import de.huberlin.wbi.cuneiform.core.semanticmodel.ForeignLambdaExpr; import de.huberlin.wbi.cuneiform.core.semanticmodel.JsonReportEntry; import de.huberlin.wbi.hiway.app.HiWayConfiguration; import de.huberlin.wbi.hiway.common.Data; import de.huberlin.wbi.hiway.common.TaskInstance; import de.huberlin.wbi.hiway.common.WorkflowStructureUnknownException; public class GalaxyApplicationMaster extends HiWay { public static class GalaxyParam { private final String name; private String defaultValue; private Map<String, String> mappings; public GalaxyParam(String name) { this.name = name; mappings = new HashMap<>(); } public void addMapping(String from, String to) { mappings.put(from, to); } public boolean hasMapping(String from) { String to = mappings.get(from); return to != null && to.length() > 0; } public String getMapping(String from) { return mappings.get(from); } public Map<String, String> getMappings() { return mappings; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; mappings.put("null", defaultValue); } public boolean hasDefaultValue() { return defaultValue != null && defaultValue.length() > 0; } public String getDefaultValue() { return defaultValue; } public String getName() { return name; } } public static class GalaxyTool { private final String name; private String template; private Map<String, GalaxyParam> params; private Map<String, Set<GalaxyDataType>> dataTypes; // private Map<String, Set<GalaxyDataType>> outputTypes; public GalaxyTool(String name) { this.name = name; params = new HashMap<>(); dataTypes = new HashMap<>(); // outputTypes = new HashMap<>(); } @Override public String toString() { return getName(); } @Override public int hashCode() { return getName().hashCode(); } public String getName() { return name; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } public void addParam(GalaxyParam param) { params.put(param.getName(), param); } public void addDataTypes(String inputName, String[] typeNames) { Set<GalaxyDataType> newDataTypes = new HashSet<>(); for (String typeName : typeNames) newDataTypes.add(galaxyDataTypes.get(typeName)); dataTypes.put(inputName, newDataTypes); } // public void addOutputTypes(String outputName, String[] typeNames) { // Set<GalaxyDataType> dataTypes = new HashSet<>(); // for (String typeName : typeNames) // dataTypes.add(galaxyDataTypes.get(typeName)); // outputTypes.put(outputName, dataTypes); public void addDataTypes(String outputName, Set<GalaxyDataType> newDataTypes) { dataTypes.put(outputName, newDataTypes); } // public boolean hasDefaultParameter(String paramName) { // return defaultParams.containsKey(paramName); // public boolean hasInputTypes(String inputName) { // return inputTypes.containsKey(inputName); // public boolean hasOutputTypes(String outputName) { // return outputTypes.containsKey(outputName); // public String getDefaultParameter(String paramName) { // return defaultParams.get(paramName); public Set<GalaxyDataType> getDataTypes(String inputName) { return dataTypes.get(inputName); } public Map<String, Set<GalaxyDataType>> getDataTypes() { return dataTypes; } // public Set<GalaxyDataType> getOutputTypes(String outputName) { // return outputTypes.get(outputName); public boolean hasParam(String name) { return params.containsKey(name); } public GalaxyParam getParam(String name) { return params.get(name); } public Map<String, GalaxyParam> getParams() { return params; } } public static class GalaxyDataType { private final String name; private String extension; private GalaxyDataType parent; private Map<String, String> metadata; public GalaxyDataType(String name) { this.name = name; metadata = new HashMap<>(); } public GalaxyDataType getParent() { return parent; } public boolean hasParent() { return parent != null; } public String getName() { return name; } public void setParent(GalaxyDataType parent) { this.parent = parent; } public String getExtension() { return extension; } public boolean hasExtension() { return extension != null; } public void setExtension(String extension) { this.extension = extension; } public void addMetadata(String name, String value) { metadata.put(name, value); } // public boolean hasMetadata(String name) { // if (metadata.containsKey(name)) { // return true; // } else if (parent != null) { // return parent.hasMetadata(name); // return false; // public String getMetadata(String name) { // if (metadata.containsKey(name)) { // return metadata.get(name); // } else if (parent != null) { // return parent.getMetadata(name); // return null; public Map<String, String> getMetadata() { Map<String, String> allMetadata = new HashMap<>(); if (parent != null) { allMetadata.putAll(parent.getMetadata()); } allMetadata.putAll(metadata); return allMetadata; } } public static class GalaxyTaskInstance extends TaskInstance { // private Map<String, Data> nameToData; private GalaxyTool galaxyTool; private StringBuilder pickleScript; public GalaxyTaskInstance(long id, String taskName, GalaxyTool galaxyTool) { // super(id, getRunId(), taskName, Math.abs(taskName.hashCode()), ForeignLambdaExpr.LANGID_BASH); super(id, UUID.randomUUID(), taskName, Math.abs(taskName.hashCode()), ForeignLambdaExpr.LANGID_BASH); // nameToData = new HashMap<>(); this.galaxyTool = galaxyTool; pickleScript = new StringBuilder("import cPickle as pickle\ntool_state = {"); for (GalaxyParam param : galaxyTool.getParams().values()) { String defaultValue = param.getDefaultValue(); if (param.hasDefaultValue()) { addParameter(param.getName(), defaultValue); pickleScript.append(", "); } } } // public void addInputData(String name, Data data) { // nameToData.put(name, data); // super.addInputData(data); // public void addOutputData(String name, Data data) { // nameToData.put(name, data); // super.addOutputData(data); // public Data getDataByName(String name) { // return nameToData.get(name); public GalaxyTool getGalaxyTool() { return galaxyTool; } public void addToolState(String toolState) { pickleScript.append(toolState.replaceAll("^\\{", "").replaceAll("\\}$", "").replaceAll("null", "\"null\"").replaceAll("\\\\", "").replaceAll("\"\"", "\"").replaceAll("\"\\{", "\\{").replaceAll("\\}\"", "\\}").replaceAll("\"\\[", "\\[").replaceAll("\\]\"", "\\]").replaceAll("\\{\"__class__\":[^\"]*\"UnvalidatedValue\",[^\"]*\"value\":[^\"](\"[^\"]*\")\\}", "$1")); } public void addFileName(String name, String value) { System.out.print(galaxyTool.getName() + " "); System.out.print(name + " "); System.out.print(value + " "); System.out.println(); pickleScript.append(", "); addParameter(name, value); for (GalaxyDataType type : galaxyTool.getDataTypes(name)) { Map <String, String> metadata = type.getMetadata(); pickleScript.append(", \"" + name + "_metadata\": {"); for (Iterator<String> it = metadata.keySet().iterator(); it.hasNext(); ) { String metadataName = it.next(); addParameter(metadataName, metadata.get(metadataName)); if (it.hasNext()) { pickleScript.append(", "); } } pickleScript.append("}"); } } private void addParameter(String name, String value) { // if (galaxyTool.hasParam(name)) { // GalaxyParam param = galaxyTool.getParam(name); // if (param.hasMapping(value)) // value = param.getMapping(value); pickleScript.append("\"" + name + "\": \"" + value + "\""); } public void buildPickleScript() { pickleScript.append("}\npickle.dump(tool_state, open(\"" + id + ".p\", \"wb\"))\n"); String pickleString = pickleScript.toString(); for (GalaxyParam param : galaxyTool.getParams().values()) { Map<String, String> mappings = param.getMappings(); for (String from : mappings.keySet()) { String to = mappings.get(from); pickleString = pickleString.replaceAll("\"" + param.getName() + "\": \"?" + from + "\"?", "\"" + param.getName() + "\": \"" + to + "\""); } } try (BufferedWriter scriptWriter = new BufferedWriter(new FileWriter("params_" + id + ".py"))) { scriptWriter.write(pickleString); } catch (IOException e) { e.printStackTrace(); } } public void buildTemplate() { try (BufferedWriter scriptWriter = new BufferedWriter(new FileWriter("template_" + id + ".tmpl"))) { scriptWriter.write(getGalaxyTool().getTemplate()); } catch (IOException e) { e.printStackTrace(); } } } private static final Log log = LogFactory.getLog(GalaxyApplicationMaster.class); // public static void main(String[] args) { // HiWay.loop(new GalaxyApplicationMaster(), args); @Override public boolean init(String[] args) throws ParseException { super.init(args); galaxyTools = new HashMap<>(); // pythonPath = hiWayConf.get(HiWayConfiguration.HIWAY_GALAXY_PYTHONPATH); if (!processDataTypeDir(new File(hiWayConf.get(HiWayConfiguration.HIWAY_GALAXY_DATATYPES)))) return false; DocumentBuilder builder; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); for (String toolDir : hiWayConf.get(HiWayConfiguration.HIWAY_GALAXY_TOOLS).split(",")) { if (!processToolDir(new File(toolDir.trim()), builder)) return false; } } catch (ParserConfigurationException | FactoryConfigurationError e) { e.printStackTrace(); return false; } return true; } public static void main(String[] args) { processDataTypeDir(new File("galaxy-galaxy-dist-5123ed7f1603/lib/galaxy/datatypes")); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); galaxyTools = new HashMap<>(); processToolDir(new File("galaxy-galaxy-dist-5123ed7f1603/tools"), builder); } catch (ParserConfigurationException | FactoryConfigurationError e) { e.printStackTrace(); } // parseWorkflow("galaxy101.ga"); parseWorkflow("RNAseq.ga"); } private static boolean processDataTypeDir(File dir) { galaxyDataTypes = new HashMap<>(); for (File file : dir.listFiles()) { if (file.getName().endsWith(".py")) { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; String[] splitLine; GalaxyDataType dataType = null; while ((line = reader.readLine()) != null) { if (line.startsWith("class")) { line = line.replace("class", "").replaceAll(" ", "").replace(":", "").replace(")", ""); splitLine = line.split("\\("); if (splitLine.length == 1) continue; String name = splitLine[0]; dataType = addAndGetDataType(name); String parentNames = splitLine[1].substring(splitLine[1].lastIndexOf(".") + 1); String[] splitSplit = parentNames.split(","); GalaxyDataType parentType = addAndGetDataType(splitSplit[0]); dataType.setParent(parentType); } else if (line.startsWith(" file_ext = ")) { dataType.setExtension(line.replace(" file_ext = ", "").replaceAll("[\\\"']", "")); } else if (line.startsWith(" MetadataElement(")) { line = line.replace("MetadataElement(", "").replace(")", "").trim(); splitLine = line.split(", "); String name = null, value = null; for (String split : splitLine) { String[] splitSplit = split.split("="); switch (splitSplit[0]) { case "name": name = splitSplit[1].replaceAll("[\\\"']", ""); break; case "default": value = splitSplit[1].replaceAll("[\\\"']", ""); break; case "no_value": if (value == null) value = splitSplit[1].replaceAll("[\\\"']", ""); } } if ((name != null) && (value != null)) { dataType.addMetadata(name, value); } } } } catch (IOException e) { e.printStackTrace(); return false; } } } Set<String> delete = new HashSet<>(); for (String name : galaxyDataTypes.keySet()) if (!isDataType(galaxyDataTypes.get(name))) delete.add(name); galaxyDataTypes.keySet().removeAll(delete); Map<String, GalaxyDataType> add = new HashMap<>(); for (String name : galaxyDataTypes.keySet()) { GalaxyDataType dataType = galaxyDataTypes.get(name); add.put(name.toLowerCase(), dataType); if (dataType.hasExtension()) { String extension = dataType.getExtension(); add.put(extension, dataType); add.put(extension.toLowerCase(), dataType); } } galaxyDataTypes.putAll(add); // for (GalaxyDataType dataType : galaxyDataTypes.values()) // System.out.println(dataType.getExtension() + ": " + dataType.getName() + " --> " + dataType.getParent().getName()); return true; } private static GalaxyDataType addAndGetDataType(String name) { if (!galaxyDataTypes.containsKey(name)) { galaxyDataTypes.put(name, new GalaxyDataType(name)); } return galaxyDataTypes.get(name); } private static boolean isDataType(GalaxyDataType dataType) { if (dataType.getName().equals("Data")) return true; GalaxyDataType parent = dataType.getParent(); if (parent != null) return isDataType(parent); return false; } private static boolean processToolDir(File dir, DocumentBuilder builder) { for (File file : dir.listFiles()) { if (file.isDirectory()) { processToolDir(file, builder); } else if (file.getName().endsWith(".xml")) { try { Document doc = builder.parse(file); Element rootEl = doc.getDocumentElement(); if (rootEl.getNodeName() == "tool") { String toolName = rootEl.getAttribute("name"); GalaxyTool tool = new GalaxyTool(toolName); Element commandEl = (Element) rootEl.getElementsByTagName("command").item(0); if (commandEl != null) { String command = commandEl.getChildNodes().item(0).getNodeValue().trim(); String script = command.split(" ")[0]; String interpreter = commandEl.getAttribute("interpreter"); if (interpreter.length() > 0) command = interpreter + " " + command; command = command.replaceAll("\\.metadata\\.", "_metadata.").replace(script, dir.getCanonicalPath() + "/" + script); command = command.replace("D:\\Documents\\Workspace2\\hiway\\hiway-core\\galaxy-galaxy-dist-5123ed7f1603\\tools/", "/home/hiway/software/shed_tools/toolshed.g2.bx.psu.edu/repos/devteam/join/de21bdbb8d28/join/"); command = command.replace("D:\\Documents\\Workspace2\\hiway\\hiway-core\\galaxy-galaxy-dist-5123ed7f1603\\tools\\", "/home/hiway/software/galaxy/tools/"); tool.setTemplate(command); } Element inputsEl = (Element) rootEl.getElementsByTagName("inputs").item(0); if (inputsEl != null) { NodeList paramNds = inputsEl.getElementsByTagName("param"); for (int i = 0; i < paramNds.getLength(); i++) { Element paramEl = (Element) paramNds.item(i); String type = paramEl.getAttribute("type"); String paramName = paramEl.getAttribute("name"); GalaxyParam param = new GalaxyParam(paramName); tool.addParam(param); switch (type) { case "data": String format = paramEl.getAttribute("format"); String[] splitFormat = format.split(","); tool.addDataTypes(paramName, splitFormat); break; case "boolean": String trueValue = paramEl.getAttribute("truevalue"); param.addMapping("True", trueValue); String falseValue = paramEl.getAttribute("falsevalue"); param.addMapping("False", falseValue); case "select": param.setDefaultValue("None"); default: String defaultValue = paramEl.getAttribute("value"); if (defaultValue != null && defaultValue.length() > 0) param.setDefaultValue(defaultValue); } } } Element outputsEl = (Element) rootEl.getElementsByTagName("outputs").item(0); if (outputsEl != null) { NodeList dataNds = outputsEl.getElementsByTagName("data"); for (int i = 0; i < dataNds.getLength(); i++) { Element dataEl = (Element) dataNds.item(i); String outputName = dataEl.getAttribute("name"); String format = dataEl.getAttribute("format"); if (format.equals("input")) { String metadata_source = dataEl.getAttribute("metadata_source"); if (metadata_source != null && metadata_source.length() > 0) { tool.addDataTypes(outputName, tool.getDataTypes(metadata_source)); } else { tool.addDataTypes(outputName, tool.getDataTypes().values().iterator().next()); } } else { String[] splitFormat = format.split(","); tool.addDataTypes(outputName, splitFormat); } } } if (tool.getTemplate() != null) { // System.out.println(file + ":" + tool.getName() /* + " " + tool.getCommand() */); galaxyTools.put(tool.getName(), tool); } } } catch (SAXException | IOException e) { e.printStackTrace(); return false; } } } return true; } // private String pythonPath; // private static String path; private static Map<String, GalaxyTool> galaxyTools; private static Map<String, GalaxyDataType> galaxyDataTypes; public GalaxyApplicationMaster() { super(); // path = "$PATH"; } @Override public void parseWorkflow() { } public static void parseWorkflow(String _fileName) { Map<String, Data> files = new HashMap<>(); // log.info("Parsing Galaxy workflow " + workflowFile); Map<Long, GalaxyTaskInstance> tasks = new HashMap<>(); // try (BufferedReader reader = new BufferedReader(new FileReader(workflowFile.getLocalPath()))) { try (BufferedReader reader = new BufferedReader(new FileReader(_fileName))) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } JSONObject workflow = new JSONObject(sb.toString()); JSONObject steps = workflow.getJSONObject("steps"); // (1) Parse Nodes for (int i = 0; i < steps.length(); i++) { JSONObject step = steps.getJSONObject(Integer.toString(i)); long id = step.getLong("id"); String type = step.getString("type"); if (type.equals("data_input")) { JSONArray inputs = step.getJSONArray("inputs"); for (int j = 0; j < inputs.length(); j++) { JSONObject input = inputs.getJSONObject(j); String name = input.getString("name"); String fileName = name; String idName = id + "_output"; Data data = new Data(fileName); data.setInput(true); files.put(idName, data); } } else if (type.equals("tool")) { String name = step.getString("name"); GalaxyTool tool = galaxyTools.get(name); if (tool == null) { log.error("Tool " + name + " could not be located in local Galaxy installation."); // onError(new RuntimeException()); } GalaxyTaskInstance task = new GalaxyTaskInstance(id, name, tool); tasks.put(id, task); Map<String, String> renameOutputs = new HashMap<>(); Set<String> hideOutputs = new HashSet<>(); if (step.has("post_job_actions")) { JSONObject post_job_actions = step.getJSONObject("post_job_actions"); for (Iterator<?> it = post_job_actions.keys(); it.hasNext();) { JSONObject post_job_action = post_job_actions.getJSONObject((String) it.next()); String action_type = post_job_action.getString("action_type"); if (action_type.equals("RenameDatasetAction")) { String output_name = post_job_action.getString("output_name"); JSONObject action_arguments = post_job_action.getJSONObject("action_arguments"); String newname = action_arguments.getString("newname"); renameOutputs.put(output_name, newname); } else if (action_type.equals("HideDatasetAction")) { String output_name = post_job_action.getString("output_name"); hideOutputs.add(output_name); } } } task.addToolState(step.getString("tool_state")); JSONArray outputs = step.getJSONArray("outputs"); List<String> outputFiles = new LinkedList<>(); for (int j = 0; j < outputs.length(); j++) { JSONObject output = outputs.getJSONObject(j); String outputName = output.getString("name"); Set<GalaxyDataType> outputTypes = tool.getDataTypes(outputName); String fileName = id + "_" + outputName; for (GalaxyDataType outputType : outputTypes) if (outputType.hasExtension()) fileName = fileName + "." + outputType.getExtension(); if (renameOutputs.containsKey(outputName)) fileName = renameOutputs.get(outputName); String idName = id + "_" + outputName; Data data = new Data(fileName); if (!hideOutputs.contains(outputName)) { data.setOutput(true); } files.put(idName, data); task.addOutputData(data); task.addFileName(outputName, data.getLocalPath()); outputFiles.add(fileName); } task.getReport().add( new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(), task.getLanguageLabel(), task.getId(), null, JsonReportEntry.KEY_INVOC_OUTPUT, new JSONObject().put("output", outputFiles))); } } // (2) Parse Edges and determine command for (int i = 0; i < steps.length(); i++) { JSONObject step = steps.getJSONObject(Integer.toString(i)); long id = step.getLong("id"); String type = step.getString("type"); if (type.equals("tool")) { GalaxyTaskInstance task = tasks.get(id); JSONObject input_connections = step.getJSONObject("input_connections"); for (Iterator<?> it = input_connections.keys(); it.hasNext();) { String input_connection_key = (String) it.next(); JSONObject input_connection = input_connections.getJSONObject(input_connection_key); long parentId = input_connection.getLong("id"); String idName = parentId + "_" + input_connection.getString("output_name"); TaskInstance parentTask = tasks.get(parentId); if (parentTask != null) { task.addParentTask(parentTask); parentTask.addChildTask(task); } task.addInputData(files.get(idName)); task.addFileName(input_connection_key, files.get(idName).getLocalPath()); continue; } // (a) Build pickle python script task.buildPickleScript(); task.buildTemplate(); /* JSONObject tool_state = new JSONObject(tool_state_s); Map<String, String> params = new HashMap<>(); for (Iterator<?> it = tool_state.keys(); it.hasNext();) { String key = (String) it.next(); String value = tool_state.getString(key).replaceAll("\\\"", ""); params.put(key, value); } String command = tool.getTemplate(); System.out.println(command); Pattern paramPattern = Pattern.compile("\\$[^ ,]*"); Matcher paramMatcher = paramPattern.matcher(command); while (paramMatcher.find()) { String match = paramMatcher.group(); String matchRegEx = match.replace("$", "\\$").replace("{", "\\{").replace("}", "\\}"); System.out.print("\t" + match); String paramName = match.replace("$", "").replace("{", "").replace("}", ""); if (tool.hasInputTypes(paramName)) { command = command.replaceAll(matchRegEx, task.getDataByName(paramName).getLocalPath()); System.out.println(" <-- " + task.getDataByName(paramName).getLocalPath()); continue; } if (tool.hasOutputTypes(paramName)) { command = command.replaceAll(matchRegEx, task.getDataByName(paramName).getLocalPath()); System.out.println(" <-- " + task.getDataByName(paramName).getLocalPath()); continue; } if (paramName.contains(".metadata.")) { String[] splitParamName = paramName.split("\\."); Set<GalaxyDataType> dataTypes = tool.hasInputTypes(splitParamName[0]) ? tool.getInputTypes(splitParamName[0]) : tool.getOutputTypes(splitParamName[0]); for (GalaxyDataType dataType : dataTypes) { if (dataType.hasMetadata(splitParamName[2])) { command = command.replaceAll(matchRegEx, dataType.getMetadata(splitParamName[2])); System.out.println(" <-- " + dataType.getMetadata(splitParamName[2])); break; } } continue; } if (params.containsKey(paramName)) { command = command.replace(match, params.get(paramName)); System.out.println(" <-- " + params.get(paramName)); continue; } if (tool.hasDefaultParameter(paramName)) { command = command.replace(match, tool.getDefaultParameter(paramName)); System.out.println(" <-- " + tool.getDefaultParameter(paramName)); continue; } } System.out.println(command); task.setCommand(command); task.getReport().add( new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(), task.getLanguageLabel(), task.getId(), null, JsonReportEntry.KEY_INVOC_SCRIPT, task.getCommand())); */ } } } catch (IOException | JSONException | WorkflowStructureUnknownException e) { e.printStackTrace(); // onError(e); } // scheduler.addTasks(tasks.values()); } }