method2testcases
stringlengths 118
3.08k
|
---|
### Question:
StateGuard { public <E extends Exception> void withReadLock(GuardedRunnable<E> task) throws E { lockRead(); try { task.run(); } finally { unlockRead(); } } StateGuard(Class<?> type); boolean withReadLockIfInitialized(GuardedRunnable<E> task); boolean withWriteLockIfInitialized(GuardedRunnable<E> task); void withReadLock(GuardedRunnable<E> task); T withReadLock(GuardedSupplier<T, E> task); void withWriteLock(GuardedRunnable<E> task); T withWriteLock(GuardedSupplier<T, E> task); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); void becomeInitialized(GuardedRunnable<E> task); boolean isInitialized(); boolean becomeTerminating(); Waiting becomeTerminating(GuardedSupplier<List<Waiting>, E> task); void becomeTerminating(GuardedRunnable<E> task); boolean becomeTerminated(); Waiting becomeTerminated(GuardedSupplier<List<Waiting>, E> task); void becomeTerminated(GuardedRunnable<E> task); void lockReadWithStateCheck(); void lockReadWithStateCheck(State state); T withReadLockAndStateCheck(GuardedSupplier<T, E> task); void withReadLockAndStateCheck(GuardedRunnable<E> task); boolean tryLockReadWithStateCheck(); boolean tryLockReadWithStateCheck(State state); void lockRead(); boolean tryLockRead(long timeout, TimeUnit unit); void unlockRead(); void lockWriteWithStateCheck(); void lockWrite(); boolean tryLockWrite(long timeout, TimeUnit unit); void unlockWrite(); boolean isWriteLocked(); @Override String toString(); }### Answer:
@Test public void testRunWithReadLock() throws Exception { GuardedRunnable<?> task = mock(GuardedRunnable.class); guard.withReadLock(task); verify(task).run(); verifyNoMoreInteractions(task); }
@Test public void testGetWithReadLock() throws Exception { GuardedSupplier<String, ?> task = () -> "test"; assertEquals("test", guard.withReadLock(task)); } |
### Question:
StateGuard { public boolean becomeTerminating() { assert writeLock.isHeldByCurrentThread() : "Thread must hold write lock."; if (state != TERMINATED && state != TERMINATING) { state = TERMINATING; return true; } return false; } StateGuard(Class<?> type); boolean withReadLockIfInitialized(GuardedRunnable<E> task); boolean withWriteLockIfInitialized(GuardedRunnable<E> task); void withReadLock(GuardedRunnable<E> task); T withReadLock(GuardedSupplier<T, E> task); void withWriteLock(GuardedRunnable<E> task); T withWriteLock(GuardedSupplier<T, E> task); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); void becomeInitialized(GuardedRunnable<E> task); boolean isInitialized(); boolean becomeTerminating(); Waiting becomeTerminating(GuardedSupplier<List<Waiting>, E> task); void becomeTerminating(GuardedRunnable<E> task); boolean becomeTerminated(); Waiting becomeTerminated(GuardedSupplier<List<Waiting>, E> task); void becomeTerminated(GuardedRunnable<E> task); void lockReadWithStateCheck(); void lockReadWithStateCheck(State state); T withReadLockAndStateCheck(GuardedSupplier<T, E> task); void withReadLockAndStateCheck(GuardedRunnable<E> task); boolean tryLockReadWithStateCheck(); boolean tryLockReadWithStateCheck(State state); void lockRead(); boolean tryLockRead(long timeout, TimeUnit unit); void unlockRead(); void lockWriteWithStateCheck(); void lockWrite(); boolean tryLockWrite(long timeout, TimeUnit unit); void unlockWrite(); boolean isWriteLocked(); @Override String toString(); }### Answer:
@Test public void testBecomeTerminating() { guard.lockWrite(); try { assertFalse(guard.becomeTerminating()); guard.becomeInitialized(); assertTrue(guard.becomeTerminating()); } finally { guard.unlockWrite(); } } |
### Question:
StateGuard { public boolean becomeTerminated() { assert writeLock.isHeldByCurrentThread() : "Thread must hold write lock."; if (state != TERMINATED) { state = TERMINATED; return true; } return false; } StateGuard(Class<?> type); boolean withReadLockIfInitialized(GuardedRunnable<E> task); boolean withWriteLockIfInitialized(GuardedRunnable<E> task); void withReadLock(GuardedRunnable<E> task); T withReadLock(GuardedSupplier<T, E> task); void withWriteLock(GuardedRunnable<E> task); T withWriteLock(GuardedSupplier<T, E> task); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); void becomeInitialized(GuardedRunnable<E> task); boolean isInitialized(); boolean becomeTerminating(); Waiting becomeTerminating(GuardedSupplier<List<Waiting>, E> task); void becomeTerminating(GuardedRunnable<E> task); boolean becomeTerminated(); Waiting becomeTerminated(GuardedSupplier<List<Waiting>, E> task); void becomeTerminated(GuardedRunnable<E> task); void lockReadWithStateCheck(); void lockReadWithStateCheck(State state); T withReadLockAndStateCheck(GuardedSupplier<T, E> task); void withReadLockAndStateCheck(GuardedRunnable<E> task); boolean tryLockReadWithStateCheck(); boolean tryLockReadWithStateCheck(State state); void lockRead(); boolean tryLockRead(long timeout, TimeUnit unit); void unlockRead(); void lockWriteWithStateCheck(); void lockWrite(); boolean tryLockWrite(long timeout, TimeUnit unit); void unlockWrite(); boolean isWriteLocked(); @Override String toString(); }### Answer:
@Test public void testBecomeTerminated() { guard.lockWrite(); try { assertFalse(guard.becomeTerminated()); guard.becomeInitialized(); assertTrue(guard.becomeTerminated()); } finally { guard.unlockWrite(); } } |
### Question:
StateGuard { public boolean tryLockReadWithStateCheck() { lockRead(); if (state != INITIALIZED) { unlockRead(); return false; } return true; } StateGuard(Class<?> type); boolean withReadLockIfInitialized(GuardedRunnable<E> task); boolean withWriteLockIfInitialized(GuardedRunnable<E> task); void withReadLock(GuardedRunnable<E> task); T withReadLock(GuardedSupplier<T, E> task); void withWriteLock(GuardedRunnable<E> task); T withWriteLock(GuardedSupplier<T, E> task); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); void becomeInitialized(GuardedRunnable<E> task); boolean isInitialized(); boolean becomeTerminating(); Waiting becomeTerminating(GuardedSupplier<List<Waiting>, E> task); void becomeTerminating(GuardedRunnable<E> task); boolean becomeTerminated(); Waiting becomeTerminated(GuardedSupplier<List<Waiting>, E> task); void becomeTerminated(GuardedRunnable<E> task); void lockReadWithStateCheck(); void lockReadWithStateCheck(State state); T withReadLockAndStateCheck(GuardedSupplier<T, E> task); void withReadLockAndStateCheck(GuardedRunnable<E> task); boolean tryLockReadWithStateCheck(); boolean tryLockReadWithStateCheck(State state); void lockRead(); boolean tryLockRead(long timeout, TimeUnit unit); void unlockRead(); void lockWriteWithStateCheck(); void lockWrite(); boolean tryLockWrite(long timeout, TimeUnit unit); void unlockWrite(); boolean isWriteLocked(); @Override String toString(); }### Answer:
@Test public void testTryLockReadWithStateCheck() { assertFalse(guard.tryLockReadWithStateCheck()); assertFalse(guard.tryLockReadWithStateCheck(StateGuard.State.INITIALIZED)); guard.lockWrite(); guard.becomeInitialized(); guard.unlockWrite(); assertTrue(guard.tryLockReadWithStateCheck()); guard.unlockRead(); assertTrue(guard.tryLockReadWithStateCheck(StateGuard.State.INITIALIZED)); guard.unlockRead(); } |
### Question:
StateGuard { public void lockWriteWithStateCheck() { lockWrite(); if (state != INITIALIZED) { unlockWrite(); throw new IllegalStateException(type.getSimpleName() + " is not " + INITIALIZED.name().toLowerCase(Locale.US) + '.'); } } StateGuard(Class<?> type); boolean withReadLockIfInitialized(GuardedRunnable<E> task); boolean withWriteLockIfInitialized(GuardedRunnable<E> task); void withReadLock(GuardedRunnable<E> task); T withReadLock(GuardedSupplier<T, E> task); void withWriteLock(GuardedRunnable<E> task); T withWriteLock(GuardedSupplier<T, E> task); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); void becomeInitialized(GuardedRunnable<E> task); boolean isInitialized(); boolean becomeTerminating(); Waiting becomeTerminating(GuardedSupplier<List<Waiting>, E> task); void becomeTerminating(GuardedRunnable<E> task); boolean becomeTerminated(); Waiting becomeTerminated(GuardedSupplier<List<Waiting>, E> task); void becomeTerminated(GuardedRunnable<E> task); void lockReadWithStateCheck(); void lockReadWithStateCheck(State state); T withReadLockAndStateCheck(GuardedSupplier<T, E> task); void withReadLockAndStateCheck(GuardedRunnable<E> task); boolean tryLockReadWithStateCheck(); boolean tryLockReadWithStateCheck(State state); void lockRead(); boolean tryLockRead(long timeout, TimeUnit unit); void unlockRead(); void lockWriteWithStateCheck(); void lockWrite(); boolean tryLockWrite(long timeout, TimeUnit unit); void unlockWrite(); boolean isWriteLocked(); @Override String toString(); }### Answer:
@Test public void testLockWriteWithStateCheck() { expect( IllegalStateException.class, getClass().getSimpleName() + " is not initialized.", guard::lockWriteWithStateCheck ); guard.lockWrite(); guard.becomeInitialized(); guard.unlockWrite(); guard.lockWriteWithStateCheck(); assertTrue(guard.isWriteLocked()); guard.unlockWrite(); } |
### Question:
StateGuard { @Override public String toString() { readLock.lock(); try { return ToString.format(this); } finally { readLock.unlock(); } } StateGuard(Class<?> type); boolean withReadLockIfInitialized(GuardedRunnable<E> task); boolean withWriteLockIfInitialized(GuardedRunnable<E> task); void withReadLock(GuardedRunnable<E> task); T withReadLock(GuardedSupplier<T, E> task); void withWriteLock(GuardedRunnable<E> task); T withWriteLock(GuardedSupplier<T, E> task); void becomeInitializing(); boolean isInitializing(); void becomeInitialized(); void becomeInitialized(GuardedRunnable<E> task); boolean isInitialized(); boolean becomeTerminating(); Waiting becomeTerminating(GuardedSupplier<List<Waiting>, E> task); void becomeTerminating(GuardedRunnable<E> task); boolean becomeTerminated(); Waiting becomeTerminated(GuardedSupplier<List<Waiting>, E> task); void becomeTerminated(GuardedRunnable<E> task); void lockReadWithStateCheck(); void lockReadWithStateCheck(State state); T withReadLockAndStateCheck(GuardedSupplier<T, E> task); void withReadLockAndStateCheck(GuardedRunnable<E> task); boolean tryLockReadWithStateCheck(); boolean tryLockReadWithStateCheck(State state); void lockRead(); boolean tryLockRead(long timeout, TimeUnit unit); void unlockRead(); void lockWriteWithStateCheck(); void lockWrite(); boolean tryLockWrite(long timeout, TimeUnit unit); void unlockWrite(); boolean isWriteLocked(); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(guard.toString(), ToString.format(guard), guard.toString()); } |
### Question:
CloudSeedNodeProviderConfig extends CloudPropertiesBase<CloudSeedNodeProviderConfig> { @Override public String toString() { return ToString.format(this); } String getProvider(); void setProvider(String provider); CloudSeedNodeProviderConfig withProvider(String provider); String getEndpoint(); void setEndpoint(String endpoint); CloudSeedNodeProviderConfig withEndpoint(String endpoint); CredentialsSupplier getCredentials(); void setCredentials(CredentialsSupplier credentials); CloudSeedNodeProviderConfig withCredentials(CredentialsSupplier credentials); Properties getProperties(); void setProperties(Properties properties); CloudSeedNodeProviderConfig withProperty(String key, String value); Set<String> getRegions(); void setRegions(Set<String> regions); CloudSeedNodeProviderConfig withRegion(String region); Set<String> getZones(); void setZones(Set<String> zones); CloudSeedNodeProviderConfig withZone(String zone); Map<String, String> getTags(); void setTags(Map<String, String> tags); CloudSeedNodeProviderConfig withTag(String name, String value); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
StampedStateGuard { public void becomeInitializing() { assert lock.isWriteLocked() : "Thread must hold write lock."; if (state == INITIALIZING || state == INITIALIZED) { throw new IllegalStateException(type.getSimpleName() + " is already " + state.name().toLowerCase(Locale.US) + '.'); } state = INITIALIZING; } 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(); }### Answer:
@Test public void testBecomeInitializing() { long lock = guard.lockWrite(); try { assertFalse(guard.isInitializing()); guard.becomeInitializing(); assertTrue(guard.isInitializing()); expect(IllegalStateException.class, getClass().getSimpleName() + " is already initializing.", guard::becomeInitializing); } finally { guard.unlockWrite(lock); } } |
### Question:
StampedStateGuard { public void becomeInitialized() { assert lock.isWriteLocked() : "Thread must hold write lock."; if (state == INITIALIZED) { throw new IllegalStateException(type.getSimpleName() + " is already " + INITIALIZED.name().toLowerCase(Locale.US) + '.'); } state = INITIALIZED; } 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(); }### Answer:
@Test public void testBecomeInitialized() { long lock = guard.lockWrite(); try { assertFalse(guard.isInitialized()); guard.becomeInitialized(); assertTrue(guard.isInitialized()); expect(IllegalStateException.class, getClass().getSimpleName() + " is already initialized.", guard::becomeInitialized); expect(IllegalStateException.class, getClass().getSimpleName() + " is already initialized.", guard::becomeInitializing); } finally { guard.unlockWrite(lock); } } |
### Question:
StampedStateGuard { public boolean becomeTerminating() { assert lock.isWriteLocked() : "Thread must hold write lock."; if (state != TERMINATING && state != TERMINATED) { state = TERMINATING; 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(); }### Answer:
@Test public void testBecomeTerminating() { long lock = guard.lockWrite(); try { assertFalse(guard.becomeTerminating()); guard.becomeInitialized(); assertTrue(guard.becomeTerminating()); } finally { guard.unlockWrite(lock); } } |
### Question:
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(); }### Answer:
@Test public void testBecomeTerminated() { long lock = guard.lockWrite(); try { assertFalse(guard.becomeTerminated()); guard.becomeInitialized(); assertTrue(guard.becomeTerminated()); } finally { guard.unlockWrite(lock); } } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void testToString() { assertEquals(guard.toString(), ToString.format(guard), guard.toString()); } |
### Question:
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; }### Answer:
@Test public void testToString() { cfg.setEndpoints(singletonList("http: cfg.setUsername("test"); cfg.setPassword("test"); assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
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); }### Answer:
@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))); } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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); } } |
### Question:
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; }### Answer:
@Test public void testToString() { cfg.setUrl("http: assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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); } } |
### Question:
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(); }### Answer:
@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))); } |
### Question:
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(); }### Answer:
@Test public void testToString() { assertTrue(cfg.toString(), cfg.toString().startsWith(CandidateConfig.class.getSimpleName())); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void testOnLockAcquire() throws Exception { handler.onLockAcquire(lock); verify(candidate).becomeLeader(leaderCtx.capture()); assertEquals(localNode, leaderCtx.getValue().localNode()); } |
### Question:
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(); }### Answer:
@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()) ); } } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void testToString() { assertTrue(factory.toString(), factory.toString().startsWith(ElectionServiceFactory.class.getSimpleName())); } |
### Question:
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(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
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(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(factory), factory.toString()); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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; }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
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); }### Answer:
@Test public void testRegister() { registry.doRegister(serviceUrl); }
@Test public void registryService() throws Exception { registry.doRegister(serviceUrl); } |
### Question:
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); }### Answer:
@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()); } } |
### Question:
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); }### Answer:
@Test public void keepAlive() { URL url = serviceUrl; registry.keepAlive(url); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
SessionTracker { void flushSessions(Date now) { if (shuttingDown.get()) { return; } sendSessions(now); } SessionTracker(Configuration configuration); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test public void testDefaults() { assertTrue(config.shouldAutoCaptureSessions()); } |
### Question:
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; }### Answer:
@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")); } |
### Question:
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; }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testUncaughtHandlerModification() { Set<Bugsnag> bugsnags = Bugsnag.uncaughtExceptionClients(); bugsnags.clear(); } |
### Question:
MetaData extends HashMap<String, Object> { void clearTab(String tabName) { remove(tabName); } void addToTab(String tabName, String key, Object value); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testInvalidUserSpecified() { HandledState.newInstance( HandledState.SeverityReasonType.REASON_CALLBACK_SPECIFIED); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test public void testThreadName() { for (ThreadState threadState : threadStates) { assertNotNull(threadState.getName()); } } |
### Question:
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); }### Answer:
@Test public void testThreadStacktrace() { for (ThreadState threadState : threadStates) { List<Stackframe> stacktrace = threadState.getStacktrace(); assertNotNull(stacktrace); } } |
### Question:
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(); }### Answer:
@Test public void testSize() { assertEquals(4, filteredMap.size()); } |
### Question:
ScheduledTaskBeanLocator implements ApplicationContextAware { TaskScheduler resolveTaskScheduler() { return resolveSchedulerBean(TaskScheduler.class); } @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@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()); } |
### Question:
ScheduledTaskBeanLocator implements ApplicationContextAware { ScheduledExecutorService resolveScheduledExecutorService() { return resolveSchedulerBean(ScheduledExecutorService.class); } @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void testIsEmpty() { assertFalse(filteredMap.isEmpty()); Map<String, Object> map = Collections.emptyMap(); FilteredMap emptyMap = new FilteredMap(map, Collections.<String>emptyList()); assertTrue(emptyMap.isEmpty()); } |
### Question:
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(); }### Answer:
@Test public void testClear() { assertEquals(4, filteredMap.size()); filteredMap.clear(); assertTrue(filteredMap.isEmpty()); } |
### Question:
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(); }### Answer:
@Test public void testContainsKey() { assertTrue(filteredMap.containsKey(KEY_FILTERED)); assertTrue(filteredMap.containsKey(KEY_UNFILTERED)); assertTrue(filteredMap.containsKey(KEY_NESTED)); assertFalse(filteredMap.containsKey("fake")); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@Test public void apiHost_shouldRemoveScheme() { Config c = newConfig("hostwithhttp.com:1234"); assertThat(c.getApiHost()).isEqualTo("hostwithhttp.com:1234"); assertThat( newConfig("http: assertThat( newConfig("https: } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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) { } } |
### Question:
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); }### Answer:
@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))); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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); } } |
### Question:
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; }### Answer:
@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); } } |
### Question:
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; }### Answer:
@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); } |
### Question:
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); }### Answer:
@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) { } } |
### Question:
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; }### Answer:
@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) { } } |
### Question:
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; }### Answer:
@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); } |
### Question:
PointDComparatorX extends PointDComparator { public static int compareExact(PointD a, PointD b) { if (a == b) return 0; if (a.x < b.x) return -1; if (a.x > b.x) return +1; if (a.y < b.y) return -1; if (a.y > b.y) return +1; return 0; } PointDComparatorX(); PointDComparatorX(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); }### Answer:
@Test public void testCompareExact() { assertEquals(0, PointDComparatorX.compareExact(new PointD(1, 2), new PointD(1, 2))); assertEquals(-1, PointDComparatorX.compareExact(new PointD(1, 2), new PointD(2, 2))); assertEquals(-1, PointDComparatorX.compareExact(new PointD(1, 2), new PointD(1, 3))); assertEquals(+1, PointDComparatorX.compareExact(new PointD(1, 2), new PointD(0, 2))); assertEquals(+1, PointDComparatorX.compareExact(new PointD(1, 2), new PointD(1, 1))); assertEquals(-1, PointDComparatorX.compareExact(new PointD(1, 2), new PointD(2, 1))); assertEquals(+1, PointDComparatorX.compareExact(new PointD(2, 1), new PointD(1, 2))); } |
### Question:
QuadTree extends AbstractMap<PointD, V> { @Override public V get(Object key) { final Node<V> node = findNode((PointD) key); return (checkLeaf(node) ? node._entries.get(key) : null); } QuadTree(RectD bounds); QuadTree(RectD bounds, int capacity); QuadTree(RectD bounds, Map<PointD, V> map); boolean containsKey(PointD key, Node<V> node); boolean containsValue(V value, Node<V> node); void copyTo(Map.Entry<PointD, V>[] array, int arrayIndex); Node<V> findNode(int level, int gridX, int gridY); Node<V> findNode(PointD key); Node<V> findNodeByValue(V value); Map<PointD, V> findRange(PointD center, double radius); Map<PointD, V> findRange(RectD range); Node<V> move(PointD oldKey, PointD newKey, Node<V> node); Map<Integer, Node<V>> nodes(); void setProbeUseBitMask(boolean value); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Set<Entry<PointD, V>> entrySet(); @Override V get(Object key); @Override V put(PointD key, V value); @Override void putAll(Map<? extends PointD, ? extends V> map); @Override V remove(Object key); @Override boolean remove(Object key, Object value); @Override V replace(PointD key, V value); @Override boolean replace(PointD key, V oldValue, V newValue); final static int MAX_LEVEL; final static int PROBE_LEVEL; final RectD bounds; final int capacity; final Node<V> rootNode; }### Answer:
@Test public void testGet() { assertEquals("first value", _tree.get(firstKey)); assertEquals(null, _tree.get(invalidKey)); } |
### Question:
MathUtils { public static <T> T getAny(T[] array) { try { return array[RANDOM.nextInt(array.length)]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("empty array", e); } } private MathUtils(); static int compare(double a, double b, double epsilon); static int compare(float a, float b, float epsilon); static boolean equals(double a, double b, double epsilon); static boolean equals(float a, float b, float epsilon); static T getAny(T[] array); static T getAny(Collection<T> collection); static T getAny(List<T> list); static boolean isPrime(int candidate); static double normalize(double[] array); static float normalize(float[] array); static double restrict(double a, double min, double max); static float restrict(float a, float min, float max); static int restrict(int a, int min, int max); static long restrict(long a, long min, long max); static int toIntExact(double value); static int toIntExact(float value); static long toLongExact(double value); static long toLongExact(float value); }### Answer:
@Test public void testGetAny() { final String[] array = new String[] { "a" }; assertEquals("a", MathUtils.<String>getAny(array)); assertEquals("a", MathUtils.<String>getAny(Arrays.asList(array))); assertEquals("a", MathUtils.<String>getAny(new HashSet<>(Arrays.asList(array)))); try { MathUtils.<String>getAny(new String[] {}); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } try { MathUtils.<String>getAny(new HashSet<>()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } try { MathUtils.<String>getAny(new ArrayList<>()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } } |
### Question:
MathUtils { public static boolean isPrime(int candidate) { if (candidate <= 0) throw new IllegalArgumentException("candidate <= 0"); if ((candidate & 1) == 0) return (candidate == 2); final int root = (int) Math.sqrt(candidate); for (int i = 3; i <= root; i += 2) if ((candidate % i) == 0) return false; return true; } private MathUtils(); static int compare(double a, double b, double epsilon); static int compare(float a, float b, float epsilon); static boolean equals(double a, double b, double epsilon); static boolean equals(float a, float b, float epsilon); static T getAny(T[] array); static T getAny(Collection<T> collection); static T getAny(List<T> list); static boolean isPrime(int candidate); static double normalize(double[] array); static float normalize(float[] array); static double restrict(double a, double min, double max); static float restrict(float a, float min, float max); static int restrict(int a, int min, int max); static long restrict(long a, long min, long max); static int toIntExact(double value); static int toIntExact(float value); static long toLongExact(double value); static long toLongExact(float value); }### Answer:
@Test public void testIsPrime() { assertTrue(MathUtils.isPrime(1)); assertTrue(MathUtils.isPrime(2)); assertTrue(MathUtils.isPrime(3)); assertTrue(MathUtils.isPrime(3559)); assertFalse(MathUtils.isPrime(4)); assertFalse(MathUtils.isPrime(3561)); try { MathUtils.isPrime(0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } try { MathUtils.isPrime(-1); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } } |
### Question:
MathUtils { public static int toIntExact(double value) { if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) throw new ArithmeticException("value <> Integer: " + value); return (int) value; } private MathUtils(); static int compare(double a, double b, double epsilon); static int compare(float a, float b, float epsilon); static boolean equals(double a, double b, double epsilon); static boolean equals(float a, float b, float epsilon); static T getAny(T[] array); static T getAny(Collection<T> collection); static T getAny(List<T> list); static boolean isPrime(int candidate); static double normalize(double[] array); static float normalize(float[] array); static double restrict(double a, double min, double max); static float restrict(float a, float min, float max); static int restrict(int a, int min, int max); static long restrict(long a, long min, long max); static int toIntExact(double value); static int toIntExact(float value); static long toLongExact(double value); static long toLongExact(float value); }### Answer:
@Test public void testToIntExact() { try { MathUtils.toIntExact(2.0 * Integer.MAX_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { MathUtils.toIntExact(2.0 * Integer.MIN_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { MathUtils.toIntExact(2f * Integer.MAX_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { MathUtils.toIntExact(2f * Integer.MIN_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } } |
### Question:
MathUtils { public static long toLongExact(double value) { if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) throw new ArithmeticException("value <> Long: " + value); return (long) value; } private MathUtils(); static int compare(double a, double b, double epsilon); static int compare(float a, float b, float epsilon); static boolean equals(double a, double b, double epsilon); static boolean equals(float a, float b, float epsilon); static T getAny(T[] array); static T getAny(Collection<T> collection); static T getAny(List<T> list); static boolean isPrime(int candidate); static double normalize(double[] array); static float normalize(float[] array); static double restrict(double a, double min, double max); static float restrict(float a, float min, float max); static int restrict(int a, int min, int max); static long restrict(long a, long min, long max); static int toIntExact(double value); static int toIntExact(float value); static long toLongExact(double value); static long toLongExact(float value); }### Answer:
@Test public void testToLongExact() { try { MathUtils.toLongExact(2.0 * Long.MAX_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { MathUtils.toLongExact(2.0 * Long.MIN_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { MathUtils.toLongExact(2f * Long.MAX_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } try { MathUtils.toLongExact(2f * Long.MIN_VALUE); fail("expected ArithmeticException"); } catch (ArithmeticException e) { } } |
### Question:
IEXTradingException extends RuntimeException { public int getStatus() { return status; } IEXTradingException(final String message); IEXTradingException(final String message, final int status); int getStatus(); static final String DEFAULT_PREFIX; }### Answer:
@Test public void shouldSuccessfullyCreateExceptionWithStatus() { final String message = "test"; final int statusCode = 500; final IEXTradingException exception = new IEXTradingException(message, statusCode); assertThat(exception.getStatus()).isEqualTo(statusCode); assertThat(exception.getMessage()).containsSequence(DEFAULT_PREFIX, message); } |
### Question:
SectorRequestBuilder extends AbstractRequestFilterBuilder<List<Sector>, SectorRequestBuilder> implements IEXCloudV1RestRequest<List<Sector>> { @Override public RestRequest<List<Sector>> build() { return RestRequestBuilder.<List<Sector>>builder() .withPath("/ref-data/sectors").get() .withResponse(new GenericType<List<Sector>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<Sector>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateSectorRequest() { final RestRequest<List<Sector>> request = new SectorRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/sectors"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<Sector>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
ExchangeRequestBuilder extends AbstractRequestFilterBuilder<List<Exchange>, ExchangeRequestBuilder> implements IEXCloudV1RestRequest<List<Exchange>> { @Override public RestRequest<List<Exchange>> build() { return RestRequestBuilder.<List<Exchange>>builder() .withPath("/ref-data/exchanges").get() .withResponse(new GenericType<List<Exchange>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<Exchange>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateExchangeRequest() { final RestRequest<List<Exchange>> request = new ExchangeRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/exchanges"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<Exchange>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
MutualFundSymbolsRequestBuilder extends AbstractRequestFilterBuilder<List<ExchangeSymbol>, MutualFundSymbolsRequestBuilder> implements IEXCloudV1RestRequest<List<ExchangeSymbol>> { @Override public RestRequest<List<ExchangeSymbol>> build() { return RestRequestBuilder.<List<ExchangeSymbol>>builder() .withPath("/ref-data/mutual-funds/symbols").get() .withResponse(new GenericType<List<ExchangeSymbol>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<ExchangeSymbol>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateMutualFundsSymbolsRequest() { final RestRequest<List<ExchangeSymbol>> request = new MutualFundSymbolsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/mutual-funds/symbols"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<ExchangeSymbol>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
UsExchangeRequestBuilder extends AbstractRequestFilterBuilder<List<UsExchange>, UsExchangeRequestBuilder> implements IEXCloudV1RestRequest<List<UsExchange>> { @Override public RestRequest<List<UsExchange>> build() { return RestRequestBuilder.<List<UsExchange>>builder() .withPath("/ref-data/market/us/exchanges").get() .withResponse(new GenericType<List<UsExchange>>() { }) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<UsExchange>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateUsExchangesRequest() { final RestRequest<List<UsExchange>> request = new UsExchangeRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/market/us/exchanges"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<UsExchange>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
TagRequestBuilder extends AbstractRequestFilterBuilder<List<Tag>, TagRequestBuilder> implements IEXCloudV1RestRequest<List<Tag>> { @Override public RestRequest<List<Tag>> build() { return RestRequestBuilder.<List<Tag>>builder() .withPath("/ref-data/tags").get() .withResponse(new GenericType<List<Tag>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<Tag>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final RestRequest<List<Tag>> request = new TagRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/tags"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<Tag>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
FxSymbolRequestBuilder extends AbstractRequestFilterBuilder<FxSymbol, FxSymbolRequestBuilder> implements IEXCloudV1RestRequest<FxSymbol> { @Override public RestRequest<FxSymbol> build() { return RestRequestBuilder.<FxSymbol>builder() .withPath("/ref-data/fx/symbols").get() .withResponse(new GenericType<FxSymbol>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<FxSymbol> build(); }### Answer:
@Test public void shouldSuccessfullyCreateFxSymbolsRequest() { final RestRequest<FxSymbol> request = new FxSymbolRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/fx/symbols"); assertThat(request.getResponseType()).isEqualTo(new GenericType<FxSymbol>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
SymbolsRequestBuilder extends AbstractRequestFilterBuilder<List<ExchangeSymbol>, SymbolsRequestBuilder> implements IEXCloudV1RestRequest<List<ExchangeSymbol>> { @Override public RestRequest<List<ExchangeSymbol>> build() { return RestRequestBuilder.<List<ExchangeSymbol>>builder() .withPath("/ref-data/symbols").get() .withResponse(new GenericType<List<ExchangeSymbol>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<ExchangeSymbol>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateSymbolsRequest() { final RestRequest<List<ExchangeSymbol>> request = new SymbolsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/symbols"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<ExchangeSymbol>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
IEXSymbolsRequestBuilder extends AbstractRequestFilterBuilder<List<Symbol>, SymbolsRequestBuilder> implements IEXCloudV1RestRequest<List<Symbol>> { @Override public RestRequest<List<Symbol>> build() { return RestRequestBuilder.<List<Symbol>>builder() .withPath("/ref-data/iex/symbols").get() .withResponse(new GenericType<List<Symbol>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<Symbol>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateIEXSymbolsRequest() { final RestRequest<List<Symbol>> request = new IEXSymbolsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/iex/symbols"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<Symbol>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
OtcSymbolsRequestBuilder extends AbstractRequestFilterBuilder<List<ExchangeSymbol>, OtcSymbolsRequestBuilder> implements IEXCloudV1RestRequest<List<ExchangeSymbol>> { @Override public RestRequest<List<ExchangeSymbol>> build() { return RestRequestBuilder.<List<ExchangeSymbol>>builder() .withPath("/ref-data/otc/symbols").get() .withResponse(new GenericType<List<ExchangeSymbol>>() {}) .addQueryParam(getFilterParams()) .build(); } @Override RestRequest<List<ExchangeSymbol>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateOtcSymbolsRequest() { final RestRequest<List<ExchangeSymbol>> request = new OtcSymbolsRequestBuilder().build(); assertThat(request.getMethodType()).isEqualTo(MethodType.GET); assertThat(request.getPath()).isEqualTo("/ref-data/otc/symbols"); assertThat(request.getResponseType()).isEqualTo(new GenericType<List<ExchangeSymbol>>() { }); assertThat(request.getPathParams()).isEmpty(); assertThat(request.getQueryParams()).isEmpty(); } |
### Question:
CurrencyConversion extends CurrencyRate { public BigDecimal getAmount() { return amount; } @JsonCreator CurrencyConversion(
@JsonProperty("symbol") final String symbol,
@JsonProperty("rate") final BigDecimal rate,
@JsonProperty("timestamp") final Long timestamp,
@JsonProperty("amount") final BigDecimal amount,
@JsonProperty("isDerived") final Boolean isDerived); BigDecimal getAmount(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void constructor() { final String symbol = fixture.create(String.class); final BigDecimal rate = fixture.create(BigDecimal.class); final Long timestamp = fixture.create(Long.class); final BigDecimal amount = fixture.create(BigDecimal.class); final Boolean isDerived = fixture.create(Boolean.class); final CurrencyConversion currencyConversion = new CurrencyConversion(symbol, rate, timestamp, amount, isDerived); assertThat(currencyConversion.getSymbol()).isEqualTo(symbol); assertThat(currencyConversion.getRate()).isEqualTo(rate); assertThat(currencyConversion.getTimestamp()).isEqualTo(timestamp); assertThat(currencyConversion.getAmount()).isEqualTo(amount); assertThat(currencyConversion.isDerived()).isEqualTo(isDerived); } |
### Question:
SocketManager { public <T> void unsubscribe(final SocketRequest<T> request) { final Socket socket = socketStore.remove(request); if (socket == null) { return; } socket.disconnect(); } SocketManager(final SocketWrapper socketWrapper, final String url); void subscribe(final SocketRequest<T> request, final Consumer<T> consumer); void unsubscribe(final SocketRequest<T> request); }### Answer:
@Test public void shouldNotThrowExceptionWhenThereIsNoSubscription() { final SocketRequest<String> request = new SocketRequest<>(new TypeReference<String>() {}, "/test", Arrays.asList("Test", "Test2")); socketManager.unsubscribe(request); } |
### Question:
SocketWrapper { public Socket socket(final String uri, final boolean reconnect) throws URISyntaxException { return IO.socket(uri, createOptions(reconnect)); } Socket socket(final String uri, final boolean reconnect); }### Answer:
@Test public void shouldSuccessfullyCreateSocket() throws URISyntaxException { final String uri = "uri"; when(IO.socket(eq(uri), any(IO.Options.class))).thenReturn(socketMock); final Socket socket = socketWrapper.socket(uri, false); assertThat(socket).isEqualTo(socketMock); } |
### Question:
GenericSocketEndpoint implements ISocketEndpoint { @Override public <R> void subscribe(final SocketRequest<R> socketRequest, final Consumer<R> consumer) { socketManager.subscribe(socketRequest, consumer); } GenericSocketEndpoint(final SocketManager socketManager); @Override void subscribe(final SocketRequest<R> socketRequest, final Consumer<R> consumer); @Override void unsubscribe(final SocketRequest<R> socketRequest); }### Answer:
@Test public void shouldSuccessfullySubscribe() { final SocketRequest<TOPS> request = new TopsAsyncRequestBuilder().build(); final Consumer<TOPS> topsConsumer = mock(Consumer.class); genericSocketEndpoint.subscribe(request, topsConsumer); verify(socketManagerMock).subscribe(eq(request), eq(topsConsumer)); } |
### Question:
GenericSocketEndpoint implements ISocketEndpoint { @Override public <R> void unsubscribe(final SocketRequest<R> socketRequest) { socketManager.unsubscribe(socketRequest); } GenericSocketEndpoint(final SocketManager socketManager); @Override void subscribe(final SocketRequest<R> socketRequest, final Consumer<R> consumer); @Override void unsubscribe(final SocketRequest<R> socketRequest); }### Answer:
@Test public void shouldSuccessfullyUnsubscribe() { final SocketRequest<TOPS> request = new TopsAsyncRequestBuilder().build(); genericSocketEndpoint.unsubscribe(request); verify(socketManagerMock).unsubscribe(eq(request)); } |
### Question:
AbstractSymbolAsyncRequestBuilder implements IAsyncRequestBuilder<R> { public B withSymbols(final String... symbols) { this.symbols.addAll(Arrays.asList(symbols)); return (B) this; } B withSymbol(final String symbol); B withSymbols(final String... symbols); }### Answer:
@Test public void shouldSuccessfullyCreateAsyncRequestWithMultipleSymbols() { final String ibmSymbol = "ibm"; final String aaplSymbol = "aapl"; final SocketRequest<LastTrade> request = new LastAsyncRequestBuilder() .withSymbols(ibmSymbol, aaplSymbol) .build(); final String param = String.valueOf(request.getParam()); assertThat(param).containsSequence(ibmSymbol).containsSequence(aaplSymbol); } |
### Question:
BookAsyncRequestBuilder extends AbstractDeepAsyncRequestBuilder<DeepAsyncResponse<Book>,
BookAsyncRequestBuilder> { @Override public SocketRequest<DeepAsyncResponse<Book>> build() { return SocketRequestBuilder.<DeepAsyncResponse<Book>>builder() .withPath("/deep") .withResponse(new TypeReference<DeepAsyncResponse<Book>>() {}) .withParam(getDeepParam()) .build(); } BookAsyncRequestBuilder(); @Override SocketRequest<DeepAsyncResponse<Book>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final String symbol = "IBM"; final SocketRequest<DeepAsyncResponse<Book>> request = new BookAsyncRequestBuilder() .withSymbol(symbol) .build(); assertThat(request.getPath()).isEqualTo("/deep"); final DeepAsyncRequest param = (DeepAsyncRequest) request.getParam(); assertThat(param.getSymbols()).containsExactly(symbol); assertThat(param.getChannels()).containsExactly(DeepChannel.BOOK); } |
### Question:
TradingStatusAsyncRequestBuilder extends AbstractDeepAsyncRequestBuilder<DeepAsyncResponse<TradingStatus>,
TradingStatusAsyncRequestBuilder> { @Override public SocketRequest<DeepAsyncResponse<TradingStatus>> build() { return SocketRequestBuilder.<DeepAsyncResponse<TradingStatus>>builder() .withPath("/deep") .withResponse(new TypeReference<DeepAsyncResponse<TradingStatus>>() {}) .withParam(getDeepParam()) .build(); } TradingStatusAsyncRequestBuilder(); @Override SocketRequest<DeepAsyncResponse<TradingStatus>> build(); }### Answer:
@Test public void shouldSuccessfullyCreateRequest() { final String symbol = "IBM"; final SocketRequest<DeepAsyncResponse<TradingStatus>> request = new TradingStatusAsyncRequestBuilder() .withSymbol(symbol) .build(); assertThat(request.getPath()).isEqualTo("/deep"); final DeepAsyncRequest param = (DeepAsyncRequest) request.getParam(); assertThat(param.getSymbols()).containsExactly(symbol); assertThat(param.getChannels()).containsExactly(DeepChannel.TRADING_STATUS); } |
### Question:
HistoricalCurrencyRate extends CurrencyRate { public LocalDate getDate() { return date; } @JsonCreator HistoricalCurrencyRate(
@JsonProperty("symbol") final String symbol,
@JsonProperty("rate") final BigDecimal rate,
@JsonProperty("timestamp") final Long timestamp,
@JsonProperty("date") final LocalDate date,
@JsonProperty("isDerived") final Boolean isDerived); LocalDate getDate(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void constructor() { final String symbol = fixture.create(String.class); final BigDecimal rate = fixture.create(BigDecimal.class); final Long timestamp = fixture.create(Long.class); final LocalDate date = fixture.create(LocalDate.class); final Boolean isDerived = fixture.create(Boolean.class); final HistoricalCurrencyRate historicalCurrencyRate = new HistoricalCurrencyRate(symbol, rate, timestamp, date, isDerived); assertThat(historicalCurrencyRate.getSymbol()).isEqualTo(symbol); assertThat(historicalCurrencyRate.getRate()).isEqualTo(rate); assertThat(historicalCurrencyRate.getTimestamp()).isEqualTo(timestamp); assertThat(historicalCurrencyRate.getDate()).isEqualTo(date); assertThat(historicalCurrencyRate.isDerived()).isEqualTo(isDerived); } |
### Question:
TopsAsyncRequestBuilder extends AbstractSymbolAsyncRequestBuilder<TOPS, TopsAsyncRequestBuilder> { @Override public SocketRequest<TOPS> build() { return SocketRequestBuilder.<TOPS>builder() .withPath("/tops") .withResponse(new TypeReference<TOPS>() {}) .withParam(getSymbol()) .build(); } @Override SocketRequest<TOPS> build(); }### Answer:
@Test public void shouldSuccessfullyCreateAsyncRequest() { final String symbol = "IBM"; final SocketRequest<TOPS> request = new TopsAsyncRequestBuilder() .withSymbol(symbol) .build(); assertThat(request.getPath()).isEqualTo("/tops"); assertThat(String.valueOf(request.getParam())).contains(symbol); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.