src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
StampedStateGuard { public boolean becomeTerminated() { assert lock.isWriteLocked() : "Thread must hold write lock."; if (state != TERMINATED) { state = TERMINATED; return true; } return false; } StampedStateGuard(Class<?> type); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); boolean isInitialized(); boolean becomeTerminating(); boolean becomeTerminated(); long lockReadWithStateCheck(); long lockRead(); void unlockRead(long stamp); long lockWriteWithStateCheck(); long lockWrite(); void unlockWrite(long stamp); boolean isWriteLocked(); @Override String toString(); }
@Test public void testBecomeTerminated() { long lock = guard.lockWrite(); try { assertFalse(guard.becomeTerminated()); guard.becomeInitialized(); assertTrue(guard.becomeTerminated()); } finally { guard.unlockWrite(lock); } }
StampedStateGuard { public long lockReadWithStateCheck() { long locked = lock.readLock(); if (state != INITIALIZED) { lock.unlockRead(locked); throw new IllegalStateException(type.getSimpleName() + " is not " + INITIALIZED.name().toLowerCase(Locale.US) + '.'); } return locked; } StampedStateGuard(Class<?> type); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); boolean isInitialized(); boolean becomeTerminating(); boolean becomeTerminated(); long lockReadWithStateCheck(); long lockRead(); void unlockRead(long stamp); long lockWriteWithStateCheck(); long lockWrite(); void unlockWrite(long stamp); boolean isWriteLocked(); @Override String toString(); }
@Test public void testLockReadWithStateCheck() { expect(IllegalStateException.class, getClass().getSimpleName() + " is not initialized.", guard::lockReadWithStateCheck); long lock = guard.lockWrite(); guard.becomeInitialized(); guard.unlockWrite(lock); lock = guard.lockReadWithStateCheck(); guard.unlockRead(lock); }
StampedStateGuard { public long lockWriteWithStateCheck() { long locked = lock.writeLock(); if (state != INITIALIZED) { lock.unlockWrite(locked); throw new IllegalStateException(type.getSimpleName() + " is not " + INITIALIZED.name().toLowerCase(Locale.US) + '.'); } return locked; } StampedStateGuard(Class<?> type); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); boolean isInitialized(); boolean becomeTerminating(); boolean becomeTerminated(); long lockReadWithStateCheck(); long lockRead(); void unlockRead(long stamp); long lockWriteWithStateCheck(); long lockWrite(); void unlockWrite(long stamp); boolean isWriteLocked(); @Override String toString(); }
@Test public void testLockWriteWithStateCheck() { expect(IllegalStateException.class, getClass().getSimpleName() + " is not initialized.", guard::lockWriteWithStateCheck); long lock = guard.lockWrite(); guard.becomeInitialized(); guard.unlockWrite(lock); lock = guard.lockWriteWithStateCheck(); assertTrue(guard.isWriteLocked()); guard.unlockWrite(lock); }
StampedStateGuard { @Override public String toString() { long locked = lock.readLock(); try { return ToString.format(this); } finally { lock.unlockRead(locked); } } StampedStateGuard(Class<?> type); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); boolean isInitialized(); boolean becomeTerminating(); boolean becomeTerminated(); long lockReadWithStateCheck(); long lockRead(); void unlockRead(long stamp); long lockWriteWithStateCheck(); long lockWrite(); void unlockWrite(long stamp); boolean isWriteLocked(); @Override String toString(); }
@Test public void testToString() { assertEquals(guard.toString(), ToString.format(guard), guard.toString()); }
ToString { public static String format(Object obj) { return doFormat(null, false, obj); } private ToString(); static String format(Object obj); static String format(Class<?> alias, Object obj); static String formatProperties(Object obj); }
@Test public void testNull() throws Exception { assertEquals("null", ToString.format(null)); assertEquals("null", ToString.format(ClassA.class, null)); } @Test public void testObject() throws Exception { ClassA objA = new ClassA( "AAA", 100, 1, "IGNORE", "ccc", Optional.empty(), OptionalInt.empty(), OptionalLong.empty(), OptionalDouble.empty() ); ClassB objB = new ClassB( "AAA", 100, 1, "IGNORE", "BBB", 200, "ccc", Optional.empty(), OptionalInt.empty(), OptionalLong.empty(), OptionalDouble.empty() ); EmptyClass emptyObj = new EmptyClass(); assertEquals( "ClassA[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc" + "]", ToString.format(objA) ); assertEquals( "ClassB[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc, " + "str-val2=BBB, " + "int-val2=200" + "]", ToString.format(objB) ); assertEquals("EmptyClass", ToString.format(emptyObj)); } @Test public void testObjectWithAlias() throws Exception { ClassA objA = new ClassA( "AAA", 100, 1, "IGNORE", "ccc", Optional.empty(), OptionalInt.empty(), OptionalLong.empty(), OptionalDouble.empty() ); ClassB objB = new ClassB( "AAA", 100, 1, "IGNORE", "BBB", 200, "ccc", Optional.empty(), OptionalInt.empty(), OptionalLong.empty(), OptionalDouble.empty() ); EmptyClass emptyObj = new EmptyClass(); assertEquals( "ClassB[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc" + "]", ToString.format(ClassB.class, objA) ); assertEquals( "ClassA[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc" + "]", ToString.format(objA) ); assertEquals( "ClassA[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc, " + "str-val2=BBB, " + "int-val2=200" + "]", ToString.format(ClassA.class, objB) ); assertEquals( "ClassB[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc, " + "str-val2=BBB, " + "int-val2=200" + "]", ToString.format(objB) ); assertEquals("ClassB", ToString.format(ClassB.class, emptyObj)); assertEquals("EmptyClass", ToString.format(emptyObj)); } @Test public void testOptional() throws Exception { ClassA objA = new ClassA( "AAA", 100, 1, "IGNORE", "ccc", Optional.of("TEST"), OptionalInt.of(1050), OptionalLong.of(100500), OptionalDouble.of(100.500) ); ClassB objB = new ClassB( "AAA", 100, 1, "IGNORE", "BBB", 200, "ccc", Optional.of("TEST"), OptionalInt.of(1050), OptionalLong.of(100500), OptionalDouble.of(100.500) ); assertEquals( "ClassA[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc, " + "opt-str=TEST, " + "opt-int=1050, " + "opt-long=100500, " + "opt-double=100.5" + "]", ToString.format(objA) ); assertEquals( "ClassB[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc, " + "opt-str=TEST, " + "opt-int=1050, " + "opt-long=100500, " + "opt-double=100.5, " + "str-val2=BBB, " + "int-val2=200" + "]", ToString.format(objB) ); } @Test public void testOptionalNull() throws Exception { ClassA objA = new ClassA( "AAA", 100, 1, "IGNORE", "ccc", null, null, null, null ); assertEquals( "ClassA[" + "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc" + "]", ToString.format(objA) ); } @Test public void testArray() throws Exception { String[] arr1 = {"A", "B", "C"}; String[][] arr2 = {{"A", "B", "C"}, {"D", "E", "F"}}; ClassC obj = new ClassC(arr1, arr2); assertEquals("ClassC[c1=[A, B, C], c2=[[A, B, C], [D, E, F]]]", ToString.format(obj)); }
EtcdSeedNodeProviderConfig { @Override public String toString() { return ToString.format(this); } List<String> getEndpoints(); void setEndpoints(List<String> endpoints); EtcdSeedNodeProviderConfig withEndpoints(List<String> endpoints); EtcdSeedNodeProviderConfig withEndpoint(String endpoint); String getUsername(); void setUsername(String username); EtcdSeedNodeProviderConfig withUsername(String username); String getPassword(); void setPassword(String password); EtcdSeedNodeProviderConfig withPassword(String password); String getBasePath(); void setBasePath(String basePath); EtcdSeedNodeProviderConfig withBasePath(String basePath); int getCleanupInterval(); void setCleanupInterval(int cleanupInterval); EtcdSeedNodeProviderConfig withCleanupInterval(int cleanupInterval); @Override String toString(); static final int DEFAULT_CLEANUP_INTERVAL; static final String DEFAULT_BASE_PATH; }
@Test public void testToString() { cfg.setEndpoints(singletonList("http: cfg.setUsername("test"); cfg.setPassword("test"); assertEquals(ToString.format(cfg), cfg.toString()); }
ToString { public static String formatProperties(Object obj) { return doFormat(null, true, obj); } private ToString(); static String format(Object obj); static String format(Class<?> alias, Object obj); static String formatProperties(Object obj); }
@Test public void testPropertiesOnly() throws Exception { ClassA objA = new ClassA( "AAA", 100, 1, "IGNORE", "ccc", Optional.empty(), OptionalInt.empty(), OptionalLong.empty(), OptionalDouble.empty() ); ClassB objB = new ClassB( "AAA", 100, 1, "IGNORE", "BBB", 200, "ccc", Optional.empty(), OptionalInt.empty(), OptionalLong.empty(), OptionalDouble.empty() ); EmptyClass emptyObj = new EmptyClass(); assertEquals( "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc", ToString.formatProperties(objA) ); assertEquals( "str-val=AAA, " + "int-val=100, " + "camel-case=1, " + "custom-format=test-ccc, " + "str-val2=BBB, " + "int-val2=200", ToString.formatProperties(objB) ); assertEquals("", ToString.formatProperties(emptyObj)); } @Test public void testFieldOfClassType() { class TestClass { private final Class<TestClass> type1; public TestClass(Class<TestClass> type1) { this.type1 = type1; } } assertEquals( "type1=" + TestClass.class.getName(), ToString.formatProperties(new TestClass(TestClass.class)) ); } @Test public void testNullValue() { class TestClass { private final Object val; public TestClass(Object val) { this.val = val; } } assertEquals("", ToString.formatProperties(new TestClass(null))); }
ExtendedScheduledExecutor extends ScheduledThreadPoolExecutor { public ScheduledFuture<?> repeatAtFixedRate(RepeatingRunnable command, long initialDelay, long period, TimeUnit unit) { return super.scheduleAtFixedRate(RepeatingTask.of(command), initialDelay, period, unit); } ExtendedScheduledExecutor(int corePoolSize); ExtendedScheduledExecutor(int corePoolSize, ThreadFactory threadFactory); ExtendedScheduledExecutor(int corePoolSize, RejectedExecutionHandler handler); ExtendedScheduledExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler); ScheduledFuture<?> repeatAtFixedRate(RepeatingRunnable command, long initialDelay, long period, TimeUnit unit); ScheduledFuture<?> repeatWithFixedDelay(RepeatingRunnable command, long initialDelay, long delay, TimeUnit unit); }
@Test public void testRepeatAtFixedRate() throws Exception { ExtendedScheduledExecutor exec = new ExtendedScheduledExecutor(1); try { AtomicInteger count = new AtomicInteger(); exec.repeatAtFixedRate(() -> count.incrementAndGet() < 3, 0, 1, TimeUnit.NANOSECONDS); busyWait("command executed", () -> count.get() == 3); sleep(10); assertEquals(3, count.get()); } finally { shutDown(exec); } }
ExtendedScheduledExecutor extends ScheduledThreadPoolExecutor { public ScheduledFuture<?> repeatWithFixedDelay(RepeatingRunnable command, long initialDelay, long delay, TimeUnit unit) { return super.scheduleWithFixedDelay(RepeatingTask.of(command), initialDelay, delay, unit); } ExtendedScheduledExecutor(int corePoolSize); ExtendedScheduledExecutor(int corePoolSize, ThreadFactory threadFactory); ExtendedScheduledExecutor(int corePoolSize, RejectedExecutionHandler handler); ExtendedScheduledExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler); ScheduledFuture<?> repeatAtFixedRate(RepeatingRunnable command, long initialDelay, long period, TimeUnit unit); ScheduledFuture<?> repeatWithFixedDelay(RepeatingRunnable command, long initialDelay, long delay, TimeUnit unit); }
@Test public void testRepeatWithFixedDelay() throws Exception { ExtendedScheduledExecutor exec = new ExtendedScheduledExecutor(1); try { AtomicInteger count = new AtomicInteger(); exec.repeatWithFixedDelay(() -> count.incrementAndGet() < 3, 0, 1, TimeUnit.NANOSECONDS); busyWait("command executed", () -> count.get() == 3); sleep(10); assertEquals(3, count.get()); } finally { shutDown(exec); } }
AsyncUtils { public static Waiting shutdown(ExecutorService executor) { if (executor == null) { return Waiting.NO_WAIT; } else { executor.shutdown(); return () -> { while (!executor.awaitTermination(500, TimeUnit.MILLISECONDS)) { executor.shutdown(); } }; } } private AsyncUtils(); static Executor fallbackExecutor(); static Waiting shutdown(ExecutorService executor); static T getUninterruptedly(Future<T> future); static CompletableFuture<Void> allOf(Collection<CompletableFuture<?>> all); static Future<?> cancelledFuture(); }
@Test public void testShutdown() throws Exception { assertSame(Waiting.NO_WAIT, AsyncUtils.shutdown(null)); ExecutorService pool = mock(ExecutorService.class); AtomicInteger waitCalls = new AtomicInteger(3); when(pool.awaitTermination(anyLong(), any(TimeUnit.class))).then(call -> waitCalls.decrementAndGet() == 0); Waiting waiting = AsyncUtils.shutdown(pool); assertNotNull(waiting); InOrder order = inOrder(pool); order.verify(pool).shutdown(); waiting.await(); order.verify(pool).awaitTermination(500, TimeUnit.MILLISECONDS); order.verify(pool).shutdown(); order.verify(pool).awaitTermination(500, TimeUnit.MILLISECONDS); order.verify(pool).shutdown(); order.verify(pool).awaitTermination(500, TimeUnit.MILLISECONDS); order.verifyNoMoreInteractions(); }
AsyncUtils { public static Executor fallbackExecutor() { return FALLBACK_EXECUTOR; } private AsyncUtils(); static Executor fallbackExecutor(); static Waiting shutdown(ExecutorService executor); static T getUninterruptedly(Future<T> future); static CompletableFuture<Void> allOf(Collection<CompletableFuture<?>> all); static Future<?> cancelledFuture(); }
@Test public void testFallbackExecutor() throws Exception { assertNotNull(AsyncUtils.fallbackExecutor()); for (int i = 0; i < 100; i++) { CountDownLatch executed = new CountDownLatch(1); AsyncUtils.fallbackExecutor().execute(executed::countDown); await(executed); } }
ConsulSeedNodeProviderConfig { @Override public String toString() { return ToString.format(this); } String getUrl(); void setUrl(String url); ConsulSeedNodeProviderConfig withUrl(String url); long getCleanupInterval(); void setCleanupInterval(long cleanupInterval); ConsulSeedNodeProviderConfig withCleanupInterval(long cleanupInterval); String getBasePath(); void setBasePath(String basePath); ConsulSeedNodeProviderConfig withBasePath(String basePath); Long getConnectTimeout(); void setConnectTimeout(Long connectTimeout); ConsulSeedNodeProviderConfig withConnectTimeout(Long connectTimeout); Long getReadTimeout(); void setReadTimeout(Long readTimeout); ConsulSeedNodeProviderConfig withReadTimeout(Long readTimeout); Long getWriteTimeout(); void setWriteTimeout(Long writeTimeout); ConsulSeedNodeProviderConfig withWriteTimeout(Long writeTimeout); String getAclToken(); void setAclToken(String aclToken); ConsulSeedNodeProviderConfig withAclToken(String aclToken); @Override String toString(); static final long DEFAULT_CLEANUP_INTERVAL; static final String DEFAULT_BASE_PATH; }
@Test public void testToString() { cfg.setUrl("http: assertEquals(ToString.format(cfg), cfg.toString()); }
AsyncUtils { public static <T> T getUninterruptedly(Future<T> future) throws ExecutionException { ArgAssert.notNull(future, "future"); boolean interrupted = false; try { while (true) { try { return future.get(); } catch (InterruptedException e) { interrupted = true; Thread.interrupted(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } private AsyncUtils(); static Executor fallbackExecutor(); static Waiting shutdown(ExecutorService executor); static T getUninterruptedly(Future<T> future); static CompletableFuture<Void> allOf(Collection<CompletableFuture<?>> all); static Future<?> cancelledFuture(); }
@Test public void testGetUninterruptedlyNoInterrupt() throws Exception { CompletableFuture<String> future = new CompletableFuture<>(); Future<Object> testFuture = runAsync(() -> AsyncUtils.getUninterruptedly(future) ); future.complete("something"); assertEquals("something", get(testFuture)); } @Test public void testGetUninterruptedlyInterrupt() throws Exception { CompletableFuture<String> future = new CompletableFuture<>(); CountDownLatch interrupted = new CountDownLatch(1); Future<Object> testFuture = runAsync(() -> { Thread.currentThread().interrupt(); interrupted.countDown(); String result = AsyncUtils.getUninterruptedly(future); assertTrue(Thread.currentThread().isInterrupted()); return result; }); await(interrupted); sleep(50); future.complete("something"); assertEquals("something", get(testFuture)); }
AsyncUtils { public static CompletableFuture<Void> allOf(Collection<CompletableFuture<?>> all) { return CompletableFuture.allOf(all.toArray(EMPTY_FUTURES)); } private AsyncUtils(); static Executor fallbackExecutor(); static Waiting shutdown(ExecutorService executor); static T getUninterruptedly(Future<T> future); static CompletableFuture<Void> allOf(Collection<CompletableFuture<?>> all); static Future<?> cancelledFuture(); }
@Test public void testAllOf() throws Exception { List<CompletableFuture<?>> futures = asList( new CompletableFuture<>(), new CompletableFuture<>(), new CompletableFuture<>() ); CompletableFuture<Void> all = AsyncUtils.allOf(futures); futures.get(0).complete(null); assertFalse(all.isDone()); futures.get(1).complete(null); assertFalse(all.isDone()); futures.get(2).complete(null); assertTrue(all.isDone()); } @Test public void testAllOfEmpty() throws Exception { CompletableFuture<Void> empty = AsyncUtils.allOf(emptyList()); assertTrue(empty.isDone()); }
AsyncUtils { public static Future<?> cancelledFuture() { return CANCELLED_FUTURE; } private AsyncUtils(); static Executor fallbackExecutor(); static Waiting shutdown(ExecutorService executor); static T getUninterruptedly(Future<T> future); static CompletableFuture<Void> allOf(Collection<CompletableFuture<?>> all); static Future<?> cancelledFuture(); }
@Test public void testCancelledFuture() throws Exception { Future<?> f = AsyncUtils.cancelledFuture(); assertTrue(f.isDone()); assertTrue(f.isCancelled()); assertFalse(f.cancel(true)); assertFalse(f.cancel(false)); assertNull(f.get()); assertNull(f.get(1, TimeUnit.SECONDS)); }
UuidBase implements Serializable, Comparable<T> { @Override public String toString() { return digits(hiBits >> 32, 8) + digits(hiBits >> 16, 4) + digits(hiBits, 4) + digits(loBits >> 48, 4) + digits(loBits, 12); } UuidBase(); UuidBase(long hiBits, long loBits); UuidBase(String s); long hiBits(); long loBits(); @Override int compareTo(T other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testToAndFromString() throws Exception { assertEquals(newUuid(0, 0), newUuid(newUuid(0, 0).toString())); assertEquals(newUuid(0, 1), newUuid(newUuid(0, 1).toString())); assertEquals(newUuid(1, 0), newUuid(newUuid(1, 0).toString())); assertEquals(newUuid(1, 1), newUuid(newUuid(1, 1).toString())); for (int i = 0; i < 100; i++) { T id1 = newUuid(); T id2 = newUuid(id1.toString()); assertEquals(id1, id2); } }
UuidBase implements Serializable, Comparable<T> { @Override public int compareTo(T other) { long hiBits2 = other.hiBits(); long loBits2 = other.loBits(); if (hiBits < hiBits2) { return -1; } else if (hiBits > hiBits2) { return 1; } else { return Long.compare(loBits, loBits2); } } UuidBase(); UuidBase(long hiBits, long loBits); UuidBase(String s); long hiBits(); long loBits(); @Override int compareTo(T other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testCompareTo() { assertEquals(0, newUuid(0, 0).compareTo(newUuid(0, 0))); assertEquals(-1, newUuid(0, 0).compareTo(newUuid(0, 1))); assertEquals(1, newUuid(0, 1).compareTo(newUuid(0, 0))); assertEquals(-1, newUuid(0, 1).compareTo(newUuid(1, 0))); assertEquals(1, newUuid(1, 1).compareTo(newUuid(0, 1))); }
CandidateConfig { @Override public String toString() { return ToString.format(this); } CandidateConfig(); CandidateConfig(String group); String getGroup(); void setGroup(String group); CandidateConfig withGroup(String group); Candidate getCandidate(); void setCandidate(Candidate candidate); CandidateConfig withCandidate(Candidate candidate); @Override String toString(); }
@Test public void testToString() { assertTrue(cfg.toString(), cfg.toString().startsWith(CandidateConfig.class.getSimpleName())); }
CandidateHandler implements AsyncLockCallback, JmxSupport<CandidateJmx> { public Waiting terminate() { terminated = true; CountDownLatch done = new CountDownLatch(1); worker.execute(() -> { try { leaderFuture.cancel(false); boolean doTerminate = false; if (leaderCtx != null) { doTerminate = true; if (log.isInfoEnabled()) { log.info("Stopping leader [group={}, candidate={}]", group, candidate); } } else if (followerCtx != null) { doTerminate = true; if (log.isInfoEnabled()) { log.info("Stopping follower [group={}, candidate={}]", group, candidate); } } if (doTerminate) { candidate.terminate(); } } catch (RuntimeException | Error e) { log.error("Failed to execute election worker thread termination task.", e); } finally { followerCtx = null; disposeLeader(); if (lock.isHeldByCurrentThread()) { lock.unlockAsync(); } done.countDown(); } }); return done::await; } CandidateHandler( String group, Candidate candidate, ExecutorService worker, DistributedLock lock, ClusterNode localNode, HekateSupport hekate ); String group(); Candidate candidate(); @Override void onLockAcquire(DistributedLock lock); @Override void onLockBusy(LockOwnerInfo owner); @Override void onLockOwnerChange(LockOwnerInfo owner); void initialize(); Waiting terminate(); Waiting shutdown(); LeaderFuture leaderFuture(); @Override CandidateJmx jmx(); }
@Test public void testTerminate() throws Exception { handler.terminate(); handler.shutdown(); verify(candidate, never()).terminate(); verify(worker).shutdown(); reset(candidate); handler.onLockBusy(new DefaultLockOwnerInfo(1, newNode())); handler.onLockOwnerChange(new DefaultLockOwnerInfo(1, newNode())); handler.onLockAcquire(lock); verifyNoMoreInteractions(candidate); }
CandidateHandler implements AsyncLockCallback, JmxSupport<CandidateJmx> { @Override public void onLockAcquire(DistributedLock lock) { if (!terminated) { if (log.isInfoEnabled()) { log.info("Switching to leader state [group={}, candidate={}]", group, candidate); } followerCtx = null; leaderCtx = new DefaultLeaderContext(); try { candidate.becomeLeader(leaderCtx); } finally { updateLeaderFuture(localNode); } } } CandidateHandler( String group, Candidate candidate, ExecutorService worker, DistributedLock lock, ClusterNode localNode, HekateSupport hekate ); String group(); Candidate candidate(); @Override void onLockAcquire(DistributedLock lock); @Override void onLockBusy(LockOwnerInfo owner); @Override void onLockOwnerChange(LockOwnerInfo owner); void initialize(); Waiting terminate(); Waiting shutdown(); LeaderFuture leaderFuture(); @Override CandidateJmx jmx(); }
@Test public void testOnLockAcquire() throws Exception { handler.onLockAcquire(lock); verify(candidate).becomeLeader(leaderCtx.capture()); assertEquals(localNode, leaderCtx.getValue().localNode()); }
ZooKeeperSeedNodeProvider implements SeedNodeProvider, ConfigReportSupport { public int connectTimeout() { return connectTimeout; } ZooKeeperSeedNodeProvider(ZooKeeperSeedNodeProviderConfig cfg); @Override void report(ConfigReporter report); String connectionString(); String basePath(); int connectTimeout(); int sessionTimeout(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override long cleanupInterval(); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override String toString(); }
@Test public void testConnectTimeout() throws Exception { try (ServerSocket sock = new ServerSocket()) { InetSocketAddress addr = newSocketAddress(); sock.bind(addr); ZooKeeperSeedNodeProvider provider = createProvider(cfg -> cfg.withConnectionString(addr.getHostString() + ':' + addr.getPort()) ); expectCause(HekateException.class, "Timeout connecting to ZooKeeper", () -> provider.startDiscovery(CLUSTER_1, newSocketAddress()) ); } }
CandidateHandler implements AsyncLockCallback, JmxSupport<CandidateJmx> { @Override public void onLockBusy(LockOwnerInfo owner) { if (!terminated) { ClusterNode leader = owner.node(); if (log.isInfoEnabled()) { log.info("Switching to follower state [group={}, leader={}, candidate={}]", group, leader, candidate); } disposeLeader(); followerCtx = new DefaultFollowerContext(leader); try { candidate.becomeFollower(followerCtx); } finally { updateLeaderFuture(leader); } } } CandidateHandler( String group, Candidate candidate, ExecutorService worker, DistributedLock lock, ClusterNode localNode, HekateSupport hekate ); String group(); Candidate candidate(); @Override void onLockAcquire(DistributedLock lock); @Override void onLockBusy(LockOwnerInfo owner); @Override void onLockOwnerChange(LockOwnerInfo owner); void initialize(); Waiting terminate(); Waiting shutdown(); LeaderFuture leaderFuture(); @Override CandidateJmx jmx(); }
@Test public void testOnLockBusy() throws Exception { LockOwnerInfo lockOwner = new DefaultLockOwnerInfo(1, newNode()); handler.onLockBusy(lockOwner); verify(candidate).becomeFollower(followerCtx.capture()); assertEquals(localNode, followerCtx.getValue().localNode()); assertEquals(lockOwner.node(), followerCtx.getValue().leader()); }
ElectionServiceFactory implements ServiceFactory<ElectionService> { @Override public String toString() { return ToString.format(this); } List<CandidateConfig> getCandidates(); void setCandidates(List<CandidateConfig> candidates); ElectionServiceFactory withCandidate(CandidateConfig candidate); CandidateConfig withCandidate(String group); List<CandidateConfigProvider> getConfigProviders(); void setConfigProviders(List<CandidateConfigProvider> configProviders); ElectionServiceFactory withConfigProvider(CandidateConfigProvider configProvider); @Override ElectionService createService(); @Override String toString(); }
@Test public void testToString() { assertTrue(factory.toString(), factory.toString().startsWith(ElectionServiceFactory.class.getSimpleName())); }
NetworkSslConfig { @Override public String toString() { return ToString.format(this); } Provider getProvider(); void setProvider(Provider provider); NetworkSslConfig withProvider(Provider provider); String getKeyStoreAlgorithm(); void setKeyStoreAlgorithm(String keyStoreAlgorithm); NetworkSslConfig withKeyStoreAlgorithm(String keyStoreAlgorithm); String getKeyStorePath(); void setKeyStorePath(String keyStorePath); NetworkSslConfig withKeyStorePath(String keyStorePath); String getKeyStoreType(); void setKeyStoreType(String keyStoreType); NetworkSslConfig withKeyStoreType(String keyStoreType); String getKeyStorePassword(); void setKeyStorePassword(String keyStorePassword); NetworkSslConfig withKeyStorePassword(String keyStorePassword); String getTrustStorePath(); void setTrustStorePath(String trustStorePath); NetworkSslConfig withTrustStorePath(String trustStorePath); String getTrustStoreType(); void setTrustStoreType(String trustStoreType); NetworkSslConfig withTrustStoreType(String trustStoreType); String getTrustStorePassword(); void setTrustStorePassword(String trustStorePassword); NetworkSslConfig withTrustStorePassword(String trustStorePassword); String getTrustStoreAlgorithm(); void setTrustStoreAlgorithm(String trustStoreAlgorithm); NetworkSslConfig withTrustStoreAlgorithm(String trustStoreAlgorithm); int getSslSessionCacheSize(); void setSslSessionCacheSize(int sslSessionCacheSize); NetworkSslConfig withSslSessionCacheSize(int sslSessionCacheSize); int getSslSessionCacheTimeout(); void setSslSessionCacheTimeout(int sslSessionCacheTimeout); NetworkSslConfig withSslSessionCacheTimeout(int sslSessionCacheTimeout); @Override String toString(); }
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); }
NettyClientFactory implements NetworkConnector<T> { @Override public String protocol() { return getProtocol(); } EventLoopGroup getEventLoop(); void setEventLoop(EventLoopGroup eventLoop); NettyClientFactory<T> withEventLoop(EventLoopGroup eventLoop); String getProtocol(); void setProtocol(String protocol); NettyClientFactory<T> withProtocol(String protocol); Integer getConnectTimeout(); void setConnectTimeout(Integer connectTimeout); NettyClientFactory<T> withConnectTimeout(Integer connectTimeout); long getIdleTimeout(); void setIdleTimeout(long idleTimeout); NettyClientFactory<T> withIdleTimeout(long idleTimeout); boolean isTcpNoDelay(); void setTcpNoDelay(boolean tcpNoDelay); NettyClientFactory<T> withTcpNoDelay(boolean tcpNoDelay); Integer getSoReceiveBufferSize(); void setSoReceiveBufferSize(Integer soReceiveBufferSize); NettyClientFactory<T> withSoReceiveBufferSize(Integer soReceiveBufferSize); Integer getSoSendBufferSize(); void setSoSendBufferSize(Integer soSendBufferSize); NettyClientFactory<T> withSoSendBufferSize(Integer soSendBufferSize); Boolean getSoReuseAddress(); void setSoReuseAddress(Boolean soReuseAddress); NettyClientFactory<T> withSoReuseAddress(Boolean soReuseAddress); CodecFactory<T> getCodecFactory(); void setCodecFactory(CodecFactory<T> codecFactory); NettyClientFactory<T> withCodecFactory(CodecFactory<T> codecFactory); NettyMetricsSink getMetrics(); void setMetrics(NettyMetricsSink metrics); NettyClientFactory<T> withMetrics(NettyMetricsSink metrics); String getLoggerCategory(); void setLoggerCategory(String loggerCategory); NettyClientFactory<T> withLoggerCategory(String loggerCategory); SslContext getSsl(); void setSsl(SslContext ssl); NettyClientFactory<T> withSsl(SslContext ssl); @Override NetworkClient<T> newClient(); @Override String protocol(); @Override String toString(); }
@Test public void testProtocol() { assertNull(factory.getProtocol()); factory.setProtocol("test"); assertEquals("test", factory.getProtocol()); assertSame(factory, factory.withProtocol("test2")); assertEquals("test2", factory.getProtocol()); }
NettyClientFactory implements NetworkConnector<T> { @Override public String toString() { return ToString.format(this); } EventLoopGroup getEventLoop(); void setEventLoop(EventLoopGroup eventLoop); NettyClientFactory<T> withEventLoop(EventLoopGroup eventLoop); String getProtocol(); void setProtocol(String protocol); NettyClientFactory<T> withProtocol(String protocol); Integer getConnectTimeout(); void setConnectTimeout(Integer connectTimeout); NettyClientFactory<T> withConnectTimeout(Integer connectTimeout); long getIdleTimeout(); void setIdleTimeout(long idleTimeout); NettyClientFactory<T> withIdleTimeout(long idleTimeout); boolean isTcpNoDelay(); void setTcpNoDelay(boolean tcpNoDelay); NettyClientFactory<T> withTcpNoDelay(boolean tcpNoDelay); Integer getSoReceiveBufferSize(); void setSoReceiveBufferSize(Integer soReceiveBufferSize); NettyClientFactory<T> withSoReceiveBufferSize(Integer soReceiveBufferSize); Integer getSoSendBufferSize(); void setSoSendBufferSize(Integer soSendBufferSize); NettyClientFactory<T> withSoSendBufferSize(Integer soSendBufferSize); Boolean getSoReuseAddress(); void setSoReuseAddress(Boolean soReuseAddress); NettyClientFactory<T> withSoReuseAddress(Boolean soReuseAddress); CodecFactory<T> getCodecFactory(); void setCodecFactory(CodecFactory<T> codecFactory); NettyClientFactory<T> withCodecFactory(CodecFactory<T> codecFactory); NettyMetricsSink getMetrics(); void setMetrics(NettyMetricsSink metrics); NettyClientFactory<T> withMetrics(NettyMetricsSink metrics); String getLoggerCategory(); void setLoggerCategory(String loggerCategory); NettyClientFactory<T> withLoggerCategory(String loggerCategory); SslContext getSsl(); void setSsl(SslContext ssl); NettyClientFactory<T> withSsl(SslContext ssl); @Override NetworkClient<T> newClient(); @Override String protocol(); @Override String toString(); }
@Test public void testToString() { assertEquals(ToString.format(factory), factory.toString()); }
NettyUtils { public static Waiting shutdown(EventExecutorGroup executor) { if (executor == null) { return Waiting.NO_WAIT; } else { return executor.shutdownGracefully(0, Long.MAX_VALUE, TimeUnit.MILLISECONDS)::await; } } private NettyUtils(); static Waiting shutdown(EventExecutorGroup executor); static void runAtAllCost(EventLoop eventLoop, Runnable task); }
@Test public void testShutdown() throws Exception { assertSame(Waiting.NO_WAIT, NettyUtils.shutdown(null)); EventExecutorGroup mock = mock(EventExecutorGroup.class); when(mock.shutdownGracefully(anyLong(), anyLong(), any())).thenReturn(genericMock(Future.class)); NettyUtils.shutdown(mock); verify(mock).shutdownGracefully(eq(0L), eq(Long.MAX_VALUE), same(TimeUnit.MILLISECONDS)); }
NettyUtils { public static void runAtAllCost(EventLoop eventLoop, Runnable task) { boolean notified = false; if (!eventLoop.isShuttingDown()) { try { eventLoop.execute(task); notified = true; } catch (RejectedExecutionException e) { } } if (!notified) { AsyncUtils.fallbackExecutor().execute(task); } } private NettyUtils(); static Waiting shutdown(EventExecutorGroup executor); static void runAtAllCost(EventLoop eventLoop, Runnable task); }
@Test public void testRunAtAllCost() throws Exception { EventLoop eventLoop = new DefaultEventLoop(); try { Exchanger<Boolean> exchanger = new Exchanger<>(); NettyUtils.runAtAllCost(eventLoop, () -> { try { exchanger.exchange(eventLoop.inEventLoop()); } catch (InterruptedException e) { } }); assertTrue(exchanger.exchange(null)); NettyUtils.shutdown(eventLoop).awaitUninterruptedly(); NettyUtils.runAtAllCost(eventLoop, () -> { try { exchanger.exchange(eventLoop.inEventLoop()); } catch (InterruptedException e) { } }); assertFalse(exchanger.exchange(null)); } finally { NettyUtils.shutdown(eventLoop).awaitUninterruptedly(); } }
NettyMessage extends InputStream implements DataReader, NetworkMessage<Object> { @Override public <V> V preview(Preview<V> preview) throws IOException { int idx = buf.readerIndex(); buf.readerIndex(0); try { return preview.apply(this); } finally { buf.readerIndex(idx); } } NettyMessage(ByteBuf buf, Codec<Object> codec); void prepare(Logger log); boolean release(); @Override Object decode(); @Override void handleAsync(Executor worker, Consumer<NetworkMessage<Object>> handler); @Override V preview(Preview<V> preview); @Override int previewInt(PreviewInt preview); @Override long previewLong(PreviewLong preview); @Override double previewDouble(PreviewDouble preview); @Override boolean previewBoolean(PreviewBoolean preview); @Override InputStream asStream(); @Override int available(); @Override int read(); @Override int read(byte[] b, int off, int len); @Override long skip(long n); @Override boolean readBoolean(); @Override byte readByte(); @Override char readChar(); @Override double readDouble(); @Override float readFloat(); @Override void readFully(byte[] b); @Override void readFully(byte[] b, int off, int len); @Override int readInt(); @Override @Deprecated String readLine(); @Override long readLong(); @Override short readShort(); @Override String readUTF(); @Override int readUnsignedByte(); @Override int readUnsignedShort(); @Override int skipBytes(int n); @Override boolean markSupported(); @Override void reset(); @Override void mark(int readLimit); @SuppressWarnings("unchecked") NetworkMessage<T> cast(); @Override String toString(); }
@Test public void testPreview() throws Exception { ByteBuf buf = Unpooled.buffer(); buf.writeByte(10); buf.writeBoolean(true); buf.writeInt(100); buf.writeLong(1000); buf.writeDouble(1.01); NettyMessage msg = new NettyMessage(buf, new Codec<Object>() { @Override public boolean isStateful() { return false; } @Override public Class<Object> baseType() { return Object.class; } @Override public Object decode(DataReader in) throws IOException { throw new AssertionError("Should not be called."); } @Override public void encode(Object obj, DataWriter out) throws IOException { throw new AssertionError("Should not be called."); } }); assertEquals((byte)10, (byte)msg.preview(DataInput::readByte)); assertEquals(0, buf.readerIndex()); assertTrue(msg.previewBoolean(m -> { m.skipBytes(1); return m.readBoolean(); })); assertEquals(0, buf.readerIndex()); assertEquals(100, msg.previewInt(m -> { m.skipBytes(2); return m.readInt(); })); assertEquals(0, buf.readerIndex()); assertEquals(1000, msg.previewLong(m -> { m.skipBytes(6); return m.readLong(); })); assertEquals(0, buf.readerIndex()); assertEquals(1.01, msg.previewDouble(m -> { m.skipBytes(14); return m.readDouble(); }), 1000); assertEquals(0, buf.readerIndex()); assertEquals(1, buf.refCnt()); msg.release(); assertEquals(0, buf.refCnt()); }
NettyMessage extends InputStream implements DataReader, NetworkMessage<Object> { @Override public void handleAsync(Executor worker, Consumer<NetworkMessage<Object>> handler) { ArgAssert.notNull(worker, "Worker"); ArgAssert.notNull(handler, "Handler"); buf.retain(); worker.execute(() -> { try { handler.accept(this); } finally { buf.release(); } }); } NettyMessage(ByteBuf buf, Codec<Object> codec); void prepare(Logger log); boolean release(); @Override Object decode(); @Override void handleAsync(Executor worker, Consumer<NetworkMessage<Object>> handler); @Override V preview(Preview<V> preview); @Override int previewInt(PreviewInt preview); @Override long previewLong(PreviewLong preview); @Override double previewDouble(PreviewDouble preview); @Override boolean previewBoolean(PreviewBoolean preview); @Override InputStream asStream(); @Override int available(); @Override int read(); @Override int read(byte[] b, int off, int len); @Override long skip(long n); @Override boolean readBoolean(); @Override byte readByte(); @Override char readChar(); @Override double readDouble(); @Override float readFloat(); @Override void readFully(byte[] b); @Override void readFully(byte[] b, int off, int len); @Override int readInt(); @Override @Deprecated String readLine(); @Override long readLong(); @Override short readShort(); @Override String readUTF(); @Override int readUnsignedByte(); @Override int readUnsignedShort(); @Override int skipBytes(int n); @Override boolean markSupported(); @Override void reset(); @Override void mark(int readLimit); @SuppressWarnings("unchecked") NetworkMessage<T> cast(); @Override String toString(); }
@Test public void testHandleAsync() throws Exception { ByteBuf buf = Unpooled.buffer(); buf.writeByte(1); NettyMessage msg = new NettyMessage(buf, new Codec<Object>() { @Override public boolean isStateful() { return false; } @Override public Class<Object> baseType() { return Object.class; } @Override public Object decode(DataReader in) throws IOException { return in.readByte(); } @Override public void encode(Object obj, DataWriter out) throws IOException { throw new AssertionError("Should not be called."); } }); Object val; ExecutorService thread = Executors.newSingleThreadExecutor(); try { Exchanger<Object> ref = new Exchanger<>(); msg.handleAsync(thread, m -> { try { ref.exchange(m.decode()); } catch (InterruptedException | IOException e) { } }); val = ref.exchange(null); } finally { thread.shutdownNow(); thread.awaitTermination(AWAIT_TIMEOUT, TimeUnit.SECONDS); } assertEquals((byte)1, val); assertEquals(1, buf.refCnt()); }
ZooKeeperSeedNodeProviderConfig { @Override public String toString() { return ToString.format(this); } String getConnectionString(); void setConnectionString(String connectionString); ZooKeeperSeedNodeProviderConfig withConnectionString(String connectionString); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); ZooKeeperSeedNodeProviderConfig withConnectTimeout(int connectTimeout); int getSessionTimeout(); void setSessionTimeout(int sessionTimeout); ZooKeeperSeedNodeProviderConfig withSessionTimeout(int sessionTimeout); String getBasePath(); void setBasePath(String basePath); ZooKeeperSeedNodeProviderConfig withBasePath(String basePath); int getCleanupInterval(); void setCleanupInterval(int cleanupInterval); ZooKeeperSeedNodeProviderConfig withCleanupInterval(int cleanupInterval); @Override String toString(); static final int DEFAULT_CONNECT_TIMEOUT; static final int DEFAULT_SESSION_TIMEOUT; static final int DEFAULT_CLEANUP_INTERVAL; static final String DEFAULT_BASE_PATH; }
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); }
ConsulRegistry extends FailbackRegistry { @Override protected void doRegister(URL url) { NewService newService = createServiceDef(url, this.ttl); try { this.consulClient.agentServiceRegister(newService); } catch (Exception e) { throw new RpcException( "Failed to register " + url + " to Consul " + getUrl() + ", cause: " + e.getMessage(), e); } } ConsulRegistry(URL url); @Override boolean isAvailable(); void keepAlive(URL url); }
@Test public void testRegister() { registry.doRegister(serviceUrl); } @Test public void registryService() throws Exception { registry.doRegister(serviceUrl); }
KetamaNodeLocator { public String getPrimary(final String key) { final List<String> rv = getNodesForKey(hash(key), 1); assert rv != null && rv.get(0) != null: "Found no node for key " + key; return rv.get(0); } KetamaNodeLocator(final List<String> nodes); void updateLocator(List<String> nodes); String getPrimary(final String key); List<String> getPriorityList(final String key, final int listSize); }
@Test public void testDistribution() { final int nodeSize = 10; final int keySize = 10000; final List<String> nodes = generateRandomStrings(nodeSize); final long start1 = System.currentTimeMillis(); final KetamaNodeLocator locator = new KetamaNodeLocator(nodes); assertTrue((System.currentTimeMillis() - start1) < 100); final int[] counts = new int[nodeSize]; for (int ix = 0; ix < nodeSize; ix++) { counts[ix] = 0; } final List<String> keys = generateRandomStrings(keySize); for (final String key : keys) { final String primary = locator.getPrimary(key); counts[nodes.indexOf(primary)] += 1; } final int min = (keySize * 7) / (nodeSize * 10); final int max = (keySize * 13) / (nodeSize * 10); int total = 0; boolean error = false; final StringBuilder sb = new StringBuilder("Key distribution error - \n"); for (int ix = 0; ix < nodeSize; ix++) { if (counts[ix] < min || counts[ix] > max) { error = true; sb.append(" !! "); } else { sb.append(" "); } sb.append(StringUtils.rightPad(nodes.get(ix), 12)).append(": ").append(counts[ix]).append("\n"); total += counts[ix]; } assertEquals(keySize, total); if (error) { fail(sb.toString()); } } @Test public void testWeightedDistribution() { final int nodeSize = 5; final int keySize = 10000; final List<String> nodes = generateRandomStrings(nodeSize); final List<String> weightedNodes = new ArrayList<String>(nodes); weightedNodes.add(nodes.get(3)); for (int ix = 0; ix < 4; ix++) { weightedNodes.add(nodes.get(4)); } final long start1 = System.currentTimeMillis(); final KetamaNodeLocator locator = new KetamaNodeLocator(weightedNodes); assertTrue((System.currentTimeMillis() - start1) < 100); final int[] counts = new int[nodeSize]; for (int ix = 0; ix < nodeSize; ix++) { counts[ix] = 0; } final List<String> keys = generateRandomStrings(keySize); for (final String key : keys) { final String primary = locator.getPrimary(key); counts[nodes.indexOf(primary)] += 1; } final int min = (keySize * 7) / (nodeSize * 2 * 10); final int max = (keySize * 13) / (nodeSize * 2 * 10); int total = 0; boolean error = false; final StringBuilder sb = new StringBuilder("Key distribution error - \n"); for (int ix = 0; ix < nodeSize; ix++) { int expectedMin = min; int expectedMax = max; if (ix == 3) { expectedMin = 2*min; expectedMax=2*max; } if (ix == 4) { expectedMin = 5*min; expectedMax=5*max; } if (counts[ix] < expectedMin || counts[ix] > expectedMax) { error = true; sb.append(" !! "); } else { sb.append(" "); } sb.append(StringUtils.rightPad(nodes.get(ix), 12)).append(": ").append(counts[ix]).append("\n"); total += counts[ix]; } assertEquals(keySize, total); if (error) { fail(sb.toString()); } }
KetamaNodeLocator { public List<String> getPriorityList(final String key, final int listSize) { final List<String> rv = getNodesForKey(hash(key), listSize); assert rv != null : "Found no node for key " + key; return rv; } KetamaNodeLocator(final List<String> nodes); void updateLocator(List<String> nodes); String getPrimary(final String key); List<String> getPriorityList(final String key, final int listSize); }
@Test public void testNodeListAtScale() { final int nodeSize = 10000; final List<String> nodes = generateRandomStrings(nodeSize); final long start1 = System.currentTimeMillis(); final KetamaNodeLocator locator = new KetamaNodeLocator(nodes); assertTrue((System.currentTimeMillis() - start1) < 5000); final List<String> keys = generateRandomStrings(5 + RandomUtils.nextInt(5)); for (final String key : keys) { final long start2 = System.currentTimeMillis(); final List<String> superlist = locator.getPriorityList(key, nodeSize); assertTrue((System.currentTimeMillis() - start2) < 200); assertEquals(nodeSize, superlist.size()); } }
ConsulRegistry extends FailbackRegistry { private void keepAlive() { for (URL url : new HashSet<URL>(getRegistered())) { if (url.getParameter(Constants.DYNAMIC_KEY, true)) { keepAlive(url); } } } ConsulRegistry(URL url); @Override boolean isAvailable(); void keepAlive(URL url); }
@Test public void keepAlive() { URL url = serviceUrl; registry.keepAlive(url); }
SourceTemplate { public SourceTemplate(Writer writer, String className, List<BsonDocumentObjectElement> annotatedElements) { this.writer = writer; this.className = className; this.annotatedElements = annotatedElements; } SourceTemplate(Writer writer, String className, List<BsonDocumentObjectElement> annotatedElements); void writeSource(); }
@Test() public void testSourceTemplate() throws Exception { List<BsonDocumentObjectElement> bsoes = getBSOE(); Writer w = new PrintWriter(System.out); SourceTemplate st = new SourceTemplate(w, "info.sunng.bason.BasonManager", bsoes); st.writeSource(); }
SessionTracker { void flushSessions(Date now) { if (shuttingDown.get()) { return; } sendSessions(now); } SessionTracker(Configuration configuration); }
@Test public void zeroSessionDelivery() { CustomDelivery sessionDelivery = new CustomDelivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { super.deliver(serializer, object, headers); fail("Should not be called if no sessions enqueued"); } }; configuration.sessionDelivery = sessionDelivery; sessionTracker.flushSessions(new Date()); assertFalse(sessionDelivery.delivered); } @Test public void zeroSessionCount() { CustomDelivery sessionDelivery = new CustomDelivery() {}; configuration.sessionDelivery = sessionDelivery; sessionTracker.flushSessions(new Date(10120000L)); sessionTracker.flushSessions(new Date(14000000L)); assertFalse(sessionDelivery.delivered); }
FilteredMap implements Map<String, Object> { @Override public Set<Entry<String, Object>> entrySet() { return filteredCopy.entrySet(); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testEntrySet() { Set<Map.Entry<String, Object>> entries = filteredMap.entrySet(); assertEquals(4, entries.size()); int expectedCount = 0; for (Map.Entry<String, Object> entry : entries) { String key = entry.getKey(); if (key.equals(KEY_FILTERED)) { expectedCount++; assertEquals(PLACEHOLDER_FILTERED, entry.getValue()); } else if (key.equals(KEY_UNFILTERED)) { expectedCount++; assertEquals(VAL_UNFILTERED, entry.getValue()); } else if (key.equals(KEY_NESTED)) { expectedCount++; Object value = entry.getValue(); assertTrue(value instanceof FilteredMap); } else if (key.equals(KEY_UNMODIFIABLE)) { expectedCount++; @SuppressWarnings("unchecked") Map<String, Object> nested = (Map<String, Object>) entry.getValue(); assertEquals(2, nested.entrySet().size()); } } assertEquals(4, expectedCount); }
Configuration { public boolean shouldAutoCaptureSessions() { return autoCaptureSessions.get(); } Configuration(String apiKey); void setAutoCaptureSessions(boolean autoCaptureSessions); boolean shouldAutoCaptureSessions(); void setSendUncaughtExceptions(boolean sendUncaughtExceptions); boolean shouldSendUncaughtExceptions(); void setEndpoints(String notify, String sessions); public String apiKey; public String appType; public String appVersion; public Delivery delivery; public Delivery sessionDelivery; public String[] filters; public String[] ignoreClasses; public String[] notifyReleaseStages; public String[] projectPackages; public String releaseStage; public boolean sendThreads; }
@Test public void testDefaults() { assertTrue(config.shouldAutoCaptureSessions()); }
Configuration { Map<String, String> getErrorApiHeaders() { Map<String, String> map = new HashMap<String, String>(); map.put(HEADER_API_PAYLOAD_VERSION, Report.PAYLOAD_VERSION); map.put(HEADER_API_KEY, apiKey); map.put(HEADER_BUGSNAG_SENT_AT, DateUtils.toIso8601(new Date())); return map; } Configuration(String apiKey); void setAutoCaptureSessions(boolean autoCaptureSessions); boolean shouldAutoCaptureSessions(); void setSendUncaughtExceptions(boolean sendUncaughtExceptions); boolean shouldSendUncaughtExceptions(); void setEndpoints(String notify, String sessions); public String apiKey; public String appType; public String appVersion; public Delivery delivery; public Delivery sessionDelivery; public String[] filters; public String[] ignoreClasses; public String[] notifyReleaseStages; public String[] projectPackages; public String releaseStage; public boolean sendThreads; }
@Test public void testErrorApiHeaders() { Map<String, String> headers = config.getErrorApiHeaders(); assertEquals(config.apiKey, headers.get("Bugsnag-Api-Key")); assertNotNull(headers.get("Bugsnag-Sent-At")); assertNotNull(headers.get("Bugsnag-Payload-Version")); }
Configuration { Map<String, String> getSessionApiHeaders() { Map<String, String> map = new HashMap<String, String>(); map.put(HEADER_API_PAYLOAD_VERSION, "1.0"); map.put(HEADER_API_KEY, apiKey); map.put(HEADER_BUGSNAG_SENT_AT, DateUtils.toIso8601(new Date())); return map; } Configuration(String apiKey); void setAutoCaptureSessions(boolean autoCaptureSessions); boolean shouldAutoCaptureSessions(); void setSendUncaughtExceptions(boolean sendUncaughtExceptions); boolean shouldSendUncaughtExceptions(); void setEndpoints(String notify, String sessions); public String apiKey; public String appType; public String appVersion; public Delivery delivery; public Delivery sessionDelivery; public String[] filters; public String[] ignoreClasses; public String[] notifyReleaseStages; public String[] projectPackages; public String releaseStage; public boolean sendThreads; }
@Test public void testSessionApiHeaders() { Map<String, String> headers = config.getSessionApiHeaders(); assertEquals(config.apiKey, headers.get("Bugsnag-Api-Key")); assertNotNull(headers.get("Bugsnag-Sent-At")); assertNotNull(headers.get("Bugsnag-Payload-Version")); }
Configuration { public void setEndpoints(String notify, String sessions) throws IllegalArgumentException { if (notify == null || notify.isEmpty()) { throw new IllegalArgumentException("Notify endpoint cannot be empty or null."); } else { if (delivery instanceof HttpDelivery) { ((HttpDelivery) delivery).setEndpoint(notify); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint"); } } boolean invalidSessionsEndpoint = sessions == null || sessions.isEmpty(); String sessionEndpoint = null; if (invalidSessionsEndpoint && this.autoCaptureSessions.get()) { LOGGER.warn("The session tracking endpoint has not been" + " set. Session tracking is disabled"); this.autoCaptureSessions.set(false); } else { sessionEndpoint = sessions; } if (sessionDelivery instanceof HttpDelivery) { ((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint); } else { LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint"); } } Configuration(String apiKey); void setAutoCaptureSessions(boolean autoCaptureSessions); boolean shouldAutoCaptureSessions(); void setSendUncaughtExceptions(boolean sendUncaughtExceptions); boolean shouldSendUncaughtExceptions(); void setEndpoints(String notify, String sessions); public String apiKey; public String appType; public String appVersion; public Delivery delivery; public Delivery sessionDelivery; public String[] filters; public String[] ignoreClasses; public String[] notifyReleaseStages; public String[] projectPackages; public String releaseStage; public boolean sendThreads; }
@Test public void testEndpoints() { String notify = "https: String sessions = "https: config.setEndpoints(notify, sessions); assertEquals(notify, getDeliveryEndpoint(config.delivery)); assertEquals(sessions, getDeliveryEndpoint(config.sessionDelivery)); } @Test(expected = IllegalArgumentException.class) public void testNullNotifyEndpoint() { config.setEndpoints(null, "http: } @Test(expected = IllegalArgumentException.class) public void testEmptyNotifyEndpoint() { config.setEndpoints("", "http: } @Test public void testInvalidSessionWarningLogged() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); config.setEndpoints("http: String logMsg = new String(baos.toByteArray()); assertTrue(logMsg.contains("The session tracking endpoint " + "has not been set. Session tracking is disabled")); } @Test public void testBaseDeliveryIgnoresEndpoint() { Delivery delivery = new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { } @Override public void close() { } }; config.delivery = delivery; config.sessionDelivery = delivery; ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); config.setEndpoints("http: String logMsg = new String(baos.toByteArray()); assertTrue(logMsg.contains("Delivery is not instance of " + "HttpDelivery, cannot set notify endpoint")); assertTrue(logMsg.contains("Delivery is not instance of " + "HttpDelivery, cannot set sessions endpoint")); }
Bugsnag implements Closeable { public static Set<Bugsnag> uncaughtExceptionClients() { UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler(); if (handler instanceof ExceptionHandler) { ExceptionHandler bugsnagHandler = (ExceptionHandler) handler; return Collections.unmodifiableSet(bugsnagHandler.uncaughtExceptionClients()); } return Collections.emptySet(); } Bugsnag(String apiKey); Bugsnag(String apiKey, boolean sendUncaughtExceptions); void addCallback(Callback callback); Delivery getDelivery(); Delivery getSessionDelivery(); void setAppType(String appType); void setAppVersion(String appVersion); void setDelivery(Delivery delivery); void setSessionDelivery(Delivery delivery); @Deprecated void setEndpoint(String endpoint); void setFilters(String... filters); void setIgnoreClasses(String... ignoreClasses); void setNotifyReleaseStages(String... notifyReleaseStages); void setProjectPackages(String... projectPackages); void setProxy(Proxy proxy); void setReleaseStage(String releaseStage); void setSendThreads(boolean sendThreads); void setTimeout(int timeout); Report buildReport(Throwable throwable); boolean notify(Throwable throwable); boolean notify(Throwable throwable, Callback callback); boolean notify(Throwable throwable, Severity severity); boolean notify(Throwable throwable, Severity severity, Callback callback); boolean notify(Report report); boolean notify(Report report, Callback reportCallback); void startSession(); void setAutoCaptureSessions(boolean autoCaptureSessions); boolean shouldAutoCaptureSessions(); @Deprecated void setSessionEndpoint(String endpoint); void setEndpoints(String notify, String sessions); @Override void close(); static void addThreadMetaData(String tabName, String key, Object value); static void clearThreadMetaData(); static void clearThreadMetaData(String tabName); static void clearThreadMetaData(String tabName, String key); static Set<Bugsnag> uncaughtExceptionClients(); }
@Test(expected = UnsupportedOperationException.class) public void testUncaughtHandlerModification() { Set<Bugsnag> bugsnags = Bugsnag.uncaughtExceptionClients(); bugsnags.clear(); }
MetaData extends HashMap<String, Object> { public void addToTab(String tabName, String key, Object value) { Map<String, Object> tab = getTab(tabName); tab.put(key, value); } void addToTab(String tabName, String key, Object value); }
@Test @SuppressWarnings("unchecked") public void testSingleTabSingleValue() { MetaData metaData = new MetaData(); metaData.addToTab("tab-name", "key-1", "value-1"); assertEquals(1, metaData.size()); assertEquals(1, ((Map<String, Object>) metaData.get("tab-name")).size()); assertEquals("value-1", ((Map<String, Object>) metaData.get("tab-name")).get("key-1")); } @Test @SuppressWarnings("unchecked") public void testSingleTabMultipleValues() { MetaData metaData = new MetaData(); metaData.addToTab("tab-name", "key-1", "value-1"); metaData.addToTab("tab-name", "key-2", "value-2"); assertEquals(1, metaData.size()); assertEquals(2, ((Map<String, Object>) metaData.get("tab-name")).size()); assertEquals("value-1", ((Map<String, Object>) metaData.get("tab-name")).get("key-1")); assertEquals("value-2", ((Map<String, Object>) metaData.get("tab-name")).get("key-2")); } @Test @SuppressWarnings("unchecked") public void testMultipleTabs() { MetaData metaData = new MetaData(); metaData.addToTab("tab-name-1", "key-1", "value-1"); metaData.addToTab("tab-name-2", "key-1", "value-1"); assertEquals(2, metaData.size()); assertEquals(1, ((Map<String, Object>) metaData.get("tab-name-1")).size()); assertEquals(1, ((Map<String, Object>) metaData.get("tab-name-2")).size()); assertEquals("value-1", ((Map<String, Object>) metaData.get("tab-name-1")).get("key-1")); assertEquals("value-1", ((Map<String, Object>) metaData.get("tab-name-1")).get("key-1")); }
MetaData extends HashMap<String, Object> { void clearTab(String tabName) { remove(tabName); } void addToTab(String tabName, String key, Object value); }
@Test @SuppressWarnings("unchecked") public void testClearTab() { MetaData metaData = new MetaData(); metaData.addToTab("tab-name-1", "key-1", "value-1"); metaData.addToTab("tab-name-2", "key-1", "value-1"); assertEquals(2, metaData.size()); metaData.clearTab("tab-name-1"); assertEquals(1, metaData.size()); assertNull(metaData.get("tab-name-1")); assertEquals(1, ((Map<String, Object>) metaData.get("tab-name-2")).size()); }
HandledState { static HandledState newInstance(SeverityReasonType severityReasonType) { return newInstance(severityReasonType, Collections.<String, String>emptyMap(), null, false); } private HandledState(SeverityReasonType severityReasonType, Map<String, String> severityReasonAttributes, Severity currentSeverity, boolean unhandled); }
@Test(expected = IllegalArgumentException.class) public void testInvalidUserSpecified() { HandledState.newInstance( HandledState.SeverityReasonType.REASON_CALLBACK_SPECIFIED); }
ThreadState { @JsonProperty("id") public long getId() { return thread.getId(); } ThreadState(Configuration config, Thread thread, StackTraceElement[] stackTraceElements); @JsonProperty("id") long getId(); @JsonProperty("name") String getName(); @JsonProperty("stacktrace") List<Stackframe> getStacktrace(); @JsonProperty("errorReportingThread") Boolean isErrorReportingThread(); void setErrorReportingThread(Boolean errorReportingThread); }
@Test public void testThreadStateContainsCurrentThread() { int count = 0; for (ThreadState thread : threadStates) { if (thread.getId() == Thread.currentThread().getId()) { count++; } } assertEquals(1, count); } @Test public void testCurrentThread() throws IOException { JsonNode root = serialiseThreadStateToJson(threadStates); long currentThreadId = Thread.currentThread().getId(); int currentThreadCount = 0; for (JsonNode jsonNode : root) { if (currentThreadId == jsonNode.get("id").asLong()) { assertTrue(jsonNode.get("errorReportingThread").asBoolean()); currentThreadCount++; } else { assertFalse(jsonNode.has("errorReportingThread")); } } assertEquals(1, currentThreadCount); }
ThreadState { @JsonProperty("name") public String getName() { return thread.getName(); } ThreadState(Configuration config, Thread thread, StackTraceElement[] stackTraceElements); @JsonProperty("id") long getId(); @JsonProperty("name") String getName(); @JsonProperty("stacktrace") List<Stackframe> getStacktrace(); @JsonProperty("errorReportingThread") Boolean isErrorReportingThread(); void setErrorReportingThread(Boolean errorReportingThread); }
@Test public void testThreadName() { for (ThreadState threadState : threadStates) { assertNotNull(threadState.getName()); } }
ThreadState { @JsonProperty("stacktrace") public List<Stackframe> getStacktrace() { return Stackframe.getStacktrace(config, stackTraceElements); } ThreadState(Configuration config, Thread thread, StackTraceElement[] stackTraceElements); @JsonProperty("id") long getId(); @JsonProperty("name") String getName(); @JsonProperty("stacktrace") List<Stackframe> getStacktrace(); @JsonProperty("errorReportingThread") Boolean isErrorReportingThread(); void setErrorReportingThread(Boolean errorReportingThread); }
@Test public void testThreadStacktrace() { for (ThreadState threadState : threadStates) { List<Stackframe> stacktrace = threadState.getStacktrace(); assertNotNull(stacktrace); } }
ScheduledTaskConfiguration implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { BugsnagScheduledTaskExceptionHandler bugsnagErrorHandler = new BugsnagScheduledTaskExceptionHandler(bugsnag); TaskScheduler registrarScheduler = taskRegistrar.getScheduler(); TaskScheduler taskScheduler = registrarScheduler != null ? registrarScheduler : beanLocator.resolveTaskScheduler(); if (taskScheduler != null) { configureExistingTaskScheduler(taskScheduler, bugsnagErrorHandler); } else { ScheduledExecutorService executorService = beanLocator.resolveScheduledExecutorService(); taskScheduler = createNewTaskScheduler(executorService, bugsnagErrorHandler); taskRegistrar.setScheduler(taskScheduler); } } @Override void configureTasks(ScheduledTaskRegistrar taskRegistrar); }
@Test public void existingSchedulerUsed() { ThreadPoolTaskScheduler expected = new ThreadPoolTaskScheduler(); registrar.setScheduler(expected); configuration.configureTasks(registrar); assertEquals(expected, registrar.getScheduler()); } @Test public void noSchedulersAvailable() { configuration.configureTasks(registrar); assertTrue(registrar.getScheduler() instanceof ThreadPoolTaskScheduler); } @Test public void findSchedulerByType() throws NoSuchFieldException, IllegalAccessException { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); when(context.getBean(TaskScheduler.class)).thenReturn(scheduler); configuration.configureTasks(registrar); assertNull(registrar.getScheduler()); Object errorHandler = accessField(scheduler, "errorHandler"); assertTrue(errorHandler instanceof BugsnagScheduledTaskExceptionHandler); } @Test public void findSchedulerByName() throws NoSuchFieldException, IllegalAccessException { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); Throwable exc = new NoUniqueBeanDefinitionException(TaskScheduler.class); when(context.getBean(TaskScheduler.class)).thenThrow(exc); when(context.getBean("taskScheduler", TaskScheduler.class)).thenReturn(scheduler); configuration.configureTasks(registrar); assertNull(registrar.getScheduler()); Object errorHandler = accessField(scheduler, "errorHandler"); assertTrue(errorHandler instanceof BugsnagScheduledTaskExceptionHandler); } @Test public void findExecutorByType() throws NoSuchFieldException, IllegalAccessException { ScheduledExecutorService expected = Executors.newScheduledThreadPool(1); when(context.getBean(ScheduledExecutorService.class)).thenReturn(expected); configuration.configureTasks(registrar); TaskScheduler scheduler = registrar.getScheduler(); assertTrue(scheduler instanceof ConcurrentTaskScheduler); assertEquals(expected, accessField(scheduler, "scheduledExecutor")); } @Test public void findExecutorByName() throws NoSuchFieldException, IllegalAccessException { ScheduledExecutorService expected = Executors.newScheduledThreadPool(4); Throwable exc = new NoUniqueBeanDefinitionException(ScheduledExecutorService.class); when(context.getBean(ScheduledExecutorService.class)).thenThrow(exc); when(context.getBean("taskScheduler", ScheduledExecutorService.class)) .thenReturn(expected); configuration.configureTasks(registrar); TaskScheduler scheduler = registrar.getScheduler(); assertTrue(scheduler instanceof ConcurrentTaskScheduler); assertEquals(expected, accessField(scheduler, "scheduledExecutor")); }
FilteredMap implements Map<String, Object> { @Override public int size() { return filteredCopy.size(); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testSize() { assertEquals(4, filteredMap.size()); }
ScheduledTaskBeanLocator implements ApplicationContextAware { TaskScheduler resolveTaskScheduler() { return resolveSchedulerBean(TaskScheduler.class); } @Override void setApplicationContext(ApplicationContext applicationContext); }
@Test public void findSchedulerByType() { ThreadPoolTaskScheduler expected = new ThreadPoolTaskScheduler(); when(context.getBean(TaskScheduler.class)).thenReturn(expected); assertEquals(expected, beanLocator.resolveTaskScheduler()); } @Test public void findSchedulerByName() { ThreadPoolTaskScheduler expected = new ThreadPoolTaskScheduler(); Throwable exc = new NoUniqueBeanDefinitionException(TaskScheduler.class); when(context.getBean(TaskScheduler.class)).thenThrow(exc); when(context.getBean("taskScheduler", TaskScheduler.class)).thenReturn(expected); assertEquals(expected, beanLocator.resolveTaskScheduler()); } @Test public void noTaskSchedulerAvailable() { assertNull(beanLocator.resolveTaskScheduler()); }
ScheduledTaskBeanLocator implements ApplicationContextAware { ScheduledExecutorService resolveScheduledExecutorService() { return resolveSchedulerBean(ScheduledExecutorService.class); } @Override void setApplicationContext(ApplicationContext applicationContext); }
@Test public void findExecutorByType() { ScheduledExecutorService expected = Executors.newScheduledThreadPool(1); when(context.getBean(ScheduledExecutorService.class)).thenReturn(expected); assertEquals(expected, beanLocator.resolveScheduledExecutorService()); } @Test public void findExecutorByName() { ScheduledExecutorService expected = Executors.newScheduledThreadPool(4); Throwable exc = new NoUniqueBeanDefinitionException(ScheduledExecutorService.class); when(context.getBean(ScheduledExecutorService.class)).thenThrow(exc); when(context.getBean("taskScheduler", ScheduledExecutorService.class)) .thenReturn(expected); assertEquals(expected, beanLocator.resolveScheduledExecutorService()); } @Test public void noScheduledExecutorAvailable() { assertNull(beanLocator.resolveScheduledExecutorService()); }
FilteredMap implements Map<String, Object> { @Override public boolean isEmpty() { return filteredCopy.isEmpty(); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testIsEmpty() { assertFalse(filteredMap.isEmpty()); Map<String, Object> map = Collections.emptyMap(); FilteredMap emptyMap = new FilteredMap(map, Collections.<String>emptyList()); assertTrue(emptyMap.isEmpty()); }
FilteredMap implements Map<String, Object> { @Override public void clear() { filteredCopy.clear(); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testClear() { assertEquals(4, filteredMap.size()); filteredMap.clear(); assertTrue(filteredMap.isEmpty()); }
FilteredMap implements Map<String, Object> { @Override public boolean containsKey(Object key) { return filteredCopy.containsKey(key); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testContainsKey() { assertTrue(filteredMap.containsKey(KEY_FILTERED)); assertTrue(filteredMap.containsKey(KEY_UNFILTERED)); assertTrue(filteredMap.containsKey(KEY_NESTED)); assertFalse(filteredMap.containsKey("fake")); }
FilteredMap implements Map<String, Object> { @Override public Object remove(Object key) { return filteredCopy.remove(key); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testRemove() { HashMap<String, Object> map = new HashMap<String, Object>(); map.put(KEY_UNFILTERED, VAL_UNFILTERED); map.put(KEY_FILTERED, VAL_FILTERED); HashMap<String, Object> emptyMap = new HashMap<String, Object>(); Set<String> filters = Collections.singleton(KEY_FILTERED); Map<String, Object> removeMap = new FilteredMap(emptyMap, filters); removeMap.putAll(map); assertEquals(2, removeMap.size()); removeMap.remove(KEY_FILTERED); assertEquals(1, removeMap.size()); removeMap.remove(KEY_UNFILTERED); assertEquals(0, removeMap.size()); }
FilteredMap implements Map<String, Object> { @Override public Object get(Object key) { return filteredCopy.get(key); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testGet() { assertEquals(PLACEHOLDER_FILTERED, filteredMap.get(KEY_FILTERED)); assertEquals(VAL_UNFILTERED, filteredMap.get(KEY_UNFILTERED)); Object actual = filteredMap.get(KEY_NESTED); assertTrue(actual instanceof FilteredMap); @SuppressWarnings("unchecked") Map<String, Object> nestedMap = (Map<String, Object>) actual; assertEquals(VAL_UNFILTERED, nestedMap.get(KEY_UNFILTERED)); assertEquals(PLACEHOLDER_FILTERED, nestedMap.get(KEY_FILTERED)); }
FilteredMap implements Map<String, Object> { @Override public Set<String> keySet() { return filteredCopy.keySet(); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testKeySet() { Set<String> keySet = filteredMap.keySet(); assertEquals(4, keySet.size()); assertTrue(keySet.contains(KEY_FILTERED)); assertTrue(keySet.contains(KEY_UNFILTERED)); assertTrue(keySet.contains(KEY_NESTED)); }
FilteredMap implements Map<String, Object> { @Override public Collection<Object> values() { return filteredCopy.values(); } FilteredMap(Map<String, Object> map, Collection<String> keyFilters); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Object get(Object key); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void putAll(Map<? extends String, ?> mapValues); @Override void clear(); @Override Set<String> keySet(); @Override Collection<Object> values(); @Override Set<Entry<String, Object>> entrySet(); }
@Test public void testValues() { Collection<Object> values = filteredMap.values(); assertEquals(4, values.size()); assertTrue(values.contains(VAL_UNFILTERED)); assertTrue(values.contains(PLACEHOLDER_FILTERED)); values.remove(PLACEHOLDER_FILTERED); values.remove(VAL_UNFILTERED); Object nestedObj = values.toArray(new Object[1])[0]; assertTrue(nestedObj instanceof FilteredMap); @SuppressWarnings("unchecked") Map<String, Object> nestedMap = (Map<String, Object>) nestedObj; values = nestedMap.values(); assertEquals(2, values.size()); assertTrue(values.contains(VAL_UNFILTERED)); assertTrue(values.contains(PLACEHOLDER_FILTERED)); }
Config { public String getApiHost() { return apiHost; } Config(String clientId, String secret, String apiHost, boolean useHttps, List<Scope> scopes, OkHttpClient httpClient, HttpLoggingInterceptor.Level httpLoggingLevel); String getClientId(); String getSecret(); String getApiHost(); boolean useHttps(); List<Scope> getScopes(); OkHttpClient okHttpClient(); HttpLoggingInterceptor.Level level(); static Builder with(); }
@Test public void apiHost_shouldRemoveScheme() { Config c = newConfig("hostwithhttp.com:1234"); assertThat(c.getApiHost()).isEqualTo("hostwithhttp.com:1234"); assertThat( newConfig("http: assertThat( newConfig("https: }
Fortran { public static double aint(double n) { return (n >= 0 ? Math.floor(n) : Math.ceil(n)); } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test public void testAint() { assertEquals(3d, Fortran.aint(3.6d), DELTA); assertEquals(3d, Fortran.aint(3.4d), DELTA); assertEquals(-3d, Fortran.aint(-3.6d), DELTA); assertEquals(-3d, Fortran.aint(-3.4d), DELTA); assertEquals(3f, Fortran.aint(3.6f), DELTA); assertEquals(3f, Fortran.aint(3.4f), DELTA); assertEquals(-3f, Fortran.aint(-3.6f), DELTA); assertEquals(-3f, Fortran.aint(-3.4f), DELTA); }
Fortran { public static double modulo(double a, double p) { if (p == 0) throw new ArithmeticException("p == 0"); return a - floor(a / p) * p; } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test(expected=ArithmeticException.class) public void testModuloIntegerZero() { Fortran.modulo(10, 0); } @Test(expected=ArithmeticException.class) public void testModuloLongZero() { Fortran.modulo(10L, 0L); } @Test public void testModulo() { assertEquals(1d, Fortran.modulo(4d, 3d), DELTA); assertEquals(1f, Fortran.modulo(4f, 3f), DELTA); assertEquals(2d, Fortran.modulo(12d, 5d), DELTA); assertEquals(2f, Fortran.modulo(12f, 5f), DELTA); assertEquals(0.1d, Fortran.modulo(9.7d, 4.8d), DELTA); assertEquals(0.1f, Fortran.modulo(9.7f, 4.8f), DELTA); assertEquals(1, Fortran.modulo(4, 3)); assertEquals(1L, Fortran.modulo(4L, 3L)); assertEquals(2, Fortran.modulo(12, 5)); assertEquals(2L, Fortran.modulo(12L, 5L)); assertEquals(-2d, Fortran.modulo(4d, -3d), DELTA); assertEquals(-2f, Fortran.modulo(4f, -3f), DELTA); assertEquals(-3d, Fortran.modulo(12d, -5d), DELTA); assertEquals(-3f, Fortran.modulo(12f, -5f), DELTA); assertEquals(-4.7d, Fortran.modulo(9.7d, -4.8d), DELTA); assertEquals(-4.7f, Fortran.modulo(9.7f, -4.8f), DELTA); assertEquals(-2, Fortran.modulo(4, -3)); assertEquals(-2L, Fortran.modulo(4L, -3L)); assertEquals(-3, Fortran.modulo(12, -5)); assertEquals(-3L, Fortran.modulo(12L, -5L)); assertEquals(2d, Fortran.modulo(-4d, 3d), DELTA); assertEquals(2f, Fortran.modulo(-4f, 3f), DELTA); assertEquals(3d, Fortran.modulo(-12d, 5d), DELTA); assertEquals(3f, Fortran.modulo(-12f, 5f), DELTA); assertEquals(4.7d, Fortran.modulo(-9.7d, 4.8d), DELTA); assertEquals(4.7f, Fortran.modulo(-9.7f, 4.8f), DELTA); assertEquals(2, Fortran.modulo(-4, 3)); assertEquals(2L, Fortran.modulo(-4L, 3L)); assertEquals(3, Fortran.modulo(-12, 5)); assertEquals(3L, Fortran.modulo(-12L, 5L)); assertEquals(-1d, Fortran.modulo(-4d, -3d), DELTA); assertEquals(-1f, Fortran.modulo(-4f, -3f), DELTA); assertEquals(-2d, Fortran.modulo(-12d, -5d), DELTA); assertEquals(-2f, Fortran.modulo(-12f, -5f), DELTA); assertEquals(-0.1d, Fortran.modulo(-9.7d, -4.8d), DELTA); assertEquals(-0.1f, Fortran.modulo(-9.7f, -4.8f), DELTA); assertEquals(-1, Fortran.modulo(-4, -3)); assertEquals(-1L, Fortran.modulo(-4L, -3L)); assertEquals(-2, Fortran.modulo(-12, -5)); assertEquals(-2L, Fortran.modulo(-12L, -5L)); } @Test(expected=ArithmeticException.class) public void testModuloDoubleZero() { Fortran.modulo(10d, 0d); } @Test(expected=ArithmeticException.class) public void testModuloFloatZero() { Fortran.modulo(10f, 0f); }
Fortran { public static int nint(double n) { if (n > 0.0) return MathUtils.toIntExact(n + 0.5); else if (n < 0.0) return MathUtils.toIntExact(n - 0.5); else return 0; } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test public void testNint() { assertEquals(4, Fortran.nint(3.6d)); assertEquals(4, Fortran.nint(3.5d)); assertEquals(3, Fortran.nint(3.4d)); assertEquals(-4, Fortran.nint(-3.6d)); assertEquals(-4, Fortran.nint(-3.5d)); assertEquals(-3, Fortran.nint(-3.4d)); assertEquals(4, Fortran.nint(3.6f)); assertEquals(4, Fortran.nint(3.5f)); assertEquals(3, Fortran.nint(3.4f)); assertEquals(-4, Fortran.nint(-3.6f)); assertEquals(-4, Fortran.nint(-3.5f)); assertEquals(-3, Fortran.nint(-3.4f)); try { Fortran.nint(1e100); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { Fortran.nint(1e30f); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } }
Fortran { public static double sum(double... args) { double sum = 0; for (double n: args) sum += n; return sum; } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test public void testSum() { assertEquals(0d, Fortran.sum(new double[] {}), DELTA); assertEquals(5d, Fortran.sum(new double[] { 5 }), DELTA); assertEquals(15d, Fortran.sum(new double[] { 2, 5, 1, 3, 4 }), DELTA); assertEquals(0f, Fortran.sum(new float[] {}), DELTA); assertEquals(5f, Fortran.sum(new float[] { 5 }), DELTA); assertEquals(15f, Fortran.sum(new float[] { 2, 5, 1, 3, 4 }), DELTA); assertEquals(0, Fortran.sum(new int[] {})); assertEquals(5, Fortran.sum(new int[] { 5 })); assertEquals(15, Fortran.sum(new int[] { 2, 5, 1, 3, 4 })); assertEquals(0L, Fortran.sum(new long[] {})); assertEquals(5L, Fortran.sum(new long[] { 5 })); assertEquals(15L, Fortran.sum(new long[] { 2, 5, 1, 3, 4 })); try { Fortran.sum(new int[] { Integer.MAX_VALUE, 1 }); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { Fortran.sum(new long[] { Long.MAX_VALUE, 1 }); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } }
SubdivisionSearch { public SubdivisionElement find(PointD q) { if (_tree instanceof Trapezoid) return SubdivisionElement.NULL_FACE; return ((Node) _tree).find(q); } SubdivisionSearch(Subdivision source, boolean ordered); SubdivisionElement find(PointD q); String format(); void validate(); final double epsilon; final Subdivision source; }
@Test public void testSingleEdgeX() { final SubdivisionSearch search = checkSearch(new LineD(-5, 0, +5, 0)); assertTrue(search.find(new PointD(0, -1)).isUnboundedFace()); assertTrue(search.find(new PointD(0, +1)).isUnboundedFace()); assertTrue(search.find(new PointD(-6, 0)).isUnboundedFace()); assertTrue(search.find(new PointD(+6, 0)).isUnboundedFace()); } @Test public void testSingleEdgeY() { final SubdivisionSearch search = checkSearch(new LineD(0, -5, 0, +5)); assertTrue(search.find(new PointD(-1, 0)).isUnboundedFace()); assertTrue(search.find(new PointD(+1, 0)).isUnboundedFace()); assertTrue(search.find(new PointD(0, -6)).isUnboundedFace()); assertTrue(search.find(new PointD(0, +6)).isUnboundedFace()); }
Subdivision implements Graph<PointD> { public SubdivisionEdge findEdge(PointD origin, PointD destination) { final SubdivisionEdge edge = _vertices.get(origin); if (edge == null) return null; return (epsilon == 0 ? edge.findEdgeTo(destination) : edge.findEdgeTo(destination, epsilon)); } Subdivision(double epsilon); NavigableMap<Integer, SubdivisionEdge> edges(); NavigableMap<Integer, SubdivisionFace> faces(); boolean isEmpty(); Map<PointD, PointD[]> vertexRegions(); NavigableMap<PointD, SubdivisionEdge> vertices(); AddEdgeResult addEdge(PointD start, PointD end); Subdivision copy(); SubdivisionElement find(PointD q, double epsilon); SubdivisionEdge findEdge(PointD origin, PointD destination); SubdivisionFace findFace(PointD q); SubdivisionFace findFace(PointD[] polygon, boolean verify); FindEdgeResult findNearestEdge(PointD q); PointD findNearestVertex(PointD q); static Subdivision fromLines(LineD[] lines, double epsilon); static Subdivision fromPolygons(PointD[][] polygons, double epsilon); SubdivisionEdge[] getEdgesByOrigin(); List<SubdivisionEdge> getZeroAreaCycles(); static SubdivisionIntersection intersection(Subdivision division1, Subdivision division2); boolean moveVertex(PointD oldVertex, PointD newVertex); RemoveEdgeResult removeEdge(int edgeKey); boolean removeVertex(PointD vertex); boolean renumberEdges(); boolean renumberFaces(); SubdivisionEdge splitEdge(int edgeKey); boolean structureEquals(Subdivision division); LineD[] toLines(); PointD[][] toPolygons(); void validate(); @Override int connectivity(); @Override int nodeCount(); @Override Set<PointD> nodes(); @Override boolean contains(PointD node); @Override PointD findNearestNode(PointD location); @Override double getDistance(PointD source, PointD target); @Override List<PointD> getNeighbors(PointD node); @Override PointD getWorldLocation(PointD node); @Override PointD[] getWorldRegion(PointD node); final double epsilon; }
@Test public void testFindEdge() { final PointD[] points = { new PointD(0, 0), new PointD(-1, -2), new PointD(-1, 2), new PointD(1, 2), new PointD(1, -2) }; final LineD[] lines = { new LineD(points[1], points[0]), new LineD(points[0], points[2]), new LineD(points[0], points[3]), new LineD(points[4], points[0]) }; final Subdivision division = Subdivision.fromLines(lines, 0); division.validate(); for (SubdivisionEdge edge: division.edges().values()) assertSame(edge, division.findEdge(edge.origin(), edge.destination())); for (int i = 0; i < points.length; i++) { assertNull(division.findEdge(points[i], new PointD(1, 0))); assertNull(division.findEdge(new PointD(1, 0), points[i])); if (i == 0) continue; for (int j = 1; j < points.length; j++) if (j != i) assertNull(division.findEdge(points[i], points[j])); } }
Subdivision implements Graph<PointD> { public FindEdgeResult findNearestEdge(PointD q) { final SubdivisionFace face = findFace(q); return face.findNearestEdge(q); } Subdivision(double epsilon); NavigableMap<Integer, SubdivisionEdge> edges(); NavigableMap<Integer, SubdivisionFace> faces(); boolean isEmpty(); Map<PointD, PointD[]> vertexRegions(); NavigableMap<PointD, SubdivisionEdge> vertices(); AddEdgeResult addEdge(PointD start, PointD end); Subdivision copy(); SubdivisionElement find(PointD q, double epsilon); SubdivisionEdge findEdge(PointD origin, PointD destination); SubdivisionFace findFace(PointD q); SubdivisionFace findFace(PointD[] polygon, boolean verify); FindEdgeResult findNearestEdge(PointD q); PointD findNearestVertex(PointD q); static Subdivision fromLines(LineD[] lines, double epsilon); static Subdivision fromPolygons(PointD[][] polygons, double epsilon); SubdivisionEdge[] getEdgesByOrigin(); List<SubdivisionEdge> getZeroAreaCycles(); static SubdivisionIntersection intersection(Subdivision division1, Subdivision division2); boolean moveVertex(PointD oldVertex, PointD newVertex); RemoveEdgeResult removeEdge(int edgeKey); boolean removeVertex(PointD vertex); boolean renumberEdges(); boolean renumberFaces(); SubdivisionEdge splitEdge(int edgeKey); boolean structureEquals(Subdivision division); LineD[] toLines(); PointD[][] toPolygons(); void validate(); @Override int connectivity(); @Override int nodeCount(); @Override Set<PointD> nodes(); @Override boolean contains(PointD node); @Override PointD findNearestNode(PointD location); @Override double getDistance(PointD source, PointD target); @Override List<PointD> getNeighbors(PointD node); @Override PointD getWorldLocation(PointD node); @Override PointD[] getWorldRegion(PointD node); final double epsilon; }
@Test public void testFindNearestEdge() { final Subdivision division = SubdivisionLinesTest.createSquareStar(false); assertEquals(division.edges().get(0), division.findNearestEdge(new PointD(-1.1, 0)).edge); assertEquals(division.edges().get(1), division.findNearestEdge(new PointD(-0.9, 0)).edge); assertEquals(division.edges().get(2), division.findNearestEdge(new PointD(0, 2.1)).edge); assertEquals(division.edges().get(3), division.findNearestEdge(new PointD(0, 1.9)).edge); assertEquals(division.edges().get(4), division.findNearestEdge(new PointD(0.9, 0)).edge); assertEquals(division.edges().get(5), division.findNearestEdge(new PointD(1.1, 0)).edge); assertEquals(division.edges().get(6), division.findNearestEdge(new PointD(0, -1.9)).edge); assertEquals(division.edges().get(7), division.findNearestEdge(new PointD(0, -2.1)).edge); assertEquals(division.edges().get(8), division.findNearestEdge(new PointD(-0.5, -1.1)).edge); assertEquals(division.edges().get(9), division.findNearestEdge(new PointD(-0.5, -0.9)).edge); assertEquals(division.edges().get(10), division.findNearestEdge(new PointD(-0.5, 0.9)).edge); assertEquals(division.edges().get(11), division.findNearestEdge(new PointD(-0.5, 1.1)).edge); assertEquals(division.edges().get(12), division.findNearestEdge(new PointD(0.5, 1.1)).edge); assertEquals(division.edges().get(13), division.findNearestEdge(new PointD(0.5, 0.9)).edge); assertEquals(division.edges().get(14), division.findNearestEdge(new PointD(0.5, -0.9)).edge); assertEquals(division.edges().get(15), division.findNearestEdge(new PointD(0.5, -1.1)).edge); }
Subdivision implements Graph<PointD> { public boolean structureEquals(Subdivision division) { if (_nextEdgeKey != division._nextEdgeKey) return false; if (_nextFaceKey != division._nextFaceKey) return false; if (_faces.size() != division._faces.size()) return false; if (_vertices.size() != division._vertices.size()) return false; for (PointD key: _vertices.keySet()) { final SubdivisionEdge edge = _vertices.get(key); final SubdivisionEdge otherEdge = division._vertices.get(key); if (!edge.equals(otherEdge)) return false; } for (int key: _faces.keySet()) { final SubdivisionFace face = _faces.get(key); final SubdivisionFace otherFace = division._faces.get(key); if (!face.equals(otherFace)) return false; } return true; } Subdivision(double epsilon); NavigableMap<Integer, SubdivisionEdge> edges(); NavigableMap<Integer, SubdivisionFace> faces(); boolean isEmpty(); Map<PointD, PointD[]> vertexRegions(); NavigableMap<PointD, SubdivisionEdge> vertices(); AddEdgeResult addEdge(PointD start, PointD end); Subdivision copy(); SubdivisionElement find(PointD q, double epsilon); SubdivisionEdge findEdge(PointD origin, PointD destination); SubdivisionFace findFace(PointD q); SubdivisionFace findFace(PointD[] polygon, boolean verify); FindEdgeResult findNearestEdge(PointD q); PointD findNearestVertex(PointD q); static Subdivision fromLines(LineD[] lines, double epsilon); static Subdivision fromPolygons(PointD[][] polygons, double epsilon); SubdivisionEdge[] getEdgesByOrigin(); List<SubdivisionEdge> getZeroAreaCycles(); static SubdivisionIntersection intersection(Subdivision division1, Subdivision division2); boolean moveVertex(PointD oldVertex, PointD newVertex); RemoveEdgeResult removeEdge(int edgeKey); boolean removeVertex(PointD vertex); boolean renumberEdges(); boolean renumberFaces(); SubdivisionEdge splitEdge(int edgeKey); boolean structureEquals(Subdivision division); LineD[] toLines(); PointD[][] toPolygons(); void validate(); @Override int connectivity(); @Override int nodeCount(); @Override Set<PointD> nodes(); @Override boolean contains(PointD node); @Override PointD findNearestNode(PointD location); @Override double getDistance(PointD source, PointD target); @Override List<PointD> getNeighbors(PointD node); @Override PointD getWorldLocation(PointD node); @Override PointD[] getWorldRegion(PointD node); final double epsilon; }
@Test public void testStructureEquals() { final Subdivision division = SubdivisionLinesTest.createTriforce(false); division.validate(); final Subdivision clone = division.copy(); clone.validate(); assertTrue(division.structureEquals(clone)); assertEquals(division.edges().size(), clone.edges().size()); for (int i = 0; i < division.edges().size(); i++) { final SubdivisionEdge edge = division.edges().get(i); final SubdivisionEdge cloneEdge = clone.edges().get(i); assertEquals(edge, cloneEdge); } assertEquals(division.faces().size(), clone.faces().size()); for (int i = 0; i < division.faces().size(); i++) { final SubdivisionFace face = division.faces().get(i); final SubdivisionFace cloneFace = clone.faces().get(i); assertEquals(face, cloneFace); } }
GeoUtils { public static LineD[] connectPoints(boolean isClosed, PointD... points) { if (points == null) throw new NullPointerException("points"); if (points.length < 2) return new LineD[0]; final LineD[] lines = new LineD[isClosed ? points.length : points.length - 1]; for (int i = 0; i < points.length - 1; i++) lines[i] = new LineD(points[i], points[i + 1]); if (isClosed) lines[lines.length - 1] = new LineD(points[points.length - 1], points[0]); return lines; } private GeoUtils(); static LineD[] connectPoints(boolean isClosed, PointD... points); static PointD[] convexHull(PointD... points); @SuppressWarnings("unchecked") static T[] fromDoubles(Class<T> type, double... items); @SuppressWarnings("unchecked") static T[] fromInts(Class<T> type, int... items); static int nearestPoint(List<PointD> points, PointD q); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon, double epsilon); static double polygonArea(PointD... polygon); static PointD polygonCentroid(PointD... polygon); static LineD randomLine(double x, double y, double width, double height); static PointD randomPoint(double x, double y, double width, double height); static PointD randomPoint(RectD bounds); static PointD[] randomPoints(int count, RectD bounds); static PointD[] randomPoints(int count, RectD bounds, PointDComparator comparer, double distance); static PointD[] randomPolygon(double x, double y, double width, double height); static RectD randomRect(double x, double y, double width, double height); @SuppressWarnings("unchecked") static double[] toDoubles(Class<T> type, T... items); @SuppressWarnings("unchecked") static int[] toInts(Class<T> type, T... items); }
@Test public void testConnectPoints() { final PointD p0 = new PointD(0, 0), p1 = new PointD(1, 1), p2 = new PointD(2, 0); assertArrayEquals(new LineD[0], GeoUtils.connectPoints(false)); assertArrayEquals(new LineD[0], GeoUtils.connectPoints(true)); assertArrayEquals(new LineD[0], GeoUtils.connectPoints(false, p0)); assertArrayEquals(new LineD[0], GeoUtils.connectPoints(true, p0)); assertArrayEquals(new LineD[] { new LineD(p0, p1) }, GeoUtils.connectPoints(false, p0, p1)); assertArrayEquals(new LineD[] { new LineD(p0, p1), new LineD(p1, p0) }, GeoUtils.connectPoints(true, p0, p1)); assertArrayEquals(new LineD[] { new LineD(p0, p1), new LineD(p1, p2) }, GeoUtils.connectPoints(false, p0, p1, p2)); assertArrayEquals(new LineD[] { new LineD(p0, p1), new LineD(p1, p2), new LineD(p2, p0) }, GeoUtils.connectPoints(true, p0, p1, p2)); }
Fortran { public static double anint(double n) { if (n > 0) return Math.floor(n + 0.5); else if (n < 0) return Math.ceil(n - 0.5); else return 0; } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test public void testAnint() { assertEquals(4d, Fortran.anint(3.6d), DELTA); assertEquals(4d, Fortran.anint(3.5d), DELTA); assertEquals(3d, Fortran.anint(3.4d), DELTA); assertEquals(-4d, Fortran.anint(-3.6d), DELTA); assertEquals(-4d, Fortran.anint(-3.5d), DELTA); assertEquals(-3d, Fortran.anint(-3.4d), DELTA); assertEquals(4f, Fortran.anint(3.6f), DELTA); assertEquals(4f, Fortran.anint(3.5f), DELTA); assertEquals(3f, Fortran.anint(3.4f), DELTA); assertEquals(-4f, Fortran.anint(-3.6f), DELTA); assertEquals(-4f, Fortran.anint(-3.5f), DELTA); assertEquals(-3f, Fortran.anint(-3.4f), DELTA); }
GeoUtils { public static PointD[] convexHull(PointD... points) { if (points == null || points.length == 0) throw new NullPointerException("points"); switch (points.length) { case 1: return new PointD[] { points[0] }; case 2: if (points[0] == points[1]) return new PointD[] { points[0] }; else return new PointD[] { points[0], points[1] }; } final ConvexHullVertex[] p = new ConvexHullVertex[points.length]; PointD pnv = points[0]; p[0] = new ConvexHullVertex(pnv, 0); int i, n = 0; for (i = 1; i < p.length; i++) { final PointD piv = points[i]; p[i] = new ConvexHullVertex(piv, i); final int result = PointDComparatorY.compareExact(piv, pnv); if (result < 0) { n = i; pnv = piv; } else if (result == 0) p[i].delete = true; } if (n > 0) { final ConvexHullVertex swap = p[0]; p[0] = p[n]; p[n] = swap; } Arrays.sort(p, 1, p.length, new ConvexHullVertexComparator(p[0])); for (i = 0, n = 0; i < p.length; i++) if (!p[i].delete) p[n++] = p[i]; if (n == 1) return new PointD[] { p[0].vertex }; ConvexHullVertex top = p[1]; top.next = p[0]; int hullCount = 2; for (i = 2; i < n; ) { final ConvexHullVertex pi = p[i]; if (top.next.vertex.crossProductLength(top.vertex, pi.vertex) > 0) { pi.next = top; top = pi; ++i; ++hullCount; } else { top = top.next; --hullCount; } } final PointD[] hull = new PointD[hullCount]; for (i = 0; i < hull.length; i++) { hull[i] = top.vertex; top = top.next; } assert(top == null); return hull; } private GeoUtils(); static LineD[] connectPoints(boolean isClosed, PointD... points); static PointD[] convexHull(PointD... points); @SuppressWarnings("unchecked") static T[] fromDoubles(Class<T> type, double... items); @SuppressWarnings("unchecked") static T[] fromInts(Class<T> type, int... items); static int nearestPoint(List<PointD> points, PointD q); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon, double epsilon); static double polygonArea(PointD... polygon); static PointD polygonCentroid(PointD... polygon); static LineD randomLine(double x, double y, double width, double height); static PointD randomPoint(double x, double y, double width, double height); static PointD randomPoint(RectD bounds); static PointD[] randomPoints(int count, RectD bounds); static PointD[] randomPoints(int count, RectD bounds, PointDComparator comparer, double distance); static PointD[] randomPolygon(double x, double y, double width, double height); static RectD randomRect(double x, double y, double width, double height); @SuppressWarnings("unchecked") static double[] toDoubles(Class<T> type, T... items); @SuppressWarnings("unchecked") static int[] toInts(Class<T> type, T... items); }
@Test public void testConvexHull() { final PointD p0 = new PointD(0, 0), p1 = new PointD(1, 1), p2 = new PointD(2, 0); assertArrayEquals(new PointD[] { p0 }, GeoUtils.convexHull(p0)); assertArrayEquals(new PointD[] { p0 }, GeoUtils.convexHull(p0, p0)); assertArrayEquals(new PointD[] { p0 }, GeoUtils.convexHull(p0, p0, p0)); assertArrayEquals(new PointD[] { p0, p1 }, GeoUtils.convexHull(p0, p1)); assertArrayEquals(new PointD[] { p1, p0 }, GeoUtils.convexHull(p0, p1, p0)); assertArrayEquals(new PointD[] { p1, p0 }, GeoUtils.convexHull(p0, p0, p1)); assertArrayEquals(new PointD[] { p1, p0 }, GeoUtils.convexHull(p0, p1, p1)); assertArrayEquals(new PointD[] { p1, p2, p0 }, GeoUtils.convexHull(p0, p1, p2)); assertArrayEquals(new PointD[] { p1, p2, p0 }, GeoUtils.convexHull(p1, p0, p2)); final PointD p3 = new PointD(1, 0); assertArrayEquals(new PointD[] { p1, p2, p0 }, GeoUtils.convexHull(p3, p1, p0, p2)); }
GeoUtils { public static PolygonLocation pointInPolygon(PointD q, PointD[] polygon) { if (polygon == null) throw new NullPointerException("polygon"); if (polygon.length < 3) throw new IllegalArgumentException("polygon.length < 3"); int rightCrossings = 0, leftCrossings = 0; final int lastIndex = polygon.length - 1; double x1 = polygon[lastIndex].x - q.x; double y1 = polygon[lastIndex].y - q.y; for (PointD vertex: polygon) { final double x0 = vertex.x - q.x; final double y0 = vertex.y - q.y; if (x0 == 0 && y0 == 0) return PolygonLocation.VERTEX; final boolean rightStraddle = ((y0 > 0) != (y1 > 0)); final boolean leftStraddle = ((y0 < 0) != (y1 < 0)); if (rightStraddle || leftStraddle) { final double x = (x0 * y1 - x1 * y0) / (y1 - y0); if (rightStraddle && x > 0) ++rightCrossings; if (leftStraddle && x < 0) ++leftCrossings; } x1 = x0; y1 = y0; } if (rightCrossings % 2 != leftCrossings % 2) return PolygonLocation.EDGE; return (rightCrossings % 2 != 0 ? PolygonLocation.INSIDE : PolygonLocation.OUTSIDE); } private GeoUtils(); static LineD[] connectPoints(boolean isClosed, PointD... points); static PointD[] convexHull(PointD... points); @SuppressWarnings("unchecked") static T[] fromDoubles(Class<T> type, double... items); @SuppressWarnings("unchecked") static T[] fromInts(Class<T> type, int... items); static int nearestPoint(List<PointD> points, PointD q); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon, double epsilon); static double polygonArea(PointD... polygon); static PointD polygonCentroid(PointD... polygon); static LineD randomLine(double x, double y, double width, double height); static PointD randomPoint(double x, double y, double width, double height); static PointD randomPoint(RectD bounds); static PointD[] randomPoints(int count, RectD bounds); static PointD[] randomPoints(int count, RectD bounds, PointDComparator comparer, double distance); static PointD[] randomPolygon(double x, double y, double width, double height); static RectD randomRect(double x, double y, double width, double height); @SuppressWarnings("unchecked") static double[] toDoubles(Class<T> type, T... items); @SuppressWarnings("unchecked") static int[] toInts(Class<T> type, T... items); }
@Test public void testPointInPolygon() { final PointD[] p = { new PointD(0, 0), new PointD(1, 1), new PointD(2, 0) }; assertEquals(PolygonLocation.INSIDE, GeoUtils.pointInPolygon(new PointD(1.0, 0.5), p)); assertEquals(PolygonLocation.OUTSIDE, GeoUtils.pointInPolygon(new PointD(0.0, 0.5), p)); assertEquals(PolygonLocation.OUTSIDE, GeoUtils.pointInPolygon(new PointD(2.0, 0.5), p)); assertEquals(PolygonLocation.OUTSIDE, GeoUtils.pointInPolygon(new PointD(1.0, -0.5), p)); assertEquals(PolygonLocation.OUTSIDE, GeoUtils.pointInPolygon(new PointD(1.0, 2.5), p)); assertEquals(PolygonLocation.EDGE, GeoUtils.pointInPolygon(new PointD(1.0, 0.0), p)); assertEquals(PolygonLocation.EDGE, GeoUtils.pointInPolygon(new PointD(0.5, 0.5), p)); assertEquals(PolygonLocation.EDGE, GeoUtils.pointInPolygon(new PointD(1.5, 0.5), p)); assertEquals(PolygonLocation.VERTEX, GeoUtils.pointInPolygon(new PointD(0.0, 0.0), p)); assertEquals(PolygonLocation.VERTEX, GeoUtils.pointInPolygon(new PointD(1.0, 1.0), p)); assertEquals(PolygonLocation.VERTEX, GeoUtils.pointInPolygon(new PointD(2.0, 0.0), p)); } @Test public void testPointInPolygonEpsilon() { final PointD[] p = { new PointD(0, 0), new PointD(1, 1), new PointD(2, 0) }; assertEquals(PolygonLocation.INSIDE, GeoUtils.pointInPolygon(new PointD(1.0, 0.5), p, 0.2)); assertEquals(PolygonLocation.OUTSIDE, GeoUtils.pointInPolygon(new PointD(1.0, -0.5), p, 0.2)); assertEquals(PolygonLocation.OUTSIDE, GeoUtils.pointInPolygon(new PointD(0.0, 0.5), p, 0.2)); assertEquals(PolygonLocation.OUTSIDE, GeoUtils.pointInPolygon(new PointD(2.0, 0.5), p, 0.2)); assertEquals(PolygonLocation.VERTEX, GeoUtils.pointInPolygon(new PointD(1.0, 0.9), p, 0.2)); assertEquals(PolygonLocation.VERTEX, GeoUtils.pointInPolygon(new PointD(0.0, 0.1), p, 0.2)); assertEquals(PolygonLocation.VERTEX, GeoUtils.pointInPolygon(new PointD(2.1, 0.0), p, 0.2)); assertEquals(PolygonLocation.EDGE, GeoUtils.pointInPolygon(new PointD(1.0, -0.1), p, 0.2)); assertEquals(PolygonLocation.EDGE, GeoUtils.pointInPolygon(new PointD(0.6, 0.5), p, 0.2)); assertEquals(PolygonLocation.EDGE, GeoUtils.pointInPolygon(new PointD(1.4, 0.5), p, 0.2)); }
GeoUtils { public static double polygonArea(PointD... polygon) { if (polygon == null) throw new NullPointerException("polygon"); if (polygon.length < 3) throw new IllegalArgumentException("polygon.length < 3"); double area = 0; for (int i = polygon.length - 1, j = 0; j < polygon.length; i = j++) area += (polygon[i].x * polygon[j].y - polygon[j].x * polygon[i].y); return area / 2.0; } private GeoUtils(); static LineD[] connectPoints(boolean isClosed, PointD... points); static PointD[] convexHull(PointD... points); @SuppressWarnings("unchecked") static T[] fromDoubles(Class<T> type, double... items); @SuppressWarnings("unchecked") static T[] fromInts(Class<T> type, int... items); static int nearestPoint(List<PointD> points, PointD q); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon, double epsilon); static double polygonArea(PointD... polygon); static PointD polygonCentroid(PointD... polygon); static LineD randomLine(double x, double y, double width, double height); static PointD randomPoint(double x, double y, double width, double height); static PointD randomPoint(RectD bounds); static PointD[] randomPoints(int count, RectD bounds); static PointD[] randomPoints(int count, RectD bounds, PointDComparator comparer, double distance); static PointD[] randomPolygon(double x, double y, double width, double height); static RectD randomRect(double x, double y, double width, double height); @SuppressWarnings("unchecked") static double[] toDoubles(Class<T> type, T... items); @SuppressWarnings("unchecked") static int[] toInts(Class<T> type, T... items); }
@Test public void testPolygonArea() { final double epsilon = 0.001; PointD p0 = new PointD(0, 0), p1 = new PointD(1, 1), p2 = new PointD(2, 0); PointD p3 = new PointD(0, 2), p4 = new PointD(2, 2); assertEquals(-1, GeoUtils.polygonArea(p0, p1, p2), epsilon); assertEquals(+1, GeoUtils.polygonArea(p2, p1, p0), epsilon); assertEquals(-4, GeoUtils.polygonArea(p0, p3, p4, p2), epsilon); assertEquals(+4, GeoUtils.polygonArea(p2, p4, p3, p0), epsilon); assertEquals(0, GeoUtils.polygonArea(p0, p1, p4), epsilon); assertEquals(0, GeoUtils.polygonArea(p0, p1, p3, p1, p2, p1, p4, p1), epsilon); }
GeoUtils { public static PointD polygonCentroid(PointD... polygon) { if (polygon == null) throw new NullPointerException("polygon"); if (polygon.length < 3) throw new IllegalArgumentException("polygon.length < 3"); double area = 0, x = 0, y = 0; for (int i = polygon.length - 1, j = 0; j < polygon.length; i = j++) { final double factor = polygon[i].x * polygon[j].y - polygon[j].x * polygon[i].y; area += factor; x += (polygon[i].x + polygon[j].x) * factor; y += (polygon[i].y + polygon[j].y) * factor; } area *= 3.0; return new PointD(x / area, y / area); } private GeoUtils(); static LineD[] connectPoints(boolean isClosed, PointD... points); static PointD[] convexHull(PointD... points); @SuppressWarnings("unchecked") static T[] fromDoubles(Class<T> type, double... items); @SuppressWarnings("unchecked") static T[] fromInts(Class<T> type, int... items); static int nearestPoint(List<PointD> points, PointD q); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon, double epsilon); static double polygonArea(PointD... polygon); static PointD polygonCentroid(PointD... polygon); static LineD randomLine(double x, double y, double width, double height); static PointD randomPoint(double x, double y, double width, double height); static PointD randomPoint(RectD bounds); static PointD[] randomPoints(int count, RectD bounds); static PointD[] randomPoints(int count, RectD bounds, PointDComparator comparer, double distance); static PointD[] randomPolygon(double x, double y, double width, double height); static RectD randomRect(double x, double y, double width, double height); @SuppressWarnings("unchecked") static double[] toDoubles(Class<T> type, T... items); @SuppressWarnings("unchecked") static int[] toInts(Class<T> type, T... items); }
@Test public void testPolygonCentroid() { final PointD p0 = new PointD(0, 0), p1 = new PointD(1, 1), p2 = new PointD(2, 0); final PointD p3 = new PointD(0, 2), p4 = new PointD(2, 2); assertEquals(new PointD(1, 1 / 3.0), GeoUtils.polygonCentroid(p0, p1, p2)); assertEquals(new PointD(1, 1 / 3.0), GeoUtils.polygonCentroid(p2, p1, p0)); assertEquals(p1, GeoUtils.polygonCentroid(p0, p3, p4, p2)); assertEquals(p1, GeoUtils.polygonCentroid(p2, p4, p3, p0)); }
GeoUtils { public static PointD[] randomPoints(int count, RectD bounds) { if (count < 0) throw new IllegalArgumentException("count < 0"); final double width = bounds.width(), height = bounds.height(); if (width == 0) throw new IllegalArgumentException("bounds.width == 0"); if (height == 0) throw new IllegalArgumentException("bounds.height == 0"); final PointD[] points = new PointD[count]; for (int i = 0; i < points.length; i++) points[i] = new PointD( bounds.min.x + RANDOM.nextDouble(width), bounds.min.y + RANDOM.nextDouble(height)); return points; } private GeoUtils(); static LineD[] connectPoints(boolean isClosed, PointD... points); static PointD[] convexHull(PointD... points); @SuppressWarnings("unchecked") static T[] fromDoubles(Class<T> type, double... items); @SuppressWarnings("unchecked") static T[] fromInts(Class<T> type, int... items); static int nearestPoint(List<PointD> points, PointD q); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon); static PolygonLocation pointInPolygon(PointD q, PointD[] polygon, double epsilon); static double polygonArea(PointD... polygon); static PointD polygonCentroid(PointD... polygon); static LineD randomLine(double x, double y, double width, double height); static PointD randomPoint(double x, double y, double width, double height); static PointD randomPoint(RectD bounds); static PointD[] randomPoints(int count, RectD bounds); static PointD[] randomPoints(int count, RectD bounds, PointDComparator comparer, double distance); static PointD[] randomPolygon(double x, double y, double width, double height); static RectD randomRect(double x, double y, double width, double height); @SuppressWarnings("unchecked") static double[] toDoubles(Class<T> type, T... items); @SuppressWarnings("unchecked") static int[] toInts(Class<T> type, T... items); }
@Test public void testRandomPoints() { final RectD bounds = new RectD(-100, -100, 200, 200); final PointD[] points = GeoUtils.randomPoints(100, bounds); for (PointD p: points) assertTrue(bounds.contains(p)); }
MultiLineIntersection { public static MultiLinePoint[] findSimple(LineD[] lines) { if (lines == null) throw new NullPointerException("lines"); final TreeMap<PointD, EventPoint> crossings = new TreeMap<>(PointDComparatorY::compareExact); for (int i = 0; i < lines.length - 1; i++) for (int j = i + 1; j < lines.length; j++) { final LineIntersection crossing = lines[i].intersect(lines[j]); if (crossing.exists()) { final PointD p = crossing.shared; final EventPoint e = EventPoint.tryAdd(crossings, p); e.tryAddLines(i, crossing.first, j, crossing.second); } } return EventPoint.output(crossings.values()); } private MultiLineIntersection(); static MultiLinePoint[] find(LineD[] lines); static MultiLinePoint[] findSimple(LineD[] lines); static MultiLinePoint[] findSimple(LineD[] lines, double epsilon); static LineD[] split(LineD[] lines, MultiLinePoint[] crossings); }
@Test public void testEpsilon() { LineD[] lines = new LineD[] { new LineD(0, 2, 5, 2), new LineD(3, 2.1, 5, 4) }; MultiLinePoint[] results = findBoth(lines); assertEquals(0, results.length); results = MultiLineIntersection.findSimple(lines, 1.0); assertEquals(1, results.length); MultiLinePoint result = results[0]; assertTrue(PointD.equals(new PointD(3, 2), result.shared, 1.0)); assertEquals(2, result.lines.length); assertEquals(0, result.lines[0].index); assertEquals(LineLocation.BETWEEN, result.lines[0].location); assertEquals(1, result.lines[1].index); assertEquals(LineLocation.START, result.lines[1].location); lines = new LineD[] { new LineD(3, 1, 1, 1), new LineD(1, 1.1, 3, 3), new LineD(1, 0.9, 3, -2) }; results = findBoth(lines); assertEquals(0, results.length); results = MultiLineIntersection.findSimple(lines, 1.0); assertEquals(1, results.length); result = results[0]; assertTrue(PointD.equals(new PointD(1, 1), result.shared, 1.0)); assertEquals(3, result.lines.length); assertEquals(0, result.lines[0].index); assertEquals(LineLocation.END, result.lines[0].location); assertEquals(1, result.lines[1].index); assertEquals(LineLocation.START, result.lines[1].location); assertEquals(2, result.lines[2].index); assertEquals(LineLocation.START, result.lines[1].location); }
PolygonGrid implements Graph<PointI> { public PolygonGrid asReadOnly() { return (isReadOnly ? this : new PolygonGrid(_data)); } PolygonGrid(RegularPolygon element); PolygonGrid(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid(PolygonGrid grid); private PolygonGrid(InstanceData data); SizeD centerDistance(); PointI[][] edgeNeighborOffsets(); final RegularPolygon element(); final PolygonGridShift gridShift(); PointI[][] neighborOffsets(); final SizeI size(); RectD worldBounds(); static boolean areCompatible(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid asReadOnly(); boolean contains(int column, int row); boolean contains(RectI rect); @SuppressWarnings("unchecked") T[][] createArray(Class<T> clazz); PointI[] getEdgeNeighborOffsets(PointI location); RectD getElementBounds(int column, int row); RectD getElementBounds(PointI location); RectD getElementBounds(RectI region); PointD[] getElementVertices(int column, int row); PointI getNeighbor(PointI location, int index); int getNeighborIndex(PointI location, PointI neighbor); PointI[] getNeighborOffsets(PointI location); int getStepDistance(PointI source, PointI target); PointD gridToWorld(int column, int row); PointD gridToWorld(PointI location); boolean isValid(int column, int row); boolean isValid(PointI location); final void setElement(RegularPolygon element); final void setGridShift(PolygonGridShift gridShift); final void setSize(SizeI size); PointI worldToGrid(double x, double y); PointI worldToGrid(PointD location); PointI worldToGridClipped(double x, double y); PointI worldToGridClipped(PointD location); @Override int connectivity(); @Override int nodeCount(); @Override List<PointI> nodes(); @Override boolean contains(PointI node); @Override PointI findNearestNode(PointD location); @Override double getDistance(PointI source, PointI target); @Override List<PointI> getNeighbors(PointI node); @Override List<PointI> getNeighbors(PointI node, int steps); @Override PointD getWorldLocation(PointI node); @Override PointD[] getWorldRegion(PointI node); static final PointI INVALID_LOCATION; final boolean isReadOnly; }
@Test public void testAsReadOnly() { assertFalse(grid.isReadOnly); assertTrue(readOnly.isReadOnly); assertNotSame(readOnly, grid.asReadOnly()); assertSame(readOnly, readOnly.asReadOnly()); }
PolygonGrid implements Graph<PointI> { public final RegularPolygon element() { return _data.element; } PolygonGrid(RegularPolygon element); PolygonGrid(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid(PolygonGrid grid); private PolygonGrid(InstanceData data); SizeD centerDistance(); PointI[][] edgeNeighborOffsets(); final RegularPolygon element(); final PolygonGridShift gridShift(); PointI[][] neighborOffsets(); final SizeI size(); RectD worldBounds(); static boolean areCompatible(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid asReadOnly(); boolean contains(int column, int row); boolean contains(RectI rect); @SuppressWarnings("unchecked") T[][] createArray(Class<T> clazz); PointI[] getEdgeNeighborOffsets(PointI location); RectD getElementBounds(int column, int row); RectD getElementBounds(PointI location); RectD getElementBounds(RectI region); PointD[] getElementVertices(int column, int row); PointI getNeighbor(PointI location, int index); int getNeighborIndex(PointI location, PointI neighbor); PointI[] getNeighborOffsets(PointI location); int getStepDistance(PointI source, PointI target); PointD gridToWorld(int column, int row); PointD gridToWorld(PointI location); boolean isValid(int column, int row); boolean isValid(PointI location); final void setElement(RegularPolygon element); final void setGridShift(PolygonGridShift gridShift); final void setSize(SizeI size); PointI worldToGrid(double x, double y); PointI worldToGrid(PointD location); PointI worldToGridClipped(double x, double y); PointI worldToGridClipped(PointD location); @Override int connectivity(); @Override int nodeCount(); @Override List<PointI> nodes(); @Override boolean contains(PointI node); @Override PointI findNearestNode(PointD location); @Override double getDistance(PointI source, PointI target); @Override List<PointI> getNeighbors(PointI node); @Override List<PointI> getNeighbors(PointI node, int steps); @Override PointD getWorldLocation(PointI node); @Override PointD[] getWorldRegion(PointI node); static final PointI INVALID_LOCATION; final boolean isReadOnly; }
@Test public void testElement() { try { readOnly.setElement(grid.element()); fail("expected IllegalStateException"); } catch (IllegalStateException e) { } grid.setElement(new RegularPolygon(5.0, 4, PolygonOrientation.ON_EDGE)); assertNotEquals(element, grid.element()); testData(); }
PolygonGrid implements Graph<PointI> { public final PolygonGridShift gridShift() { return _data.gridShift; } PolygonGrid(RegularPolygon element); PolygonGrid(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid(PolygonGrid grid); private PolygonGrid(InstanceData data); SizeD centerDistance(); PointI[][] edgeNeighborOffsets(); final RegularPolygon element(); final PolygonGridShift gridShift(); PointI[][] neighborOffsets(); final SizeI size(); RectD worldBounds(); static boolean areCompatible(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid asReadOnly(); boolean contains(int column, int row); boolean contains(RectI rect); @SuppressWarnings("unchecked") T[][] createArray(Class<T> clazz); PointI[] getEdgeNeighborOffsets(PointI location); RectD getElementBounds(int column, int row); RectD getElementBounds(PointI location); RectD getElementBounds(RectI region); PointD[] getElementVertices(int column, int row); PointI getNeighbor(PointI location, int index); int getNeighborIndex(PointI location, PointI neighbor); PointI[] getNeighborOffsets(PointI location); int getStepDistance(PointI source, PointI target); PointD gridToWorld(int column, int row); PointD gridToWorld(PointI location); boolean isValid(int column, int row); boolean isValid(PointI location); final void setElement(RegularPolygon element); final void setGridShift(PolygonGridShift gridShift); final void setSize(SizeI size); PointI worldToGrid(double x, double y); PointI worldToGrid(PointD location); PointI worldToGridClipped(double x, double y); PointI worldToGridClipped(PointD location); @Override int connectivity(); @Override int nodeCount(); @Override List<PointI> nodes(); @Override boolean contains(PointI node); @Override PointI findNearestNode(PointD location); @Override double getDistance(PointI source, PointI target); @Override List<PointI> getNeighbors(PointI node); @Override List<PointI> getNeighbors(PointI node, int steps); @Override PointD getWorldLocation(PointI node); @Override PointD[] getWorldRegion(PointI node); static final PointI INVALID_LOCATION; final boolean isReadOnly; }
@Test public void testGridShift() { try { readOnly.setGridShift(grid.gridShift()); fail("expected IllegalStateException"); } catch (IllegalStateException e) { } assertEquals(PolygonGridShift.COLUMN_DOWN, grid.gridShift()); grid.setGridShift(PolygonGridShift.COLUMN_UP); testData(); }
Fortran { public static int ceiling(double n) { return MathUtils.toIntExact(Math.ceil(n)); } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test public void testCeiling() { assertEquals(4, Fortran.ceiling(3.6d)); assertEquals(4, Fortran.ceiling(3.4d)); assertEquals(-3, Fortran.ceiling(-3.6d)); assertEquals(-3, Fortran.ceiling(-3.4d)); assertEquals(4, Fortran.ceiling(3.6f)); assertEquals(4, Fortran.ceiling(3.4f)); assertEquals(-3, Fortran.ceiling(-3.6f)); assertEquals(-3, Fortran.ceiling(-3.4f)); try { Fortran.ceiling(1e100); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { Fortran.ceiling(1e30f); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } }
PolygonGrid implements Graph<PointI> { public final SizeI size() { return _data.size; } PolygonGrid(RegularPolygon element); PolygonGrid(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid(PolygonGrid grid); private PolygonGrid(InstanceData data); SizeD centerDistance(); PointI[][] edgeNeighborOffsets(); final RegularPolygon element(); final PolygonGridShift gridShift(); PointI[][] neighborOffsets(); final SizeI size(); RectD worldBounds(); static boolean areCompatible(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid asReadOnly(); boolean contains(int column, int row); boolean contains(RectI rect); @SuppressWarnings("unchecked") T[][] createArray(Class<T> clazz); PointI[] getEdgeNeighborOffsets(PointI location); RectD getElementBounds(int column, int row); RectD getElementBounds(PointI location); RectD getElementBounds(RectI region); PointD[] getElementVertices(int column, int row); PointI getNeighbor(PointI location, int index); int getNeighborIndex(PointI location, PointI neighbor); PointI[] getNeighborOffsets(PointI location); int getStepDistance(PointI source, PointI target); PointD gridToWorld(int column, int row); PointD gridToWorld(PointI location); boolean isValid(int column, int row); boolean isValid(PointI location); final void setElement(RegularPolygon element); final void setGridShift(PolygonGridShift gridShift); final void setSize(SizeI size); PointI worldToGrid(double x, double y); PointI worldToGrid(PointD location); PointI worldToGridClipped(double x, double y); PointI worldToGridClipped(PointD location); @Override int connectivity(); @Override int nodeCount(); @Override List<PointI> nodes(); @Override boolean contains(PointI node); @Override PointI findNearestNode(PointD location); @Override double getDistance(PointI source, PointI target); @Override List<PointI> getNeighbors(PointI node); @Override List<PointI> getNeighbors(PointI node, int steps); @Override PointD getWorldLocation(PointI node); @Override PointD[] getWorldRegion(PointI node); static final PointI INVALID_LOCATION; final boolean isReadOnly; }
@Test public void testSize() { try { readOnly.setSize(grid.size()); fail("expected IllegalStateException"); } catch (IllegalStateException e) { } assertEquals(new SizeI(1, 1), grid.size()); grid.setSize(new SizeI(5, 5)); testData(); }
PolygonGrid implements Graph<PointI> { public final void setSize(SizeI size) { if (isReadOnly) throw new IllegalStateException("isReadOnly"); if (size.width < 1) throw new IllegalArgumentException("size.width < 1"); if (size.height < 1) throw new IllegalArgumentException("size.height < 1"); _data.size = size; _data.onSizeChanged(); } PolygonGrid(RegularPolygon element); PolygonGrid(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid(PolygonGrid grid); private PolygonGrid(InstanceData data); SizeD centerDistance(); PointI[][] edgeNeighborOffsets(); final RegularPolygon element(); final PolygonGridShift gridShift(); PointI[][] neighborOffsets(); final SizeI size(); RectD worldBounds(); static boolean areCompatible(RegularPolygon element, PolygonGridShift gridShift); PolygonGrid asReadOnly(); boolean contains(int column, int row); boolean contains(RectI rect); @SuppressWarnings("unchecked") T[][] createArray(Class<T> clazz); PointI[] getEdgeNeighborOffsets(PointI location); RectD getElementBounds(int column, int row); RectD getElementBounds(PointI location); RectD getElementBounds(RectI region); PointD[] getElementVertices(int column, int row); PointI getNeighbor(PointI location, int index); int getNeighborIndex(PointI location, PointI neighbor); PointI[] getNeighborOffsets(PointI location); int getStepDistance(PointI source, PointI target); PointD gridToWorld(int column, int row); PointD gridToWorld(PointI location); boolean isValid(int column, int row); boolean isValid(PointI location); final void setElement(RegularPolygon element); final void setGridShift(PolygonGridShift gridShift); final void setSize(SizeI size); PointI worldToGrid(double x, double y); PointI worldToGrid(PointD location); PointI worldToGridClipped(double x, double y); PointI worldToGridClipped(PointD location); @Override int connectivity(); @Override int nodeCount(); @Override List<PointI> nodes(); @Override boolean contains(PointI node); @Override PointI findNearestNode(PointD location); @Override double getDistance(PointI source, PointI target); @Override List<PointI> getNeighbors(PointI node); @Override List<PointI> getNeighbors(PointI node, int steps); @Override PointD getWorldLocation(PointI node); @Override PointD[] getWorldRegion(PointI node); static final PointI INVALID_LOCATION; final boolean isReadOnly; }
@Test public void testSubdivision() { grid = new PolygonGrid(new RegularPolygon(10, 4, PolygonOrientation.ON_EDGE)); grid.setSize(new SizeI(6, 4)); PolygonGridMap map = new PolygonGridMap(grid, PointD.EMPTY, 0); checkGridMap(map); grid = new PolygonGrid(new RegularPolygon(10, 4, PolygonOrientation.ON_VERTEX)); grid.setSize(new SizeI(4, 6)); map = new PolygonGridMap(grid, PointD.EMPTY, 0); checkGridMap(map); grid = new PolygonGrid(new RegularPolygon(10, 6, PolygonOrientation.ON_EDGE)); grid.setSize(new SizeI(6, 4)); map = new PolygonGridMap(grid, PointD.EMPTY, 0); checkGridMap(map); grid = new PolygonGrid(new RegularPolygon(10, 6, PolygonOrientation.ON_VERTEX)); grid.setSize(new SizeI(4, 6)); map = new PolygonGridMap(grid, PointD.EMPTY, 0); checkGridMap(map); }
PointDComparatorY extends PointDComparator { @Override public int compare(PointD a, PointD b) { return (epsilon == 0 ? compareExact(a, b) : compareEpsilon(a, b, epsilon)); } PointDComparatorY(); PointDComparatorY(double epsilon); @Override int compare(PointD a, PointD b); int compareEpsilon(PointD a, PointD b); static int compareEpsilon(PointD a, PointD b, double epsilon); static int compareExact(PointD a, PointD b); }
@Test public void testCompare() { assertEquals(0, comparer.epsilon, 0); assertEquals(0, comparer.compare(new PointD(1, 2), new PointD(1, 2))); assertEquals(-1, comparer.compare(new PointD(1, 2), new PointD(2, 2))); assertEquals(-1, comparer.compare(new PointD(1, 2), new PointD(1, 3))); assertEquals(+1, comparer.compare(new PointD(1, 2), new PointD(0, 2))); assertEquals(+1, comparer.compare(new PointD(1, 2), new PointD(1, 1))); assertEquals(0, comparer001.epsilon, 0.01); assertEquals(-1, comparer001.compare(new PointD(1, 2), new PointD(1.1, 2))); assertEquals(-1, comparer001.compare(new PointD(1, 2), new PointD(1, 2.1))); assertEquals(+1, comparer001.compare(new PointD(1, 2), new PointD(0.9, 2))); assertEquals(+1, comparer001.compare(new PointD(1, 2), new PointD(1, 1.9))); assertEquals(0, comparer05.epsilon, 0.5); assertEquals(0, comparer05.compare(new PointD(1, 2), new PointD(1.1, 2))); assertEquals(0, comparer05.compare(new PointD(1, 2), new PointD(1, 2.1))); assertEquals(0, comparer05.compare(new PointD(1, 2), new PointD(0.9, 2))); assertEquals(0, comparer05.compare(new PointD(1, 2), new PointD(1, 1.9))); }
PointDComparatorY extends PointDComparator { public int compareEpsilon(PointD a, PointD b) { return compareEpsilon(a, b, epsilon); } PointDComparatorY(); PointDComparatorY(double epsilon); @Override int compare(PointD a, PointD b); int compareEpsilon(PointD a, PointD b); static int compareEpsilon(PointD a, PointD b, double epsilon); static int compareExact(PointD a, PointD b); }
@Test public void testCompareEpsilon() { assertEquals(0, comparer.epsilon, 0); assertEquals(0, comparer.compareEpsilon(new PointD(1, 2), new PointD(1, 2))); assertEquals(-1, comparer.compareEpsilon(new PointD(1, 2), new PointD(2, 2))); assertEquals(-1, comparer.compareEpsilon(new PointD(1, 2), new PointD(1, 3))); assertEquals(+1, comparer.compareEpsilon(new PointD(1, 2), new PointD(0, 2))); assertEquals(+1, comparer.compareEpsilon(new PointD(1, 2), new PointD(1, 1))); assertEquals(0, comparer001.epsilon, 0.01); assertEquals(-1, comparer001.compareEpsilon(new PointD(1, 2), new PointD(1.1, 2))); assertEquals(-1, comparer001.compareEpsilon(new PointD(1, 2), new PointD(1, 2.1))); assertEquals(+1, comparer001.compareEpsilon(new PointD(1, 2), new PointD(0.9, 2))); assertEquals(+1, comparer001.compareEpsilon(new PointD(1, 2), new PointD(1, 1.9))); assertEquals(0, comparer05.epsilon, 0.5); assertEquals(0, comparer05.compareEpsilon(new PointD(1, 2), new PointD(1.1, 2))); assertEquals(0, comparer05.compareEpsilon(new PointD(1, 2), new PointD(1, 2.1))); assertEquals(0, comparer05.compareEpsilon(new PointD(1, 2), new PointD(0.9, 2))); assertEquals(0, comparer05.compareEpsilon(new PointD(1, 2), new PointD(1, 1.9))); } @Test public void testCompareEpsilonStatic() { assertEquals(-1, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1.1, 2), 0.01)); assertEquals(-1, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1, 2.1), 0.01)); assertEquals(+1, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(0.9, 2), 0.01)); assertEquals(+1, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1, 1.9), 0.01)); assertEquals(0, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1.1, 2), 0.5)); assertEquals(0, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1, 2.1), 0.5)); assertEquals(0, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(0.9, 2), 0.5)); assertEquals(0, PointDComparatorY.compareEpsilon(new PointD(1, 2), new PointD(1, 1.9), 0.5)); }
PointDComparatorY extends PointDComparator { public static int compareExact(PointD a, PointD b) { if (a == b) return 0; if (a.y < b.y) return -1; if (a.y > b.y) return +1; if (a.x < b.x) return -1; if (a.x > b.x) return +1; return 0; } PointDComparatorY(); PointDComparatorY(double epsilon); @Override int compare(PointD a, PointD b); int compareEpsilon(PointD a, PointD b); static int compareEpsilon(PointD a, PointD b, double epsilon); static int compareExact(PointD a, PointD b); }
@Test public void testCompareExact() { assertEquals(0, PointDComparatorY.compareExact(new PointD(1, 2), new PointD(1, 2))); assertEquals(-1, PointDComparatorY.compareExact(new PointD(1, 2), new PointD(2, 2))); assertEquals(-1, PointDComparatorY.compareExact(new PointD(1, 2), new PointD(1, 3))); assertEquals(+1, PointDComparatorY.compareExact(new PointD(1, 2), new PointD(0, 2))); assertEquals(+1, PointDComparatorY.compareExact(new PointD(1, 2), new PointD(1, 1))); assertEquals(+1, PointDComparatorY.compareExact(new PointD(1, 2), new PointD(2, 1))); assertEquals(-1, PointDComparatorY.compareExact(new PointD(2, 1), new PointD(1, 2))); }
Angle { public static Compass degreesToCompass(double degrees) { degrees = Fortran.modulo(degrees + 22.5, 360); final int point = (int) (degrees / 45); return Compass.fromDegrees(point * 45); } private Angle(); static Compass degreesToCompass(double degrees); static double distanceDegrees(double start, double end); static double distanceRadians(double start, double end); static double normalizeDegrees(double degrees); static int normalizeRoundedDegrees(double degrees); static double normalizeRadians(double radians); static final double DEGREES_TO_RADIANS; static final double RADIANS_TO_DEGREES; }
@Test public void testDegreesToCompass() { assertEquals(Compass.NORTH, Angle.degreesToCompass(-22.0)); assertEquals(Compass.NORTH, Angle.degreesToCompass(0.0)); assertEquals(Compass.NORTH, Angle.degreesToCompass(22.0)); assertEquals(Compass.NORTH_WEST, Angle.degreesToCompass(-23.0)); assertEquals(Compass.NORTH_EAST, Angle.degreesToCompass(23.0)); }
Angle { public static double distanceDegrees(double start, double end) { double dist = end - start; if (dist > 180) dist -= 360; else if (dist <= -180) dist += 360; return dist; } private Angle(); static Compass degreesToCompass(double degrees); static double distanceDegrees(double start, double end); static double distanceRadians(double start, double end); static double normalizeDegrees(double degrees); static int normalizeRoundedDegrees(double degrees); static double normalizeRadians(double radians); static final double DEGREES_TO_RADIANS; static final double RADIANS_TO_DEGREES; }
@Test public void testDistanceDegrees() { for (double a = 0; a < 360; a++) for (double b = 0; b < 360; b++) { double dist = Angle.distanceDegrees(a, b); assertTrue(-180 < dist && dist <= 180); assertEquals(b, Angle.normalizeDegrees(a + dist), DELTA); } }
Angle { public static double distanceRadians(double start, double end) { double dist = end - start; if (dist > Math.PI) dist -= 2 * Math.PI; else if (dist <= -Math.PI) dist += 2 * Math.PI; return dist; } private Angle(); static Compass degreesToCompass(double degrees); static double distanceDegrees(double start, double end); static double distanceRadians(double start, double end); static double normalizeDegrees(double degrees); static int normalizeRoundedDegrees(double degrees); static double normalizeRadians(double radians); static final double DEGREES_TO_RADIANS; static final double RADIANS_TO_DEGREES; }
@Test public void testDistanceRadians() { for (double a = 0; a < 2 * Math.PI; a += Angle.DEGREES_TO_RADIANS) for (double b = 0; b < 2 * Math.PI; b += Angle.DEGREES_TO_RADIANS) { double dist = Angle.distanceRadians(a, b); assertTrue(-Math.PI < dist && dist <= Math.PI); assertEquals(b, Angle.normalizeRadians(a + dist), Angle.DEGREES_TO_RADIANS / 2); } }
Angle { public static double normalizeDegrees(double degrees) { degrees %= 360; if (degrees < 0) degrees += 360; return degrees; } private Angle(); static Compass degreesToCompass(double degrees); static double distanceDegrees(double start, double end); static double distanceRadians(double start, double end); static double normalizeDegrees(double degrees); static int normalizeRoundedDegrees(double degrees); static double normalizeRadians(double radians); static final double DEGREES_TO_RADIANS; static final double RADIANS_TO_DEGREES; }
@Test public void testNormalizeDegrees() { assertEquals(0, Angle.normalizeDegrees(0), DELTA); assertEquals(0.4, Angle.normalizeDegrees(0.4), DELTA); assertEquals(359.6, Angle.normalizeDegrees(-0.4), DELTA); assertEquals(0, Angle.normalizeDegrees(360), DELTA); assertEquals(0.4, Angle.normalizeDegrees(360.4), DELTA); assertEquals(359.4, Angle.normalizeDegrees(-0.6), DELTA); assertEquals(180, Angle.normalizeDegrees(180), DELTA); assertEquals(180, Angle.normalizeDegrees(540), DELTA); assertEquals(180, Angle.normalizeDegrees(-180), DELTA); assertEquals(180, Angle.normalizeDegrees(-540), DELTA); }
Fortran { public static int floor(double n) { return MathUtils.toIntExact(Math.floor(n)); } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test public void testFloor() { assertEquals(3, Fortran.floor(3.6d)); assertEquals(3, Fortran.floor(3.4d)); assertEquals(-4, Fortran.floor(-3.6d)); assertEquals(-4, Fortran.floor(-3.4d)); assertEquals(3, Fortran.floor(3.6f)); assertEquals(3, Fortran.floor(3.4f)); assertEquals(-4, Fortran.floor(-3.6f)); assertEquals(-4, Fortran.floor(-3.4f)); try { Fortran.floor(1e100); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { Fortran.floor(1e30f); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } }
Angle { public static int normalizeRoundedDegrees(double degrees) { int angle = Fortran.nint(degrees); angle %= 360; if (angle < 0) angle += 360; return angle; } private Angle(); static Compass degreesToCompass(double degrees); static double distanceDegrees(double start, double end); static double distanceRadians(double start, double end); static double normalizeDegrees(double degrees); static int normalizeRoundedDegrees(double degrees); static double normalizeRadians(double radians); static final double DEGREES_TO_RADIANS; static final double RADIANS_TO_DEGREES; }
@Test public void testNormalizeRoundedDegrees() { assertEquals(0, Angle.normalizeRoundedDegrees(0)); assertEquals(0, Angle.normalizeRoundedDegrees(0.4)); assertEquals(0, Angle.normalizeRoundedDegrees(-0.4)); assertEquals(0, Angle.normalizeRoundedDegrees(360)); assertEquals(0, Angle.normalizeRoundedDegrees(360.4)); assertEquals(359, Angle.normalizeRoundedDegrees(-0.6)); assertEquals(180, Angle.normalizeRoundedDegrees(180)); assertEquals(180, Angle.normalizeRoundedDegrees(540)); assertEquals(180, Angle.normalizeRoundedDegrees(-180)); assertEquals(180, Angle.normalizeRoundedDegrees(-540)); try { Angle.normalizeRoundedDegrees(1e100); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } }
Angle { public static double normalizeRadians(double radians) { radians %= 2 * Math.PI; if (radians < 0) radians += 2 * Math.PI; return radians; } private Angle(); static Compass degreesToCompass(double degrees); static double distanceDegrees(double start, double end); static double distanceRadians(double start, double end); static double normalizeDegrees(double degrees); static int normalizeRoundedDegrees(double degrees); static double normalizeRadians(double radians); static final double DEGREES_TO_RADIANS; static final double RADIANS_TO_DEGREES; }
@Test public void testNormalizeRadians() { assertEquals(0, Angle.normalizeRadians(0), DELTA); assertEquals(0.4, Angle.normalizeRadians(0.4), DELTA); assertEquals(2 * Math.PI - 0.4, Angle.normalizeRadians(-0.4), DELTA); assertEquals(0, Angle.normalizeRadians(2 * Math.PI), DELTA); assertEquals(0.4, Angle.normalizeRadians(2 * Math.PI + 0.4), DELTA); assertEquals(2 * Math.PI - 0.6, Angle.normalizeRadians(-0.6), DELTA); assertEquals(Math.PI, Angle.normalizeRadians(Math.PI), DELTA); assertEquals(Math.PI, Angle.normalizeRadians(3 * Math.PI), DELTA); assertEquals(Math.PI, Angle.normalizeRadians(-Math.PI), DELTA); assertEquals(Math.PI, Angle.normalizeRadians(-3 * Math.PI), DELTA); }
RegularPolygon { public int angleToIndex(double angle) { final double segment = 360.0 / connectivity; if (hasTopIndex) angle += segment / 2.0; angle = Fortran.modulo(angle + 90.0, 360.0); return (int) (angle / segment); } RegularPolygon(double length, int sides, PolygonOrientation orientation); RegularPolygon(double length, int sides, PolygonOrientation orientation, boolean vertexNeighbors); int angleToIndex(double angle); RegularPolygon circumscribe(double radius); RegularPolygon circumscribe(double width, double height); int compassToIndex(Compass compass); double indexToAngle(int index); Compass indexToCompass(int index); RegularPolygon inflate(double delta); RegularPolygon inscribe(double radius); RegularPolygon inscribe(double width, double height); int opposingIndex(int index); RegularPolygon resize(double length); final RectD bounds; final int connectivity; final boolean hasTopIndex; final double innerRadius; final double length; final PolygonOrientation orientation; final double outerRadius; final int sides; final boolean vertexNeighbors; final PointD[] vertices; }
@Test public void testAngleToIndex() { assertEquals(0, hexagonEdge.angleToIndex(-90.0)); assertEquals(1, hexagonEdge.angleToIndex(-30.0)); assertEquals(2, hexagonEdge.angleToIndex(30.0)); assertEquals(3, hexagonEdge.angleToIndex(90.0)); assertEquals(4, hexagonEdge.angleToIndex(150.0)); assertEquals(5, hexagonEdge.angleToIndex(210.0)); assertEquals(0, hexagonVertex.angleToIndex(-60.0)); assertEquals(1, hexagonVertex.angleToIndex(0.0)); assertEquals(2, hexagonVertex.angleToIndex(60.0)); assertEquals(3, hexagonVertex.angleToIndex(120.0)); assertEquals(4, hexagonVertex.angleToIndex(180.0)); assertEquals(5, hexagonVertex.angleToIndex(240.0)); assertEquals(1, squareEdge.angleToIndex(-23.0)); assertEquals(2, squareEdge.angleToIndex(-22.0)); assertEquals(3, squareEdge.angleToIndex(67.0)); assertEquals(4, squareEdge.angleToIndex(68.0)); assertEquals(5, squareEdge.angleToIndex(157.0)); assertEquals(6, squareEdge.angleToIndex(158.0)); assertEquals(7, squareEdge.angleToIndex(247.0)); assertEquals(0, squareEdge.angleToIndex(248.0)); }
RegularPolygon { public int compassToIndex(Compass compass) { return angleToIndex(compass.degrees() - 90); } RegularPolygon(double length, int sides, PolygonOrientation orientation); RegularPolygon(double length, int sides, PolygonOrientation orientation, boolean vertexNeighbors); int angleToIndex(double angle); RegularPolygon circumscribe(double radius); RegularPolygon circumscribe(double width, double height); int compassToIndex(Compass compass); double indexToAngle(int index); Compass indexToCompass(int index); RegularPolygon inflate(double delta); RegularPolygon inscribe(double radius); RegularPolygon inscribe(double width, double height); int opposingIndex(int index); RegularPolygon resize(double length); final RectD bounds; final int connectivity; final boolean hasTopIndex; final double innerRadius; final double length; final PolygonOrientation orientation; final double outerRadius; final int sides; final boolean vertexNeighbors; final PointD[] vertices; }
@Test public void testCompassToIndex() { assertEquals(0, hexagonEdge.compassToIndex(Compass.NORTH)); assertEquals(1, hexagonEdge.compassToIndex(Compass.NORTH_EAST)); assertEquals(2, hexagonEdge.compassToIndex(Compass.SOUTH_EAST)); assertEquals(3, hexagonEdge.compassToIndex(Compass.SOUTH)); assertEquals(4, hexagonEdge.compassToIndex(Compass.SOUTH_WEST)); assertEquals(5, hexagonEdge.compassToIndex(Compass.NORTH_WEST)); assertEquals(0, hexagonVertex.compassToIndex(Compass.NORTH_EAST)); assertEquals(1, hexagonVertex.compassToIndex(Compass.EAST)); assertEquals(2, hexagonVertex.compassToIndex(Compass.SOUTH_EAST)); assertEquals(3, hexagonVertex.compassToIndex(Compass.SOUTH_WEST)); assertEquals(4, hexagonVertex.compassToIndex(Compass.WEST)); assertEquals(5, hexagonVertex.compassToIndex(Compass.NORTH_WEST)); assertEquals(0, squareEdge.compassToIndex(Compass.NORTH)); assertEquals(1, squareEdge.compassToIndex(Compass.NORTH_EAST)); assertEquals(2, squareEdge.compassToIndex(Compass.EAST)); assertEquals(3, squareEdge.compassToIndex(Compass.SOUTH_EAST)); assertEquals(4, squareEdge.compassToIndex(Compass.SOUTH)); assertEquals(5, squareEdge.compassToIndex(Compass.SOUTH_WEST)); assertEquals(6, squareEdge.compassToIndex(Compass.WEST)); assertEquals(7, squareEdge.compassToIndex(Compass.NORTH_WEST)); }
RegularPolygon { public double indexToAngle(int index) { final double segment = 360.0 / connectivity; double angle = Fortran.modulo(index, connectivity) * segment; if (!hasTopIndex) angle += segment / 2.0; return Fortran.modulo(angle - 90.0, 360.0); } RegularPolygon(double length, int sides, PolygonOrientation orientation); RegularPolygon(double length, int sides, PolygonOrientation orientation, boolean vertexNeighbors); int angleToIndex(double angle); RegularPolygon circumscribe(double radius); RegularPolygon circumscribe(double width, double height); int compassToIndex(Compass compass); double indexToAngle(int index); Compass indexToCompass(int index); RegularPolygon inflate(double delta); RegularPolygon inscribe(double radius); RegularPolygon inscribe(double width, double height); int opposingIndex(int index); RegularPolygon resize(double length); final RectD bounds; final int connectivity; final boolean hasTopIndex; final double innerRadius; final double length; final PolygonOrientation orientation; final double outerRadius; final int sides; final boolean vertexNeighbors; final PointD[] vertices; }
@Test public void testIndexToAngle() { assertEquals(30.0, hexagonEdge.indexToAngle(2), 0); assertEquals(90.0, hexagonEdge.indexToAngle(3), 0); assertEquals(150.0, hexagonEdge.indexToAngle(4), 0); assertEquals(210.0, hexagonEdge.indexToAngle(5), 0); assertEquals(270.0, hexagonEdge.indexToAngle(6), 0); assertEquals(330.0, hexagonEdge.indexToAngle(7), 0); assertEquals(60.0, hexagonVertex.indexToAngle(2), 0); assertEquals(120.0, hexagonVertex.indexToAngle(3), 0); assertEquals(180.0, hexagonVertex.indexToAngle(4), 0); assertEquals(240.0, hexagonVertex.indexToAngle(5), 0); assertEquals(300.0, hexagonVertex.indexToAngle(6), 0); assertEquals(0.0, hexagonVertex.indexToAngle(7), 0); assertEquals(0.0, squareEdge.indexToAngle(2), 0); assertEquals(45.0, squareEdge.indexToAngle(3), 0); assertEquals(90.0, squareEdge.indexToAngle(4), 0); assertEquals(135.0, squareEdge.indexToAngle(-3), 0); assertEquals(180.0, squareEdge.indexToAngle(-2), 0); assertEquals(225.0, squareEdge.indexToAngle(-1), 0); assertEquals(270.0, squareEdge.indexToAngle(0), 0); assertEquals(315.0, squareEdge.indexToAngle(1), 0); }
RegularPolygon { public Compass indexToCompass(int index) { final double degrees = indexToAngle(index) + 90; return Angle.degreesToCompass(degrees); } RegularPolygon(double length, int sides, PolygonOrientation orientation); RegularPolygon(double length, int sides, PolygonOrientation orientation, boolean vertexNeighbors); int angleToIndex(double angle); RegularPolygon circumscribe(double radius); RegularPolygon circumscribe(double width, double height); int compassToIndex(Compass compass); double indexToAngle(int index); Compass indexToCompass(int index); RegularPolygon inflate(double delta); RegularPolygon inscribe(double radius); RegularPolygon inscribe(double width, double height); int opposingIndex(int index); RegularPolygon resize(double length); final RectD bounds; final int connectivity; final boolean hasTopIndex; final double innerRadius; final double length; final PolygonOrientation orientation; final double outerRadius; final int sides; final boolean vertexNeighbors; final PointD[] vertices; }
@Test public void testIndexToCompass() { assertEquals(Compass.SOUTH_EAST, hexagonEdge.indexToCompass(2)); assertEquals(Compass.SOUTH, hexagonEdge.indexToCompass(3)); assertEquals(Compass.SOUTH_WEST, hexagonEdge.indexToCompass(4)); assertEquals(Compass.NORTH_WEST, hexagonEdge.indexToCompass(5)); assertEquals(Compass.NORTH, hexagonEdge.indexToCompass(6)); assertEquals(Compass.NORTH_EAST, hexagonEdge.indexToCompass(7)); assertEquals(Compass.SOUTH_EAST, hexagonVertex.indexToCompass(2)); assertEquals(Compass.SOUTH_WEST, hexagonVertex.indexToCompass(3)); assertEquals(Compass.WEST, hexagonVertex.indexToCompass(4)); assertEquals(Compass.NORTH_WEST, hexagonVertex.indexToCompass(5)); assertEquals(Compass.NORTH_EAST, hexagonVertex.indexToCompass(6)); assertEquals(Compass.EAST, hexagonVertex.indexToCompass(7)); assertEquals(Compass.EAST, squareEdge.indexToCompass(2)); assertEquals(Compass.SOUTH_EAST, squareEdge.indexToCompass(3)); assertEquals(Compass.SOUTH, squareEdge.indexToCompass(4)); assertEquals(Compass.SOUTH_WEST, squareEdge.indexToCompass(-3)); assertEquals(Compass.WEST, squareEdge.indexToCompass(-2)); assertEquals(Compass.NORTH_WEST, squareEdge.indexToCompass(-1)); assertEquals(Compass.NORTH, squareEdge.indexToCompass(0)); assertEquals(Compass.NORTH_EAST, squareEdge.indexToCompass(1)); }
LineIntersection { @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || !(obj instanceof LineIntersection)) return false; final LineIntersection other = (LineIntersection) obj; return (first == other.first && second == other.second && relation == other.relation && shared.equals(other.shared)); } private LineIntersection(LineRelation relation); private LineIntersection(PointD shared, LineLocation first, LineLocation second, LineRelation relation); boolean exists(); boolean existsBetween(); static LineIntersection find(PointD startA, PointD endA, PointD startB, PointD endB); static LineIntersection find(PointD startA, PointD endA, PointD startB, PointD endB, double epsilon); static LineLocation locateCollinear(PointD start, PointD end, PointD q); static LineLocation locateCollinear(PointD start, PointD end, PointD q, double epsilon); PointD startOrEnd(LineD a, LineD b); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final LineLocation first; final LineLocation second; final LineRelation relation; final PointD shared; }
@Test public void testIntersect() { LineIntersection result = new LineD(0, 0, 0.9, 0.9).intersect(new LineD(1, 1, 2, 2)); assertEquals(null, result.shared); assertEquals(null, result.first); assertEquals(null, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); result = new LineD(0, 1, 2, 3).intersect(new LineD(1, 0, 3, 2)); assertEquals(null, result.shared); assertEquals(null, result.first); assertEquals(null, result.second); assertEquals(LineRelation.PARALLEL, result.relation); result = new LineD(0, 0, 0.9, 0.9).intersect(new LineD(0, 2, 0.9, 1.1)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.AFTER, result.first); assertEquals(LineLocation.AFTER, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(0.9, 0.9, 0, 0).intersect(new LineD(1.1, 0.9, 2, 0)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.BEFORE, result.first); assertEquals(LineLocation.BEFORE, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); } @Test public void testIntersectCollinear() { LineIntersection result = new LineD(1, 1, 0, 0).intersect(new LineD(1, 1, 0, 0)); assertTrue(PointD.equals(new PointD(0, 0), result.shared, 0.01)); assertEquals(LineLocation.END, result.first); assertEquals(LineLocation.END, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); result = new LineD(0, 0, 1, 1).intersect(new LineD(1, 1, 2, 2)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.END, result.first); assertEquals(LineLocation.START, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); result = new LineD(1, 1, 0, 0).intersect(new LineD(2, 2, 1, 1)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.START, result.first); assertEquals(LineLocation.END, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); result = new LineD(0, 0, 2, 2).intersect(new LineD(3, 3, 1, 1)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.BETWEEN, result.first); assertEquals(LineLocation.END, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); } @Test public void testIntersectDivergent() { LineIntersection result = new LineD(0, 0, 1, 1).intersect(new LineD(1, 1, 2, 0)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.END, result.first); assertEquals(LineLocation.START, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(1, 1, 0, 0).intersect(new LineD(2, 0, 1, 1)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.START, result.first); assertEquals(LineLocation.END, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(0, 0, 2, 2).intersect(new LineD(1, 1, 2, 0)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.BETWEEN, result.first); assertEquals(LineLocation.START, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(0, 0, 1, 1).intersect(new LineD(0, 2, 2, 0)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.END, result.first); assertEquals(LineLocation.BETWEEN, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(0, 0, 2, 2).intersect(new LineD(0, 2, 2, 0)); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.BETWEEN, result.first); assertEquals(LineLocation.BETWEEN, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); } @Test public void testIntersectEpsilon() { LineIntersection result = new LineD(0, 0, 0.9, 0.9).intersect(new LineD(1, 1, 2, 2), 0.01); assertEquals(null, result.shared); assertEquals(null, result.first); assertEquals(null, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); result = new LineD(0, 0, 0.9, 0.9).intersect(new LineD(1, 1, 2, 2), 0.5); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.END, result.first); assertEquals(LineLocation.START, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); result = new LineD(0.9, 0.9, 0.1, 0.1).intersect(new LineD(1.1, 1.1, 0, 0), 0.5); assertTrue(PointD.equals(new PointD(0, 0), result.shared, 0.01)); assertEquals(LineLocation.END, result.first); assertEquals(LineLocation.END, result.second); assertEquals(LineRelation.COLLINEAR, result.relation); result = new LineD(0, 0, 0.9, 0.9).intersect(new LineD(1, 1, 2, 0), 0.01); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.AFTER, result.first); assertEquals(LineLocation.START, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(0, 0, 0.9, 0.9).intersect(new LineD(1, 1, 2, 0), 0.5); assertTrue(PointD.equals(new PointD(0.9, 0.9), result.shared, 0.01)); assertEquals(LineLocation.END, result.first); assertEquals(LineLocation.START, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(0, 0, 2, 2).intersect(new LineD(0.9, 1.1, 2, 0), 0.01); assertTrue(PointD.equals(new PointD(1, 1), result.shared, 0.01)); assertEquals(LineLocation.BETWEEN, result.first); assertEquals(LineLocation.BETWEEN, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); result = new LineD(0, 0, 2, 2).intersect(new LineD(0.9, 1.1, 2, 0), 0.5); assertTrue(PointD.equals(new PointD(0.9, 1.1), result.shared, 0.01)); assertEquals(LineLocation.BETWEEN, result.first); assertEquals(LineLocation.START, result.second); assertEquals(LineRelation.DIVERGENT, result.relation); }
Fortran { public static long knint(double n) { if (n > 0.0) return MathUtils.toLongExact(n + 0.5); else if (n < 0.0) return MathUtils.toLongExact(n - 0.5); else return 0; } private Fortran(); static double aint(double n); static float aint(float n); static double anint(double n); static float anint(float n); static int ceiling(double n); static int ceiling(float n); static int floor(double n); static int floor(float n); static long knint(double n); static long knint(float n); static double max(double... args); static float max(float... args); static int max(int... args); static long max(long... args); static double min(double... args); static float min(float... args); static int min(int... args); static long min(long... args); static double modulo(double a, double p); static float modulo(float a, float p); static int modulo(int a, int p); static long modulo(long a, long p); static int nint(double n); static int nint(float n); static double sum(double... args); static float sum(float... args); static int sum(int... args); static long sum(long... args); }
@Test public void testKnint() { assertEquals(4L, Fortran.knint(3.6d)); assertEquals(4L, Fortran.knint(3.5d)); assertEquals(3L, Fortran.knint(3.4d)); assertEquals(-4L, Fortran.knint(-3.6d)); assertEquals(-4L, Fortran.knint(-3.5d)); assertEquals(-3L, Fortran.knint(-3.4d)); assertEquals(4L, Fortran.knint(3.6f)); assertEquals(4L, Fortran.knint(3.5f)); assertEquals(3L, Fortran.knint(3.4f)); assertEquals(-4L, Fortran.knint(-3.6f)); assertEquals(-4L, Fortran.knint(-3.5f)); assertEquals(-3L, Fortran.knint(-3.4f)); try { Fortran.knint(1e100); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { Fortran.knint(1e30f); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } }
Voronoi { private Voronoi(PointD[] points, RectD[] clip, boolean findDelaunay) { if (points == null) throw new NullPointerException("points"); if (points.length < 2) throw new IllegalArgumentException("points.length < 2"); if (clip == null) throw new NullPointerException("clip"); if (clip.length != 1) throw new IllegalArgumentException("clip.length != 1"); _sites = new SiteVertex[points.length]; for (int i = 0; i < _sites.length; i++) _sites[i] = new SiteVertex(points[i], i); final Comparator<SiteVertex> comparator = (s, t) -> { if (s == t) return 0; if (s.y < t.y) return -1; if (s.y > t.y) return 1; if (s.x < t.x) return -1; if (s.x > t.x) return 1; return 0; }; Arrays.sort(_sites, comparator); _minX = _maxX = _sites[0].x; for (int i = 1; i < _sites.length; i++) { final double x = _sites[i].x; if (x < _minX) _minX = x; if (x > _maxX) _maxX = x; } _minY = _sites[0].y; _maxY = _sites[_sites.length - 1].y; final int maxVertexCount = Math.max(0, 2 * _sites.length - 5); final int maxEdgeCount = Math.max(1, 3 * _sites.length - 6); if (findDelaunay) { _delaunayEdges = new ArrayList<>(maxEdgeCount); return; } final double dx = _maxX - _minX; final double dy = _maxY - _minY; final double d = Math.max(dx, dy) * 1.1; _minClipX = _minX - (d - dx) / 2; _maxClipX = _maxX + (d - dx) / 2; _minClipY = _minY - (d - dy) / 2; _maxClipY = _maxY + (d - dy) / 2; if (clip[0].width() > 0 && clip[0].height() > 0) { _minClipX = Math.min(_minClipX, clip[0].min.x); _maxClipX = Math.max(_maxClipX, clip[0].max.x); _minClipY = Math.min(_minClipY, clip[0].min.y); _maxClipY = Math.max(_maxClipY, clip[0].max.y); } clip[0] = new RectD( new PointD(_minClipX, _minClipY), new PointD(_maxClipX, _maxClipY)); _voronoiVertices = new ArrayList<>(maxVertexCount + 5); _voronoiEdges = new ArrayList<>(maxEdgeCount); _vertexIndices = new int[maxVertexCount]; } private Voronoi(PointD[] points, RectD[] clip, boolean findDelaunay); static VoronoiResults findAll(PointD[] points); static VoronoiResults findAll(PointD[] points, RectD clip); static PointI[] findDelaunay(PointD[] points); static Subdivision findDelaunaySubdivision(PointD[] points); }
@Test public void testVoronoi() { for (int i = 0; i < 10; i++) testVoronoiResults(createRandom(100, -1000, -1000, 2000, 2000)); }