src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ConfigDef { public List<ConfigValue> validate(Map<String, String> props) { return new ArrayList<>(validateAll(props).values()); } ConfigDef(); ConfigDef(ConfigDef base); Set<String> names(); ConfigDef define(ConfigKey key); ConfigDef define(String name, Type type, Object defaultValue, Validator validator, Importance i...
@Test public void testValidate() { Map<String, ConfigValue> expected = new HashMap<>(); String errorMessageB = "Missing required configuration \"b\" which has no default value."; String errorMessageC = "Missing required configuration \"c\" which has no default value."; ConfigValue configA = new ConfigValue("a", 1, Arra...
ConfigDef { public Set<String> names() { return Collections.unmodifiableSet(configKeys.keySet()); } ConfigDef(); ConfigDef(ConfigDef base); Set<String> names(); ConfigDef define(ConfigKey key); ConfigDef define(String name, Type type, Object defaultValue, Validator validator, Importance importance, String documentatio...
@Test public void testNames() { final ConfigDef configDef = new ConfigDef() .define("a", Type.STRING, Importance.LOW, "docs") .define("b", Type.STRING, Importance.LOW, "docs"); Set<String> names = configDef.names(); assertEquals(new HashSet<>(Arrays.asList("a", "b")), names); try { names.add("new"); fail(); } catch (Un...
ConfigDef { public String toRst() { StringBuilder b = new StringBuilder(); for (ConfigKey key : sortedConfigs()) { if (key.internalConfig) { continue; } getConfigKeyRst(key, b); b.append("\n"); } return b.toString(); } ConfigDef(); ConfigDef(ConfigDef base); Set<String> names(); ConfigDef define(ConfigKey key); Config...
@Test public void toRst() { final ConfigDef def = new ConfigDef() .define("opt1", Type.STRING, "a", ValidString.in("a", "b", "c"), Importance.HIGH, "docs1") .define("opt2", Type.INT, Importance.MEDIUM, "docs2") .define("opt3", Type.LIST, Arrays.asList("a", "b"), Importance.LOW, "docs3"); final String expectedRst = "" +...
ConfigDef { public String toEnrichedRst() { StringBuilder b = new StringBuilder(); String lastKeyGroupName = ""; for (ConfigKey key : sortedConfigs()) { if (key.internalConfig) { continue; } if (key.group != null) { if (!lastKeyGroupName.equalsIgnoreCase(key.group)) { b.append(key.group).append("\n"); char[] underLine ...
@Test public void toEnrichedRst() { final ConfigDef def = new ConfigDef() .define("opt1.of.group1", Type.STRING, "a", ValidString.in("a", "b", "c"), Importance.HIGH, "Doc doc.", "Group One", 0, Width.NONE, "..", Collections.<String>emptyList()) .define("opt2.of.group1", Type.INT, ConfigDef.NO_DEFAULT_VALUE, Importance....
ConfigDef { public static String convertToString(Object parsedValue, Type type) { if (parsedValue == null) { return null; } if (type == null) { return parsedValue.toString(); } switch (type) { case BOOLEAN: case SHORT: case INT: case LONG: case DOUBLE: case STRING: case PASSWORD: return parsedValue.toString(); case LIS...
@Test public void testConvertValueToStringBoolean() { assertEquals("true", ConfigDef.convertToString(true, Type.BOOLEAN)); assertNull(ConfigDef.convertToString(null, Type.BOOLEAN)); } @Test public void testConvertValueToStringShort() { assertEquals("32767", ConfigDef.convertToString(Short.MAX_VALUE, Type.SHORT)); asser...
AbstractConfig { public Map<String, Object> originalsWithPrefix(String prefix) { Map<String, Object> result = new RecordingMap<>(prefix, false); for (Map.Entry<String, ?> entry : originals.entrySet()) { if (entry.getKey().startsWith(prefix) && entry.getKey().length() > prefix.length()) result.put(entry.getKey().substri...
@Test public void testOriginalsWithPrefix() { Properties props = new Properties(); props.put("foo.bar", "abc"); props.put("setting", "def"); TestConfig config = new TestConfig(props); Map<String, Object> originalsWithPrefix = config.originalsWithPrefix("foo."); assertTrue(config.unused().contains("foo.bar")); originals...
AbstractConfig { public Map<String, Object> valuesWithPrefixOverride(String prefix) { Map<String, Object> result = new RecordingMap<>(values(), prefix, true); for (Map.Entry<String, ?> entry : originals.entrySet()) { if (entry.getKey().startsWith(prefix) && entry.getKey().length() > prefix.length()) { String keyWithNoP...
@Test public void testValuesWithPrefixOverride() { String prefix = "prefix."; Properties props = new Properties(); props.put("sasl.mechanism", "PLAIN"); props.put("prefix.sasl.mechanism", "GSSAPI"); props.put("prefix.sasl.kerberos.kinit.cmd", "/usr/bin/kinit2"); props.put("prefix.ssl.truststore.location", "my location"...
AbstractConfig { public Set<String> unused() { Set<String> keys = new HashSet<>(originals.keySet()); keys.removeAll(used); return keys; } @SuppressWarnings("unchecked") AbstractConfig(ConfigDef definition, Map<?, ?> originals, boolean doLog); AbstractConfig(ConfigDef definition, Map<?, ?> originals); void ignore(Stri...
@Test public void testUnused() { Properties props = new Properties(); String configValue = "org.apache.kafka.common.config.AbstractConfigTest$ConfiguredFakeMetricsReporter"; props.put(TestConfig.METRIC_REPORTER_CLASSES_CONFIG, configValue); props.put(FakeMetricsReporterConfig.EXTRA_CONFIG, "my_value"); TestConfig confi...
Cluster { public static Cluster bootstrap(List<InetSocketAddress> addresses) { List<Node> nodes = new ArrayList<>(); int nodeId = -1; for (InetSocketAddress address : addresses) nodes.add(new Node(nodeId--, address.getHostString(), address.getPort())); return new Cluster(null, true, nodes, new ArrayList<PartitionInfo>(...
@Test public void testBootstrap() { String ipAddress = "140.211.11.105"; String hostName = "www.example.com"; Cluster cluster = Cluster.bootstrap(Arrays.asList( new InetSocketAddress(ipAddress, 9002), new InetSocketAddress(hostName, 9002) )); Set<String> expectedHosts = Utils.mkSet(ipAddress, hostName); Set<String> act...
PartitionInfo { @Override public String toString() { return String.format("Partition(topic = %s, partition = %d, leader = %s, replicas = %s, isr = %s)", topic, partition, leader == null ? "none" : leader.idString(), formatNodeIds(replicas), formatNodeIds(inSyncReplicas)); } PartitionInfo(String topic, int partition, No...
@Test public void testToString() { String topic = "sample"; int partition = 0; Node leader = new Node(0, "localhost", 9092); Node r1 = new Node(1, "localhost", 9093); Node r2 = new Node(2, "localhost", 9094); Node[] replicas = new Node[] {leader, r1, r2}; Node[] inSyncReplicas = new Node[] {leader, r1, r2}; PartitionIn...
RecordHeaders implements Headers { @Override public Headers add(Header header) throws IllegalStateException { canWrite(); headers.add(header); return this; } RecordHeaders(); RecordHeaders(Header[] headers); RecordHeaders(Iterable<Header> headers); @Override Headers add(Header header); @Override Headers add(String ke...
@Test public void testAdd() { Headers headers = new RecordHeaders(); headers.add(new RecordHeader("key", "value".getBytes())); Header header = headers.iterator().next(); assertHeader("key", "value", header); headers.add(new RecordHeader("key2", "value2".getBytes())); assertHeader("key2", "value2", headers.lastHeader("k...
RecordHeaders implements Headers { @Override public Iterable<Header> headers(final String key) { checkKey(key); return new Iterable<Header>() { @Override public Iterator<Header> iterator() { return new FilterByKeyIterator(headers.iterator(), key); } }; } RecordHeaders(); RecordHeaders(Header[] headers); RecordHeaders...
@Test public void testHeaders() throws IOException { RecordHeaders headers = new RecordHeaders(); headers.add(new RecordHeader("key", "value".getBytes())); headers.add(new RecordHeader("key1", "key1value".getBytes())); headers.add(new RecordHeader("key", "value2".getBytes())); headers.add(new RecordHeader("key2", "key2...
Topic { static boolean containsValidPattern(String topic) { return LEGAL_CHARS_PATTERN.matcher(topic).matches(); } static void validate(String topic); static boolean isInternal(String topic); static boolean hasCollisionChars(String topic); static boolean hasCollision(String topicA, String topicB); static final String ...
@Test public void shouldRecognizeInvalidCharactersInTopicNames() { char[] invalidChars = {'/', '\\', ',', '\u0000', ':', '"', '\'', ';', '*', '?', ' ', '\t', '\r', '\n', '='}; for (char c : invalidChars) { String topicName = "Is " + c + "illegal"; assertFalse(Topic.containsValidPattern(topicName)); } }
Java { public static boolean isIBMJdk() { return System.getProperty("java.vendor").contains("IBM"); } private Java(); static boolean isIBMJdk(); static final String JVM_SPEC_VERSION; static final boolean IS_JAVA9_COMPATIBLE; }
@Test public void testIsIBMJdk() { System.setProperty("java.vendor", "Oracle Corporation"); assertFalse(Java.isIBMJdk()); System.setProperty("java.vendor", "IBM Corporation"); assertTrue(Java.isIBMJdk()); } @Test public void testLoadKerberosLoginModule() throws ClassNotFoundException { String clazz = Java.isIBMJdk() ? ...
Crc32C { public static Checksum create() { return CHECKSUM_FACTORY.create(); } static long compute(byte[] bytes, int offset, int size); static long compute(ByteBuffer buffer, int offset, int size); static Checksum create(); }
@Test public void testUpdate() { final byte[] bytes = "Any String you want".getBytes(); final int len = bytes.length; Checksum crc1 = Crc32C.create(); Checksum crc2 = Crc32C.create(); Checksum crc3 = Crc32C.create(); crc1.update(bytes, 0, len); for (int i = 0; i < len; i++) crc2.update(bytes[i]); crc3.update(bytes, 0, ...
Crc32C { public static long compute(byte[] bytes, int offset, int size) { Checksum crc = create(); crc.update(bytes, offset, size); return crc.getValue(); } static long compute(byte[] bytes, int offset, int size); static long compute(ByteBuffer buffer, int offset, int size); static Checksum create(); }
@Test public void testValue() { final byte[] bytes = "Some String".getBytes(); assertEquals(608512271, Crc32C.compute(bytes, 0, bytes.length)); }
Crc32 implements Checksum { @Override public void update(byte[] b, int off, int len) { if (off < 0 || len < 0 || off > b.length - len) throw new ArrayIndexOutOfBoundsException(); int localCrc = crc; while (len > 7) { final int c0 = (b[off + 0] ^ localCrc) & 0xff; final int c1 = (b[off + 1] ^ (localCrc >>>= 8)) & 0xff; ...
@Test public void testUpdate() { final byte[] bytes = "Any String you want".getBytes(); final int len = bytes.length; Checksum crc1 = Crc32C.create(); Checksum crc2 = Crc32C.create(); Checksum crc3 = Crc32C.create(); crc1.update(bytes, 0, len); for (int i = 0; i < len; i++) crc2.update(bytes[i]); crc3.update(bytes, 0, ...
Crc32 implements Checksum { public static long crc32(byte[] bytes) { return crc32(bytes, 0, bytes.length); } Crc32(); static long crc32(byte[] bytes); static long crc32(byte[] bytes, int offset, int size); static long crc32(ByteBuffer buffer, int offset, int size); @Override long getValue(); @Override void reset(); @Ov...
@Test public void testValue() { final byte[] bytes = "Some String".getBytes(); assertEquals(2021503672, Crc32.crc32(bytes)); }
ByteUtils { public static int readUnsignedIntLE(InputStream in) throws IOException { return in.read() | (in.read() << 8) | (in.read() << 16) | (in.read() << 24); } private ByteUtils(); static long readUnsignedInt(ByteBuffer buffer); static long readUnsignedInt(ByteBuffer buffer, int index); static int readUnsignedIntL...
@Test public void testReadUnsignedIntLEFromArray() { byte[] array1 = {0x01, 0x02, 0x03, 0x04, 0x05}; assertEquals(0x04030201, ByteUtils.readUnsignedIntLE(array1, 0)); assertEquals(0x05040302, ByteUtils.readUnsignedIntLE(array1, 1)); byte[] array2 = {(byte) 0xf1, (byte) 0xf2, (byte) 0xf3, (byte) 0xf4, (byte) 0xf5, (byte...
ByteUtils { public static long readUnsignedInt(ByteBuffer buffer) { return buffer.getInt() & 0xffffffffL; } private ByteUtils(); static long readUnsignedInt(ByteBuffer buffer); static long readUnsignedInt(ByteBuffer buffer, int index); static int readUnsignedIntLE(InputStream in); static int readUnsignedIntLE(byte[] b...
@Test public void testReadUnsignedInt() { ByteBuffer buffer = ByteBuffer.allocate(4); long writeValue = 133444; ByteUtils.writeUnsignedInt(buffer, writeValue); buffer.flip(); long readValue = ByteUtils.readUnsignedInt(buffer); assertEquals(writeValue, readValue); }
ByteUtils { public static void writeUnsignedIntLE(OutputStream out, int value) throws IOException { out.write(value); out.write(value >>> 8); out.write(value >>> 16); out.write(value >>> 24); } private ByteUtils(); static long readUnsignedInt(ByteBuffer buffer); static long readUnsignedInt(ByteBuffer buffer, int index...
@Test public void testWriteUnsignedIntLEToArray() { int value1 = 0x04030201; byte[] array1 = new byte[4]; ByteUtils.writeUnsignedIntLE(array1, 0, value1); assertArrayEquals(new byte[] {0x01, 0x02, 0x03, 0x04}, array1); array1 = new byte[8]; ByteUtils.writeUnsignedIntLE(array1, 2, value1); assertArrayEquals(new byte[] {...
ByteUtils { public static int readVarint(ByteBuffer buffer) { int value = 0; int i = 0; int b; while (((b = buffer.get()) & 0x80) != 0) { value |= (b & 0x7f) << i; i += 7; if (i > 28) throw illegalVarintException(value); } value |= b << i; return (value >>> 1) ^ -(value & 1); } private ByteUtils(); static long readUns...
@Test(expected = IllegalArgumentException.class) public void testInvalidVarint() { ByteBuffer buf = ByteBuffer.wrap(new byte[] {xFF, xFF, xFF, xFF, xFF, x01}); ByteUtils.readVarint(buf); }
ByteUtils { public static long readVarlong(DataInput in) throws IOException { long value = 0L; int i = 0; long b; while (((b = in.readByte()) & 0x80) != 0) { value |= (b & 0x7f) << i; i += 7; if (i > 63) throw illegalVarlongException(value); } value |= b << i; return (value >>> 1) ^ -(value & 1); } private ByteUtils()...
@Test(expected = IllegalArgumentException.class) public void testInvalidVarlong() { ByteBuffer buf = ByteBuffer.wrap(new byte[] {xFF, xFF, xFF, xFF, xFF, xFF, xFF, xFF, xFF, xFF, x01}); ByteUtils.readVarlong(buf); }
Utils { public static String getHost(String address) { Matcher matcher = HOST_PORT_PATTERN.matcher(address); return matcher.matches() ? matcher.group(1) : null; } static List<T> sorted(Collection<T> collection); static String utf8(byte[] bytes); static String utf8(ByteBuffer buffer, int length); static String utf8(Byt...
@Test public void testGetHost() { assertEquals("127.0.0.1", getHost("127.0.0.1:8000")); assertEquals("mydomain.com", getHost("PLAINTEXT: assertEquals("MyDomain.com", getHost("PLAINTEXT: assertEquals("My_Domain.com", getHost("PLAINTEXT: assertEquals("::1", getHost("[::1]:1234")); assertEquals("2001:db8:85a3:8d3:1319:8a2...
Utils { public static Integer getPort(String address) { Matcher matcher = HOST_PORT_PATTERN.matcher(address); return matcher.matches() ? Integer.parseInt(matcher.group(2)) : null; } static List<T> sorted(Collection<T> collection); static String utf8(byte[] bytes); static String utf8(ByteBuffer buffer, int length); sta...
@Test public void testGetPort() { assertEquals(8000, getPort("127.0.0.1:8000").intValue()); assertEquals(8080, getPort("mydomain.com:8080").intValue()); assertEquals(8080, getPort("MyDomain.com:8080").intValue()); assertEquals(1234, getPort("[::1]:1234").intValue()); assertEquals(5678, getPort("[2001:db8:85a3:8d3:1319:...
Utils { public static String formatAddress(String host, Integer port) { return host.contains(":") ? "[" + host + "]:" + port : host + ":" + port; } static List<T> sorted(Collection<T> collection); static String utf8(byte[] bytes); static String utf8(ByteBuffer buffer, int length); static String utf8(ByteBuffer buffer,...
@Test public void testFormatAddress() { assertEquals("127.0.0.1:8000", formatAddress("127.0.0.1", 8000)); assertEquals("mydomain.com:8080", formatAddress("mydomain.com", 8080)); assertEquals("[::1]:1234", formatAddress("::1", 1234)); assertEquals("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:5678", formatAddress("2001:db8:85...
Utils { public static <T> String join(T[] strs, String separator) { return join(Arrays.asList(strs), separator); } static List<T> sorted(Collection<T> collection); static String utf8(byte[] bytes); static String utf8(ByteBuffer buffer, int length); static String utf8(ByteBuffer buffer, int offset, int length); static ...
@Test public void testJoin() { assertEquals("", Utils.join(Collections.emptyList(), ",")); assertEquals("1", Utils.join(Arrays.asList("1"), ",")); assertEquals("1,2,3", Utils.join(Arrays.asList(1, 2, 3), ",")); }
Utils { public static int abs(int n) { return (n == Integer.MIN_VALUE) ? 0 : Math.abs(n); } static List<T> sorted(Collection<T> collection); static String utf8(byte[] bytes); static String utf8(ByteBuffer buffer, int length); static String utf8(ByteBuffer buffer, int offset, int length); static byte[] utf8(String stri...
@Test public void testAbs() { assertEquals(0, Utils.abs(Integer.MIN_VALUE)); assertEquals(10, Utils.abs(-10)); assertEquals(10, Utils.abs(10)); assertEquals(0, Utils.abs(0)); assertEquals(1, Utils.abs(-1)); }
Utils { public static byte[] toArray(ByteBuffer buffer) { return toArray(buffer, 0, buffer.remaining()); } static List<T> sorted(Collection<T> collection); static String utf8(byte[] bytes); static String utf8(ByteBuffer buffer, int length); static String utf8(ByteBuffer buffer, int offset, int length); static byte[] u...
@Test public void toArray() { byte[] input = {0, 1, 2, 3, 4}; ByteBuffer buffer = ByteBuffer.wrap(input); assertArrayEquals(input, Utils.toArray(buffer)); assertEquals(0, buffer.position()); assertArrayEquals(new byte[] {1, 2}, Utils.toArray(buffer, 1, 2)); assertEquals(0, buffer.position()); buffer.position(2); assert...
Utils { public static byte[] readBytes(ByteBuffer buffer, int offset, int length) { byte[] dest = new byte[length]; if (buffer.hasArray()) { System.arraycopy(buffer.array(), buffer.arrayOffset() + offset, dest, 0, length); } else { buffer.mark(); buffer.position(offset); buffer.get(dest, 0, length); buffer.reset(); } r...
@Test public void testReadBytes() { byte[] myvar = "Any String you want".getBytes(); ByteBuffer buffer = ByteBuffer.allocate(myvar.length); buffer.put(myvar); buffer.rewind(); this.subTest(buffer); buffer = ByteBuffer.wrap(myvar).asReadOnlyBuffer(); this.subTest(buffer); }
Utils { public static long min(long first, long ... rest) { long min = first; for (long r : rest) { if (r < min) min = r; } return min; } static List<T> sorted(Collection<T> collection); static String utf8(byte[] bytes); static String utf8(ByteBuffer buffer, int length); static String utf8(ByteBuffer buffer, int offse...
@Test public void testMin() { assertEquals(1, Utils.min(1)); assertEquals(1, Utils.min(1, 2, 3)); assertEquals(1, Utils.min(2, 1, 3)); assertEquals(1, Utils.min(2, 3, 1)); }
Utils { public static void closeAll(Closeable... closeables) throws IOException { IOException exception = null; for (Closeable closeable : closeables) { try { closeable.close(); } catch (IOException e) { if (exception != null) exception.addSuppressed(e); else exception = e; } } if (exception != null) throw exception; }...
@Test public void testCloseAll() { TestCloseable[] closeablesWithoutException = TestCloseable.createCloseables(false, false, false); try { Utils.closeAll(closeablesWithoutException); TestCloseable.checkClosed(closeablesWithoutException); } catch (IOException e) { fail("Unexpected exception: " + e); } TestCloseable[] cl...
Utils { public static void readFullyOrFail(FileChannel channel, ByteBuffer destinationBuffer, long position, String description) throws IOException { if (position < 0) { throw new IllegalArgumentException("The file channel position cannot be negative, but it is " + position); } int expectedReadBytes = destinationBuffer...
@Test public void testReadFullyOrFailWithRealFile() throws IOException { try (FileChannel channel = FileChannel.open(TestUtils.tempFile().toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE)) { String msg = "hello, world"; channel.write(ByteBuffer.wrap(msg.getBytes()), 0); channel.force(true); assertEquals("Mes...
Utils { public static void readFully(FileChannel channel, ByteBuffer destinationBuffer, long position) throws IOException { if (position < 0) { throw new IllegalArgumentException("The file channel position cannot be negative, but it is " + position); } long currentPosition = position; int bytesRead; do { bytesRead = ch...
@Test public void testReadFullyWithPartialFileChannelReads() throws IOException { FileChannel channelMock = EasyMock.createMock(FileChannel.class); final int bufferSize = 100; StringBuilder expectedBufferContent = new StringBuilder(); fileChannelMockExpectReadWithRandomBytes(channelMock, expectedBufferContent, bufferSi...
Utils { public static void delete(final File file) throws IOException { if (file == null) return; Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException { if (exc instanceof NoSuchFileException && path.toFile().eq...
@Test(timeout = 120000) public void testRecursiveDelete() throws IOException { Utils.delete(null); File tempFile = TestUtils.tempFile(); Utils.delete(tempFile); assertFalse(Files.exists(tempFile.toPath())); File tempDir = TestUtils.tempDirectory(); File tempDir2 = TestUtils.tempDirectory(tempDir.toPath(), "a"); TestUti...
Shell { public static String execCommand(String ... cmd) throws IOException { return execCommand(cmd, -1); } Shell(long timeout); int exitCode(); Process process(); static String execCommand(String ... cmd); static String execCommand(String[] cmd, long timeout); }
@Test public void testEchoHello() throws Exception { assumeTrue(!OperatingSystem.IS_WINDOWS); String output = Shell.execCommand("echo", "hello"); assertEquals("hello\n", output); } @Test public void testHeadDevZero() throws Exception { assumeTrue(!OperatingSystem.IS_WINDOWS); final int length = 100000; String output = ...
LegacyRecord { public long checksum() { return ByteUtils.readUnsignedInt(buffer, CRC_OFFSET); } LegacyRecord(ByteBuffer buffer); LegacyRecord(ByteBuffer buffer, Long wrapperRecordTimestamp, TimestampType wrapperRecordTimestampType); long computeChecksum(); long checksum(); boolean isValid(); Long wrapperRecordTimestam...
@Test public void testChecksum() { assertEquals(record.checksum(), record.computeChecksum()); byte attributes = LegacyRecord.computeAttributes(magic, this.compression, TimestampType.CREATE_TIME); assertEquals(record.checksum(), LegacyRecord.computeChecksum( magic, attributes, this.timestamp, this.key == null ? null : t...
FileLogInputStream implements LogInputStream<FileLogInputStream.FileChannelRecordBatch> { @Override public FileChannelRecordBatch nextBatch() throws IOException { if (position + HEADER_SIZE_UP_TO_MAGIC >= end) return null; logHeaderBuffer.rewind(); Utils.readFullyOrFail(channel, logHeaderBuffer, position, "log header")...
@Test public void testWriteTo() throws IOException { try (FileRecords fileRecords = FileRecords.open(tempFile())) { fileRecords.append(MemoryRecords.withRecords(magic, compression, new SimpleRecord("foo".getBytes()))); fileRecords.flush(); FileLogInputStream logInputStream = new FileLogInputStream(fileRecords.channel()...
DefaultRecord implements Record { public static DefaultRecord readFrom(DataInput input, long baseOffset, long baseTimestamp, int baseSequence, Long logAppendTime) throws IOException { int sizeOfBodyInBytes = ByteUtils.readVarint(input); ByteBuffer recordBuffer = ByteBuffer.allocate(sizeOfBodyInBytes); input.readFully(r...
@Test(expected = InvalidRecordException.class) public void testInvalidKeySize() { byte attributes = 0; long timestampDelta = 2; int offsetDelta = 1; int sizeOfBodyInBytes = 100; int keySize = 105; ByteBuffer buf = ByteBuffer.allocate(sizeOfBodyInBytes + ByteUtils.sizeOfVarint(sizeOfBodyInBytes)); ByteUtils.writeVarint(...
MemoryRecords extends AbstractRecords { @Override public Iterable<MutableRecordBatch> batches() { return batches; } private MemoryRecords(ByteBuffer buffer); @Override int sizeInBytes(); @Override long writeTo(GatheringByteChannel channel, long position, int length); int writeFullyTo(GatheringByteChannel channel); int...
@Test public void testIterator() { ByteBuffer buffer = ByteBuffer.allocate(1024); MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, magic, compression, TimestampType.CREATE_TIME, firstOffset, logAppendTime, pid, epoch, firstSequence, false, false, partitionLeaderEpoch, buffer.limit()); SimpleRecord[] reco...
MemoryRecords extends AbstractRecords { public static MemoryRecordsBuilder builder(ByteBuffer buffer, CompressionType compressionType, TimestampType timestampType, long baseOffset) { return builder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, compressionType, timestampType, baseOffset); } private MemoryRecords(ByteBuffer ...
@Test public void testHasRoomForMethod() { MemoryRecordsBuilder builder = MemoryRecords.builder(ByteBuffer.allocate(1024), magic, compression, TimestampType.CREATE_TIME, 0L); builder.append(0L, "a".getBytes(), "1".getBytes()); assertTrue(builder.hasRoomFor(1L, "b".getBytes(), "2".getBytes(), Record.EMPTY_HEADERS)); bui...
MemoryRecords extends AbstractRecords { public FilterResult filterTo(TopicPartition partition, RecordFilter filter, ByteBuffer destinationBuffer, int maxRecordBatchSize, BufferSupplier decompressionBufferSupplier) { return filterTo(partition, batches(), filter, destinationBuffer, maxRecordBatchSize, decompressionBuffer...
@Test public void testFilterTo() { ByteBuffer buffer = ByteBuffer.allocate(2048); MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, magic, compression, TimestampType.CREATE_TIME, 0L); builder.append(10L, null, "a".getBytes()); builder.close(); builder = MemoryRecords.builder(buffer, magic, compression, Times...
ByteBufferLogInputStream implements LogInputStream<MutableRecordBatch> { public MutableRecordBatch nextBatch() throws IOException { int remaining = buffer.remaining(); if (remaining < LOG_OVERHEAD) return null; int recordSize = buffer.getInt(buffer.position() + SIZE_OFFSET); if (recordSize < LegacyRecord.RECORD_OVERHEA...
@Test(expected = CorruptRecordException.class) public void iteratorRaisesOnTooSmallRecords() throws IOException { ByteBuffer buffer = ByteBuffer.allocate(1024); MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, CompressionType.NONE, TimestampType.CREATE_TIME, 0L); builder.append(15L, "a".getBytes(), "1".getB...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { public static void writeEmptyHeader(ByteBuffer buffer, byte magic, long producerId, short producerEpoch, int baseSequence, long baseOffset, long lastOffset, int partitionLeaderEpoch, TimestampType timestampType, long timestamp, boolean isTra...
@Test public void testWriteEmptyHeader() { long producerId = 23423L; short producerEpoch = 145; int baseSequence = 983; long baseOffset = 15L; long lastOffset = 37; int partitionLeaderEpoch = 15; long timestamp = System.currentTimeMillis(); for (TimestampType timestampType : Arrays.asList(TimestampType.CREATE_TIME, Tim...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { @Override public int sizeInBytes() { return LOG_OVERHEAD + buffer.getInt(LENGTH_OFFSET); } DefaultRecordBatch(ByteBuffer buffer); @Override byte magic(); @Override void ensureValid(); long baseTimestamp(); @Override long maxTimestamp(); @Ove...
@Test public void testSizeInBytes() { Header[] headers = new Header[] { new RecordHeader("foo", "value".getBytes()), new RecordHeader("bar", (byte[]) null) }; long timestamp = System.currentTimeMillis(); SimpleRecord[] records = new SimpleRecord[] { new SimpleRecord(timestamp, "key".getBytes(), "value".getBytes()), new...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { public boolean isValid() { return sizeInBytes() >= RECORD_BATCH_OVERHEAD && checksum() == computeChecksum(); } DefaultRecordBatch(ByteBuffer buffer); @Override byte magic(); @Override void ensureValid(); long baseTimestamp(); @Override long ...
@Test(expected = InvalidRecordException.class) public void testInvalidRecordCountTooManyNonCompressedV2() { long now = System.currentTimeMillis(); DefaultRecordBatch batch = recordsWithInvalidRecordCount(RecordBatch.MAGIC_VALUE_V2, now, CompressionType.NONE, 5); for (Record record: batch) { record.isValid(); } } @Test(...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { @Override public void setLastOffset(long offset) { buffer.putLong(BASE_OFFSET_OFFSET, offset - lastOffsetDelta()); } DefaultRecordBatch(ByteBuffer buffer); @Override byte magic(); @Override void ensureValid(); long baseTimestamp(); @Override...
@Test public void testSetLastOffset() { SimpleRecord[] simpleRecords = new SimpleRecord[] { new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes()) }; MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MA...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { @Override public void setPartitionLeaderEpoch(int epoch) { buffer.putInt(PARTITION_LEADER_EPOCH_OFFSET, epoch); } DefaultRecordBatch(ByteBuffer buffer); @Override byte magic(); @Override void ensureValid(); long baseTimestamp(); @Override lo...
@Test public void testSetPartitionLeaderEpoch() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getByt...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { @Override public void setMaxTimestamp(TimestampType timestampType, long maxTimestamp) { long currentMaxTimestamp = maxTimestamp(); if (timestampType() == timestampType && currentMaxTimestamp == maxTimestamp) return; byte attributes = compute...
@Test(expected = IllegalArgumentException.class) public void testSetNoTimestampTypeNotAllowed() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), ...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { @Override public boolean isControlBatch() { return (attributes() & CONTROL_FLAG_MASK) > 0; } DefaultRecordBatch(ByteBuffer buffer); @Override byte magic(); @Override void ensureValid(); long baseTimestamp(); @Override long maxTimestamp(); @O...
@Test public void testReadAndWriteControlBatch() { long producerId = 1L; short producerEpoch = 0; int coordinatorEpoch = 15; ByteBuffer buffer = ByteBuffer.allocate(128); MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE, TimestampType.CREATE_TIME, 0L,...
DefaultRecordBatch extends AbstractRecordBatch implements MutableRecordBatch { static int incrementSequence(int baseSequence, int increment) { if (baseSequence > Integer.MAX_VALUE - increment) return increment - (Integer.MAX_VALUE - baseSequence) - 1; return baseSequence + increment; } DefaultRecordBatch(ByteBuffer buf...
@Test public void testIncrementSequence() { assertEquals(10, DefaultRecordBatch.incrementSequence(5, 5)); assertEquals(0, DefaultRecordBatch.incrementSequence(Integer.MAX_VALUE, 1)); assertEquals(4, DefaultRecordBatch.incrementSequence(Integer.MAX_VALUE - 5, 10)); }
FileRecords extends AbstractRecords implements Closeable { public FileChannel channel() { return channel; } FileRecords(File file, FileChannel channel, int start, int end, boolean isSlice); @Override int sizeInBytes(); File file...
@Test public void testIterationDoesntChangePosition() throws IOException { long position = fileRecords.channel().position(); Iterator<Record> records = fileRecords.records().iterator(); for (byte[] value : values) { assertTrue(records.hasNext()); assertEquals(records.next().value(), ByteBuffer.wrap(value)); } assertEqu...
FileRecords extends AbstractRecords implements Closeable { public FileRecords read(int position, int size) throws IOException { if (position < 0) throw new IllegalArgumentException("Invalid position: " + position); if (size < 0) throw new IllegalArgumentException("Invalid size: " + size); final int end; if (this.start ...
@Test public void testRead() throws IOException { FileRecords read = fileRecords.read(0, fileRecords.sizeInBytes()); TestUtils.checkEquals(fileRecords.batches(), read.batches()); List<RecordBatch> items = batches(read); RecordBatch second = items.get(1); read = fileRecords.read(second.sizeInBytes(), fileRecords.sizeInB...
FileRecords extends AbstractRecords implements Closeable { public int truncateTo(int targetSize) throws IOException { int originalSize = sizeInBytes(); if (targetSize > originalSize || targetSize < 0) throw new KafkaException("Attempt to truncate log segment to " + targetSize + " bytes failed, " + " size of this log se...
@Test public void testTruncateNotCalledIfSizeIsSameAsTargetSize() throws IOException { FileChannel channelMock = EasyMock.createMock(FileChannel.class); EasyMock.expect(channelMock.size()).andReturn(42L).atLeastOnce(); EasyMock.expect(channelMock.position(42L)).andReturn(null); EasyMock.replay(channelMock); FileRecords...
MemoryRecordsBuilder { public void close() { if (aborted) throw new IllegalStateException("Cannot close MemoryRecordsBuilder as it has already been aborted"); if (builtRecords != null) return; validateProducerState(); closeForRecordAppends(); if (numRecords == 0L) { buffer().position(initialPosition); builtRecords = Me...
@Test(expected = IllegalArgumentException.class) public void testWriteTransactionalWithInvalidPID() { ByteBuffer buffer = ByteBuffer.allocate(128); buffer.position(bufferOffset); long pid = RecordBatch.NO_PRODUCER_ID; short epoch = 15; int sequence = 2342; MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer,...
MemoryRecordsBuilder { public Long appendEndTxnMarker(long timestamp, EndTransactionMarker marker) { if (producerId == RecordBatch.NO_PRODUCER_ID) throw new IllegalArgumentException("End transaction marker requires a valid producerId"); if (!isTransactional) throw new IllegalArgumentException("End transaction marker de...
@Test(expected = IllegalArgumentException.class) public void testWriteEndTxnMarkerNonTransactionalBatch() { ByteBuffer buffer = ByteBuffer.allocate(128); buffer.position(bufferOffset); long pid = 9809; short epoch = 15; int sequence = RecordBatch.NO_SEQUENCE; MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buff...
MemoryRecordsBuilder { private Long appendWithOffset(long offset, boolean isControlRecord, long timestamp, ByteBuffer key, ByteBuffer value, Header[] headers) { try { if (isControlRecord != isControlBatch) throw new IllegalArgumentException("Control records can only be appended to control batches"); if (lastOffset != n...
@Test(expected = IllegalArgumentException.class) public void testAppendAtInvalidOffset() { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.position(bufferOffset); long logAppendTime = System.currentTimeMillis(); MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.MAGIC_VALUE_V1, compressio...
ProduceRequest extends AbstractRequest { public boolean isTransactional() { return transactional; } private ProduceRequest(short version, short acks, int timeout, Map<TopicPartition, MemoryRecords> partitionRecords, String transactionalId); ProduceRequest(Struct struct, short version); @Override Struct toStruct(); @O...
@Test public void shouldBeFlaggedAsTransactionalWhenTransactionalRecords() throws Exception { final MemoryRecords memoryRecords = MemoryRecords.withTransactionalRecords(0, CompressionType.NONE, 1L, (short) 1, 1, 1, simpleRecord); final ProduceRequest request = new ProduceRequest.Builder(RecordBatch.CURRENT_MAGIC_VALUE,...
ProduceRequest extends AbstractRequest { public boolean isIdempotent() { return idempotent; } private ProduceRequest(short version, short acks, int timeout, Map<TopicPartition, MemoryRecords> partitionRecords, String transactionalId); ProduceRequest(Struct struct, short version); @Override Struct toStruct(); @Overrid...
@Test public void shouldBeFlaggedAsIdempotentWhenIdempotentRecords() throws Exception { final MemoryRecords memoryRecords = MemoryRecords.withIdempotentRecords(1, CompressionType.NONE, 1L, (short) 1, 1, 1, simpleRecord); final ProduceRequest request = new ProduceRequest.Builder(RecordBatch.CURRENT_MAGIC_VALUE, (short) ...
StreamsConfig extends AbstractConfig { public Map<String, Object> getProducerConfigs(final String clientId) { final Map<String, Object> clientProvidedProps = getClientPropsWithPrefix(PRODUCER_PREFIX, ProducerConfig.configNames()); if (eosEnabled) { if (clientProvidedProps.containsKey(ProducerConfig.ENABLE_IDEMPOTENCE_C...
@Test public void testGetProducerConfigs() throws Exception { final String clientId = "client"; final Map<String, Object> returnedProps = streamsConfig.getProducerConfigs(clientId); assertEquals(returnedProps.get(ProducerConfig.CLIENT_ID_CONFIG), clientId + "-producer"); assertEquals(returnedProps.get(ProducerConfig.LI...
StreamsConfig extends AbstractConfig { public Map<String, Object> getConsumerConfigs(final StreamThread streamThread, final String groupId, final String clientId) throws ConfigException { final Map<String, Object> consumerProps = getCommonConsumerConfigs(); consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); co...
@Test public void testGetConsumerConfigs() throws Exception { final String groupId = "example-application"; final String clientId = "client"; final Map<String, Object> returnedProps = streamsConfig.getConsumerConfigs(null, groupId, clientId); assertEquals(returnedProps.get(ConsumerConfig.CLIENT_ID_CONFIG), clientId + "...
StreamsConfig extends AbstractConfig { public Map<String, Object> getRestoreConsumerConfigs(final String clientId) throws ConfigException { final Map<String, Object> consumerProps = getCommonConsumerConfigs(); consumerProps.remove(ConsumerConfig.GROUP_ID_CONFIG); consumerProps.put(CommonClientConfigs.CLIENT_ID_CONFIG, ...
@Test public void testGetRestoreConsumerConfigs() throws Exception { final String clientId = "client"; final Map<String, Object> returnedProps = streamsConfig.getRestoreConsumerConfigs(clientId); assertEquals(returnedProps.get(ConsumerConfig.CLIENT_ID_CONFIG), clientId + "-restore-consumer"); assertNull(returnedProps.g...
StreamsConfig extends AbstractConfig { public Serde defaultKeySerde() { try { Serde<?> serde = getConfiguredInstance(DEFAULT_KEY_SERDE_CLASS_CONFIG, Serde.class); serde.configure(originals(), true); return serde; } catch (final Exception e) { throw new StreamsException(String.format("Failed to configure key serde %s", ...
@Test(expected = StreamsException.class) public void shouldThrowStreamsExceptionIfKeySerdeConfigFails() throws Exception { props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, MisconfiguredSerde.class); final StreamsConfig streamsConfig = new StreamsConfig(props); streamsConfig.defaultKeySerde(); }
StreamsConfig extends AbstractConfig { public Serde defaultValueSerde() { try { Serde<?> serde = getConfiguredInstance(DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serde.class); serde.configure(originals(), false); return serde; } catch (final Exception e) { throw new StreamsException(String.format("Failed to configure value serd...
@Test(expected = StreamsException.class) public void shouldThrowStreamsExceptionIfValueSerdeConfigFails() throws Exception { props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, MisconfiguredSerde.class); final StreamsConfig streamsConfig = new StreamsConfig(props); streamsConfig.defaultValueSerde(); }
JsonConverter implements Converter { @Override public void configure(Map<String, ?> configs, boolean isKey) { Object enableConfigsVal = configs.get(SCHEMAS_ENABLE_CONFIG); if (enableConfigsVal != null) enableSchemas = enableConfigsVal.toString().equals("true"); serializer.configure(configs, isKey); deserializer.configu...
@Test public void testJsonSchemaCacheSizeFromConfigFile() throws URISyntaxException, IOException { URL url = getClass().getResource("/connect-test.properties"); File propFile = new File(url.toURI()); String workerPropsFile = propFile.getAbsolutePath(); Map<String, String> workerProps = !workerPropsFile.isEmpty() ? Util...
Stores { public static StoreFactory create(final String name) { return new StoreFactory() { @Override public <K> ValueFactory<K> withKeys(final Serde<K> keySerde) { return new ValueFactory<K>() { @Override public <V> KeyValueFactory<K, V> withValues(final Serde<V> valueSerde) { return new KeyValueFactory<K, V>() { @Ove...
@Test public void shouldCreateInMemoryStoreSupplierWithLoggedConfig() throws Exception { final StateStoreSupplier supplier = Stores.create("store") .withKeys(Serdes.String()) .withValues(Serdes.String()) .inMemory() .enableLogging(Collections.singletonMap("retention.ms", "1000")) .build(); final Map<String, String> con...
SerializedKeyValueIterator implements KeyValueIterator<K, V> { @Override public KeyValue<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } final KeyValue<Bytes, byte[]> next = bytesIterator.next(); return KeyValue.pair(serdes.keyFrom(next.key.get()), serdes.valueFrom(next.value)); } SerializedKeyVa...
@Test public void shouldReturnNextValueWhenItExists() throws Exception { assertThat(serializedKeyValueIterator.next(), equalTo(KeyValue.pair("hi", "there"))); assertThat(serializedKeyValueIterator.next(), equalTo(KeyValue.pair("hello", "world"))); } @Test public void shouldThrowNoSuchElementOnNextWhenIteratorExhausted(...
SerializedKeyValueIterator implements KeyValueIterator<K, V> { @Override public boolean hasNext() { return bytesIterator.hasNext(); } SerializedKeyValueIterator(final KeyValueIterator<Bytes, byte[]> bytesIterator, final StateSerdes<K, V> serdes); @Override void close(); @Override K peekNe...
@Test public void shouldReturnFalseOnHasNextWhenNoMoreResults() throws Exception { advanceIteratorToEnd(); assertFalse(serializedKeyValueIterator.hasNext()); } @Test public void shouldReturnTrueOnHasNextWhenMoreResults() { assertTrue(serializedKeyValueIterator.hasNext()); } @Test public void shouldReturnFalseOnHasNextW...
SerializedKeyValueIterator implements KeyValueIterator<K, V> { @Override public void remove() { throw new UnsupportedOperationException("remove() is not supported in " + getClass().getName()); } SerializedKeyValueIterator(final KeyValueIterator<Bytes, byte[]> bytesIterator, final StateSer...
@Test(expected = UnsupportedOperationException.class) public void shouldThrowUnsupportedOperationOnRemove() throws Exception { serializedKeyValueIterator.remove(); } @Test(expected = UnsupportedOperationException.class) public void shouldThrowUnsupportedOperationOnRemove() { serializedKeyValueIterator.remove(); }
SessionKeySchema implements SegmentedBytesStore.KeySchema { @Override public HasNextCondition hasNextCondition(final Bytes binaryKeyFrom, final Bytes binaryKeyTo, final long from, final long to) { return new HasNextCondition() { @Override public boolean hasNext(final KeyValueIterator<Bytes, ?> iterator) { while (iterat...
@Test public void shouldFetchExactKeysSkippingLongerKeys() throws Exception { final Bytes key = Bytes.wrap(new byte[]{0}); final List<Integer> result = getValues(sessionKeySchema.hasNextCondition(key, key, 0, Long.MAX_VALUE)); assertThat(result, equalTo(Arrays.asList(2, 4))); } @Test public void shouldFetchExactKeySkip...
SessionKeySchema implements SegmentedBytesStore.KeySchema { @Override public Bytes upperRange(Bytes key, long to) { final byte[] maxSuffix = ByteBuffer.allocate(SUFFIX_SIZE) .putLong(to) .putLong(to) .array(); return OrderedBytes.upperRange(key, maxSuffix); } @Override void init(final String topic); @Override Bytes up...
@Test public void testUpperBoundWithLargeTimestamps() throws Exception { Bytes upper = sessionKeySchema.upperRange(Bytes.wrap(new byte[]{0xA, 0xB, 0xC}), Long.MAX_VALUE); assertThat( "shorter key with max timestamp should be in range", upper.compareTo( SessionKeySerde.bytesToBinary( new Windowed<>( Bytes.wrap(new byte[...
SessionKeySchema implements SegmentedBytesStore.KeySchema { @Override public Bytes lowerRange(Bytes key, long from) { return OrderedBytes.lowerRange(key, MIN_SUFFIX); } @Override void init(final String topic); @Override Bytes upperRangeFixedSize(final Bytes key, final long to); @Override Bytes lowerRangeFixedSize(fina...
@Test public void testLowerBoundWithZeroTimestamp() throws Exception { Bytes lower = sessionKeySchema.lowerRange(Bytes.wrap(new byte[]{0xA, 0xB, 0xC}), 0); assertThat(lower, equalTo(SessionKeySerde.bytesToBinary(new Windowed<>(Bytes.wrap(new byte[]{0xA, 0xB, 0xC}), new SessionWindow(0, 0))))); } @Test public void testL...
CompositeReadOnlySessionStore implements ReadOnlySessionStore<K, V> { private KeyValueIterator<Windowed<K>, V> fetch(Fetcher<K, V> fetcher) { final List<ReadOnlySessionStore<K, V>> stores = storeProvider.stores(storeName, queryableStoreType); for (final ReadOnlySessionStore<K, V> store : stores) { try { final KeyValueI...
@Test public void shouldFetchResulstFromUnderlyingSessionStore() throws Exception { underlyingSessionStore.put(new Windowed<>("a", new SessionWindow(0, 0)), 1L); underlyingSessionStore.put(new Windowed<>("a", new SessionWindow(10, 10)), 2L); final List<KeyValue<Windowed<String>, Long>> results = toList(sessionStore.fet...
NamedCache { synchronized void evict() { if (tail == null) { return; } final LRUNode eldest = tail; currentSizeBytes -= eldest.size(); remove(eldest); cache.remove(eldest.key); if (eldest.entry.isDirty()) { flush(eldest); } } NamedCache(final String name, final StreamsMetrics metrics); long size(); }
@Test public void shouldNotThrowNullPointerWhenCacheIsEmptyAndEvictionCalled() throws Exception { cache.evict(); }
NamedCache { synchronized void put(final Bytes key, final LRUCacheEntry value) { if (!value.isDirty() && dirtyKeys.contains(key)) { throw new IllegalStateException(String.format("Attempting to put a clean entry for key [%s] " + "into NamedCache [%s] when it already contains " + "a dirty entry for the same key", key, na...
@Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionWhenTryingToOverwriteDirtyEntryWithCleanEntry() throws Exception { cache.put(Bytes.wrap(new byte[]{0}), new LRUCacheEntry(new byte[]{10}, true, 0, 0, 0, "")); cache.put(Bytes.wrap(new byte[]{0}), new LRUCacheEntry(new byte[]{10}, ...
NamedCache { synchronized LRUCacheEntry get(final Bytes key) { if (key == null) { return null; } final LRUNode node = getInternal(key); if (node == null) { return null; } updateLRU(node); return node.entry; } NamedCache(final String name, final StreamsMetrics metrics); long size(); }
@Test public void shouldReturnNullIfKeyIsNull() throws Exception { assertNull(cache.get(null)); }
CachingWindowStore extends WrappedStateStore.AbstractStateStore implements WindowStore<K, V>, CachedStateStore<Windowed<K>, V> { @Override public synchronized WindowStoreIterator<V> fetch(final K key, final long timeFrom, final long timeTo) { validateStoreOpen(); final Bytes keyBytes = Bytes.wrap(serdes.rawKey(key)); f...
@Test public void shouldFlushEvictedItemsIntoUnderlyingStore() throws Exception { int added = addItemsToCache(); final KeyValueIterator<Bytes, byte[]> iter = underlying.fetch(Bytes.wrap("0".getBytes()), DEFAULT_TIMESTAMP, DEFAULT_TIMESTAMP); final KeyValue<Bytes, byte[]> next = iter.next(); assertEquals(DEFAULT_TIMESTA...
CachingSessionStore extends WrappedStateStore.AbstractStateStore implements SessionStore<K, AGG>, CachedStateStore<Windowed<K>, AGG> { @Override public KeyValueIterator<Windowed<K>, AGG> fetch(final K key) { return findSessions(key, 0, Long.MAX_VALUE); } CachingSessionStore(final SessionStore<Bytes, byte[]> bytesStore,...
@Test public void shouldFlushItemsToStoreOnEviction() throws Exception { final List<KeyValue<Windowed<String>, Long>> added = addSessionsUntilOverflow("a", "b", "c", "d"); assertEquals(added.size() - 1, cache.size()); final KeyValueIterator<Bytes, byte[]> iterator = underlying.fetch(Bytes.wrap(added.get(0).key.key().ge...
CachingSessionStore extends WrappedStateStore.AbstractStateStore implements SessionStore<K, AGG>, CachedStateStore<Windowed<K>, AGG> { public KeyValueIterator<Windowed<K>, AGG> findSessions(final K key, final long earliestSessionEndTime, final long latestSessionStartTime) { validateStoreOpen(); final Bytes binarySessio...
@Test public void shouldQueryItemsInCacheAndStore() throws Exception { final List<KeyValue<Windowed<String>, Long>> added = addSessionsUntilOverflow("a"); final KeyValueIterator<Windowed<String>, Long> iterator = cachingStore.findSessions("a", 0, added.size() * 10); final List<KeyValue<Windowed<String>, Long>> actual =...
SegmentedCacheFunction implements CacheFunction { @Override public Bytes key(Bytes cacheKey) { return Bytes.wrap(bytesFromCacheKey(cacheKey)); } SegmentedCacheFunction(KeySchema keySchema, long segmentInterval); @Override Bytes key(Bytes cacheKey); @Override Bytes cacheKey(Bytes key); long segmentId(Bytes key); }
@Test public void key() throws Exception { assertThat( cacheFunction.key(THE_CACHE_KEY), equalTo(THE_KEY) ); }
SegmentedCacheFunction implements CacheFunction { @Override public Bytes cacheKey(Bytes key) { final byte[] keyBytes = key.get(); ByteBuffer buf = ByteBuffer.allocate(SEGMENT_ID_BYTES + keyBytes.length); buf.putLong(segmentId(key)).put(keyBytes); return Bytes.wrap(buf.array()); } SegmentedCacheFunction(KeySchema keySch...
@Test public void cacheKey() throws Exception { final long segmentId = TIMESTAMP / SEGMENT_INTERVAL; final Bytes actualCacheKey = cacheFunction.cacheKey(THE_KEY); final ByteBuffer buffer = ByteBuffer.wrap(actualCacheKey.get()); assertThat(buffer.getLong(), equalTo(segmentId)); byte[] actualKey = new byte[buffer.remaini...
SegmentedCacheFunction implements CacheFunction { int compareSegmentedKeys(Bytes cacheKey, Bytes storeKey) { long storeSegmentId = segmentId(storeKey); long cacheSegmentId = ByteBuffer.wrap(cacheKey.get()).getLong(); final int segmentCompare = Long.compare(cacheSegmentId, storeSegmentId); if (segmentCompare == 0) { byt...
@Test public void compareSegmentedKeys() throws Exception { assertThat( "same key in same segment should be ranked the same", cacheFunction.compareSegmentedKeys( cacheFunction.cacheKey(THE_KEY), THE_KEY ) == 0 ); final Bytes sameKeyInPriorSegment = WindowStoreUtils.toBinaryKey(new byte[]{0xA, 0xB, 0xC}, 1234, 42); asse...
ThreadCache { public LRUCacheEntry delete(final String namespace, final Bytes key) { final NamedCache cache = getCache(namespace); if (cache == null) { return null; } return cache.delete(key); } ThreadCache(final String name, long maxCacheSizeBytes, final StreamsMetrics metrics); long puts(); long gets(); long evicts()...
@Test public void shouldNotBlowUpOnNonExistentNamespaceWhenDeleting() throws Exception { final ThreadCache cache = new ThreadCache("testCache", 10000L, new MockStreamsMetrics(new Metrics())); assertNull(cache.delete("name", Bytes.wrap(new byte[]{1}))); }
ThreadCache { public MemoryLRUCacheBytesIterator range(final String namespace, final Bytes from, final Bytes to) { final NamedCache cache = getCache(namespace); if (cache == null) { return new MemoryLRUCacheBytesIterator(Collections.<Bytes>emptyIterator(), new NamedCache(namespace, this.metrics)); } return new MemoryLR...
@Test(expected = NoSuchElementException.class) public void shouldThrowIfNoPeekNextKey() throws Exception { final ThreadCache cache = new ThreadCache("testCache", 10000L, new MockStreamsMetrics(new Metrics())); final ThreadCache.MemoryLRUCacheBytesIterator iterator = cache.range("", Bytes.wrap(new byte[]{0}), Bytes.wrap...
Segments { long segmentId(long timestamp) { return timestamp / segmentInterval; } Segments(final String name, final long retentionPeriod, final int numSegments); void close(); }
@Test public void shouldGetSegmentIdsFromTimestamp() throws Exception { assertEquals(0, segments.segmentId(0)); assertEquals(1, segments.segmentId(60000)); assertEquals(2, segments.segmentId(120000)); assertEquals(3, segments.segmentId(180000)); } @Test public void shouldBaseSegmentIntervalOnRetentionAndNumSegments() t...
Segments { String segmentName(long segmentId) { return name + "-" + formatter.format(new Date(segmentId * segmentInterval)); } Segments(final String name, final long retentionPeriod, final int numSegments); void close(); }
@Test public void shouldGetSegmentNameFromId() throws Exception { assertEquals("test-197001010000", segments.segmentName(0)); assertEquals("test-197001010001", segments.segmentName(1)); assertEquals("test-197001010002", segments.segmentName(2)); }
Segments { Segment getOrCreateSegment(final long segmentId, final ProcessorContext context) { if (segmentId > maxSegmentId - numSegments) { final long key = segmentId % numSegments; final Segment segment = segments.get(key); if (!isSegment(segment, segmentId)) { cleanup(segmentId); } Segment newSegment = new Segment(se...
@Test public void shouldCreateSegments() throws Exception { final Segment segment1 = segments.getOrCreateSegment(0, context); final Segment segment2 = segments.getOrCreateSegment(1, context); final Segment segment3 = segments.getOrCreateSegment(2, context); assertTrue(new File(context.stateDir(), "test/test-19700101000...
CachingKeyValueStore extends WrappedStateStore.AbstractStateStore implements KeyValueStore<K, V>, CachedStateStore<K, V> { @Override public KeyValueIterator<K, V> all() { validateStoreOpen(); final KeyValueIterator<Bytes, byte[]> storeIterator = new DelegatingPeekingKeyValueIterator<>(this.name(), underlying.all()); fi...
@Test public void shouldIterateAllStoredItems() throws Exception { int items = addItemsToCache(); final KeyValueIterator<String, String> all = store.all(); final List<String> results = new ArrayList<>(); while (all.hasNext()) { results.add(all.next().key); } assertEquals(items, results.size()); }
CachingKeyValueStore extends WrappedStateStore.AbstractStateStore implements KeyValueStore<K, V>, CachedStateStore<K, V> { @Override public KeyValueIterator<K, V> range(final K from, final K to) { validateStoreOpen(); final Bytes origFrom = Bytes.wrap(serdes.rawKey(from)); final Bytes origTo = Bytes.wrap(serdes.rawKey(...
@Test public void shouldIterateOverRange() throws Exception { int items = addItemsToCache(); final KeyValueIterator<String, String> range = store.range(String.valueOf(0), String.valueOf(items)); final List<String> results = new ArrayList<>(); while (range.hasNext()) { results.add(range.next().key); } assertEquals(items...
CachingKeyValueStore extends WrappedStateStore.AbstractStateStore implements KeyValueStore<K, V>, CachedStateStore<K, V> { @Override public synchronized V get(final K key) { validateStoreOpen(); if (key == null) { return null; } final byte[] rawKey = serdes.rawKey(key); return get(rawKey); } CachingKeyValueStore(final ...
@Test public void shouldReturnNullIfKeyIsNull() throws Exception { assertNull(store.get(null)); }
SegmentIterator implements KeyValueIterator<Bytes, byte[]> { @Override public Bytes peekNextKey() { if (!hasNext()) { throw new NoSuchElementException(); } return currentIterator.peekNextKey(); } SegmentIterator(final Iterator<Segment> segments, final HasNextCondition hasNextCondition, ...
@Test(expected = NoSuchElementException.class) public void shouldThrowNoSuchElementOnPeekNextKeyIfNoNext() throws Exception { iterator = new SegmentIterator(Arrays.asList(segmentOne, segmentTwo).iterator(), hasNextCondition, Bytes.wrap("f".getBytes()), Bytes.wrap("h".getBytes())); iterator.peekNextKey(); }
SegmentIterator implements KeyValueIterator<Bytes, byte[]> { public KeyValue<Bytes, byte[]> next() { if (!hasNext()) { throw new NoSuchElementException(); } return currentIterator.next(); } SegmentIterator(final Iterator<Segment> segments, final HasNextCondition hasNextCondition, ...
@Test(expected = NoSuchElementException.class) public void shouldThrowNoSuchElementOnNextIfNoNext() throws Exception { iterator = new SegmentIterator(Arrays.asList(segmentOne, segmentTwo).iterator(), hasNextCondition, Bytes.wrap("f".getBytes()), Bytes.wrap("h".getBytes())); iterator.next(); }
CompositeReadOnlyWindowStore implements ReadOnlyWindowStore<K, V> { public <IteratorType extends KeyValueIterator<?, V>> IteratorType fetch(Fetcher<K, V, IteratorType> fetcher) { final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType); for (ReadOnlyWindowStore<K, V> windowStore : stor...
@Test public void shouldFetchValuesFromWindowStore() throws Exception { underlyingWindowStore.put("my-key", "my-value", 0L); underlyingWindowStore.put("my-key", "my-later-value", 10L); final WindowStoreIterator<String> iterator = windowStore.fetch("my-key", 0L, 25L); final List<KeyValue<Long, String>> results = Streams...
FilteredCacheIterator implements PeekingKeyValueIterator<Bytes, LRUCacheEntry> { @Override public void remove() { throw new UnsupportedOperationException(); } FilteredCacheIterator(final PeekingKeyValueIterator<Bytes, LRUCacheEntry> cacheIterator, final HasNextCondition hasNextCondition, ...
@Test(expected = UnsupportedOperationException.class) public void shouldThrowUnsupportedOperationExeceptionOnRemove() throws Exception { allIterator.remove(); }
RocksDBWindowStore extends WrappedStateStore.AbstractStateStore implements WindowStore<K, V> { @Override public WindowStoreIterator<V> fetch(K key, long timeFrom, long timeTo) { final KeyValueIterator<Bytes, byte[]> bytesIterator = bytesStore.fetch(Bytes.wrap(serdes.rawKey(key)), timeFrom, timeTo); return new WindowSto...
@SuppressWarnings("unchecked") @Test public void testPutAndFetch() throws IOException { windowStore = createWindowStore(context, false, true); long startTime = segmentSize - 4L; putFirstBatch(windowStore, startTime, context); assertEquals(Utils.mkList("zero"), toList(windowStore.fetch(0, startTime + 0L - WINDOW_SIZE, s...
ChangeLoggingSegmentedBytesStore extends WrappedStateStore.AbstractStateStore implements SegmentedBytesStore { @Override public KeyValueIterator<Bytes, byte[]> fetch(final Bytes key, final long from, final long to) { return bytesStore.fetch(key, from, to); } ChangeLoggingSegmentedBytesStore(final SegmentedBytesStore by...
@Test public void shouldDelegateToUnderlyingStoreWhenFetching() throws Exception { store.fetch(Bytes.wrap(new byte[0]), 1, 1); assertTrue(bytesStore.fetchCalled); }
WrappingStoreProvider implements StateStoreProvider { public <T> List<T> stores(final String storeName, QueryableStoreType<T> type) { final List<T> allStores = new ArrayList<>(); for (StateStoreProvider provider : storeProviders) { final List<T> stores = provider.stores(storeName, type); allStores.addAll(stores); } if ...
@Test public void shouldFindKeyValueStores() throws Exception { List<ReadOnlyKeyValueStore<String, String>> results = wrappingStoreProvider.stores("kv", QueryableStoreTypes.<String, String>keyValueStore()); assertEquals(2, results.size()); } @Test public void shouldFindWindowStores() throws Exception { final List<ReadO...
ChangeLoggingKeyValueBytesStore extends WrappedStateStore.AbstractStateStore implements KeyValueStore<Bytes, byte[]> { @Override public byte[] putIfAbsent(final Bytes key, final byte[] value) { final byte[] previous = get(key); if (previous == null) { put(key, value); } return previous; } ChangeLoggingKeyValueBytesStor...
@Test public void shouldReturnNullOnPutIfAbsentWhenNoPreviousValue() throws Exception { assertThat(store.putIfAbsent(hi, there), is(nullValue())); }
ChangeLoggingKeyValueBytesStore extends WrappedStateStore.AbstractStateStore implements KeyValueStore<Bytes, byte[]> { @Override public byte[] get(final Bytes key) { return inner.get(key); } ChangeLoggingKeyValueBytesStore(final KeyValueStore<Bytes, byte[]> inner); @Override void init(final ProcessorContext context, fi...
@Test public void shouldReturnNullOnGetWhenDoesntExist() throws Exception { assertThat(store.get(hello), is(nullValue())); }
WindowKeySchema implements RocksDBSegmentedBytesStore.KeySchema { @Override public Bytes upperRange(final Bytes key, final long to) { final byte[] maxSuffix = ByteBuffer.allocate(SUFFIX_SIZE) .putLong(to) .putInt(Integer.MAX_VALUE) .array(); return OrderedBytes.upperRange(key, maxSuffix); } @Override void init(final S...
@Test public void testUpperBoundWithLargeTimestamps() throws Exception { Bytes upper = windowKeySchema.upperRange(Bytes.wrap(new byte[]{0xA, 0xB, 0xC}), Long.MAX_VALUE); assertThat( "shorter key with max timestamp should be in range", upper.compareTo( WindowStoreUtils.toBinaryKey( new byte[]{0xA}, Long.MAX_VALUE, Integ...