method2testcases
stringlengths 118
3.08k
|
---|
### Question:
BroadcastContext implements BroadcastResult<T> { boolean onSendFailure(ClusterNode node, Throwable error) { synchronized (this) { if (errors == null) { errors = new HashMap<>(remaining, 1.0f); } errors.put(node, error); remaining--; return remaining == 0; } } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }### Answer:
@Test public void testOnSendFailure() { BroadcastContext<String> ctx = ctx(allNodes()); Exception err1 = new Exception(); Exception err2 = new Exception(); Exception err3 = new Exception(); assertFalse(ctx.onSendFailure(n1, err1)); assertFalse(ctx.onSendFailure(n2, err2)); assertTrue(ctx.onSendFailure(n3, err3)); assertEquals(new HashSet<>(allNodes()), ctx.errors().keySet()); assertSame(err1, ctx.errorOf(n1)); assertSame(err2, ctx.errorOf(n2)); assertSame(err3, ctx.errorOf(n3)); assertFalse(ctx.isSuccess()); assertFalse(ctx.isSuccess(n1)); assertFalse(ctx.isSuccess(n2)); assertFalse(ctx.isSuccess(n3)); } |
### Question:
BroadcastContext implements BroadcastResult<T> { void complete() { future.complete(this); } BroadcastContext(T message, List<ClusterNode> nodes, BroadcastFuture<T> future); @Override T message(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); boolean forgetNode(ClusterNode node); BroadcastFuture<T> future(); @Override String toString(); }### Answer:
@Test public void testComplete() { BroadcastContext<String> ctx = ctx(allNodes()); ctx.complete(); assertTrue(ctx.isSuccess()); assertFalse(ctx.nodes().isEmpty()); assertTrue(ctx.errors().isEmpty()); BroadcastContext<String> errCtx = ctx(allNodes()); errCtx.future().whenComplete((stringBroadcastResult, throwable) -> { throw TEST_ERROR; }); errCtx.complete(); } |
### Question:
AggregateContext implements AggregateResult<T> { @Override public String toString() { return ToString.format(AggregateResult.class, this); } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }### Answer:
@Test public void testToString() { AggregateContext<String> ctx = ctx(allNodes()); assertEquals(ToString.format(AggregateResult.class, ctx), ctx.toString()); } |
### Question:
AggregateContext implements AggregateResult<T> { @Override public T request() { return request; } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }### Answer:
@Test public void testRequest() { AggregateContext<String> ctx = ctx(allNodes()); assertEquals(TEST_REQUEST, ctx.request()); } |
### Question:
RpcClientConfig { @Override public String toString() { return ToString.format(this); } Class<?> getRpcInterface(); void setRpcInterface(Class<?> rpcInterface); RpcClientConfig withRpcInterface(Class<?> rpcInterface); String getTag(); void setTag(String tag); RpcClientConfig withTag(String tag); RpcLoadBalancer getLoadBalancer(); void setLoadBalancer(RpcLoadBalancer loadBalancer); RpcClientConfig withLoadBalancer(RpcLoadBalancer loadBalancer); int getPartitions(); void setPartitions(int partitions); RpcClientConfig withPartitions(int partitions); int getBackupNodes(); void setBackupNodes(int backupNodes); RpcClientConfig withBackupNodes(int backupNodes); long getTimeout(); void setTimeout(long timeout); RpcClientConfig withTimeout(long timeout); GenericRetryConfigurer getRetryPolicy(); void setRetryPolicy(GenericRetryConfigurer retryPolicy); RpcClientConfig withRetryPolicy(GenericRetryConfigurer retryPolicy); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
AggregateContext implements AggregateResult<T> { @Override public List<ClusterNode> nodes() { synchronized (this) { return nodes; } } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }### Answer:
@Test public void testNodes() { assertEquals(allNodes(), ctx(allNodes()).nodes()); assertEquals(singletonList(n1), ctx(singletonList(n1)).nodes()); AggregateContext<String> ctx = ctx(allNodes()); assertFalse(ctx.forgetNode(n1)); assertEquals(asList(n2, n3), ctx.nodes()); assertFalse(ctx.forgetNode(n2)); assertEquals(singletonList(n3), ctx.nodes()); assertTrue(ctx.forgetNode(n3)); assertTrue(ctx.nodes().isEmpty()); } |
### Question:
AggregateContext implements AggregateResult<T> { boolean onReplySuccess(ClusterNode node, Response<T> rsp) { synchronized (this) { results.put(node, rsp.payload()); return isReady(); } } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }### Answer:
@Test public void testOnReplySuccess() { AggregateContext<String> ctx = ctx(allNodes()); assertFalse(ctx.onReplySuccess(n1, responseMock("r1"))); assertFalse(ctx.onReplySuccess(n2, responseMock("r2"))); assertTrue(ctx.onReplySuccess(n3, responseMock("r3"))); assertTrue(ctx.isSuccess()); assertTrue(ctx.isSuccess(n1)); assertTrue(ctx.isSuccess(n2)); assertTrue(ctx.isSuccess(n3)); assertTrue(ctx.errors().isEmpty()); assertEquals("r1", ctx.resultOf(n1)); assertEquals("r2", ctx.resultOf(n2)); assertEquals("r3", ctx.resultOf(n3)); Set<String> results = new HashSet<>(asList("r1", "r2", "r3")); for (String r : ctx) { assertTrue(results.contains(r)); } ctx.stream().forEach(r -> assertTrue(results.contains(r)) ); assertEquals(results, new HashSet<>(ctx.results())); } |
### Question:
AggregateContext implements AggregateResult<T> { boolean onReplyFailure(ClusterNode node, Throwable error) { synchronized (this) { if (errors == null) { errors = new HashMap<>(nodes.size(), 1.0f); } errors.put(node, error); return isReady(); } } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }### Answer:
@Test public void testOnReplyFailure() { AggregateContext<String> ctx = ctx(allNodes()); Exception err1 = new Exception(); Exception err2 = new Exception(); Exception err3 = new Exception(); assertFalse(ctx.onReplyFailure(n1, err1)); assertFalse(ctx.onReplyFailure(n2, err2)); assertTrue(ctx.onReplyFailure(n3, err3)); assertEquals(new HashSet<>(allNodes()), ctx.errors().keySet()); assertSame(err1, ctx.errorOf(n1)); assertSame(err2, ctx.errorOf(n2)); assertSame(err3, ctx.errorOf(n3)); assertFalse(ctx.isSuccess()); assertFalse(ctx.isSuccess(n1)); assertFalse(ctx.isSuccess(n2)); assertFalse(ctx.isSuccess(n3)); } |
### Question:
AggregateContext implements AggregateResult<T> { void complete() { future.complete(this); } AggregateContext(T request, List<ClusterNode> nodes, AggregateFuture<T> future); @Override T request(); @Override List<ClusterNode> nodes(); @Override Map<ClusterNode, Throwable> errors(); @Override Map<ClusterNode, T> resultsByNode(); @Override String toString(); }### Answer:
@Test public void testComplete() throws Exception { AggregateContext<String> ctx = ctx(allNodes()); ctx.complete(); assertTrue(ctx.future().get().isSuccess()); assertFalse(ctx.future().get().nodes().isEmpty()); assertTrue(ctx.future().get().errors().isEmpty()); AggregateContext<String> errCtx = ctx(allNodes()); errCtx.future().whenComplete((rslt, err) -> { throw TEST_ERROR; }); errCtx.complete(); } |
### Question:
DefaultLoadBalancerContext implements LoadBalancerContext { @Override public Optional<FailedAttempt> failure() { return failure; } DefaultLoadBalancerContext(
int affinity,
Object affinityKey,
ClusterTopology topology,
PartitionMapper partitions,
Optional<FailedAttempt> failure,
TopologyContextCache topologyCtx
); @Override ClusterTopology topology(); @Override PartitionMapper partitions(); @Override boolean hasAffinity(); @Override int affinity(); @Override Object affinityKey(); @Override Optional<FailedAttempt> failure(); @Override T topologyContext(Function<ClusterTopology, T> supplier); @Override long version(); @Override ClusterHash hash(); @Override ClusterNode localNode(); @Override List<ClusterNode> nodes(); @Override ClusterNode first(); @Override ClusterNode last(); @Override Set<ClusterNode> nodeSet(); @Override List<ClusterNode> remoteNodes(); @Override NavigableSet<ClusterNode> joinOrder(); @Override Stream<ClusterNode> stream(); @Override boolean contains(ClusterNode node); @Override boolean contains(ClusterNodeId node); @Override ClusterNode get(ClusterNodeId id); @Override int size(); @Override boolean isEmpty(); @Override ClusterNode oldest(); @Override ClusterNode youngest(); @Override ClusterNode random(); @Override ClusterTopology filterAll(ClusterFilter filter); @Override ClusterTopology filter(ClusterNodeFilter filter); @Override Iterator<ClusterNode> iterator(); @Override String toString(); }### Answer:
@Test public void testFailure() throws Exception { FailedAttempt details = mock(FailedAttempt.class); ClusterNode n1 = newNode(); LoadBalancerContext ctx = newContext(100, "test", 1, toSet(n1, newNode()), details); assertNotNull(ctx.failure()); assertEquals(100, ctx.affinity()); assertEquals("test", ctx.affinityKey()); assertTrue(ctx.hasAffinity()); assertSame(details, ctx.failure().get()); } |
### Question:
MessagingBackPressureConfig { @Override public String toString() { return ToString.format(this); } MessagingBackPressureConfig(); MessagingBackPressureConfig(MessagingBackPressureConfig src); int getInLowWatermark(); void setInLowWatermark(int inLowWatermark); MessagingBackPressureConfig withInLowWatermark(int inLowWatermark); int getInHighWatermark(); void setInHighWatermark(int inHighWatermark); MessagingBackPressureConfig withInHighWatermark(int inHighWatermark); int getOutLowWatermark(); void setOutLowWatermark(int outLowWatermark); MessagingBackPressureConfig withOutLowWatermark(int outLowWatermark); int getOutHighWatermark(); void setOutHighWatermark(int outHighWatermark); MessagingBackPressureConfig withOutHighWatermark(int outHighWatermark); MessagingOverflowPolicy getOutOverflowPolicy(); void setOutOverflowPolicy(MessagingOverflowPolicy outOverflowPolicy); MessagingBackPressureConfig withOutOverflowPolicy(MessagingOverflowPolicy outOverflow); @Override String toString(); }### Answer:
@Test public void testToString() { assertTrue(cfg.toString(), cfg.toString().startsWith(MessagingBackPressureConfig.class.getSimpleName())); } |
### Question:
JmxUtils { public static ObjectName jmxName(String domain, Class<?> type) throws MalformedObjectNameException { return jmxName(domain, type, null); } private JmxUtils(); static ObjectName jmxName(String domain, Class<?> type); static ObjectName jmxName(String domain, Class<?> type, String name); }### Answer:
@Test public void testClusterAndNodeName() throws Exception { ObjectName name = new ObjectName("foo.bar", "type", getClass().getSimpleName()); assertEquals(name, JmxUtils.jmxName("foo.bar", getClass())); }
@Test public void testClusterNameOnly() throws Exception { ObjectName name = new ObjectName("foo.bar", "type", getClass().getSimpleName()); assertEquals(name, JmxUtils.jmxName("foo.bar", getClass())); }
@Test public void testNameAttribute() throws Exception { Hashtable<String, String> attrs = new Hashtable<>(); attrs.put("name", "test-name"); attrs.put("type", getClass().getSimpleName()); ObjectName name = new ObjectName("foo.bar", attrs); assertEquals(name, JmxUtils.jmxName("foo.bar", getClass(), "test-name")); } |
### Question:
JmxServiceFactory implements ServiceFactory<JmxService> { @Override public String toString() { return ToString.format(this); } @Override JmxService createService(); String getDomain(); void setDomain(String domain); JmxServiceFactory withDomain(String domain); MBeanServer getServer(); void setServer(MBeanServer server); JmxServiceFactory withServer(MBeanServer server); @Override String toString(); static final String DEFAULT_DOMAIN; }### Answer:
@Test public void testToString() { assertEquals(ToString.format(factory), factory.toString()); } |
### Question:
ResourceServiceFactory implements ServiceFactory<ResourceService> { @Override public ResourceService createService() { return new DefaultResourceService(); } @Override ResourceService createService(); @Override String toString(); }### Answer:
@Test public void testCreate() { assertNotNull(factory.createService()); } |
### Question:
ResourceServiceFactory implements ServiceFactory<ResourceService> { @Override public String toString() { return ToString.format(this); } @Override ResourceService createService(); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(factory), factory.toString()); } |
### Question:
DefaultResourceService implements ResourceService { @Override public InputStream load(String path) throws ResourceLoadingException { ArgAssert.notNull(path, "Resource path"); ArgAssert.isFalse(path.isEmpty(), "Resource path is empty."); try { URL url = new URL(path); try (InputStream in = url.openStream()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[4 * 1024]; for (int read = in.read(buf); read > 0; read = in.read(buf)) { out.write(buf, 0, read); } return new ByteArrayInputStream(out.toByteArray()); } } catch (IOException e) { throw new ResourceLoadingException("Failed to load resource [path=" + path + ']', e); } } @Override InputStream load(String path); @Override String toString(); }### Answer:
@Test public void testSuccess() throws Exception { File[] files = new File("./").listFiles(); assertNotNull(files); int checked = 0; for (File file : files) { if (file.isFile()) { String path = "file: say("Testing path: " + path); try (InputStream stream = service.load(path)) { assertNotNull(stream); assertEquals(file.length(), stream.available()); checked++; } } } assertTrue(checked > 0); }
@Test(expected = IllegalArgumentException.class) public void testNullPath() throws Exception { service.load(null); }
@Test(expected = IllegalArgumentException.class) public void testEmptyPath() throws Exception { service.load(""); }
@Test(expected = ResourceLoadingException.class) public void testInvalidUrl() throws Exception { service.load("invalid-url"); }
@Test(expected = ResourceLoadingException.class) public void testInvalidPath() throws Exception { service.load("file: } |
### Question:
DefaultResourceService implements ResourceService { @Override public String toString() { return getClass().getSimpleName(); } @Override InputStream load(String path); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(DefaultResourceService.class.getSimpleName(), service.toString()); } |
### Question:
Murmur3 { public static int hash(int n1, int n2) { int k1 = mixK1(n1); int h1 = mixH1(0, k1); k1 = mixK1(n2); h1 = mixH1(h1, k1); return mix(h1, Integer.BYTES); } private Murmur3(); static int hash(int n1, int n2); }### Answer:
@Test public void test() throws Exception { assertValidUtilityClass(Murmur3.class); Set<Integer> hashes = new HashSet<>(10000, 1.0f); for (int i = 0; i < 10000; i++) { hashes.add(Murmur3.hash(1, i)); } assertEquals(10000, hashes.size()); } |
### Question:
ErrorUtils { public static boolean isCausedBy(Class<? extends Throwable> type, Throwable error) { return findCause(type, error) != null; } private ErrorUtils(); static String stackTrace(Throwable error); static boolean isCausedBy(Class<? extends Throwable> type, Throwable error); static T findCause(Class<T> type, Throwable error); }### Answer:
@Test public void testIsCausedBy() { assertFalse(ErrorUtils.isCausedBy(Exception.class, null)); assertFalse(ErrorUtils.isCausedBy(IOException.class, new Exception())); assertTrue(ErrorUtils.isCausedBy(IOException.class, new IOException())); assertTrue(ErrorUtils.isCausedBy(IOException.class, new Exception(new IOException()))); assertTrue(ErrorUtils.isCausedBy(IOException.class, new Exception(new Exception(new IOException())))); } |
### Question:
ErrorUtils { public static String stackTrace(Throwable error) { ArgAssert.notNull(error, "error"); StringWriter out = new StringWriter(); error.printStackTrace(new PrintWriter(out)); return out.toString(); } private ErrorUtils(); static String stackTrace(Throwable error); static boolean isCausedBy(Class<? extends Throwable> type, Throwable error); static T findCause(Class<T> type, Throwable error); }### Answer:
@Test public void testStackTrace() { assertTrue(ErrorUtils.stackTrace(new Exception()).contains(ErrorUtilsTest.class.getName())); assertTrue(ErrorUtils.stackTrace(new Exception()).contains(ErrorUtilsTest.class.getName() + ".testStackTrace(")); } |
### Question:
StreamUtils { public static <T> Stream<T> nullSafe(Collection<T> collection) { if (collection == null || collection.isEmpty()) { return Stream.empty(); } return collection.stream().filter(Objects::nonNull); } private StreamUtils(); static Stream<T> nullSafe(Collection<T> collection); }### Answer:
@Test public void testNullSafe() { assertNotNull(nullSafe(null)); assertNotNull(nullSafe(emptyList())); assertEquals(singletonList("non null"), nullSafe(asList(null, "non null", null)).collect(toList())); } |
### Question:
ConfigCheck { public void that(boolean check, String msg) throws HekateConfigurationException { if (!check) { throw new HekateConfigurationException(component + ": " + msg); } } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testThatSuccess() { check.that(true, "Success"); }
@Test public void testThatFailure() { expectExactMessage(HCE, PREFIX + "Test message", () -> check.that(Boolean.valueOf("false"), "Test message") ); check.that(true, "Success"); } |
### Question:
ConfigCheck { public HekateConfigurationException fail(Throwable cause) { throw new HekateConfigurationException(component + ": " + cause.toString(), cause); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testFail() { expectExactMessage(HCE, PREFIX + "java.lang.Exception: test error message", () -> check.fail(new Exception("test error message")) ); } |
### Question:
ConfigCheck { public void isPowerOfTwo(int n, String component) throws HekateConfigurationException { that(Utils.isPowerOfTwo(n), component + " must be a power of two [value=" + n + ']'); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testIsPowerOfTwo() { expectExactMessage(HCE, PREFIX + "Ten must be a power of two [value=10]", () -> check.isPowerOfTwo(10, "Ten") ); check.isPowerOfTwo(8, "Success"); } |
### Question:
ConfigCheck { public void range(int value, int from, int to, String component) { that(value >= from && value <= to, component + " must be within the " + from + ".." + to + " range."); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testRange() { expectExactMessage(HCE, PREFIX + "Ten must be within the 1..5 range.", () -> check.range(10, 1, 5, "Ten") ); check.range(0, 0, 0, "0-0-0"); check.range(1, 0, 1, "1-0-1"); check.range(1, 1, 1, "1-1-1"); check.range(5, 1, 8, "5-1-8"); } |
### Question:
ConfigCheck { public void positive(int value, String component) { greater(value, 0, component); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testPositiveInt() { expectExactMessage(HCE, PREFIX + "Zero must be greater than 0 [value=0]", () -> check.positive(0, "Zero") ); expectExactMessage(HCE, PREFIX + "Negative must be greater than 0 [value=-1]", () -> check.positive(-1, "Negative") ); check.positive(1, "Success"); }
@Test public void testPositiveLong() { expectExactMessage(HCE, PREFIX + "Zero must be greater than 0 [value=0]", () -> check.positive(0L, "Zero") ); expectExactMessage(HCE, PREFIX + "Negative must be greater than 0 [value=-1]", () -> check.positive(-1L, "Negative") ); check.positive(1L, "Success"); } |
### Question:
ConfigCheck { public void nonNegative(int value, String component) { greaterOrEquals(value, 0, component); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testNonNegativeInt() { expectExactMessage(HCE, PREFIX + "Negative must be greater than or equals to 0 [value=-1]", () -> check.nonNegative(-1, "Negative") ); check.nonNegative(0, "Success"); check.nonNegative(1, "Success"); } |
### Question:
ConfigCheck { public void unique(Object what, Set<?> where, String component) { that(!where.contains(what), "duplicated " + component + " [value=" + what + ']'); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testUnique() { expectExactMessage(HCE, PREFIX + "duplicated One [value=one]", () -> check.unique("one", singleton("one"), "One") ); check.unique("one", emptySet(), "Success"); check.unique("one", singleton("two"), "Success"); check.unique("one", new HashSet<>(asList("two", "three")), "Success"); } |
### Question:
ConfigCheck { public void isTrue(boolean value, String msg) throws HekateConfigurationException { that(value, msg); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testIsTrue() { expectExactMessage(HCE, PREFIX + "True Epic fail", () -> check.isTrue(Boolean.valueOf("false"), "True Epic fail") ); check.isTrue(true, "Success"); } |
### Question:
ConfigCheck { public void isFalse(boolean value, String msg) throws HekateConfigurationException { that(!value, msg); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testIsFalse() { check.isFalse(false, "Success"); expectExactMessage(HCE, PREFIX + "Epic fail", () -> check.isFalse(true, "Epic fail") ); } |
### Question:
ConfigCheck { public void notNull(Object value, String component) throws HekateConfigurationException { notNull(value, component, "must be not null"); } private ConfigCheck(String component); static ConfigCheck get(Class<?> component); void that(boolean check, String msg); HekateConfigurationException fail(Throwable cause); HekateConfigurationException fail(String msg); void validSysName(String value, String component); void range(int value, int from, int to, String component); void positive(int value, String component); void positive(long value, String component); void nonNegative(int value, String component); void greater(long value, long than, String component); void greater(int value, int than, String component); void greaterOrEquals(int value, int than, String component); void unique(Object what, Set<?> where, String component); void isFalse(boolean value, String msg); void isTrue(boolean value, String msg); void notNull(Object value, String component); void notNull(Object value, String component, String details); void notEmpty(String value, String component); void notEmpty(Stream<?> stream, String component); void isPowerOfTwo(int n, String component); }### Answer:
@Test public void testNotNull() { expectExactMessage(HCE, PREFIX + "Epic fail must be not null.", () -> check.notNull(null, "Epic fail") ); check.notNull("777", "Success"); } |
### Question:
ArgAssert { public static void check(boolean that, String msg) throws IllegalArgumentException { doCheck(that, null, msg); } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }### Answer:
@Test public void testCheck() throws Exception { expectExactMessage(IAE, "test message", () -> ArgAssert.check(false, "test message") ); ArgAssert.check(true, "Success"); } |
### Question:
ArgAssert { public static <T> T notNull(T obj, String argName) { doCheck(obj != null, argName, " must be not null."); return obj; } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }### Answer:
@Test public void testNotNull() throws Exception { expectExactMessage(IAE, "something must be not null.", () -> ArgAssert.notNull(null, "something") ); ArgAssert.notNull(new Object(), "Success"); } |
### Question:
ArgAssert { public static String notEmpty(String str, String argName) { String trimmed = notNull(str, argName).trim(); doCheck(!trimmed.isEmpty(), argName, " must have non-whitespace characters."); return trimmed; } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }### Answer:
@Test public void testNotEmpty() throws Exception { expectExactMessage(IAE, "something must be not null.", () -> ArgAssert.notEmpty(null, "something") ); expectExactMessage(IAE, "something must have non-whitespace characters.", () -> ArgAssert.notEmpty("", "something") ); expectExactMessage(IAE, "something must have non-whitespace characters.", () -> ArgAssert.notEmpty(" ", "something") ); expectExactMessage(IAE, "something must have non-whitespace characters.", () -> ArgAssert.notEmpty("\n", "something") ); expectExactMessage(IAE, "something must have non-whitespace characters.", () -> ArgAssert.notEmpty(System.lineSeparator(), "something") ); assertEquals("not empty", ArgAssert.notEmpty("not empty", "Success")); assertEquals("not empty", ArgAssert.notEmpty(" not empty\n", "Success")); } |
### Question:
ArgAssert { public static void isFalse(boolean condition, String msg) { isTrue(!condition, msg); } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }### Answer:
@Test public void testIsFalse() throws Exception { expectExactMessage(IAE, "test message", () -> ArgAssert.isFalse(true, "test message") ); ArgAssert.isFalse(false, "Success"); } |
### Question:
ArgAssert { public static void isTrue(boolean condition, String msg) { check(condition, msg); } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }### Answer:
@Test public void testIsTrue() throws Exception { expectExactMessage(IAE, "test message", () -> ArgAssert.isTrue(false, "test message") ); ArgAssert.isTrue(true, "Success"); } |
### Question:
ArgAssert { public static void positive(long val, String argName) { doCheck(val > 0, argName, " must be > 0."); } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }### Answer:
@Test public void testPositive() { expectExactMessage(IAE, "testArg must be > 0.", () -> ArgAssert.positive(-1, "testArg") ); expectExactMessage(IAE, "testArg must be > 0.", () -> ArgAssert.positive(0, "testArg") ); ArgAssert.positive(10, "testArg"); } |
### Question:
ArgAssert { public static void powerOfTwo(int val, String argName) { doCheck(Utils.isPowerOfTwo(val), argName, " must be a power of two."); } private ArgAssert(); static void check(boolean that, String msg); static T notNull(T obj, String argName); static String notEmpty(String str, String argName); static void isFalse(boolean condition, String msg); static void isTrue(boolean condition, String msg); static void positive(long val, String argName); static void powerOfTwo(int val, String argName); }### Answer:
@Test public void testPowerOfTwo() { expectExactMessage(IAE, "testArg must be a power of two.", () -> ArgAssert.powerOfTwo(13, "testArg") ); expectExactMessage(IAE, "testArg must be a power of two.", () -> ArgAssert.powerOfTwo(0, "testArg") ); expectExactMessage(IAE, "testArg must be a power of two.", () -> ArgAssert.powerOfTwo(-2, "testArg") ); ArgAssert.powerOfTwo(8, "testArg"); } |
### Question:
Utils { public static int mod(int hash, int size) { if (hash < 0) { return -hash % size; } else { return hash % size; } } private Utils(); static String numberFormat(String pattern, Number number); static String byteSizeFormat(long bytes); static int mod(int hash, int size); static boolean isPowerOfTwo(int n); static String toString(Collection<T> collection, Function<? super T, String> mapper); static String nullOrTrim(String str); static String nullOrTrim(String str, String defaultVal); static String camelCase(CharSequence str); static List<T> nullSafeImmutableCopy(List<T> source); static final String NL; static final Charset UTF_8; static final int MAGIC_BYTES; }### Answer:
@Test public void testMod() { assertEquals(1, Utils.mod(6, 5)); assertEquals(1, Utils.mod(-6, 5)); } |
### Question:
Utils { public static String camelCase(CharSequence str) { StringBuilder buf = new StringBuilder(); boolean capitalize = true; for (int i = 0, len = str.length(); i < len; ++i) { char c = str.charAt(i); switch (c) { case '-': case '.': case '_': { capitalize = true; break; } default: { if (capitalize) { buf.append(Character.toUpperCase(c)); capitalize = false; } else { buf.append(c); } } } } return buf.toString(); } private Utils(); static String numberFormat(String pattern, Number number); static String byteSizeFormat(long bytes); static int mod(int hash, int size); static boolean isPowerOfTwo(int n); static String toString(Collection<T> collection, Function<? super T, String> mapper); static String nullOrTrim(String str); static String nullOrTrim(String str, String defaultVal); static String camelCase(CharSequence str); static List<T> nullSafeImmutableCopy(List<T> source); static final String NL; static final Charset UTF_8; static final int MAGIC_BYTES; }### Answer:
@Test public void testCamelCase() { assertEquals("TEST", camelCase("TEST")); assertEquals("Test", camelCase("Test")); assertEquals("TeSt", camelCase("Te.st")); assertEquals("TeSt", camelCase("Te..st")); assertEquals("TeSt", camelCase("Te.-st")); assertEquals("TeSt", camelCase("Te-st")); assertEquals("TeSt", camelCase("Te--st")); assertEquals("TeSt", camelCase("Te-_st")); assertEquals("TeSt", camelCase("Te_st")); assertEquals("TeST", camelCase("Te_s_t_")); assertEquals("TeST", camelCase("te_s_t_")); } |
### Question:
Utils { public static <T> List<T> nullSafeImmutableCopy(List<T> source) { if (source == null || source.isEmpty()) { return emptyList(); } else { return unmodifiableList(source.stream().filter(Objects::nonNull).collect(toList())); } } private Utils(); static String numberFormat(String pattern, Number number); static String byteSizeFormat(long bytes); static int mod(int hash, int size); static boolean isPowerOfTwo(int n); static String toString(Collection<T> collection, Function<? super T, String> mapper); static String nullOrTrim(String str); static String nullOrTrim(String str, String defaultVal); static String camelCase(CharSequence str); static List<T> nullSafeImmutableCopy(List<T> source); static final String NL; static final Charset UTF_8; static final int MAGIC_BYTES; }### Answer:
@Test public void nullSafeImmutableCopy() { assertTrue(Utils.nullSafeImmutableCopy(null).isEmpty()); assertTrue(Utils.nullSafeImmutableCopy(emptyList()).isEmpty()); assertTrue(Utils.nullSafeImmutableCopy(asList(null, null, null)).isEmpty()); assertEquals(3, Utils.nullSafeImmutableCopy(asList(1, 2, 3)).size()); expect(UnsupportedOperationException.class, () -> { Utils.nullSafeImmutableCopy(asList(1, 2, 3)).add(4); }); } |
### Question:
Jvm { public static String pid() { return PID; } private Jvm(); static String pid(); static void exit(int code); static void setExitHandler(ExitHandler handler); static Optional<ExitHandler> exitHandler(); }### Answer:
@Test public void testPid() { String pid1 = Jvm.pid(); String pid2 = Jvm.pid(); assertNotNull(pid1); assertEquals(pid1, pid2); } |
### Question:
Jvm { public static Optional<ExitHandler> exitHandler() { return Optional.ofNullable(exitHandler); } private Jvm(); static String pid(); static void exit(int code); static void setExitHandler(ExitHandler handler); static Optional<ExitHandler> exitHandler(); }### Answer:
@Test public void testExitHandler() { assertFalse(Jvm.exitHandler().isPresent()); try { Jvm.ExitHandler handler = mock(Jvm.ExitHandler.class); Jvm.setExitHandler(handler); assertTrue(Jvm.exitHandler().isPresent()); Jvm.exit(100500); verify(handler).exit(100500); verifyNoMoreInteractions(handler); } finally { Jvm.setExitHandler(null); assertNotNull(Jvm.exitHandler()); assertFalse(Jvm.exitHandler().isPresent()); } } |
### Question:
HekateNodeFactory { public static Hekate create(HekateBootstrap bootstrap) { return new HekateNode(bootstrap); } private HekateNodeFactory(); static Hekate create(HekateBootstrap bootstrap); }### Answer:
@Test public void test() throws Exception { assertValidUtilityClass(HekateNodeFactory.class); assertNotNull(HekateNodeFactory.create(new HekateBootstrap())); } |
### Question:
LeaveFuture extends HekateFuture<Hekate, LeaveFuture> { public static LeaveFuture completed(Hekate node) { LeaveFuture future = new LeaveFuture(); future.complete(node); return future; } static LeaveFuture completed(Hekate node); @Override Hekate get(); @Override Hekate get(long timeout, TimeUnit unit); }### Answer:
@Test public void testCompleted() { assertTrue(LeaveFuture.completed(mock(Hekate.class)).isSuccess()); } |
### Question:
TerminateFuture extends HekateFuture<Hekate, TerminateFuture> { public static TerminateFuture completed(Hekate node) { TerminateFuture future = new TerminateFuture(); future.complete(node); return future; } static TerminateFuture completed(Hekate node); @Override Hekate get(); @Override Hekate get(long timeout, TimeUnit unit); }### Answer:
@Test public void testCompleted() { assertTrue(TerminateFuture.completed(mock(Hekate.class)).isSuccess()); } |
### Question:
LockServiceFactory implements ServiceFactory<LockService> { @Override public LockService createService() { return new DefaultLockService(this); } List<LockRegionConfig> getRegions(); void setRegions(List<LockRegionConfig> regions); LockServiceFactory withRegion(LockRegionConfig region); List<LockConfigProvider> getConfigProviders(); void setConfigProviders(List<LockConfigProvider> configProviders); LockServiceFactory withConfigProvider(LockConfigProvider configProvider); long getRetryInterval(); void setRetryInterval(long retryInterval); LockServiceFactory withRetryInterval(long retryInterval); int getWorkerThreads(); void setWorkerThreads(int workerThreads); LockServiceFactory withWorkerThreads(int workerThreads); int getNioThreads(); void setNioThreads(int nioThreads); LockServiceFactory withNioThreads(int nioThreads); @Override LockService createService(); @Override String toString(); static final int DEFAULT_RETRY_INTERVAL; static final int DEFAULT_WORKER_THREADS; }### Answer:
@Test public void testCreateService() { assertNotNull(factory.createService()); } |
### Question:
DefaultFailureDetector implements FailureDetector, JmxSupport<DefaultFailureDetectorJmx>, ConfigReportSupport { public boolean isMonitored(ClusterAddress node) { ArgAssert.notNull(node, "Node"); readLock.lock(); try { return monitors.containsKey(node); } finally { readLock.unlock(); } } DefaultFailureDetector(); DefaultFailureDetector(DefaultFailureDetectorConfig cfg); @Override void report(ConfigReporter report); @Override void initialize(FailureDetectorContext context); @Override long heartbeatInterval(); @Override int failureQuorum(); @Override void terminate(); @Override boolean isAlive(ClusterAddress node); @Override Collection<ClusterAddress> heartbeatTick(); @Override boolean onHeartbeatRequest(ClusterAddress from); @Override void onHeartbeatReply(ClusterAddress node); @Override void onConnectFailure(ClusterAddress node); @Override void update(Set<ClusterAddress> nodes); int heartbeatLossThreshold(); List<ClusterAddress> monitored(); boolean isMonitored(ClusterAddress node); @Override DefaultFailureDetectorJmx jmx(); @Override String toString(); }### Answer:
@Test public void testIsMonitored() throws Exception { assertFalse(mgr.isMonitored(n1)); assertTrue(mgr.isMonitored(n2)); assertTrue(mgr.isMonitored(n3)); assertFalse(mgr.isMonitored(n4)); assertFalse(mgr.isMonitored(newNode(100).address())); } |
### Question:
SeedNodeProviderGroup implements SeedNodeProvider, JmxSupport<Collection<? extends SeedNodeProvider>>, ConfigReportSupport { @Override public void startDiscovery(String cluster, InetSocketAddress node) throws HekateException { try { withPolicy("start discovery", allProviders, provider -> { try { provider.startDiscovery(cluster, node); liveProviders.add(provider); } catch (HekateException | RuntimeException | Error e) { failSafeStop(provider, cluster, node); throw e; } } ); } catch (RuntimeException | Error | HekateException e) { stopDiscovery(cluster, node); throw e; } } SeedNodeProviderGroup(SeedNodeProviderGroupConfig cfg); @Override void report(ConfigReporter report); List<SeedNodeProvider> allProviders(); List<SeedNodeProvider> liveProviders(); Optional<T> findProvider(Class<T> type); SeedNodeProviderGroupPolicy policy(); @Override long cleanupInterval(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override Collection<? extends SeedNodeProvider> jmx(); @Override String toString(); }### Answer:
@Test public void testStartDiscovery() throws Exception { SeedNodeProviderGroup group = new SeedNodeProviderGroup(new SeedNodeProviderGroupConfig() .withProvider(p1) .withProvider(p2) ); InetSocketAddress addr = newSocketAddress(); group.startDiscovery(CLUSTER, addr); assertEquals(2, group.liveProviders().size()); assertTrue(group.liveProviders().contains(p1)); assertTrue(group.liveProviders().contains(p2)); verify(p1).startDiscovery(CLUSTER, addr); verify(p2).startDiscovery(CLUSTER, addr); verifyNoMoreInteractions(p1, p2); } |
### Question:
SeedNodeProviderGroup implements SeedNodeProvider, JmxSupport<Collection<? extends SeedNodeProvider>>, ConfigReportSupport { @Override public void stopDiscovery(String cluster, InetSocketAddress node) throws HekateException { try { for (SeedNodeProvider provider : liveProviders) { failSafeStop(provider, cluster, node); } } finally { liveProviders.clear(); } } SeedNodeProviderGroup(SeedNodeProviderGroupConfig cfg); @Override void report(ConfigReporter report); List<SeedNodeProvider> allProviders(); List<SeedNodeProvider> liveProviders(); Optional<T> findProvider(Class<T> type); SeedNodeProviderGroupPolicy policy(); @Override long cleanupInterval(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override Collection<? extends SeedNodeProvider> jmx(); @Override String toString(); }### Answer:
@Test public void testStopDiscovery() throws Exception { SeedNodeProviderGroup group = new SeedNodeProviderGroup(new SeedNodeProviderGroupConfig() .withProvider(p1) .withProvider(p2) ); group.startDiscovery(CLUSTER, selfAddr); assertEquals(2, group.liveProviders().size()); group.stopDiscovery(CLUSTER, selfAddr); assertTrue(group.liveProviders().isEmpty()); verify(p1).startDiscovery(CLUSTER, selfAddr); verify(p2).startDiscovery(CLUSTER, selfAddr); verify(p1).stopDiscovery(CLUSTER, selfAddr); verify(p2).stopDiscovery(CLUSTER, selfAddr); verifyNoMoreInteractions(p1, p2); } |
### Question:
SeedNodeProviderGroup implements SeedNodeProvider, JmxSupport<Collection<? extends SeedNodeProvider>>, ConfigReportSupport { @Override public void suspendDiscovery() throws HekateException { liveProviders.forEach(provider -> { try { provider.suspendDiscovery(); } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn("Failed to suspend discovery [provider={}]", provider, e); } } }); } SeedNodeProviderGroup(SeedNodeProviderGroupConfig cfg); @Override void report(ConfigReporter report); List<SeedNodeProvider> allProviders(); List<SeedNodeProvider> liveProviders(); Optional<T> findProvider(Class<T> type); SeedNodeProviderGroupPolicy policy(); @Override long cleanupInterval(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override Collection<? extends SeedNodeProvider> jmx(); @Override String toString(); }### Answer:
@Test public void testSuspendDiscovery() throws Exception { SeedNodeProviderGroup group = new SeedNodeProviderGroup(new SeedNodeProviderGroupConfig() .withProvider(p1) .withProvider(p2) ); group.startDiscovery(CLUSTER, selfAddr); group.suspendDiscovery(); verify(p1).startDiscovery(CLUSTER, selfAddr); verify(p2).startDiscovery(CLUSTER, selfAddr); verify(p1).suspendDiscovery(); verify(p2).suspendDiscovery(); verifyNoMoreInteractions(p1, p2); } |
### Question:
SeedNodeProviderGroup implements SeedNodeProvider, JmxSupport<Collection<? extends SeedNodeProvider>>, ConfigReportSupport { @Override public void registerRemote(String cluster, InetSocketAddress node) throws HekateException { withPolicy("register a remote seed node", liveProviders, provider -> provider.registerRemote(cluster, node) ); } SeedNodeProviderGroup(SeedNodeProviderGroupConfig cfg); @Override void report(ConfigReporter report); List<SeedNodeProvider> allProviders(); List<SeedNodeProvider> liveProviders(); Optional<T> findProvider(Class<T> type); SeedNodeProviderGroupPolicy policy(); @Override long cleanupInterval(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override Collection<? extends SeedNodeProvider> jmx(); @Override String toString(); }### Answer:
@Test public void testRegisterRemote() throws Exception { SeedNodeProviderGroup group = new SeedNodeProviderGroup(new SeedNodeProviderGroupConfig() .withProvider(p1) .withProvider(p2) ); group.startDiscovery(CLUSTER, selfAddr); InetSocketAddress addr = newSocketAddress(); group.registerRemote(CLUSTER, addr); verify(p1).startDiscovery(CLUSTER, selfAddr); verify(p2).startDiscovery(CLUSTER, selfAddr); verify(p1).registerRemote(CLUSTER, addr); verify(p2).registerRemote(CLUSTER, addr); verifyNoMoreInteractions(p1, p2); } |
### Question:
SeedNodeProviderGroup implements SeedNodeProvider, JmxSupport<Collection<? extends SeedNodeProvider>>, ConfigReportSupport { @Override public void unregisterRemote(String cluster, InetSocketAddress node) throws HekateException { withPolicy("unregister a remote seed node", liveProviders, provider -> provider.unregisterRemote(cluster, node) ); } SeedNodeProviderGroup(SeedNodeProviderGroupConfig cfg); @Override void report(ConfigReporter report); List<SeedNodeProvider> allProviders(); List<SeedNodeProvider> liveProviders(); Optional<T> findProvider(Class<T> type); SeedNodeProviderGroupPolicy policy(); @Override long cleanupInterval(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override Collection<? extends SeedNodeProvider> jmx(); @Override String toString(); }### Answer:
@Test public void testUnregisterRemote() throws Exception { SeedNodeProviderGroup group = new SeedNodeProviderGroup(new SeedNodeProviderGroupConfig() .withProvider(p1) .withProvider(p2) ); group.startDiscovery(CLUSTER, selfAddr); InetSocketAddress addr = newSocketAddress(); group.unregisterRemote(CLUSTER, addr); verify(p1).startDiscovery(CLUSTER, selfAddr); verify(p2).startDiscovery(CLUSTER, selfAddr); verify(p1).unregisterRemote(CLUSTER, addr); verify(p2).unregisterRemote(CLUSTER, addr); verifyNoMoreInteractions(p1, p2); } |
### Question:
SeedNodeProviderGroup implements SeedNodeProvider, JmxSupport<Collection<? extends SeedNodeProvider>>, ConfigReportSupport { @Override public String toString() { return ToString.format(this); } SeedNodeProviderGroup(SeedNodeProviderGroupConfig cfg); @Override void report(ConfigReporter report); List<SeedNodeProvider> allProviders(); List<SeedNodeProvider> liveProviders(); Optional<T> findProvider(Class<T> type); SeedNodeProviderGroupPolicy policy(); @Override long cleanupInterval(); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override Collection<? extends SeedNodeProvider> jmx(); @Override String toString(); }### Answer:
@Test public void testToString() { SeedNodeProvider provider = new SeedNodeProviderGroup(new SeedNodeProviderGroupConfig() .withPolicy(SeedNodeProviderGroupPolicy.IGNORE_PARTIAL_ERRORS) .withProvider(p1) .withProvider(p2) ); assertEquals(ToString.format(provider), provider.toString()); } |
### Question:
StaticSeedNodeProvider implements SeedNodeProvider, ConfigReportSupport { @Override public List<InetSocketAddress> findSeedNodes(String cluster) throws HekateException { return addresses; } StaticSeedNodeProvider(StaticSeedNodeProviderConfig cfg); @Override void report(ConfigReporter report); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override long cleanupInterval(); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); List<InetSocketAddress> getAddresses(); @Override String toString(); }### Answer:
@Test public void testValidIAddressV4() throws Exception { StaticSeedNodeProvider provider = get(ADDRESS_V4 + ":10001"); List<InetSocketAddress> nodes = provider.findSeedNodes("test"); assertFalse(nodes.isEmpty()); assertEquals(new InetSocketAddress(ADDRESS_V4, 10001), nodes.get(0)); }
@Test public void testValidAddressV6() throws Exception { StaticSeedNodeProvider provider = get("[" + ADDRESS_V6 + "]:10001"); List<InetSocketAddress> nodes = provider.findSeedNodes("test"); assertFalse(nodes.isEmpty()); assertEquals(new InetSocketAddress(ADDRESS_V6, 10001), nodes.get(0)); } |
### Question:
SeedNodeProviderGroupConfig { @Override public String toString() { return ToString.format(this); } SeedNodeProviderGroupPolicy getPolicy(); void setPolicy(SeedNodeProviderGroupPolicy policy); SeedNodeProviderGroupConfig withPolicy(SeedNodeProviderGroupPolicy policy); List<SeedNodeProvider> getProviders(); void setProviders(List<SeedNodeProvider> providers); SeedNodeProviderGroupConfig withProvider(SeedNodeProvider provider); SeedNodeProviderGroupConfig withProviders(List<SeedNodeProvider> providers); boolean hasProviders(); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
MulticastSeedNodeProvider implements SeedNodeProvider, JmxSupport<MulticastSeedNodeProviderJmx>, ConfigReportSupport { @Override public void suspendDiscovery() { suspendDiscoveryAsync().awaitUninterruptedly(); } MulticastSeedNodeProvider(); MulticastSeedNodeProvider(MulticastSeedNodeProviderConfig cfg); @Override void report(ConfigReporter report); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void startDiscovery(String cluster, InetSocketAddress address); @Override void suspendDiscovery(); @Override void stopDiscovery(String cluster, InetSocketAddress address); @Override long cleanupInterval(); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); InetSocketAddress group(); int ttl(); long interval(); long waitTime(); boolean isLoopBackDisabled(); @Override MulticastSeedNodeProviderJmx jmx(); @Override String toString(); }### Answer:
@Test public void testSuspendDiscovery() throws Exception { Map<InetSocketAddress, TestProvider> providers = new HashMap<>(); try { for (int i = 0; i < 3; i++) { TestProvider provider = createProvider(); InetSocketAddress address = newSocketAddress(10000 + i); providers.put(address, provider); provider.startDiscovery(CLUSTER_1, address); } for (Map.Entry<InetSocketAddress, TestProvider> e : providers.entrySet()) { TestProvider provider = e.getValue(); assertTrue(e.getKey().toString(), provider.getRequests() > 0); provider.suspendDiscovery(); } sleep(DISCOVERY_INTERVAL * 4); providers.values().forEach(TestProvider::clearRequests); sleep(DISCOVERY_INTERVAL * 2); providers.values().forEach(p -> assertEquals(0, p.getRequests())); } finally { for (Map.Entry<InetSocketAddress, TestProvider> e : providers.entrySet()) { e.getValue().stopDiscovery(CLUSTER_1, e.getKey()); assertTrue(e.getValue().findSeedNodes(CLUSTER_1).isEmpty()); } } } |
### Question:
ClusterFilters { public static ClusterFilter forNode(ClusterNodeId nodeId) { ArgAssert.notNull(nodeId, "Node"); return nodes -> { if (!nodes.isEmpty()) { for (ClusterNode node : nodes) { if (node.id().equals(nodeId)) { return singletonList(node); } } } return emptyList(); }; } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForId() throws Exception { List<ClusterNode> nodes = asList(newNode(), newNode(), newNode(), newNode()); for (ClusterNode n : nodes) { assertEquals(singletonList(n), ClusterFilters.forNode(n.id()).apply(nodes)); } ClusterNodeId nonExisting = newNodeId(); assertEquals(emptyList(), ClusterFilters.forNode(nonExisting).apply(nodes)); }
@Test public void testForNode() throws Exception { List<ClusterNode> nodes = asList(newNode(), newNode(), newNode(), newNode()); for (ClusterNode n : nodes) { assertEquals(singletonList(n), ClusterFilters.forNode(n).apply(nodes)); } ClusterNode nonExisting = newNode(); assertEquals(emptyList(), ClusterFilters.forNode(nonExisting).apply(nodes)); } |
### Question:
ClusterFilters { public static ClusterFilter forNext() { return NEXT; } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForNext() throws Exception { repeat(5, i -> { List<ClusterNode> nodes = new ArrayList<>(); repeat(5, j -> nodes.add(newNode(newNodeId(j), i == j , null, null))); ClusterNode expected; if (i == 4) { expected = nodes.get(0); } else { expected = nodes.get(i + 1); } assertEquals(singletonList(expected), ClusterFilters.forNext().apply(nodes)); }); }
@Test public void testForNextWithSingleLocal() throws Exception { ClusterNode node = newLocalNode(); assertEquals(singletonList(node), ClusterFilters.forNext().apply(singletonList(node))); }
@Test public void testForNextWithNoLocal() throws Exception { List<ClusterNode> nodes = asList(newNode(), newNode(), newNode(), newNode()); assertEquals(emptyList(), ClusterFilters.forNext().apply(nodes)); } |
### Question:
ClusterFilters { public static ClusterFilter forNextInJoinOrder() { return NEXT_IN_JOIN_ORDER; } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForJoinOrderNext() throws Exception { repeat(5, i -> { List<ClusterNode> nodesList = new ArrayList<>(); repeat(5, j -> nodesList.add(newNode(newNodeId(), i == j , null, null, j))); ClusterNode expected; if (i == 4) { expected = nodesList.get(0); } else { expected = nodesList.get(i + 1); } assertEquals(singletonList(expected), ClusterFilters.forNextInJoinOrder().apply(nodesList)); }); }
@Test public void testForJoinOrderNextWithSingleLocal() throws Exception { ClusterNode node = newLocalNode(); assertEquals(singletonList(node), ClusterFilters.forNextInJoinOrder().apply(singletonList(node))); }
@Test public void testForJoinOrderNextWithNoLocal() throws Exception { List<ClusterNode> nodes = asList(newNode(), newNode(), newNode(), newNode()); assertEquals(emptyList(), ClusterFilters.forNextInJoinOrder().apply(nodes)); } |
### Question:
ClusterFilters { public static ClusterFilter forOldest() { return OLDEST; } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForOldest() throws Exception { ClusterNode node1 = newLocalNode(n -> n.withJoinOrder(1)); ClusterNode node2 = newLocalNode(n -> n.withJoinOrder(2)); ClusterNode node3 = newLocalNode(n -> n.withJoinOrder(3)); assertEquals(singletonList(node1), ClusterFilters.forOldest().apply(asList(node1, node2, node3))); } |
### Question:
ClusterFilters { public static ClusterFilter forYoungest() { return YOUNGEST; } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForYoungest() throws Exception { ClusterNode node1 = newLocalNode(n -> n.withJoinOrder(1)); ClusterNode node2 = newLocalNode(n -> n.withJoinOrder(2)); ClusterNode node3 = newLocalNode(n -> n.withJoinOrder(3)); assertEquals(singletonList(node3), ClusterFilters.forYoungest().apply(asList(node1, node2, node3))); } |
### Question:
ClusterFilters { public static ClusterFilter forRole(String role) { ArgAssert.notNull(role, "Role"); return forFilter(n -> n.hasRole(role)); } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForRole() throws Exception { ClusterNode node1 = newLocalNode(n -> n.withRoles(singleton("role1"))); ClusterNode node2 = newLocalNode(n -> n.withRoles(singleton("role2"))); ClusterNode node3 = newLocalNode(n -> n.withRoles(singleton("role3"))); assertEquals(singletonList(node3), ClusterFilters.forRole("role3").apply(asList(node1, node2, node3))); assertEquals(emptyList(), ClusterFilters.forRole("INVALID").apply(asList(node1, node2, node3))); } |
### Question:
ClusterFilters { public static ClusterFilter forService(Class<? extends Service> type) { ArgAssert.notNull(type, "Service type"); return forFilter(n -> n.hasService(type)); } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForService() throws Exception { ClusterNode node1 = newLocalNode(n -> n.withServices(singletonMap(NetworkService.class.getName(), null))); ClusterNode node2 = newLocalNode(n -> n.withServices(singletonMap(ClusterService.class.getName(), null))); ClusterNode node3 = newLocalNode(n -> n.withServices(singletonMap(MessagingService.class.getName(), null))); assertEquals(singletonList(node3), ClusterFilters.forService(MessagingService.class).apply(asList(node1, node2, node3))); assertEquals(emptyList(), ClusterFilters.forService(CoordinationService.class).apply(asList(node1, node2, node3))); } |
### Question:
ClusterFilters { public static ClusterFilter forRemotes() { return REMOTES; } private ClusterFilters(); static ClusterFilter forNext(); static ClusterFilter forNextInJoinOrder(); static ClusterFilter forNode(ClusterNodeId nodeId); static ClusterFilter forNode(ClusterNode node); static ClusterFilter forOldest(); static ClusterFilter forYoungest(); static ClusterFilter forFilter(ClusterNodeFilter filter); static ClusterFilter forRole(String role); static ClusterFilter forProperty(String name); static ClusterFilter forProperty(String name, String value); static ClusterFilter forService(Class<? extends Service> type); static ClusterFilter forRemotes(); }### Answer:
@Test public void testForRemotes() throws Exception { ClusterNode node1 = newLocalNode(n -> n.withLocalNode(false)); ClusterNode node2 = newLocalNode(n -> n.withLocalNode(false)); ClusterNode node3 = newLocalNode(n -> n.withLocalNode(true)); assertEquals(asList(node1, node2), ClusterFilters.forRemotes().apply(asList(node1, node2, node3))); assertEquals(emptyList(), ClusterFilters.forService(CoordinationService.class).apply(asList(node1, node2))); } |
### Question:
TopologyContextCache { @SuppressWarnings("unchecked") public <C> C get(ClusterTopology topology, Function<ClusterTopology, C> supplier) { CacheEntry ctx = this.ctx; if (ctx == null || ctx.version() != topology.version()) { this.ctx = ctx = new CacheEntry( topology.version(), supplier.apply(topology) ); } return (C)ctx.value(); } @SuppressWarnings("unchecked") C get(ClusterTopology topology, Function<ClusterTopology, C> supplier); }### Answer:
@Test public void test() throws Exception { Function<ClusterTopology, Object> supplier = topology -> new Object(); ClusterTopology t1 = ClusterTopology.of(1, toSet(newNode())); ClusterTopology t2 = ClusterTopology.of(2, toSet(newNode(), newNode())); ClusterTopology t3 = ClusterTopology.of(3, toSet(newNode(), newNode(), newNode())); Object o1 = cache.get(t1, supplier); assertSame(o1, cache.get(t1, supplier)); Object o2 = cache.get(t2, supplier); assertNotSame(o2, o1); assertSame(o2, cache.get(t2, supplier)); Object o3 = cache.get(t3, supplier); assertNotSame(o1, o3); assertNotSame(o2, o3); assertSame(o3, cache.get(t3, supplier)); }
@Test public void testConcurrent() throws Exception { ClusterTopology[] topologies = { ClusterTopology.of(1, toSet(newNode())), ClusterTopology.of(2, toSet(newNode(), newNode())), ClusterTopology.of(3, toSet(newNode(), newNode(), newNode())) }; runParallel(4, 1_000_000, status -> { ClusterTopology top = topologies[ThreadLocalRandom.current().nextInt(topologies.length)]; assertEquals(top.hash(), cache.get(top, ClusterTopology::hash)); }); } |
### Question:
SeedNodeManager { public List<InetSocketAddress> getSeedNodes() throws HekateException { if (DEBUG) { log.debug("Getting seed nodes to join...."); } List<InetSocketAddress> nodes = provider.findSeedNodes(cluster); nodes = nodes != null ? nodes : emptyList(); if (DEBUG) { log.debug("Got a seed nodes list [seed-nodes={}]", nodes); } return nodes; } SeedNodeManager(String cluster, SeedNodeProvider provider); List<InetSocketAddress> getSeedNodes(); void startDiscovery(InetSocketAddress address); void suspendDiscovery(); void stopDiscovery(InetSocketAddress address); void startCleaning(NetworkService net, AliveAddressProvider aliveAddressProvider); Waiting stopCleaning(); @Override String toString(); }### Answer:
@Test public void testNeverReturnsNull() throws Exception { when(provider.findSeedNodes(any(String.class))).thenReturn(null); List<InetSocketAddress> nodes = manager.getSeedNodes(); assertNotNull(nodes); assertTrue(nodes.isEmpty()); verify(provider).findSeedNodes(any(String.class)); verifyNoMoreInteractions(provider); }
@Test public void testErrorOnGetSeedNodes() throws Exception { when(provider.findSeedNodes(any(String.class))).thenThrow(TEST_ERROR); try { manager.getSeedNodes(); fail("Error was expected."); } catch (AssertionError e) { assertEquals(HekateTestError.MESSAGE, e.getMessage()); } verify(provider).findSeedNodes(any(String.class)); verifyNoMoreInteractions(provider); } |
### Question:
SeedNodeManager { public void startDiscovery(InetSocketAddress address) throws HekateException { if (DEBUG) { log.debug("Starting seed nodes discovery [cluster={}, address={}]", cluster, address); } started.set(true); provider.startDiscovery(cluster, address); if (DEBUG) { log.debug("Started seed nodes discovery [cluster={}, address={}]", cluster, address); } } SeedNodeManager(String cluster, SeedNodeProvider provider); List<InetSocketAddress> getSeedNodes(); void startDiscovery(InetSocketAddress address); void suspendDiscovery(); void stopDiscovery(InetSocketAddress address); void startCleaning(NetworkService net, AliveAddressProvider aliveAddressProvider); Waiting stopCleaning(); @Override String toString(); }### Answer:
@Test public void testErrorOnStartDiscovery() throws Exception { doThrow(TEST_ERROR).when(provider).startDiscovery(any(String.class), any(InetSocketAddress.class)); try { manager.startDiscovery(newSocketAddress()); fail("Error was expected."); } catch (AssertionError e) { assertEquals(HekateTestError.MESSAGE, e.getMessage()); } verify(provider).startDiscovery(any(String.class), any(InetSocketAddress.class)); verifyNoMoreInteractions(provider); } |
### Question:
SeedNodeManager { public void suspendDiscovery() { if (DEBUG) { log.debug("Suspending seed nodes discovery..."); } try { provider.suspendDiscovery(); if (DEBUG) { log.debug("Suspended seed nodes discovery."); } } catch (Throwable t) { log.error("Failed to suspend seed nodes discovery.", t); } } SeedNodeManager(String cluster, SeedNodeProvider provider); List<InetSocketAddress> getSeedNodes(); void startDiscovery(InetSocketAddress address); void suspendDiscovery(); void stopDiscovery(InetSocketAddress address); void startCleaning(NetworkService net, AliveAddressProvider aliveAddressProvider); Waiting stopCleaning(); @Override String toString(); }### Answer:
@Test public void testNoErrorOnSuspendDiscovery() throws Exception { doThrow(TEST_ERROR).when(provider).suspendDiscovery(); manager.suspendDiscovery(); verify(provider).suspendDiscovery(); verifyNoMoreInteractions(provider); } |
### Question:
SeedNodeManager { public void stopDiscovery(InetSocketAddress address) { if (started.compareAndSet(true, false)) { try { if (DEBUG) { log.debug("Stopping seed nodes discovery [cluster={}, address={}]", cluster, address); } provider.stopDiscovery(cluster, address); if (DEBUG) { log.debug("Done stopping seed nodes discovery [cluster={}, address={}]", cluster, address); } } catch (Throwable t) { log.error("Failed to stop seed nodes discovery [cluster={}, address={}]", cluster, address, t); } } } SeedNodeManager(String cluster, SeedNodeProvider provider); List<InetSocketAddress> getSeedNodes(); void startDiscovery(InetSocketAddress address); void suspendDiscovery(); void stopDiscovery(InetSocketAddress address); void startCleaning(NetworkService net, AliveAddressProvider aliveAddressProvider); Waiting stopCleaning(); @Override String toString(); }### Answer:
@Test public void testStopDiscoveryWithoutStartDiscovery() throws Exception { manager.stopDiscovery(newSocketAddress()); verifyNoMoreInteractions(provider); } |
### Question:
SeedNodeManager { public Waiting stopCleaning() { ExecutorService cleaner; synchronized (cleanupMux) { cleaner = this.cleaner; if (cleaner != null) { if (DEBUG) { log.debug("Canceling seed nodes cleanup task [cluster={}]", cluster); } this.cleaner = null; this.net = null; this.aliveAddressProvider = null; } } return AsyncUtils.shutdown(cleaner); } SeedNodeManager(String cluster, SeedNodeProvider provider); List<InetSocketAddress> getSeedNodes(); void startDiscovery(InetSocketAddress address); void suspendDiscovery(); void stopDiscovery(InetSocketAddress address); void startCleaning(NetworkService net, AliveAddressProvider aliveAddressProvider); Waiting stopCleaning(); @Override String toString(); }### Answer:
@Test public void testStopCleaningWithoutStarting() throws Exception { manager.stopCleaning(); manager.stopCleaning(); manager.stopCleaning(); } |
### Question:
SeedNodeManager { @Override public String toString() { return provider.toString(); } SeedNodeManager(String cluster, SeedNodeProvider provider); List<InetSocketAddress> getSeedNodes(); void startDiscovery(InetSocketAddress address); void suspendDiscovery(); void stopDiscovery(InetSocketAddress address); void startCleaning(NetworkService net, AliveAddressProvider aliveAddressProvider); Waiting stopCleaning(); @Override String toString(); }### Answer:
@Test public void testToString() throws Exception { assertEquals(provider.toString(), manager.toString()); } |
### Question:
GossipSeedNodesSate { public InetSocketAddress nextSeed() { if (lastTried != null) { lastTried = seeds.stream() .filter(s -> s.status() != Status.BAN && !s.address().equals(localAddress) && compare(s.address(), lastTried) > 0) .findFirst() .map(SeedNodeState::address) .orElse(null); } if (lastTried == null) { lastTried = seeds.stream() .filter(s -> s.status() != Status.BAN && !s.address().equals(localAddress)) .findFirst() .map(SeedNodeState::address) .orElse(null); } return lastTried; } GossipSeedNodesSate(InetSocketAddress localAddress, List<InetSocketAddress> seeds); boolean isSelfJoin(); InetSocketAddress nextSeed(); void update(List<InetSocketAddress> newSeeds); void onReject(InetSocketAddress seed); void onFailure(InetSocketAddress seed, Throwable cause); void onBan(InetSocketAddress seed); @Override String toString(); }### Answer:
@Test public void testNextSeed() throws Exception { List<InetSocketAddress> seeds = new ArrayList<>(); seeds.add(newSocketAddress(1)); seeds.add(newSocketAddress(2)); seeds.add(newSocketAddress(3)); GossipSeedNodesSate s = new GossipSeedNodesSate(newSocketAddress(1000), seeds); assertFalse(s.isSelfJoin()); repeat(3, i -> { for (InetSocketAddress addr : seeds) { assertEquals(addr, s.nextSeed()); } }); } |
### Question:
GossipNodeState extends GossipNodeInfoBase implements Comparable<GossipNodeState> { @Override public GossipNodeStatus status() { return status; } GossipNodeState(ClusterNode node, GossipNodeStatus status); GossipNodeState(ClusterNode node, GossipNodeStatus status, long version, Set<ClusterNodeId> suspected); @Override ClusterNodeId id(); @Override long version(); ClusterNode node(); ClusterAddress address(); GossipNodeState merge(GossipNodeState other); @Override GossipNodeStatus status(); GossipNodeState status(GossipNodeStatus newStatus); int order(); GossipNodeState order(int order); Set<ClusterNodeId> suspected(); GossipNodeState suspect(ClusterNodeId suspected); GossipNodeState suspect(Set<ClusterNodeId> suspected); GossipNodeState unsuspect(ClusterNodeId removed); GossipNodeState unsuspect(Set<ClusterNodeId> unsuspected); boolean isSuspected(ClusterNodeId id); boolean hasSuspected(); @Override int compareTo(GossipNodeState o); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testUpdateState() throws Exception { GossipNodeState s1 = new GossipNodeState(newNode(), GossipNodeStatus.JOINING); assertSame(GossipNodeStatus.JOINING, s1.status()); GossipNodeState s2 = s1.status(GossipNodeStatus.JOINING); assertSame(s1, s2); assertSame(GossipNodeStatus.JOINING, s1.status()); GossipNodeState s3 = s1.status(GossipNodeStatus.UP); assertNotSame(s1, s3); assertSame(GossipNodeStatus.UP, s3.status()); } |
### Question:
SplitBrainManager implements ConfigReportSupport { public void checkAsync() { if (hasDetector()) { guard.withReadLockIfInitialized(() -> { if (active.compareAndSet(false, true)) { runAsync(() -> { try { guard.withReadLockIfInitialized(() -> { if (!actionApplied.get()) { if (DEBUG) { log.debug("Checking for cluster split-brain [detector={}]", detector); } if (!detector.isValid(localNode)) { if (actionApplied.compareAndSet(false, true)) { if (log.isWarnEnabled()) { log.warn("Split-brain detected."); } applyAction(); } } } }); } finally { active.compareAndSet(true, false); } }); } }); } } SplitBrainManager(SplitBrainAction action, long checkInterval, SplitBrainDetector detector); @Override void report(ConfigReporter report); long checkInterval(); boolean hasDetector(); SplitBrainDetector detector(); SplitBrainAction action(); void initialize(ClusterNode localNode, Executor async, Callback callback); void terminate(); boolean check(); void checkAsync(); void applyAction(); @Override String toString(); }### Answer:
@Test public void testCheckAsync() throws Exception { SplitBrainDetector detector = mock(SplitBrainDetector.class); Callback callback = mock(Callback.class); SplitBrainManager mgr = new SplitBrainManager(SplitBrainAction.TERMINATE, 0, detector); mgr.initialize(newNode(), Runnable::run, callback); when(detector.isValid(any())).thenReturn(false); mgr.checkAsync(); verify(callback).terminate(); } |
### Question:
SplitBrainManager implements ConfigReportSupport { @Override public String toString() { return ToString.format(this); } SplitBrainManager(SplitBrainAction action, long checkInterval, SplitBrainDetector detector); @Override void report(ConfigReporter report); long checkInterval(); boolean hasDetector(); SplitBrainDetector detector(); SplitBrainAction action(); void initialize(ClusterNode localNode, Executor async, Callback callback); void terminate(); boolean check(); void checkAsync(); void applyAction(); @Override String toString(); }### Answer:
@Test public void testToString() { SplitBrainManager mgr = new SplitBrainManager(SplitBrainAction.TERMINATE, 0, mock(SplitBrainDetector.class)); assertEquals(ToString.format(mgr), mgr.toString()); } |
### Question:
UpdatableClusterView implements ClusterView { public static UpdatableClusterView empty() { return new UpdatableClusterView(ClusterTopology.empty()); } protected UpdatableClusterView(ClusterTopology topology); static UpdatableClusterView of(ClusterTopology topology); static UpdatableClusterView of(int version, ClusterNode node); static UpdatableClusterView of(int version, Set<ClusterNode> nodes); static UpdatableClusterView empty(); void update(ClusterTopology topology); @Override ClusterView filterAll(ClusterFilter filter); @Override ClusterTopology topology(); @Override void addListener(ClusterEventListener listener); @Override void addListener(ClusterEventListener listener, ClusterEventType... eventTypes); @Override void removeListener(ClusterEventListener listener); @Override T topologyContext(Function<ClusterTopology, T> supplier); @Override CompletableFuture<ClusterTopology> futureOf(Predicate<ClusterTopology> predicate); @Override boolean awaitFor(Predicate<ClusterTopology> predicate); @Override boolean awaitFor(Predicate<ClusterTopology> predicate, long timeout, TimeUnit timeUnit); @Override String toString(); }### Answer:
@Test public void testEmpty() { UpdatableClusterView view = UpdatableClusterView.empty(); assertTrue(view.topology().isEmpty()); assertEquals(0, view.topology().version()); } |
### Question:
UpdatableClusterView implements ClusterView { public void update(ClusterTopology topology) { ArgAssert.notNull(topology, "Topology"); TOPOLOGY.accumulateAndGet(this, topology, (oldTopology, newTopology) -> newTopology.version() > oldTopology.version() ? newTopology : oldTopology ); } protected UpdatableClusterView(ClusterTopology topology); static UpdatableClusterView of(ClusterTopology topology); static UpdatableClusterView of(int version, ClusterNode node); static UpdatableClusterView of(int version, Set<ClusterNode> nodes); static UpdatableClusterView empty(); void update(ClusterTopology topology); @Override ClusterView filterAll(ClusterFilter filter); @Override ClusterTopology topology(); @Override void addListener(ClusterEventListener listener); @Override void addListener(ClusterEventListener listener, ClusterEventType... eventTypes); @Override void removeListener(ClusterEventListener listener); @Override T topologyContext(Function<ClusterTopology, T> supplier); @Override CompletableFuture<ClusterTopology> futureOf(Predicate<ClusterTopology> predicate); @Override boolean awaitFor(Predicate<ClusterTopology> predicate); @Override boolean awaitFor(Predicate<ClusterTopology> predicate, long timeout, TimeUnit timeUnit); @Override String toString(); }### Answer:
@Test public void testUpdate() throws Exception { UpdatableClusterView view = UpdatableClusterView.empty(); ClusterTopology t1 = ClusterTopology.of(1, toSet(newNode(), newNode())); ClusterTopology t1SameVer = ClusterTopology.of(1, toSet(newNode(), newNode())); ClusterTopology t2 = ClusterTopology.of(2, toSet(newNode(), newNode())); view.update(t1); assertSame(t1, view.topology()); view.update(t1SameVer); assertSame(t1, view.topology()); view.update(t2); assertSame(t2, view.topology()); view.update(t1); assertSame(t2, view.topology()); } |
### Question:
UpdatableClusterView implements ClusterView { @Override public String toString() { return ToString.format(this); } protected UpdatableClusterView(ClusterTopology topology); static UpdatableClusterView of(ClusterTopology topology); static UpdatableClusterView of(int version, ClusterNode node); static UpdatableClusterView of(int version, Set<ClusterNode> nodes); static UpdatableClusterView empty(); void update(ClusterTopology topology); @Override ClusterView filterAll(ClusterFilter filter); @Override ClusterTopology topology(); @Override void addListener(ClusterEventListener listener); @Override void addListener(ClusterEventListener listener, ClusterEventType... eventTypes); @Override void removeListener(ClusterEventListener listener); @Override T topologyContext(Function<ClusterTopology, T> supplier); @Override CompletableFuture<ClusterTopology> futureOf(Predicate<ClusterTopology> predicate); @Override boolean awaitFor(Predicate<ClusterTopology> predicate); @Override boolean awaitFor(Predicate<ClusterTopology> predicate, long timeout, TimeUnit timeUnit); @Override String toString(); }### Answer:
@Test public void testToString() { UpdatableClusterView view = UpdatableClusterView.empty(); assertEquals(ToString.format(view), view.toString()); } |
### Question:
JdbcConnectivityDetector implements SplitBrainDetector, ConfigReportSupport { @Override public String toString() { return ToString.format(this); } JdbcConnectivityDetector(DataSource ds, int timeout); @Override void report(ConfigReporter report); DataSource datasource(); int timeout(); @Override boolean isValid(ClusterNode localNode); @Override String toString(); }### Answer:
@Test public void testToString() { JdbcConnectivityDetector detector = new JdbcConnectivityDetector(mock(DataSource.class), 1); assertEquals(ToString.format(detector), detector.toString()); } |
### Question:
SplitBrainDetectorGroup implements SplitBrainDetector, ConfigReportSupport { public void setDetectors(List<SplitBrainDetector> detectors) { this.detectors = detectors; } @Override boolean isValid(ClusterNode localNode); @Override void report(ConfigReporter report); List<SplitBrainDetector> getDetectors(); void setDetectors(List<SplitBrainDetector> detectors); SplitBrainDetectorGroup withDetector(SplitBrainDetector detector); GroupPolicy getGroupPolicy(); void setGroupPolicy(GroupPolicy groupPolicy); SplitBrainDetectorGroup withGroupPolicy(GroupPolicy groupPolicy); @Override String toString(); }### Answer:
@Test public void testSetDetectors() { assertNull(group.getDetectors()); SplitBrainDetectorMock d1 = new SplitBrainDetectorMock(true); SplitBrainDetectorMock d2 = new SplitBrainDetectorMock(true); group.setDetectors(asList(d1, d2)); assertEquals(2, group.getDetectors().size()); assertTrue(group.getDetectors().contains(d1)); assertTrue(group.getDetectors().contains(d2)); group.setDetectors(null); assertNull(group.getDetectors()); assertSame(group, group.withDetector(d1)); assertEquals(1, group.getDetectors().size()); assertTrue(group.getDetectors().contains(d1)); } |
### Question:
AddressReachabilityDetector implements SplitBrainDetector, ConfigReportSupport { @Override public boolean isValid(ClusterNode localNode) { try (Socket socket = new Socket()) { InetAddress resolvedHost = InetAddress.getByName(address.getHostString()); InetSocketAddress resolvedAddress = new InetSocketAddress(resolvedHost, address.getPort()); socket.connect(resolvedAddress, timeout); if (DEBUG) { log.debug("Address reachability check success [host={}, timeout={}]", address, timeout); } return true; } catch (IOException e) { if (log.isWarnEnabled()) { log.warn("Address reachability check failed [host={}, timeout={}, error={}]", address, timeout, e.toString()); } } return false; } AddressReachabilityDetector(String address); AddressReachabilityDetector(String address, int timeout); AddressReachabilityDetector(InetSocketAddress address, int timeout); @Override void report(ConfigReporter report); InetSocketAddress address(); int timeout(); @Override boolean isValid(ClusterNode localNode); @Override String toString(); static final int DEFAULT_TIMEOUT; }### Answer:
@Test public void testValid() throws Exception { HekateTestNode node = createNode().join(); InetSocketAddress address = node.localNode().socket(); AddressReachabilityDetector detector = new AddressReachabilityDetector(address, 2000); assertTrue(detector.isValid(node.localNode())); detector = new AddressReachabilityDetector(address.getHostString() + ':' + address.getPort()); assertTrue(detector.isValid(node.localNode())); }
@Test public void testInvalid() throws Exception { AddressReachabilityDetector detector = new AddressReachabilityDetector("localhost:12345", 2000); assertFalse(detector.isValid(newNode())); } |
### Question:
HostReachabilityDetector implements SplitBrainDetector, ConfigReportSupport { @Override public boolean isValid(ClusterNode localNode) { try { InetAddress address = InetAddress.getByName(host); boolean reachable = address.isReachable(timeout); if (reachable) { if (DEBUG) { log.debug("Address reachability check success [host={}, timeout={}]", host, timeout); } } else { if (log.isWarnEnabled()) { log.warn("Address reachability check failed [host={}, timeout={}]", host, timeout); } } return reachable; } catch (IOException e) { if (log.isWarnEnabled()) { log.warn("Address reachability check failed with an error [host={}, timeout={}, cause={}]", host, timeout, e.toString()); } } return false; } HostReachabilityDetector(String host); HostReachabilityDetector(String host, int timeout); @Override void report(ConfigReporter report); String host(); int timeout(); @Override boolean isValid(ClusterNode localNode); @Override String toString(); static final int DEFAULT_TIMEOUT; }### Answer:
@Test public void testValid() throws Exception { HostReachabilityDetector detector = new HostReachabilityDetector(InetAddress.getLocalHost().getHostAddress(), 2000); assertTrue(detector.isValid(newNode())); }
@Test public void testInvalid() throws Exception { HostReachabilityDetector detector = new HostReachabilityDetector("some.invalid.host", 2000); assertFalse(detector.isValid(newNode())); } |
### Question:
KubernetesSeedNodeProviderConfig { @Override public String toString() { return ToString.format(this); } String getContainerPortName(); void setContainerPortName(String containerPortName); KubernetesSeedNodeProviderConfig withContainerPortName(String containerPortName); String getNamespace(); void setNamespace(String namespace); KubernetesSeedNodeProviderConfig withNamespace(String namespace); String getMasterUrl(); void setMasterUrl(String masterUrl); KubernetesSeedNodeProviderConfig withMasterUrl(String masterUrl); Boolean getTrustCertificates(); void setTrustCertificates(Boolean trustCertificates); KubernetesSeedNodeProviderConfig withTrustCertificates(Boolean trustCertificates); @Override String toString(); static final String DEFAULT_CONTAINER_PORT_NAME; }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
RpcServiceFactory extends MessagingConfigBase<RpcServiceFactory> implements ServiceFactory<RpcService> { @Override public String toString() { return ToString.format(this); } List<RpcClientConfig> getClients(); void setClients(List<RpcClientConfig> clients); RpcServiceFactory withClient(RpcClientConfig client); List<RpcClientConfigProvider> getClientProviders(); void setClientProviders(List<RpcClientConfigProvider> clientProviders); RpcServiceFactory withClientProvider(RpcClientConfigProvider clientProvider); List<RpcServerConfig> getServers(); void setServers(List<RpcServerConfig> servers); RpcServiceFactory withServer(RpcServerConfig server); List<RpcServerConfigProvider> getServerProviders(); void setServerProviders(List<RpcServerConfigProvider> serverProviders); RpcServiceFactory withServerProvider(RpcServerConfigProvider serverProvider); int getWorkerThreads(); void setWorkerThreads(int workerThreads); RpcServiceFactory withWorkerThreads(int workerThreads); @Override RpcService createService(); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(factory), factory.toString()); } |
### Question:
RpcRetryInfo implements GenericRetryConfigurer { @Override public String toString() { return ToString.format(this); } private RpcRetryInfo(
OptionalInt maxAttempts,
OptionalLong delay,
OptionalLong maxDelay,
List<Class<? extends Throwable>> errors
); static RpcRetryInfo parse(RpcRetry retry, PlaceholderResolver resolver); OptionalInt maxAttempts(); OptionalLong delay(); OptionalLong maxDelay(); List<Class<? extends Throwable>> errors(); @Override void configure(RetryPolicy<?> retry); @Override String toString(); }### Answer:
@Test public void testToString() { RpcRetryInfo info = buildInfo("", "", "", emptyList()); assertEquals(ToString.format(info), info.toString()); } |
### Question:
HekateSerializableClasses { public static SortedSet<Class<?>> get() { return CLASSES; } private HekateSerializableClasses(); static SortedSet<Class<?>> get(); }### Answer:
@Test public void testKnownClasses() throws Exception { SortedSet<Class<?>> known = HekateSerializableClasses.get(); for (String name : scanForSerializableClasses()) { Class<?> clazz = Class.forName(name); assertTrue(clazz.getName(), known.contains(clazz)); } } |
### Question:
KryoCodec implements Codec<Object> { @Override public boolean isStateful() { return stateful; } KryoCodec(KryoCodecFactory<?> factory); @Override boolean isStateful(); @Override Class<Object> baseType(); @Override Object decode(DataReader in); @Override void encode(Object obj, DataWriter out); @Override String toString(); }### Answer:
@Test public void testStateless() { assertEquals(factory.isCacheUnknownTypes(), factory.createCodec().isStateful()); } |
### Question:
ThreadLocalCodecFactory implements CodecFactory<T> { public static <T> CodecFactory<T> tryWrap(CodecFactory<T> factory) { ArgAssert.notNull(factory, "Codec factory is null."); if (factory instanceof ThreadLocalCodecFactory) { return factory; } Codec<T> probe = factory.createCodec(); if (probe.isStateful()) { return factory; } else { return new ThreadLocalCodecFactory<>(probe.baseType(), factory); } } private ThreadLocalCodecFactory(Class<T> baseType, CodecFactory<T> delegate); static CodecFactory<T> tryWrap(CodecFactory<T> factory); @SuppressWarnings("unchecked") static CodecFactory<T> tryUnwrap(CodecFactory<T> factory); @Override Codec<T> createCodec(); @Override String toString(); }### Answer:
@Test public void testDoNotWrapIfAlreadyWrapped() { CodecFactory<Object> wrap = ThreadLocalCodecFactory.tryWrap(factoryMock); assertTrue(wrap instanceof ThreadLocalCodecFactory); assertSame(wrap, ThreadLocalCodecFactory.tryWrap(wrap)); }
@Test public void testDoNotWrapIfStatefulCodec() { when(codecMock.isStateful()).thenReturn(true); CodecFactory<Object> wrap = ThreadLocalCodecFactory.tryWrap(factoryMock); assertSame(factoryMock, wrap); } |
### Question:
ThreadLocalCodecFactory implements CodecFactory<T> { @Override public String toString() { return ThreadLocalCodecFactory.class.getSimpleName() + "[delegate=" + delegate + ']'; } private ThreadLocalCodecFactory(Class<T> baseType, CodecFactory<T> delegate); static CodecFactory<T> tryWrap(CodecFactory<T> factory); @SuppressWarnings("unchecked") static CodecFactory<T> tryUnwrap(CodecFactory<T> factory); @Override Codec<T> createCodec(); @Override String toString(); }### Answer:
@Test public void testToString() { CodecFactory<Object> factory = ThreadLocalCodecFactory.tryWrap(factoryMock); assertEquals(ThreadLocalCodecFactory.class.getSimpleName() + "[delegate=" + factoryMock + ']', factory.toString()); } |
### Question:
CloudStoreSeedNodeProviderConfig extends CloudPropertiesBase<CloudStoreSeedNodeProviderConfig> { @Override public String toString() { return ToString.format(this); } String getProvider(); void setProvider(String provider); CloudStoreSeedNodeProviderConfig withProvider(String provider); CredentialsSupplier getCredentials(); void setCredentials(CredentialsSupplier credentials); CloudStoreSeedNodeProviderConfig withCredentials(CredentialsSupplier credentials); Properties getProperties(); void setProperties(Properties properties); CloudStoreSeedNodeProviderConfig withProperty(String key, String value); long getCleanupInterval(); void setCleanupInterval(long cleanupInterval); CloudStoreSeedNodeProviderConfig withCleanupInterval(long cleanupInterval); String getContainer(); void setContainer(String container); CloudStoreSeedNodeProviderConfig withContainer(String container); @Override String toString(); static final long DEFAULT_CLEANUP_INTERVAL; }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
JdkCodec implements Codec<Object> { @Override public boolean isStateful() { return false; } @Override boolean isStateful(); @Override Class<Object> baseType(); @Override Object decode(DataReader in); @Override void encode(Object message, DataWriter out); @Override String toString(); }### Answer:
@Test public void testStateless() { assertFalse(factory.createCodec().isStateful()); } |
### Question:
FstCodec implements Codec<Object> { @Override public boolean isStateful() { return false; } FstCodec(FSTConfiguration fst); @Override boolean isStateful(); @Override Class<Object> baseType(); @Override void encode(Object obj, DataWriter out); @Override Object decode(DataReader in); @Override String toString(); }### Answer:
@Test public void testStateless() { assertFalse(factory.createCodec().isStateful()); } |
### Question:
AutoSelectCodecFactory implements CodecFactory<T> { public CodecFactory<T> selected() { return factory; } AutoSelectCodecFactory(); static boolean isKryoAvailable(); static boolean isFstAvailable(); CodecFactory<T> selected(); @Override Codec<T> createCodec(); @Override String toString(); }### Answer:
@Test public void testKryo() throws Exception { AutoSelectCodecFactory<Object> factory = new AutoSelectCodecFactory<>(); assertEquals(KryoCodecFactory.class, factory.selected().getClass()); }
@Test public void testFst() throws Exception { ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(new ExclusiveClassLoader(singletonList(KRYO_CLASS), oldLoader)); AutoSelectCodecFactory<Object> factory = new AutoSelectCodecFactory<>(); assertEquals(FstCodecFactory.class, factory.selected().getClass()); } finally { Thread.currentThread().setContextClassLoader(oldLoader); } }
@Test public void testJdk() throws Exception { ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(new ExclusiveClassLoader(asList(KRYO_CLASS, FST_CLASS), oldLoader)); AutoSelectCodecFactory<Object> factory = new AutoSelectCodecFactory<>(); assertEquals(JdkCodecFactory.class, factory.selected().getClass()); } finally { Thread.currentThread().setContextClassLoader(oldLoader); } } |
### Question:
AutoSelectCodecFactory implements CodecFactory<T> { @Override public String toString() { return ToString.format(this); } AutoSelectCodecFactory(); static boolean isKryoAvailable(); static boolean isFstAvailable(); CodecFactory<T> selected(); @Override Codec<T> createCodec(); @Override String toString(); }### Answer:
@Test public void testToString() throws Exception { AutoSelectCodecFactory<Object> factory = new AutoSelectCodecFactory<>(); assertEquals(ToString.format(factory), factory.toString()); } |
### Question:
CoordinationProcessConfig { @Override public String toString() { return ToString.format(this); } CoordinationProcessConfig(); CoordinationProcessConfig(String name); String getName(); void setName(String name); CoordinationProcessConfig withName(String name); boolean isAsyncInit(); void setAsyncInit(boolean asyncInit); CoordinationProcessConfig withAsyncInit(boolean asyncInit); CoordinationHandler getHandler(); void setHandler(CoordinationHandler handler); CoordinationProcessConfig withHandler(CoordinationHandler handler); CodecFactory<Object> getMessageCodec(); void setMessageCodec(CodecFactory<Object> messageCodec); CoordinationProcessConfig withMessageCodec(CodecFactory<Object> messageCodec); @Override String toString(); }### Answer:
@Test public void testToString() { assertEquals(ToString.format(cfg), cfg.toString()); } |
### Question:
CoordinationServiceFactory implements ServiceFactory<CoordinationService> { @Override public CoordinationService createService() { return new DefaultCoordinationService(this); } int getNioThreads(); void setNioThreads(int nioThreads); CoordinationServiceFactory withNioThreads(int nioThreads); long getRetryInterval(); void setRetryInterval(long retryInterval); CoordinationServiceFactory withRetryInterval(long retryInterval); List<CoordinationProcessConfig> getProcesses(); void setProcesses(List<CoordinationProcessConfig> processes); CoordinationServiceFactory withProcess(CoordinationProcessConfig process); CoordinationProcessConfig withProcess(String name); List<CoordinationConfigProvider> getConfigProviders(); void setConfigProviders(List<CoordinationConfigProvider> configProviders); CoordinationServiceFactory withConfigProvider(CoordinationConfigProvider configProvider); long getIdleSocketTimeout(); void setIdleSocketTimeout(long idleSocketTimeout); CoordinationServiceFactory withIdleSocketTimeout(long idleTimeout); @Override CoordinationService createService(); static final int DEFAULT_RETRY_INTERVAL; static final long DEFAULT_IDLE_SOCKET_TIMEOUT; }### Answer:
@Test public void testCreateService() { assertNotNull(factory.createService()); } |
### Question:
CoordinationBroadcastAdaptor implements CoordinationRequestCallback { @Override public void onResponse(Object response, CoordinationMember from) { Map<CoordinationMember, Object> responsesCopy = null; synchronized (responses) { responses.put(from, response); if (responses.size() == expected) { responsesCopy = new HashMap<>(responses); } } if (responsesCopy != null && completed.compareAndSet(false, true)) { callback.onResponses(responsesCopy); } } CoordinationBroadcastAdaptor(int expectedResponses, CoordinationBroadcastCallback callback); @Override void onResponse(Object response, CoordinationMember from); @Override void onCancel(); }### Answer:
@Test public void testOnResponses() throws Exception { repeat(3, i -> { int membersSize = i + 1; CoordinationBroadcastCallback callback = mock(CoordinationBroadcastCallback.class); CoordinationBroadcastAdaptor adaptor = new CoordinationBroadcastAdaptor(membersSize, callback); ArgumentCaptor<Map<CoordinationMember, Object>> captor = newResultCaptor(); List<CoordinationMember> members = new ArrayList<>(); for (int j = 0; j < membersSize; j++) { CoordinationMember member = mock(CoordinationMember.class); members.add(member); adaptor.onResponse("test" + j, member); } verify(callback).onResponses(captor.capture()); assertEquals(membersSize, captor.getValue().size()); for (int j = 0; j < membersSize; j++) { assertEquals("test" + j, captor.getValue().get(members.get(j))); } verifyNoMoreInteractions(callback); }); } |
### Question:
CoordinationBroadcastAdaptor implements CoordinationRequestCallback { @Override public void onCancel() { if (completed.compareAndSet(false, true)) { Map<CoordinationMember, Object> responsesCopy; synchronized (responses) { responsesCopy = new HashMap<>(responses); } callback.onCancel(responsesCopy); } } CoordinationBroadcastAdaptor(int expectedResponses, CoordinationBroadcastCallback callback); @Override void onResponse(Object response, CoordinationMember from); @Override void onCancel(); }### Answer:
@Test public void testOnCancel() throws Exception { CoordinationBroadcastCallback callback = mock(CoordinationBroadcastCallback.class); CoordinationBroadcastAdaptor adaptor = new CoordinationBroadcastAdaptor(3, callback); ArgumentCaptor<Map<CoordinationMember, Object>> captor = newResultCaptor(); adaptor.onCancel(); verify(callback).onCancel(captor.capture()); assertEquals(0, captor.getValue().size()); adaptor.onCancel(); adaptor.onCancel(); adaptor.onResponse("test", mock(CoordinationMember.class)); adaptor.onResponse("test", mock(CoordinationMember.class)); adaptor.onResponse("test", mock(CoordinationMember.class)); verifyNoMoreInteractions(callback); } |
### Question:
CloudSeedNodeProvider implements SeedNodeProvider, ConfigReportSupport { @Override public String toString() { return ToString.format(this); } CloudSeedNodeProvider(CloudSeedNodeProviderConfig cfg); @Override void report(ConfigReporter report); String provider(); String endpoint(); Properties properties(); @Override void startDiscovery(String cluster, InetSocketAddress node); @Override void stopDiscovery(String cluster, InetSocketAddress node); @Override List<InetSocketAddress> findSeedNodes(String cluster); @Override void suspendDiscovery(); @Override long cleanupInterval(); @Override void registerRemote(String cluster, InetSocketAddress node); @Override void unregisterRemote(String cluster, InetSocketAddress node); @Override String toString(); }### Answer:
@Test public void testToString() throws Exception { CloudSeedNodeProvider provider = provider(); assertEquals(ToString.format(provider), provider.toString()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.