target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@SuppressWarnings("unchecked") @Test public void testEcho() { Invocation invocation = EasyMock.createMock(Invocation.class); EasyMock.expect(invocation.getMethodName()).andReturn("$echo").anyTimes(); EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[]{Enum.class}).anyTimes(); EasyMock.expect(invocation.getArguments()).andReturn(new Object[]{"hello"}).anyTimes(); EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes(); EasyMock.replay(invocation); Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class); EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); RpcResult result = new RpcResult(); result.setValue("High"); EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); URL url = URL.valueOf("test: EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); EasyMock.replay(invoker); Result filterResult = echoFilter.invoke(invoker, invocation); assertEquals("hello", filterResult.getValue()); }
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } Result invoke(Invoker<?> invoker, Invocation inv); }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } Result invoke(Invoker<?> invoker, Invocation inv); }
@SuppressWarnings("unchecked") @Test public void testNonEcho() { Invocation invocation = EasyMock.createMock(Invocation.class); EasyMock.expect(invocation.getMethodName()).andReturn("echo").anyTimes(); EasyMock.expect(invocation.getParameterTypes()).andReturn(new Class<?>[]{Enum.class}).anyTimes(); EasyMock.expect(invocation.getArguments()).andReturn(new Object[]{"hello"}).anyTimes(); EasyMock.expect(invocation.getAttachments()).andReturn(null).anyTimes(); EasyMock.replay(invocation); Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class); EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes(); EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes(); RpcResult result = new RpcResult(); result.setValue("High"); EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes(); URL url = URL.valueOf("test: EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes(); EasyMock.replay(invoker); Result filterResult = echoFilter.invoke(invoker, invocation); assertEquals("High", filterResult.getValue()); }
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } Result invoke(Invoker<?> invoker, Invocation inv); }
EchoFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) return new RpcResult(inv.getArguments()[0]); return invoker.invoke(inv); } Result invoke(Invoker<?> invoker, Invocation inv); }
@Test public void testRmiProtocol() throws Exception { { DemoService service = new DemoServiceImpl(); Exporter<?> rpcExporter = protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("rmi: service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("rmi: assertEquals(service.getSize(null), -1); assertEquals(service.getSize(new String[]{"", "", ""}), 3); Object result = service.invoke("rmi: assertEquals("rmi: rpcExporter.unexport(); } { RemoteService remoteService = new RemoteServiceImpl(); Exporter<?> rpcExporter = protocol.export(proxy.getInvoker(remoteService, RemoteService.class, URL.valueOf("rmi: remoteService = proxy.getProxy(protocol.refer(RemoteService.class, URL.valueOf("rmi: remoteService.getThreadName(); for (int i = 0; i < 100; i++) { String say = remoteService.sayHello("abcd"); assertEquals("hello abcd@" + RemoteServiceImpl.class.getName(), say); } rpcExporter.unexport(); } }
public RmiProtocol() { super(RemoteAccessException.class, RemoteException.class); }
RmiProtocol extends AbstractProxyProtocol { public RmiProtocol() { super(RemoteAccessException.class, RemoteException.class); } }
RmiProtocol extends AbstractProxyProtocol { public RmiProtocol() { super(RemoteAccessException.class, RemoteException.class); } RmiProtocol(); }
RmiProtocol extends AbstractProxyProtocol { public RmiProtocol() { super(RemoteAccessException.class, RemoteException.class); } RmiProtocol(); int getDefaultPort(); }
RmiProtocol extends AbstractProxyProtocol { public RmiProtocol() { super(RemoteAccessException.class, RemoteException.class); } RmiProtocol(); int getDefaultPort(); static final int DEFAULT_PORT; }
@Test void parseSubmitTxResponse() { String expected = "f128c720e04b8243"; String json = "{'tx_hash':'" + expected + "'}"; HashCode actual = ExplorerApiHelper.parseSubmitTxResponse(json); assertThat(actual, equalTo(HashCode.fromString(expected))); }
static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); }
ExplorerApiHelper { static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); } }
ExplorerApiHelper { static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); } private ExplorerApiHelper(); }
ExplorerApiHelper { static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); } private ExplorerApiHelper(); }
ExplorerApiHelper { static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); } private ExplorerApiHelper(); }
@Test void testWriteBytesToOversizedArray() { byte[] dest = new byte[5]; HASH_ABCD.writeBytesTo(dest, 0, 4); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0x00}, dest); }
@CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
@Test void testWriteBytesToOversizedArrayLongMaxLength() { byte[] dest = new byte[5]; HASH_ABCD.writeBytesTo(dest, 0, 5); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0x00}, dest); }
@CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
@Test void testWriteBytesToOversizedArrayShortMaxLength() { byte[] dest = new byte[5]; HASH_ABCD.writeBytesTo(dest, 0, 3); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0x00, (byte) 0x00}, dest); }
@CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
@Test void testWriteBytesToUndersizedArray() { byte[] dest = new byte[3]; assertThrows(IndexOutOfBoundsException.class, () -> HASH_ABCD.writeBytesTo(dest, 0, 4)); }
@CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
@Test void testWriteBytesToUndersizedArrayLongMaxLength() { byte[] dest = new byte[3]; assertThrows(IndexOutOfBoundsException.class, () -> HASH_ABCD.writeBytesTo(dest, 0, 5)); }
@CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
@Test void testWriteBytesToUndersizedArrayShortMaxLength() { byte[] dest = new byte[3]; HASH_ABCD.writeBytesTo(dest, 0, 2); assertArrayEquals(new byte[]{(byte) 0xaa, (byte) 0xbb, (byte) 0x00}, dest); }
@CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
HashCode { @CanIgnoreReturnValue public int writeBytesTo(byte[] dest, int offset, int maxLength) { maxLength = Ints.min(maxLength, bits() / 8); Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); writeBytesToImpl(dest, offset, maxLength); return maxLength; } HashCode(); abstract int bits(); abstract int asInt(); abstract long asLong(); abstract long padToLong(); abstract byte[] asBytes(); @CanIgnoreReturnValue int writeBytesTo(byte[] dest, int offset, int maxLength); static HashCode fromInt(int hash); static HashCode fromLong(long hash); static HashCode fromBytes(byte[] bytes); static HashCode fromString(String string); @Override final boolean equals(@Nullable Object object); @Override final int hashCode(); @Override final String toString(); }
@Test void testForBytes() { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.byteArrayFunnel().funnel(new byte[]{4, 3, 2, 1}, primitiveSink); verify(primitiveSink).putBytes(new byte[]{4, 3, 2, 1}); }
public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForBytes_null() { assertNullsThrowException(Funnels.byteArrayFunnel()); }
public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForStrings() { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.unencodedCharsFunnel().funnel("test", primitiveSink); verify(primitiveSink).putUnencodedChars("test"); }
public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForStrings_null() { assertNullsThrowException(Funnels.unencodedCharsFunnel()); }
public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void getCounter(VertxTestContext context) { String name = "counter"; long value = 10L; Counter counter = new Counter(name, value); when(qaService.getValue(name)).thenReturn(Optional.of(counter)); String getCounterUri = getCounterUri(name); get(getCounterUri) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); Counter actualCounter = JSON_SERIALIZER.fromJson(body, Counter.class); assertThat(actualCounter).isEqualTo(counter); context.completeNow(); }))); }
private void getCounter(RoutingContext rc) { String counterName = getRequiredParameter(rc.request(), COUNTER_NAME_PARAM, identity()); Optional<Counter> counter = service.getValue(counterName); respondWithJson(rc, counter); }
ApiController { private void getCounter(RoutingContext rc) { String counterName = getRequiredParameter(rc.request(), COUNTER_NAME_PARAM, identity()); Optional<Counter> counter = service.getValue(counterName); respondWithJson(rc, counter); } }
ApiController { private void getCounter(RoutingContext rc) { String counterName = getRequiredParameter(rc.request(), COUNTER_NAME_PARAM, identity()); Optional<Counter> counter = service.getValue(counterName); respondWithJson(rc, counter); } ApiController(QaService service); }
ApiController { private void getCounter(RoutingContext rc) { String counterName = getRequiredParameter(rc.request(), COUNTER_NAME_PARAM, identity()); Optional<Counter> counter = service.getValue(counterName); respondWithJson(rc, counter); } ApiController(QaService service); }
ApiController { private void getCounter(RoutingContext rc) { String counterName = getRequiredParameter(rc.request(), COUNTER_NAME_PARAM, identity()); Optional<Counter> counter = service.getValue(counterName); respondWithJson(rc, counter); } ApiController(QaService service); }
@Test void testForStringsCharset() { for (Charset charset : Charset.availableCharsets().values()) { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.stringFunnel(charset).funnel("test", primitiveSink); verify(primitiveSink).putString("test", charset); } }
public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForStringsCharset_null() { for (Charset charset : Charset.availableCharsets().values()) { assertNullsThrowException(Funnels.stringFunnel(charset)); } }
public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForInts() { Integer value = 1234; PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.integerFunnel().funnel(value, primitiveSink); verify(primitiveSink).putInt(1234); }
public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForInts_null() { assertNullsThrowException(Funnels.integerFunnel()); }
public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForLongs() { Long value = 1234L; PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.longFunnel().funnel(value, primitiveSink); verify(primitiveSink).putLong(1234); }
public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testForLongs_null() { assertNullsThrowException(Funnels.longFunnel()); }
public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testSequential() { @SuppressWarnings("unchecked") Funnel<Object> elementFunnel = mock(Funnel.class); PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnel<Iterable<?>> sequential = Funnels.sequentialFunnel(elementFunnel); sequential.funnel(Arrays.asList("foo", "bar", "baz", "quux"), primitiveSink); InOrder inOrder = inOrder(elementFunnel); inOrder.verify(elementFunnel).funnel("foo", primitiveSink); inOrder.verify(elementFunnel).funnel("bar", primitiveSink); inOrder.verify(elementFunnel).funnel("baz", primitiveSink); inOrder.verify(elementFunnel).funnel("quux", primitiveSink); }
public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<>(elementFunnel); }
Funnels { public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<>(elementFunnel); } }
Funnels { public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<>(elementFunnel); } private Funnels(); }
Funnels { public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<>(elementFunnel); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<>(elementFunnel); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void testAsOutputStream() throws Exception { PrimitiveSink sink = mock(PrimitiveSink.class); OutputStream out = Funnels.asOutputStream(sink); byte[] bytes = {1, 2, 3, 4}; out.write(255); out.write(bytes); out.write(bytes, 1, 2); verify(sink).putByte((byte) 255); verify(sink).putBytes(bytes); verify(sink).putBytes(bytes, 1, 2); }
public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); }
Funnels { public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } }
Funnels { public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } private Funnels(); }
Funnels { public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
Funnels { public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }
@Test void toStringIncludesContextInformation() { String r = context.toString(); assertThat(r).contains("hash"); assertThat(r).contains("numRegisteredActions=0"); assertThat(r).contains("closed=false"); }
@Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); boolean isClosed(); void add(CleanAction<?> cleanAction); @Override void close(); String getDescription(); int getNumRegisteredActions(); @Override String toString(); }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); boolean isClosed(); void add(CleanAction<?> cleanAction); @Override void close(); String getDescription(); int getNumRegisteredActions(); @Override String toString(); }
@Test void toStringWithDescriptionIncludesContextInformation() { String description = "Transaction#execute"; context = new Cleaner(description); String r = context.toString(); assertThat(r).contains("description=" + description); }
@Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); boolean isClosed(); void add(CleanAction<?> cleanAction); @Override void close(); String getDescription(); int getNumRegisteredActions(); @Override String toString(); }
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); boolean isClosed(); void add(CleanAction<?> cleanAction); @Override void close(); String getDescription(); int getNumRegisteredActions(); @Override String toString(); }
@Test void getConsensusConfiguration(VertxTestContext context) { Config configuration = createConfiguration(); when(qaService.getConsensusConfiguration()).thenReturn(configuration); get(GET_CONSENSUS_CONFIGURATION_PATH) .send(context.succeeding(response -> context.verify(() -> { assertAll( () -> assertThat(response.statusCode()).isEqualTo(HTTP_OK), () -> { Buffer body = response.bodyAsBuffer(); Config consensusConfig = Config.parseFrom(body.getBytes()); assertThat(consensusConfig).isEqualTo(configuration); }); context.completeNow(); }))); }
private void getConsensusConfiguration(RoutingContext rc) { Config configuration = service.getConsensusConfiguration(); rc.response() .putHeader(CONTENT_TYPE, OCTET_STREAM.toString()) .end(Buffer.buffer(configuration.toByteArray())); }
ApiController { private void getConsensusConfiguration(RoutingContext rc) { Config configuration = service.getConsensusConfiguration(); rc.response() .putHeader(CONTENT_TYPE, OCTET_STREAM.toString()) .end(Buffer.buffer(configuration.toByteArray())); } }
ApiController { private void getConsensusConfiguration(RoutingContext rc) { Config configuration = service.getConsensusConfiguration(); rc.response() .putHeader(CONTENT_TYPE, OCTET_STREAM.toString()) .end(Buffer.buffer(configuration.toByteArray())); } ApiController(QaService service); }
ApiController { private void getConsensusConfiguration(RoutingContext rc) { Config configuration = service.getConsensusConfiguration(); rc.response() .putHeader(CONTENT_TYPE, OCTET_STREAM.toString()) .end(Buffer.buffer(configuration.toByteArray())); } ApiController(QaService service); }
ApiController { private void getConsensusConfiguration(RoutingContext rc) { Config configuration = service.getConsensusConfiguration(); rc.response() .putHeader(CONTENT_TYPE, OCTET_STREAM.toString()) .end(Buffer.buffer(configuration.toByteArray())); } ApiController(QaService service); }
@Test void close() { nativeHandle = new NativeHandle(HANDLE); nativeHandle.close(); assertFalse(nativeHandle.isValid()); assertThat(nativeHandle.toString()).contains(HANDLE_STRING_REPRESENTATION); }
@Override public void close() { if (isValid()) { invalidate(); } }
NativeHandle implements AutoCloseable { @Override public void close() { if (isValid()) { invalidate(); } } }
NativeHandle implements AutoCloseable { @Override public void close() { if (isValid()) { invalidate(); } } NativeHandle(long nativeHandle); }
NativeHandle implements AutoCloseable { @Override public void close() { if (isValid()) { invalidate(); } } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); }
NativeHandle implements AutoCloseable { @Override public void close() { if (isValid()) { invalidate(); } } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); static final long INVALID_NATIVE_HANDLE; }
@Test void toStringHexRepresentation() { nativeHandle = new NativeHandle(HANDLE); assertThat(nativeHandle.toString()).contains(HANDLE_STRING_REPRESENTATION); }
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("pointer", Long.toHexString(nativeHandle).toUpperCase()) .toString(); }
NativeHandle implements AutoCloseable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("pointer", Long.toHexString(nativeHandle).toUpperCase()) .toString(); } }
NativeHandle implements AutoCloseable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("pointer", Long.toHexString(nativeHandle).toUpperCase()) .toString(); } NativeHandle(long nativeHandle); }
NativeHandle implements AutoCloseable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("pointer", Long.toHexString(nativeHandle).toUpperCase()) .toString(); } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); }
NativeHandle implements AutoCloseable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("pointer", Long.toHexString(nativeHandle).toUpperCase()) .toString(); } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); static final long INVALID_NATIVE_HANDLE; }
@Test void closeShallCallDispose() { proxy = new NativeProxyFake(1L, true); proxy.close(); assertThat(proxy.timesDisposed, equalTo(1)); }
@Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void closeShallCallDisposeOnce() { proxy = new NativeProxyFake(1L, true); proxy.close(); proxy.close(); assertThat(proxy.timesDisposed, equalTo(1)); }
@Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void closeShallNotDisposeNotOwningHandle() { proxy = new NativeProxyFake(1L, false); proxy.close(); assertThat(proxy.timesDisposed, equalTo(0)); }
@Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void closeShallThrowIfReferencedObjectInvalid() { NativeProxyFake reference = makeProxy(2L); proxy = new NativeProxyFake(1L, true, reference); reference.close(); assertThrows(IllegalStateException.class, () -> proxy.close()); }
@Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void shallNotBeValidOnceClosed() { proxy = new NativeProxyFake(1L, true); proxy.close(); assertFalse(proxy.isValidHandle()); }
@Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void notOwningShallNotBeValidOnceClosed() { proxy = new NativeProxyFake(1L, false); proxy.close(); assertFalse(proxy.isValidHandle()); }
@Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void getNativeHandle() { long expectedNativeHandle = 0x1FL; proxy = new NativeProxyFake(expectedNativeHandle, true); assertThat(proxy.getNativeHandle(), equalTo(expectedNativeHandle)); }
@Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void getNativeHandle_DirectMultiReferencedAll() { long nativeHandle = 1L; List<AbstractCloseableNativeProxy> referenced = asList(makeProxy(20L), makeProxy(21L), makeProxy(22L) ); proxy = new NativeProxyFake(nativeHandle, true, referenced); assertThat(proxy.getNativeHandle(), equalTo(nativeHandle)); referenced.forEach(CloseableNativeProxy::close); assertThat(proxy, hasInvalidReferences(referenced)); assertThrows(IllegalStateException.class, () -> proxy.getNativeHandle()); }
@Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose, Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }
@Test void getTime(VertxTestContext context) { ZonedDateTime time = ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); when(qaService.getTime()).thenReturn(Optional.of(time)); get(TIME_PATH) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); TimeDto actualTime = JSON_SERIALIZER .fromJson(body, TimeDto.class); assertThat(actualTime.getTime()).isEqualTo(time); context.completeNow(); }))); }
private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); }
ApiController { private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); } }
ApiController { private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); } ApiController(QaService service); }
ApiController { private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); } ApiController(QaService service); }
ApiController { private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); } ApiController(QaService service); }
@Test void newRegistered() { Cleaner cleaner = mock(Cleaner.class); NativeHandle handle = new NativeHandle(1L); LongConsumer destructor = (nh) -> { }; ProxyDestructor d = ProxyDestructor.newRegistered(cleaner, handle, CloseableNativeProxy.class, destructor); assertNotNull(d); verify(cleaner).add(d); }
@CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); cleaner.add(d); return d; }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); cleaner.add(d); return d; } }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); cleaner.add(d); return d; } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); cleaner.add(d); return d; } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); cleaner.add(d); return d; } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
@Test void clean() { long rawNativeHandle = 1L; NativeHandle handle = new NativeHandle(rawNativeHandle); LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = newDestructor(handle, destructor); d.clean(); assertFalse(handle.isValid()); verify(destructor).accept(rawNativeHandle); }
@Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
@Test void cleanIdempotent() { long rawNativeHandle = 1L; NativeHandle handle = spy(new NativeHandle(rawNativeHandle)); LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = newDestructor(handle, destructor); int attemptsToClean = 3; for (int i = 0; i < attemptsToClean; i++) { d.clean(); } assertFalse(handle.isValid()); verify(handle).close(); verify(destructor).accept(rawNativeHandle); }
@Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
@Test void getResourceType() { NativeHandle handle = new NativeHandle(1L); Class<?> proxyClass = CloseableNativeProxy.class; LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = new ProxyDestructor(handle, proxyClass, destructor); assertThat(d.resourceType()).hasValue(proxyClass); }
@Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }
@Test void itemsFrequencyNoItems() { Collection<?> c = Collections.emptyList(); String s = FrequencyStatsFormatter.itemsFrequency(c, Object::getClass); assertThat(s).isEqualTo("{}"); }
static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void itemsFrequencyOneItem() { Collection<Boolean> c = ImmutableList.of(true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{true=1}"); }
static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void itemsFrequencySeveralItemsSameCategory() { Collection<Boolean> c = ImmutableList.of(true, true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{true=2}"); }
static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void itemsFrequencyMoreTrue() { Collection<Boolean> c = ImmutableList.of(true, true, false); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{true=2, false=1}"); }
static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void itemsFrequencyMoreFalse() { Collection<Boolean> c = ImmutableList.of(false, false, true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).isEqualTo("{false=2, true=1}"); }
static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void itemsFrequencySeveralElementsSameFrequency() { Collection<Boolean> c = ImmutableList.of(false, false, true, true); String s = FrequencyStatsFormatter.itemsFrequency(c, Boolean::booleanValue); assertThat(s).matches("\\{((true=2, false=2)|(false=2, true=2))\\}"); }
static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void getValidatorsTimes(VertxTestContext context) { Map<PublicKey, ZonedDateTime> validatorsTimes = ImmutableMap.of( PublicKey.fromHexString("11"), ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC), PublicKey.fromHexString("22"), ZonedDateTime.of(2018, 1, 1, 0, 0, 1, 0, ZoneOffset.UTC)); when(qaService.getValidatorsTimes()).thenReturn(validatorsTimes); get(VALIDATORS_TIMES_PATH) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); Map<PublicKey, ZonedDateTime> actualValidatorsTimes = JSON_SERIALIZER .fromJson(body, new TypeToken<Map<PublicKey, ZonedDateTime>>() { }.getType()); assertThat(actualValidatorsTimes).isEqualTo(validatorsTimes); context.completeNow(); }))); }
private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); }
ApiController { private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); } }
ApiController { private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); } ApiController(QaService service); }
ApiController { private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); } ApiController(QaService service); }
ApiController { private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); } ApiController(QaService service); }
@Test void itemsFrequency() { Collection<String> c = ImmutableList.of("aa", "bb", "cc", "a", "c", ""); String s = FrequencyStatsFormatter.itemsFrequency(c, String::length); assertThat(s).isEqualTo("{2=3, 1=2, 0=1}"); }
static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
FrequencyStatsFormatter { static <ElementT, KeyT> String itemsFrequency(Collection<? extends ElementT> items, Function<? super ElementT, KeyT> keyExtractor) { Map<KeyT, Long> numItemsByType = items.stream() .collect(groupingBy(keyExtractor, counting())); String itemsFrequency = numItemsByType.entrySet().stream() .sorted(Comparator.<Map.Entry<KeyT, Long>> comparingLong(Map.Entry::getValue).reversed()) .map(Object::toString) .collect(Collectors.joining(", ")); return "{" + itemsFrequency + "}"; } private FrequencyStatsFormatter(); }
@Test void getName() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getName()).isEqualTo(NAME); }
protected final String getName() { return instanceSpec.getName(); }
AbstractService implements Service { protected final String getName() { return instanceSpec.getName(); } }
AbstractService implements Service { protected final String getName() { return instanceSpec.getName(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
AbstractService implements Service { protected final String getName() { return instanceSpec.getName(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
AbstractService implements Service { protected final String getName() { return instanceSpec.getName(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
@Test void getId() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getId()).isEqualTo(ID); }
protected final int getId() { return instanceSpec.getId(); }
AbstractService implements Service { protected final int getId() { return instanceSpec.getId(); } }
AbstractService implements Service { protected final int getId() { return instanceSpec.getId(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
AbstractService implements Service { protected final int getId() { return instanceSpec.getId(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
AbstractService implements Service { protected final int getId() { return instanceSpec.getId(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }
@Test void createService() { ServiceArtifactId artifactId = ServiceArtifactId.newJavaId("com.acme/foo-service", "1.0.0"); LoadedServiceDefinition serviceDefinition = LoadedServiceDefinition .newInstance(artifactId, TestServiceModule::new); ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(TEST_NAME, TEST_ID, artifactId); Node node = mock(Node.class); ServiceWrapper service = factory.createService(serviceDefinition, instanceSpec, node); assertThat(service.getName()).isEqualTo(TEST_NAME); assertThat(service.getService()).isInstanceOf(TestService.class); }
@Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); @Override ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node); }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); @Override ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node); }
@Test void createServiceFailsIfNoServiceBindingsInModule() { ServiceArtifactId artifactId = ServiceArtifactId .newJavaId("com.acme/incomplete-service", "1.0.0"); LoadedServiceDefinition serviceDefinition = LoadedServiceDefinition .newInstance(artifactId, IncompleteServiceModule::new); ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(TEST_NAME, TEST_ID, artifactId); Node node = mock(Node.class); Exception e = assertThrows(ConfigurationException.class, () -> factory.createService(serviceDefinition, instanceSpec, node)); assertThat(e).hasMessageContaining(Service.class.getSimpleName()); }
@Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); @Override ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node); }
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); @Override ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node); }
@Test void checkNoCopiesOfAppClasses() throws ClassNotFoundException { Class<?> referenceClass = Vertx.class; Map<String, Class<?>> referenceClasses = ImmutableMap.of( "vertx", referenceClass ); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader classLoader = mock(ClassLoader.class); when(classLoader.loadClass(referenceClass.getName())) .thenReturn((Class) referenceClass); checker.checkNoCopiesOfAppClasses(classLoader); }
void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
@Test void checkNoCopiesOfAppClassesDetectsCopies() throws ClassNotFoundException { String dependency = "vertx"; Class<?> referenceClass = Vertx.class; Map<String, Class<?>> referenceClasses = ImmutableMap.of( dependency, referenceClass ); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader classLoader = mock(ClassLoader.class); Class actual = Set.class; when(classLoader.loadClass(referenceClass.getName())) .thenReturn(actual); Exception e = assertThrows(IllegalArgumentException.class, () -> checker.checkNoCopiesOfAppClasses(classLoader)); assertThat(e).hasMessageContaining(dependency); }
void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
@Test void checkNoCopiesOfAppClassesDetectsAllCopies() throws ClassNotFoundException { Set<String> copiedLibraries = ImmutableSet.of("vertx", "gson"); Set<String> nonCopiedLibraries = ImmutableSet.of("guice"); Map<String, Class<?>> referenceClasses = ImmutableMap.of( "vertx", Vertx.class, "guice", Guice.class, "gson", Gson.class ); assertThat(Sets.union(copiedLibraries, nonCopiedLibraries)) .isEqualTo(referenceClasses.keySet()); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader classLoader = mock(ClassLoader.class); for (String library : copiedLibraries) { Class actual = Set.class; Class<?> referenceClass = referenceClasses.get(library); when(classLoader.loadClass(referenceClass.getName())) .thenReturn(actual); } for (String library : nonCopiedLibraries) { Class actual = referenceClasses.get(library); when(classLoader.loadClass(actual.getName())) .thenReturn(actual); } Exception e = assertThrows(IllegalArgumentException.class, () -> checker.checkNoCopiesOfAppClasses(classLoader)); for (String libraryName : copiedLibraries) { assertThat(e).hasMessageContaining(libraryName); } for (String libraryName : nonCopiedLibraries) { assertThat(e).hasMessageNotContaining(libraryName); } }
void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
@Test void checkNoCopiesOfAppClassesClassloaderFailsToDelegate() throws ClassNotFoundException { Class<?> referenceClass = Vertx.class; Map<String, Class<?>> referenceClasses = ImmutableMap.of( "vertx", referenceClass ); ClassLoadingScopeChecker checker = new ClassLoadingScopeChecker(referenceClasses); ClassLoader pluginClassLoader = mock(ClassLoader.class); when(pluginClassLoader.loadClass(referenceClass.getName())) .thenThrow(ClassNotFoundException.class); Exception e = assertThrows(IllegalStateException.class, () -> checker.checkNoCopiesOfAppClasses(pluginClassLoader)); assertThat(e).hasMessageFindingMatch("Classloader .+ failed to load the reference " + "application class .+ from vertx library"); }
void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
ClassLoadingScopeChecker { void checkNoCopiesOfAppClasses(ClassLoader pluginClassloader) { List<String> libraryCopies = dependencyReferenceClasses.entrySet().stream() .filter(e -> loadsCopyOf(pluginClassloader, e)) .map(Entry::getKey) .collect(toList()); if (libraryCopies.isEmpty()) { return; } String message = String.format("Classloader (%s) loads copies of the following " + "libraries: %s.%n" + "Please ensure in your service build definition that each of these libraries:%n" + " 1. Has 'provided' scope%n" + " 2. Does not specify its version (i.e., inherits it " + "from exonum-java-binding-bom)%n" + "See also: " + "https: pluginClassloader, libraryCopies); throw new IllegalArgumentException(message); } @Inject ClassLoadingScopeChecker( @Named(DEPENDENCY_REFERENCE_CLASSES_KEY) Map<String, Class<?>> dependencyReferenceClasses); }
@Test void start() { when(server.start(PORT)).thenReturn(CompletableFuture.completedFuture(PORT)); transport.start(); verify(server).start(PORT); }
void start() { try { server.start(port).get(); } catch (ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error("Start services API server was interrupted", e); Thread.currentThread().interrupt(); } }
RuntimeTransport implements AutoCloseable { void start() { try { server.start(port).get(); } catch (ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error("Start services API server was interrupted", e); Thread.currentThread().interrupt(); } } }
RuntimeTransport implements AutoCloseable { void start() { try { server.start(port).get(); } catch (ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error("Start services API server was interrupted", e); Thread.currentThread().interrupt(); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); }
RuntimeTransport implements AutoCloseable { void start() { try { server.start(port).get(); } catch (ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error("Start services API server was interrupted", e); Thread.currentThread().interrupt(); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
RuntimeTransport implements AutoCloseable { void start() { try { server.start(port).get(); } catch (ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error("Start services API server was interrupted", e); Thread.currentThread().interrupt(); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void initialize() { String serviceName = "qa"; String timeServiceName = "time"; try (TestKit testKit = TestKit.builder() .withArtifactsDirectory(QaArtifactInfo.ARTIFACT_DIR) .withDeployedArtifact(QaArtifactInfo.ARTIFACT_ID, QaArtifactInfo.ARTIFACT_FILENAME) .withService(QaArtifactInfo.ARTIFACT_ID, serviceName, 1, QaConfiguration.newBuilder() .setTimeOracleName(timeServiceName) .build()) .withTimeService(timeServiceName, 2, TimeProvider.systemTime()) .build()) { BlockchainData snapshot = testKit.getBlockchainData(serviceName); QaSchema schema = new QaSchema(snapshot); Optional<String> timeService = schema.timeOracleName().toOptional(); assertThat(timeService).hasValue(timeServiceName); MapIndex<String, Long> counters = schema.counters(); assertThat(counters.get(DEFAULT_COUNTER_NAME)).isEqualTo(0L); assertThat(counters.get(AFTER_COMMIT_COUNTER_NAME)).isEqualTo(0L); assertThat(counters.get(BEFORE_TXS_COUNTER_NAME)).isEqualTo(0L); assertThat(counters.get(AFTER_TXS_COUNTER_NAME)).isEqualTo(1L); } }
@Override public void initialize(ExecutionContext context, Configuration configuration) { updateTimeOracle(context, configuration); Stream.of( DEFAULT_COUNTER_NAME, BEFORE_TXS_COUNTER_NAME, AFTER_TXS_COUNTER_NAME, AFTER_COMMIT_COUNTER_NAME) .forEach(name -> createCounter(name, context)); }
QaServiceImpl extends AbstractService implements QaService { @Override public void initialize(ExecutionContext context, Configuration configuration) { updateTimeOracle(context, configuration); Stream.of( DEFAULT_COUNTER_NAME, BEFORE_TXS_COUNTER_NAME, AFTER_TXS_COUNTER_NAME, AFTER_COMMIT_COUNTER_NAME) .forEach(name -> createCounter(name, context)); } }
QaServiceImpl extends AbstractService implements QaService { @Override public void initialize(ExecutionContext context, Configuration configuration) { updateTimeOracle(context, configuration); Stream.of( DEFAULT_COUNTER_NAME, BEFORE_TXS_COUNTER_NAME, AFTER_TXS_COUNTER_NAME, AFTER_COMMIT_COUNTER_NAME) .forEach(name -> createCounter(name, context)); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); }
QaServiceImpl extends AbstractService implements QaService { @Override public void initialize(ExecutionContext context, Configuration configuration) { updateTimeOracle(context, configuration); Stream.of( DEFAULT_COUNTER_NAME, BEFORE_TXS_COUNTER_NAME, AFTER_TXS_COUNTER_NAME, AFTER_COMMIT_COUNTER_NAME) .forEach(name -> createCounter(name, context)); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
QaServiceImpl extends AbstractService implements QaService { @Override public void initialize(ExecutionContext context, Configuration configuration) { updateTimeOracle(context, configuration); Stream.of( DEFAULT_COUNTER_NAME, BEFORE_TXS_COUNTER_NAME, AFTER_TXS_COUNTER_NAME, AFTER_COMMIT_COUNTER_NAME) .forEach(name -> createCounter(name, context)); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
@Test void connectServiceApi() { Router serviceRouter = mock(Router.class); when(serviceRouter.getRoutes()).thenReturn(emptyList()); when(server.createRouter()).thenReturn(serviceRouter); String serviceApiPath = "test-service"; ServiceWrapper service = mock(ServiceWrapper.class); when(service.getPublicApiRelativePath()).thenReturn(serviceApiPath); transport.connectServiceApi(service); verify(service).createPublicApiHandlers(serviceRouter); verify(server).mountSubRouter(API_ROOT_PATH + "/" + serviceApiPath, serviceRouter); }
void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, serviceApiPath, router); }
RuntimeTransport implements AutoCloseable { void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, serviceApiPath, router); } }
RuntimeTransport implements AutoCloseable { void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, serviceApiPath, router); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); }
RuntimeTransport implements AutoCloseable { void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, serviceApiPath, router); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
RuntimeTransport implements AutoCloseable { void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, serviceApiPath, router); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void disconnectServiceApi() { String serviceApiPath = "test-service"; ServiceWrapper service = mock(ServiceWrapper.class); when(service.getPublicApiRelativePath()).thenReturn(serviceApiPath); transport.disconnectServiceApi(service); verify(server).removeSubRouter(API_ROOT_PATH + "/" + serviceApiPath); }
void disconnectServiceApi(ServiceWrapper service) { String serviceApiPath = createServiceApiPath(service); server.removeSubRouter(serviceApiPath); logger.info("Removed the service API endpoints at {}", serviceApiPath); }
RuntimeTransport implements AutoCloseable { void disconnectServiceApi(ServiceWrapper service) { String serviceApiPath = createServiceApiPath(service); server.removeSubRouter(serviceApiPath); logger.info("Removed the service API endpoints at {}", serviceApiPath); } }
RuntimeTransport implements AutoCloseable { void disconnectServiceApi(ServiceWrapper service) { String serviceApiPath = createServiceApiPath(service); server.removeSubRouter(serviceApiPath); logger.info("Removed the service API endpoints at {}", serviceApiPath); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); }
RuntimeTransport implements AutoCloseable { void disconnectServiceApi(ServiceWrapper service) { String serviceApiPath = createServiceApiPath(service); server.removeSubRouter(serviceApiPath); logger.info("Removed the service API endpoints at {}", serviceApiPath); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
RuntimeTransport implements AutoCloseable { void disconnectServiceApi(ServiceWrapper service) { String serviceApiPath = createServiceApiPath(service); server.removeSubRouter(serviceApiPath); logger.info("Removed the service API endpoints at {}", serviceApiPath); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void close() throws InterruptedException { when(server.stop()).thenReturn(CompletableFuture.completedFuture(null)); transport.close(); verify(server).stop(); }
@Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void closeReportsOtherFailures() { CompletableFuture<Void> stopResult = new CompletableFuture<>(); Throwable stopCause = new RuntimeException("Stop failure cause"); stopResult.completeExceptionally(stopCause); when(server.stop()).thenReturn(stopResult); IllegalStateException e = assertThrows(IllegalStateException.class, () -> transport.close()); assertThat(e).hasCause(stopCause); }
@Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }
@Test void get() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(Good.class); ServiceModule serviceModule = supplier.get(); assertThat(serviceModule, instanceOf(Good.class)); }
@Override public ServiceModule get() { return newServiceModule(); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }
@Test void getProducesFreshInstances() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(Good.class); ServiceModule serviceModule1 = supplier.get(); ServiceModule serviceModule2 = supplier.get(); assertThat(serviceModule1, instanceOf(Good.class)); assertThat(serviceModule2, instanceOf(Good.class)); assertThat(serviceModule1, not(sameInstance(serviceModule2))); }
@Override public ServiceModule get() { return newServiceModule(); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }
@Test void getPropagatesExceptions() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(BadThrowsInCtor.class); IllegalStateException e = assertThrows(IllegalStateException.class, () -> supplier.get()); Throwable cause = e.getCause(); assertThat(cause, instanceOf(RuntimeException.class)); assertThat(cause.getMessage(), equalTo("BadThrowsInCtor indeed")); }
@Override public ServiceModule get() { return newServiceModule(); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }
@Test void getAsMessage() { Id config = anyId(); byte[] serializedConfig = config.toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(serializedConfig); Id unpackedConfig = serviceConfiguration.getAsMessage(Id.class); assertThat(unpackedConfig).isEqualTo(config); }
@Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test void getAsMessageNotMessage() { byte[] serializedConfig = bytes(1, 2, 3, 4); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(serializedConfig); Exception e = assertThrows(IllegalArgumentException.class, () -> serviceConfiguration.getAsMessage(Id.class)); assertThat(e).hasCauseInstanceOf(InvalidProtocolBufferException.class); }
@Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test void getAsJson() { byte[] configuration = Service.ServiceConfiguration.newBuilder() .setFormat(Format.JSON) .setValue("{'foo' : 'bar'}") .build() .toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(configuration); Foo actualConfig = serviceConfiguration.getAsJson(Foo.class); assertThat(actualConfig.foo).isEqualTo("bar"); }
@Override public <T> T getAsJson(Class<T> configType) { String configuration = getServiceConfigurationInFormat(Format.JSON); return JsonSerializer.json().fromJson(configuration, configType); }
ServiceConfiguration implements Configuration { @Override public <T> T getAsJson(Class<T> configType) { String configuration = getServiceConfigurationInFormat(Format.JSON); return JsonSerializer.json().fromJson(configuration, configType); } }
ServiceConfiguration implements Configuration { @Override public <T> T getAsJson(Class<T> configType) { String configuration = getServiceConfigurationInFormat(Format.JSON); return JsonSerializer.json().fromJson(configuration, configType); } ServiceConfiguration(byte[] configuration); }
ServiceConfiguration implements Configuration { @Override public <T> T getAsJson(Class<T> configType) { String configuration = getServiceConfigurationInFormat(Format.JSON); return JsonSerializer.json().fromJson(configuration, configType); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
ServiceConfiguration implements Configuration { @Override public <T> T getAsJson(Class<T> configType) { String configuration = getServiceConfigurationInFormat(Format.JSON); return JsonSerializer.json().fromJson(configuration, configType); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test void resume() throws CloseFailuresException { String counterName = "resume"; ServiceInstanceSpec spec = ServiceInstanceSpec .newInstance(QA_SERVICE_NAME, QA_SERVICE_ID, ARTIFACT_ID); byte[] arguments = QaResumeArguments.newBuilder() .setCounterName(counterName) .setShouldThrowException(false) .build() .toByteArray(); try (TemporaryDb db = TemporaryDb.newInstance(); Cleaner cleaner = new Cleaner()) { Fork fork = db.createFork(cleaner); BlockchainData blockchainData = BlockchainData.fromRawAccess(fork, QA_SERVICE_NAME); ExecutionContext context = ExecutionContext.builder() .serviceName(QA_SERVICE_NAME) .serviceId(QA_SERVICE_ID) .blockchainData(blockchainData) .build(); QaServiceImpl qaService = new QaServiceImpl(spec); qaService.resume(context, arguments); QaSchema schema = new QaSchema(blockchainData); MapIndex<String, Long> counters = schema.counters(); assertThat(counters.get(counterName)).isEqualTo(0L); } }
@Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
@Test void getAsProperties() { byte[] configuration = Service.ServiceConfiguration.newBuilder() .setFormat(Format.PROPERTIES) .setValue("foo=foo\nbar=bar") .build() .toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(configuration); Properties properties = serviceConfiguration.getAsProperties(); assertThat(properties).contains(entry("foo", "foo"), entry("bar", "bar")); }
@Override public Properties getAsProperties() { String configuration = getServiceConfigurationInFormat(Format.PROPERTIES); Properties properties = new Properties(); try { properties.load(new StringReader(configuration)); } catch (IOException e) { throw new IllegalArgumentException("Error reading properties configuration", e); } return properties; }
ServiceConfiguration implements Configuration { @Override public Properties getAsProperties() { String configuration = getServiceConfigurationInFormat(Format.PROPERTIES); Properties properties = new Properties(); try { properties.load(new StringReader(configuration)); } catch (IOException e) { throw new IllegalArgumentException("Error reading properties configuration", e); } return properties; } }
ServiceConfiguration implements Configuration { @Override public Properties getAsProperties() { String configuration = getServiceConfigurationInFormat(Format.PROPERTIES); Properties properties = new Properties(); try { properties.load(new StringReader(configuration)); } catch (IOException e) { throw new IllegalArgumentException("Error reading properties configuration", e); } return properties; } ServiceConfiguration(byte[] configuration); }
ServiceConfiguration implements Configuration { @Override public Properties getAsProperties() { String configuration = getServiceConfigurationInFormat(Format.PROPERTIES); Properties properties = new Properties(); try { properties.load(new StringReader(configuration)); } catch (IOException e) { throw new IllegalArgumentException("Error reading properties configuration", e); } return properties; } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
ServiceConfiguration implements Configuration { @Override public Properties getAsProperties() { String configuration = getServiceConfigurationInFormat(Format.PROPERTIES); Properties properties = new Properties(); try { properties.load(new StringReader(configuration)); } catch (IOException e) { throw new IllegalArgumentException("Error reading properties configuration", e); } return properties; } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test void findTransactionMethodsValidService() throws Exception { Map<Integer, Method> transactions = TransactionExtractor.findTransactionMethods(ValidService.class); assertThat(transactions).hasSize(1); Method transactionMethod = ValidService.class.getMethod("transactionMethod", byte[].class, ExecutionContext.class); assertThat(singletonList(transactionMethod)) .containsExactlyElementsOf(transactions.values()); }
@VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
@Test void duplicateTransactionIdsServiceMethodExtraction() { Exception e = assertThrows(IllegalArgumentException.class, () -> TransactionExtractor .extractTransactionMethods(DuplicateTransactionIdsService.class)); assertThat(e.getMessage()) .contains(String.format("Service %s has more than one transaction with the same id (%s)", DuplicateTransactionIdsService.class.getName(), DuplicateTransactionIdsService.TRANSACTION_ID), "transactionMethod", "anotherTransactionMethod"); }
static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
@Test void missingTransactionMethodArgumentsServiceMethodExtraction() { Exception e = assertThrows(IllegalArgumentException.class, () -> TransactionExtractor .extractTransactionMethods(MissingTransactionMethodArgumentsService.class)); String methodName = "transactionMethod"; String errorMessage = String.format("Method %s in a service class %s annotated with" + " @Transaction should have precisely two parameters: transaction arguments of" + " 'byte[]' type or a protobuf type and transaction context of" + " 'com.exonum.binding.core.transaction.TransactionContext' type.", methodName, MissingTransactionMethodArgumentsService.class.getName()); assertThat(e.getMessage()).contains(errorMessage); }
static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
@Test void invalidTransactionMethodArgumentServiceMethodExtraction() { Exception e = assertThrows(IllegalArgumentException.class, () -> TransactionExtractor .extractTransactionMethods(InvalidTransactionMethodArgumentsService.class)); String methodName = "transactionMethod"; String errorMessage = String.format("Method %s in a service class %s annotated with" + " @Transaction should have precisely two parameters: transaction arguments of" + " 'byte[]' type or a protobuf type and transaction context of" + " 'com.exonum.binding.core.transaction.TransactionContext' type." + " But second parameter type was: " + String.class.getName(), methodName, InvalidTransactionMethodArgumentsService.class.getName()); assertThat(e.getMessage()).contains(errorMessage); }
static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
@Test void duplicateTransactionMethodArgumentServiceMethodExtraction() { Exception e = assertThrows(IllegalArgumentException.class, () -> TransactionExtractor .extractTransactionMethods(DuplicateTransactionMethodArgumentsService.class)); String methodName = "transactionMethod"; String errorMessage = String.format("Method %s in a service class %s annotated with" + " @Transaction should have precisely two parameters: transaction arguments of" + " 'byte[]' type or a protobuf type and transaction context of" + " 'com.exonum.binding.core.transaction.TransactionContext' type." + " But second parameter type was: " + byte[].class.getName(), methodName, DuplicateTransactionMethodArgumentsService.class.getName()); assertThat(e.getMessage()).contains(errorMessage); }
static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
TransactionExtractor { static Map<Integer, TransactionMethod> extractTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = findTransactionMethods(serviceClass); Lookup lookup = MethodHandles.publicLookup() .in(serviceClass); return transactionMethods.entrySet().stream() .peek(tx -> validateTransactionMethod(tx.getValue(), serviceClass)) .collect(toMap(Map.Entry::getKey, (e) -> toTransactionMethod(e.getValue(), lookup))); } private TransactionExtractor(); }
@Test void findMethodsValidServiceInterfaceImplementation() throws Exception { Map<Integer, Method> transactions = TransactionExtractor.findTransactionMethods( ValidServiceInterfaceImplementation.class); assertThat(transactions).hasSize(2); Method transactionMethod = ValidServiceInterfaceImplementation.class.getMethod( "transactionMethod", byte[].class, ExecutionContext.class); Method transactionMethod2 = ValidServiceInterfaceImplementation.class.getMethod( "transactionMethod2", byte[].class, ExecutionContext.class); List<Method> actualMethods = Arrays.asList(transactionMethod, transactionMethod2); assertThat(actualMethods).containsExactlyInAnyOrderElementsOf(transactions.values()); }
@VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
@Test void findTransactionMethodsValidServiceProtobufArguments() throws Exception { Map<Integer, Method> transactions = TransactionExtractor.findTransactionMethods(ValidServiceProtobufArgument.class); assertThat(transactions).hasSize(1); Method transactionMethod = ValidServiceProtobufArgument.class.getMethod("transactionMethod", TestProtoMessages.Point.class, ExecutionContext.class); assertThat(transactions.values()) .containsExactlyElementsOf(singletonList(transactionMethod)); }
@VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }
@Test void invokeValidServiceTransaction() { ValidService service = spy(new ValidService()); TransactionInvoker invoker = new TransactionInvoker(service); invoker.invokeTransaction(TRANSACTION_ID, ARGUMENTS, context); invoker.invokeTransaction(TRANSACTION_ID_2, ARGUMENTS, context); verify(service).transactionMethod(ARGUMENTS, context); verify(service).transactionMethod2(ARGUMENTS, context); }
void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
@Test void invokeInvalidTransactionId() { TransactionInvoker invoker = new TransactionInvoker(new ValidService()); int invalidTransactionId = Integer.MAX_VALUE; IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> invoker.invokeTransaction(invalidTransactionId, ARGUMENTS, context)); assertThat(e.getMessage()) .contains(String.format("No method with transaction id (%s)", invalidTransactionId)); }
void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
@Test void resumeShouldThrowException() { ServiceInstanceSpec spec = ServiceInstanceSpec .newInstance(QA_SERVICE_NAME, QA_SERVICE_ID, ARTIFACT_ID); byte[] arguments = QaResumeArguments.newBuilder() .setShouldThrowException(true) .build() .toByteArray(); ExecutionContext context = mock(ExecutionContext.class); QaServiceImpl qaService = new QaServiceImpl(spec); ExecutionException exception = assertThrows(ExecutionException.class, () -> qaService.resume(context, arguments)); assertThat(exception.getErrorCode()).isEqualTo(RESUME_SERVICE_ERROR.code); }
@Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
QaServiceImpl extends AbstractService implements QaService { @Override public void resume(ExecutionContext context, byte[] arguments) { QaResumeArguments resumeArguments = parseResumeArguments(arguments); checkExecution(!resumeArguments.getShouldThrowException(), RESUME_SERVICE_ERROR.code); createCounter(resumeArguments.getCounterName(), context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
@Test void invokeThrowingExecutionException() { ExecutionException e = new ExecutionException((byte) 0); TransactionInvoker invoker = new TransactionInvoker(new ThrowingAnyException(e)); ExecutionException actual = assertThrows(ExecutionException.class, () -> invoker.invokeTransaction(TRANSACTION_ID, ARGUMENTS, context)); assertThat(actual).isSameAs(e); }
void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
@Test void invokeThrowingRuntimeException() { RuntimeException e = new IllegalArgumentException("Unexpected runtime exception"); TransactionInvoker invoker = new TransactionInvoker(new ThrowingAnyException(e)); Exception actual = assertThrows(UnexpectedExecutionException.class, () -> invoker.invokeTransaction(TRANSACTION_ID, ARGUMENTS, context)); assertThat(actual).hasCause(e); }
void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
@Test void invokeThrowingException() { IOException e = new IOException("Unexpected checked exception"); TransactionInvoker invoker = new TransactionInvoker(new ThrowingAnyException(e)); Exception actual = assertThrows(UnexpectedExecutionException.class, () -> invoker.invokeTransaction(TRANSACTION_ID, ARGUMENTS, context)); assertThat(actual).hasCause(e); }
void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
@Test void invokeProtobufArgumentsService() { ProtobufArgumentsService service = spy(new ProtobufArgumentsService()); TransactionInvoker invoker = new TransactionInvoker(service); TestProtoMessages.Point point = TestProtoMessages.Point.newBuilder() .setX(1) .setY(1) .build(); invoker.invokeTransaction(TRANSACTION_ID, point.toByteArray(), context); verify(service).transactionMethod(point, context); }
void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
TransactionInvoker { void invokeTransaction(int transactionId, byte[] arguments, ExecutionContext context) { checkArgument(transactionMethods.containsKey(transactionId), "No method with transaction id (%s)", transactionId); TransactionMethod transactionMethod = transactionMethods.get(transactionId); transactionMethod.invoke(service, arguments, context); } @Inject TransactionInvoker(Service service); }
@Test void canModify() { Fork fork = Fork.newInstance(0x0A, false, new Cleaner()); assertTrue(fork.canModify()); }
public static Fork newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); }
Fork extends AbstractAccess { public static Fork newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } }
Fork extends AbstractAccess { public static Fork newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Fork(NativeHandle nativeHandle, ProxyDestructor destructor, Cleaner parentCleaner); }
Fork extends AbstractAccess { public static Fork newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Fork(NativeHandle nativeHandle, ProxyDestructor destructor, Cleaner parentCleaner); static Fork newInstance(long nativeHandle, Cleaner cleaner); static Fork newInstance(long nativeHandle, boolean owningHandle, Cleaner cleaner); @Override Cleaner getCleaner(); void createCheckpoint(); void rollback(); }
Fork extends AbstractAccess { public static Fork newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Fork(NativeHandle nativeHandle, ProxyDestructor destructor, Cleaner parentCleaner); static Fork newInstance(long nativeHandle, Cleaner cleaner); static Fork newInstance(long nativeHandle, boolean owningHandle, Cleaner cleaner); @Override Cleaner getCleaner(); void createCheckpoint(); void rollback(); }
@Test void findUnknownIndex() { long unknownId = 1024L; Optional<StorageIndex> index = registry.findIndex(unknownId); assertThat(index).isEmpty(); }
Optional<StorageIndex> findIndex(Long id) { return Optional.ofNullable(indexes.get(id)); }
OpenIndexRegistry { Optional<StorageIndex> findIndex(Long id) { return Optional.ofNullable(indexes.get(id)); } }
OpenIndexRegistry { Optional<StorageIndex> findIndex(Long id) { return Optional.ofNullable(indexes.get(id)); } }
OpenIndexRegistry { Optional<StorageIndex> findIndex(Long id) { return Optional.ofNullable(indexes.get(id)); } }
OpenIndexRegistry { Optional<StorageIndex> findIndex(Long id) { return Optional.ofNullable(indexes.get(id)); } }
@Test void cannotModify() { Snapshot s = Snapshot.newInstance(0x0A, false, new Cleaner()); assertFalse(s.canModify()); }
public static Snapshot newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); }
Snapshot extends AbstractAccess { public static Snapshot newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } }
Snapshot extends AbstractAccess { public static Snapshot newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Snapshot(NativeHandle nativeHandle, Cleaner cleaner); }
Snapshot extends AbstractAccess { public static Snapshot newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Snapshot(NativeHandle nativeHandle, Cleaner cleaner); static Snapshot newInstance(long nativeHandle, Cleaner cleaner); static Snapshot newInstance(long nativeHandle, boolean owningHandle, Cleaner cleaner); @Override Cleaner getCleaner(); }
Snapshot extends AbstractAccess { public static Snapshot newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Snapshot(NativeHandle nativeHandle, Cleaner cleaner); static Snapshot newInstance(long nativeHandle, Cleaner cleaner); static Snapshot newInstance(long nativeHandle, boolean owningHandle, Cleaner cleaner); @Override Cleaner getCleaner(); }
@Test void nextFailsIfModifiedBeforeFirstNext() { createFromIterable(emptyList()); notifyModified(); assertThrows(ConcurrentModificationException.class, () -> iter.next()); }
@Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
@Test void nextFailsIfModifiedAfterFirstNext() { createFromIterable(asList(1, 2)); iter.next(); notifyModified(); assertThrows(ConcurrentModificationException.class, () -> iter.next()); }
@Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
@Test void nextFailsIfHandleClosed() { NativeHandle nh = new NativeHandle(DEFAULT_NATIVE_HANDLE); createFromIterable(nh, asList(1, 2)); nh.close(); assertThrows(IllegalStateException.class, () -> iter.next()); }
@Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
@Test void beforeTransactions(TestKit testKit) { checkCounter(testKit, BEFORE_TXS_COUNTER_NAME, 0L); for (int i = 1; i <= 2; i++) { testKit.createBlock(); checkCounter(testKit, BEFORE_TXS_COUNTER_NAME, i); } }
@Override public void beforeTransactions(ExecutionContext context) { incrementCounter(BEFORE_TXS_COUNTER_NAME, context); }
QaServiceImpl extends AbstractService implements QaService { @Override public void beforeTransactions(ExecutionContext context) { incrementCounter(BEFORE_TXS_COUNTER_NAME, context); } }
QaServiceImpl extends AbstractService implements QaService { @Override public void beforeTransactions(ExecutionContext context) { incrementCounter(BEFORE_TXS_COUNTER_NAME, context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); }
QaServiceImpl extends AbstractService implements QaService { @Override public void beforeTransactions(ExecutionContext context) { incrementCounter(BEFORE_TXS_COUNTER_NAME, context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
QaServiceImpl extends AbstractService implements QaService { @Override public void beforeTransactions(ExecutionContext context) { incrementCounter(BEFORE_TXS_COUNTER_NAME, context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments, ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }
@Test void accessModificationResultsInTerminalState() { createFromIterable(asList(1, 2)); notifyModified(); assertThrows(ConcurrentModificationException.class, () -> iter.next()); assertThrows(ConcurrentModificationException.class, () -> iter.next()); }
@Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle, LongFunction<E> nextFunction, ModificationCounter modificationCounter); @Override Optional<E> next(); }
@Test void notifyModifiedThrowsIfSnapshotPassed() { Snapshot dbView = createSnapshot(); proxy = new IndexProxyImpl(dbView); UnsupportedOperationException thrown = assertThrows(UnsupportedOperationException.class, () -> proxy.notifyModified()); Pattern pattern = Pattern.compile("Cannot modify the access: .*[Ss]napshot.*" + "\\nUse a Fork to modify any collection\\.", Pattern.MULTILINE); assertThat(thrown, hasMessage(matchesPattern(pattern))); }
void notifyModified() { checkCanModify(); modCounter.notifyModified(); }
AbstractIndexProxy extends AbstractNativeProxy implements StorageIndex { void notifyModified() { checkCanModify(); modCounter.notifyModified(); } }
AbstractIndexProxy extends AbstractNativeProxy implements StorageIndex { void notifyModified() { checkCanModify(); modCounter.notifyModified(); } AbstractIndexProxy(NativeHandle nativeHandle, IndexAddress address, AbstractAccess access); }
AbstractIndexProxy extends AbstractNativeProxy implements StorageIndex { void notifyModified() { checkCanModify(); modCounter.notifyModified(); } AbstractIndexProxy(NativeHandle nativeHandle, IndexAddress address, AbstractAccess access); @Override IndexAddress getAddress(); @Override String toString(); }
AbstractIndexProxy extends AbstractNativeProxy implements StorageIndex { void notifyModified() { checkCanModify(); modCounter.notifyModified(); } AbstractIndexProxy(NativeHandle nativeHandle, IndexAddress address, AbstractAccess access); @Override IndexAddress getAddress(); @Override String toString(); }
@Test void nextThrowsIfNoNextItem0() { adapter = new RustIterAdapter<>( new RustIterTestFake(emptyList())); assertThrows(NoSuchElementException.class, () -> adapter.next()); }
@Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } RustIterAdapter(RustIter<E> rustIter); }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } RustIterAdapter(RustIter<E> rustIter); @Override boolean hasNext(); @Override E next(); }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } RustIterAdapter(RustIter<E> rustIter); @Override boolean hasNext(); @Override E next(); }
@Test void nextThrowsIfNoNextItem1() { adapter = new RustIterAdapter<>( new RustIterTestFake(singletonList(1))); adapter.next(); assertThrows(NoSuchElementException.class, () -> adapter.next()); }
@Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } RustIterAdapter(RustIter<E> rustIter); }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } RustIterAdapter(RustIter<E> rustIter); @Override boolean hasNext(); @Override E next(); }
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } RustIterAdapter(RustIter<E> rustIter); @Override boolean hasNext(); @Override E next(); }
@Test void checkIndexNameAcceptsNonEmpty() { String name = "table1"; assertThat(name, sameInstance(StoragePreconditions.checkIndexName(name))); }
@CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
@Test void checkIndexNameDoesNotAcceptNull() { assertThrows(NullPointerException.class, () -> StoragePreconditions.checkIndexName(null)); }
@CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
@Test void checkIndexNameDoesNotAcceptEmpty() { assertThrows(IllegalArgumentException.class, () -> { String name = ""; StoragePreconditions.checkIndexName(name); }); }
@CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }
@Test void checkIdInGroup() { byte[] validId = bytes("id1"); assertThat(StoragePreconditions.checkIdInGroup(validId), sameInstance(validId)); }
@CanIgnoreReturnValue static byte[] checkIdInGroup(byte[] indexId) { checkArgument(indexId.length > 0, "index identifier must not be empty"); return indexId; }
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkIdInGroup(byte[] indexId) { checkArgument(indexId.length > 0, "index identifier must not be empty"); return indexId; } }
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkIdInGroup(byte[] indexId) { checkArgument(indexId.length > 0, "index identifier must not be empty"); return indexId; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkIdInGroup(byte[] indexId) { checkArgument(indexId.length > 0, "index identifier must not be empty"); return indexId; } private StoragePreconditions(); }
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkIdInGroup(byte[] indexId) { checkArgument(indexId.length > 0, "index identifier must not be empty"); return indexId; } private StoragePreconditions(); }