index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/restore/RestoreWriteStateEngineListTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.write.restore; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.list.HollowListTypeReadState; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.schema.HollowListSchema; import com.netflix.hollow.core.write.HollowListTypeWriteState; import com.netflix.hollow.core.write.HollowListWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class RestoreWriteStateEngineListTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(1, 2, 3); addRecord(2, 3, 4); addRecord(3, 4, 5); roundTripSnapshot(); addRecord(1, 2, 3); addRecord(3, 4, 5); addRecord(1000, 1001, 1002); roundTripDelta(); assertList(0, 1, 2, 3); restoreWriteStateEngineFromReadStateEngine(); addRecord(1, 2, 3); addRecord(4, 5, 6); addRecord(1000, 1001, 1002); addRecord(1000000, 10001, 10002, 10003, 10004, 10005, 10006, 10007); roundTripDelta(); Assert.assertEquals(4, readStateEngine.getTypeState("TestList").maxOrdinal()); assertList(0, 1, 2, 3); assertList(1, 4, 5, 6); assertList(3, 1000, 1001, 1002); assertList(4, 1000000, 10001, 10002, 10003, 10004, 10005, 10006, 10007); addRecord(1000, 1001, 1002); roundTripDelta(); Assert.assertEquals(4, readStateEngine.getTypeState("TestList").maxOrdinal()); roundTripDelta(); Assert.assertEquals(3, readStateEngine.getTypeState("TestList").maxOrdinal()); } @Test public void restoreFailsIfShardConfigurationChanges() throws IOException { roundTripSnapshot(); HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowListTypeWriteState misconfiguredTypeState = new HollowListTypeWriteState(new HollowListSchema("TestList", "TestObject"), 16); writeStateEngine.addTypeState(misconfiguredTypeState); try { writeStateEngine.restoreFrom(readStateEngine); Assert.fail("Should have thrown IllegalStateException because shard configuration has changed"); } catch(IllegalStateException expected) { } } private void addRecord(int... ordinals) { HollowListWriteRecord rec = new HollowListWriteRecord(); for(int i=0;i<ordinals.length;i++) { rec.addElement(ordinals[i]); } writeStateEngine.add("TestList", rec); } private void assertList(int ordinal, int... elements) { HollowListTypeReadState readState = (HollowListTypeReadState) readStateEngine.getTypeState("TestList"); HollowOrdinalIterator iter = readState.ordinalIterator(ordinal); for(int i=0;i<elements.length;i++) { Assert.assertEquals(elements[i], iter.next()); } Assert.assertEquals(HollowOrdinalIterator.NO_MORE_ORDINALS, iter.next()); } @Override protected void initializeTypeStates() { HollowListTypeWriteState writeState = new HollowListTypeWriteState(new HollowListSchema("TestList", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,700
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/restore/RestoreWriteStateEngineObjectTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.write.restore; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class RestoreWriteStateEngineObjectTest extends AbstractStateEngineTest { private HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); super.setUp(); } @Test public void test() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); roundTripSnapshot(); addRecord(1, "one"); addRecord(3, "three"); addRecord(1000, "one thousand"); roundTripDelta(); restoreWriteStateEngineFromReadStateEngine(); addRecord(1, "one"); addRecord(4, "four"); addRecord(1000, "one thousand"); addRecord(1000000, "one million"); roundTripDelta(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 0, 1, "one"); assertObject(typeState, 1, 4, "four"); assertObject(typeState, 2, 3, "three"); /// ghost assertObject(typeState, 3, 1000, "one thousand"); assertObject(typeState, 4, 1000000, "one million"); addRecord(1, "one"); addRecord(4, "four"); addRecord(1000, "one thousand"); addRecord(1000000, "one million"); addRecord(20, "twenty"); roundTripDelta(); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 1, 4, "four"); assertObject(typeState, 2, 20, "twenty"); assertObject(typeState, 3, 1000, "one thousand"); } @Test public void restoreFailsIfShardConfigurationChanges() throws IOException { roundTripSnapshot(); HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectTypeWriteState misconfiguredTypeState = new HollowObjectTypeWriteState(schema, 4); writeStateEngine.addTypeState(misconfiguredTypeState); try { writeStateEngine.restoreFrom(readStateEngine); Assert.fail("Should have thrown IllegalStateException because shard configuration has changed"); } catch(IllegalStateException expected) { } } private void addRecord(int intVal, String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", intVal); rec.setString("f2", strVal); writeStateEngine.add("TestObject", rec); } private void assertObject(HollowObjectTypeReadState readState, int ordinal, int intVal, String strVal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); Assert.assertEquals(intVal, obj.getInt("f1")); Assert.assertEquals(strVal, obj.getString("f2")); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,701
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/restore/RestoreWriteStateEngineSetTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.write.restore; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.set.HollowSetTypeReadState; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class RestoreWriteStateEngineSetTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(1, 2, 3); addRecord(2, 3, 4); addRecord(3, 4, 5); roundTripSnapshot(); addRecord(1, 2, 3); addRecord(3, 4, 5); addRecord(1000, 1001, 1002); roundTripDelta(); assertSet(1, 2, 3, 4); restoreWriteStateEngineFromReadStateEngine(); addRecord(1, 2, 3); addRecord(4, 5, 6); addRecord(1000, 1001, 1002); addRecord(1000000, 10001, 10002, 10003, 10004, 10005, 10006, 10007); roundTripDelta(); Assert.assertEquals(4, readStateEngine.getTypeState("TestSet").maxOrdinal()); assertSet(0, 1, 2, 3); assertSet(1, 4, 5, 6); assertSet(3, 1000, 1001, 1002); assertSet(4, 1000000, 10001, 10002, 10003, 10004, 10005, 10006, 10007); addRecord(1000, 1001, 1002); roundTripDelta(); Assert.assertEquals(4, readStateEngine.getTypeState("TestSet").maxOrdinal()); roundTripDelta(); Assert.assertEquals(3, readStateEngine.getTypeState("TestSet").maxOrdinal()); } @Test public void restoreFailsIfShardConfigurationChanges() throws IOException { roundTripSnapshot(); HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowSetTypeWriteState misconfiguredTypeState = new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject"), 16); writeStateEngine.addTypeState(misconfiguredTypeState); try { writeStateEngine.restoreFrom(readStateEngine); Assert.fail("Should have thrown IllegalStateException because shard configuration has changed"); } catch(IllegalStateException expected) { } } private void addRecord(int... ordinals) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int i=0;i<ordinals.length;i++) { rec.addElement(ordinals[i], ordinals[i] + 10); // the hash code is deliberately specified here as different from the ordinal. } writeStateEngine.add("TestSet", rec); } private void assertSet(int ordinal, int... elements) { HollowSetTypeReadState readState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); Assert.assertEquals(elements.length, readState.size(ordinal)); for(int element : elements) { if(!readState.contains(ordinal, element, element + 10)) { // the hash code is deliberately specified here as different from the ordinal. Assert.fail("Set did not contain element: " + element); } } } @Override protected void initializeTypeStates() { HollowSetTypeWriteState writeState = new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,702
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/restore/RestoreWriteStateEngineSetReverseDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.write.restore; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.HollowBlobInput; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.set.HollowSetTypeReadState; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class RestoreWriteStateEngineSetReverseDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(1, 3, 2, 2); roundTripSnapshot(); assertSetContains(0, 1, 3); assertSetContains(0, 2, 2); restoreWriteStateEngineFromReadStateEngine(); addRecord(3, 3, 4, 4); writeStateEngine.prepareForWrite(); ByteArrayOutputStream reverseDeltaStream = new ByteArrayOutputStream(); ByteArrayOutputStream deltaStream = new ByteArrayOutputStream(); HollowBlobWriter writer = new HollowBlobWriter(writeStateEngine); writer.writeReverseDelta(reverseDeltaStream); writer.writeDelta(deltaStream); HollowBlobReader reader = new HollowBlobReader(readStateEngine); reader.applyDelta(HollowBlobInput.serial(deltaStream.toByteArray())); reader.applyDelta(HollowBlobInput.serial(reverseDeltaStream.toByteArray())); assertSetContains(0, 1, 3); assertSetContains(0, 2, 2); } private void assertSetContains(int setOrdinal, int valueOrdinal, int hashCode) { HollowSetTypeReadState typeState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); Assert.assertTrue(typeState.contains(setOrdinal, valueOrdinal, hashCode)); } private void addRecord(int... ordinalsAndHashCodes) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int i=0;i<ordinalsAndHashCodes.length;i+=2) { rec.addElement(ordinalsAndHashCodes[i], ordinalsAndHashCodes[i+1]); } writeStateEngine.add("TestSet", rec); } @Override protected void initializeTypeStates() { HollowSetTypeWriteState writeState = new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,703
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/ByteArrayOrdinalTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.memory; import org.junit.Assert; import org.junit.Test; public class ByteArrayOrdinalTest { @Test public void testResize() { ByteArrayOrdinalMap m = new ByteArrayOrdinalMap(); int[] ordinals = new int[179]; for (int i = 0; i < ordinals.length; i++) { ordinals[i] = m.getOrAssignOrdinal(createBuffer("TEST" + i)); } m.resize(4096); int[] newOrdinals = new int[ordinals.length]; for (int i = 0; i < ordinals.length; i++) { newOrdinals[i] = m.get(createBuffer("TEST" + i)); } Assert.assertArrayEquals(ordinals, newOrdinals); } @Test public void testResizeWhenEmpty() { ByteArrayOrdinalMap m = new ByteArrayOrdinalMap(); m.resize(4096); int[] ordinals = new int[179]; for (int i = 0; i < ordinals.length; i++) { ordinals[i] = m.getOrAssignOrdinal(createBuffer("TEST" + i)); } m.resize(16384); int[] newOrdinals = new int[ordinals.length]; for (int i = 0; i < ordinals.length; i++) { newOrdinals[i] = m.get(createBuffer("TEST" + i)); } Assert.assertArrayEquals(ordinals, newOrdinals); } static ByteDataArray createBuffer(String s) { return write(new ByteDataArray(), s); } static ByteDataArray write(ByteDataArray bdb, String s) { for (byte b : s.getBytes()) { bdb.write(b); } return bdb; } }
8,704
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/FreeOrdinalTrackerTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.memory; import org.junit.Assert; import org.junit.Test; public class FreeOrdinalTrackerTest { @Test public void minimizeNumberOfUpdatedShards() { FreeOrdinalTracker tracker = new FreeOrdinalTracker(); for(int i=0;i<100;i++) tracker.getFreeOrdinal(); // shard 3 tracker.returnOrdinalToPool(15); // shard 1 tracker.returnOrdinalToPool(13); tracker.returnOrdinalToPool(9); tracker.returnOrdinalToPool(17); tracker.returnOrdinalToPool(5); tracker.returnOrdinalToPool(1); tracker.returnOrdinalToPool(21); // shard 2 tracker.returnOrdinalToPool(2); tracker.returnOrdinalToPool(10); tracker.returnOrdinalToPool(14); /// sort for 4 shards tracker.sort(4); Assert.assertEquals(1, tracker.getFreeOrdinal()); Assert.assertEquals(5, tracker.getFreeOrdinal()); Assert.assertEquals(9, tracker.getFreeOrdinal()); Assert.assertEquals(13, tracker.getFreeOrdinal()); Assert.assertEquals(17, tracker.getFreeOrdinal()); Assert.assertEquals(21, tracker.getFreeOrdinal()); Assert.assertEquals(2, tracker.getFreeOrdinal()); Assert.assertEquals(10, tracker.getFreeOrdinal()); Assert.assertEquals(14, tracker.getFreeOrdinal()); Assert.assertEquals(15, tracker.getFreeOrdinal()); Assert.assertEquals(100, tracker.getFreeOrdinal()); Assert.assertEquals(101, tracker.getFreeOrdinal()); } }
8,705
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/ThreadSafeBitSetTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.core.memory; import java.util.BitSet; import org.junit.Assert; import org.junit.Test; public class ThreadSafeBitSetTest { @Test public void testEquality() { ThreadSafeBitSet set1 = new ThreadSafeBitSet(); ThreadSafeBitSet set2 = new ThreadSafeBitSet(14, 16385); set1.set(100); set2.set(100); Assert.assertEquals(set1, set2); Assert.assertEquals(set2, set1); set1.set(100000); Assert.assertNotEquals(set1, set2); Assert.assertNotEquals(set2, set1); set1.clearAll(); Assert.assertNotEquals(set1, set2); Assert.assertNotEquals(set2, set1); set1.set(100); Assert.assertEquals(set1, set2); Assert.assertEquals(set2, set1); } @Test public void testMaxSetBit() { ThreadSafeBitSet set1 = new ThreadSafeBitSet(); set1.set(100); Assert.assertEquals(100, set1.maxSetBit()); set1.set(100000); Assert.assertEquals(100000, set1.maxSetBit()); set1.set(1000000); Assert.assertEquals(1000000, set1.maxSetBit()); set1.clearAll(); set1.set(555555); Assert.assertEquals(555555, set1.maxSetBit()); } @Test public void testNextSetBit() { ThreadSafeBitSet set1 = new ThreadSafeBitSet(); set1.set(100); set1.set(101); set1.set(103); set1.set(100000); set1.set(1000000); Assert.assertEquals(100, set1.nextSetBit(0)); Assert.assertEquals(101, set1.nextSetBit(101)); Assert.assertEquals(103, set1.nextSetBit(102)); Assert.assertEquals(100000, set1.nextSetBit(104)); Assert.assertEquals(1000000, set1.nextSetBit(100001)); Assert.assertEquals(-1, set1.nextSetBit(1000001)); Assert.assertEquals(-1, set1.nextSetBit(1015809)); set1.clearAll(); set1.set(555555); Assert.assertEquals(555555, set1.nextSetBit(0)); Assert.assertEquals(-1, set1.nextSetBit(555556)); } @Test public void testClear() { ThreadSafeBitSet set1 = new ThreadSafeBitSet(); set1.set(10); set1.set(20); set1.set(21); set1.set(22); set1.clear(21); Assert.assertEquals(3, set1.cardinality()); } @Test public void testBasicAPIs() { ThreadSafeBitSet tsbSet = new ThreadSafeBitSet(); int[] ordinals = new int[] { 1, 5, 10 }; // init for (int ordinal : ordinals) { tsbSet.set(ordinal); } // validate content for (int ordinal : ordinals) { Assert.assertTrue(tsbSet.get(ordinal)); } Assert.assertEquals(ordinals.length, tsbSet.cardinality()); tsbSet.clear(ordinals[0]); Assert.assertFalse(tsbSet.get(0)); Assert.assertEquals(ordinals.length - 1, tsbSet.cardinality()); } @Test public void testToBitSet() { BitSet bSet = new BitSet(); ThreadSafeBitSet tsbSet = new ThreadSafeBitSet(); int[] ordinals = new int[] { 1, 5, 10 }; // init for (int ordinal : ordinals) { bSet.set(ordinal); tsbSet.set(ordinal); } // validate content for (int ordinal : ordinals) { Assert.assertEquals(bSet.get(ordinal), tsbSet.get(ordinal)); } Assert.assertEquals(bSet.cardinality(), tsbSet.cardinality()); // compare toBitSet BitSet bSet2 = tsbSet.toBitSet(); Assert.assertEquals(bSet, bSet2); // compare toString Assert.assertEquals(bSet.toString(), bSet.toString()); } @Test public void testOrAll() { BitSet bSet = new BitSet(); ThreadSafeBitSet[] tsbSets = new ThreadSafeBitSet[3]; int[] ordinals = new int[] { 1, 5, 10 }; // init int i = 0; for (int ordinal : ordinals) { tsbSets[i] = new ThreadSafeBitSet(); tsbSets[i].set(ordinal); i++; bSet.set(ordinal); } // validate content ThreadSafeBitSet result = ThreadSafeBitSet.orAll(tsbSets); Assert.assertEquals(bSet.cardinality(), result.cardinality()); Assert.assertEquals(bSet, result.toBitSet()); } @Test public void testAndNot() { ThreadSafeBitSet tsbSet1 = new ThreadSafeBitSet(); ThreadSafeBitSet tsbSet2 = new ThreadSafeBitSet(); for (int i = 0; i < 3; i++) { tsbSet1.set(i); tsbSet2.set(i * 2); } // determine andNot BitSet andNot_bSet = new BitSet(); ThreadSafeBitSet andNot_tsbSet = new ThreadSafeBitSet(); int ordinal = tsbSet1.nextSetBit(0); while (ordinal != -1) { if (!tsbSet2.get(ordinal)) { andNot_bSet.set(ordinal); andNot_tsbSet.set(ordinal); } ordinal = tsbSet1.nextSetBit(ordinal + 1); } Assert.assertFalse(tsbSet1.equals(tsbSet2)); Assert.assertNotEquals(tsbSet1, tsbSet2); Assert.assertNotEquals(tsbSet1.toBitSet(), tsbSet2.toBitSet()); // validate content ThreadSafeBitSet result = tsbSet1.andNot(tsbSet2); Assert.assertEquals(andNot_tsbSet.cardinality(), result.cardinality()); Assert.assertTrue(andNot_tsbSet.equals(result)); Assert.assertEquals(andNot_tsbSet, result); Assert.assertEquals(andNot_bSet, result.toBitSet()); } }
8,706
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/encoding/VarIntTest.java
package com.netflix.hollow.core.memory.encoding; import com.netflix.hollow.core.read.HollowBlobInput; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import org.junit.Assert; import org.junit.Test; public class VarIntTest { private final static byte[] BYTES_EMPTY = new byte[]{}; private final static byte[] BYTES_TRUNCATED = new byte[]{(byte) 0x81}; private final static byte[] BYTES_VALUE_129 = new byte[]{(byte) 0x81, (byte) 0x01}; @Test public void testReadVLongInputStream() throws IOException { InputStream is = new ByteArrayInputStream(BYTES_VALUE_129); Assert.assertEquals(129, VarInt.readVLong(is)); } @Test public void testVLongByteArray() throws IOException { long value = 129L; byte[] serialized = new byte[VarInt.sizeOfVLong(value)]; VarInt.writeVLong(serialized, 0, value); Assert.assertEquals(VarInt.sizeOfVLong(value), VarInt.nextVLongSize(serialized, 0)); Assert.assertEquals(value, VarInt.readVLong(serialized, 0)); } @Test(expected = EOFException.class) public void testReadVLongEmptyInputStream() throws IOException { InputStream is = new ByteArrayInputStream(BYTES_EMPTY); VarInt.readVLong(is); } @Test(expected = EOFException.class) public void testReadVLongTruncatedInputStream() throws IOException { InputStream is = new ByteArrayInputStream(BYTES_TRUNCATED); VarInt.readVLong(is); } @Test public void testReadVIntInputStream() throws IOException { InputStream is = new ByteArrayInputStream(BYTES_VALUE_129); Assert.assertEquals(129, VarInt.readVInt(is)); } @Test(expected = EOFException.class) public void testReadVIntEmptyInputStream() throws IOException { InputStream is = new ByteArrayInputStream(BYTES_EMPTY); VarInt.readVInt(is); } @Test(expected = EOFException.class) public void testReadVIntTruncatedInputStream() throws IOException { InputStream is = new ByteArrayInputStream(BYTES_TRUNCATED); VarInt.readVInt(is); } @Test public void testReadVLongHollowBlobInput() throws IOException { HollowBlobInput hbi = HollowBlobInput.serial(BYTES_VALUE_129); Assert.assertEquals(129l, VarInt.readVLong(hbi)); } @Test(expected = EOFException.class) public void testReadVLongEmptyHollowBlobInput() throws IOException { HollowBlobInput hbi = HollowBlobInput.serial(BYTES_EMPTY); VarInt.readVLong(hbi); } @Test(expected = EOFException.class) public void testReadVLongTruncatedHollowBlobInput() throws IOException { HollowBlobInput hbi = HollowBlobInput.serial(BYTES_TRUNCATED); VarInt.readVLong(hbi); } @Test public void testReadVIntHollowBlobInput() throws IOException { HollowBlobInput hbi = HollowBlobInput.serial(BYTES_VALUE_129); Assert.assertEquals(129l, VarInt.readVInt(hbi)); } @Test public void testVIntByteArray() throws IOException { int value = 129; byte[] serialized = new byte[VarInt.sizeOfVInt(value)]; VarInt.writeVInt(serialized, 0, value); Assert.assertEquals(value, VarInt.readVInt(serialized, 0)); } @Test(expected = EOFException.class) public void testReadVIntEmptyHollowBlobInput() throws IOException { HollowBlobInput hbi = HollowBlobInput.serial(BYTES_EMPTY); VarInt.readVInt(hbi); } @Test(expected = EOFException.class) public void testReadVIntTruncatedHollowBlobInput() throws IOException { HollowBlobInput hbi = HollowBlobInput.serial(BYTES_TRUNCATED); VarInt.readVInt(hbi); } @Test public void testVNullByteArray() throws IOException { byte[] serialized = new byte[1]; VarInt.writeVNull(serialized, 0); Assert.assertTrue(VarInt.readVNull(serialized, 0)); Assert.assertFalse(VarInt.readVNull(new byte[1], 0)); } }
8,707
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/encoding/FixedLengthElementArrayTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.memory.encoding; import com.netflix.hollow.core.memory.FixedLengthData; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import java.util.Random; import org.junit.Assert; import org.junit.Test; public class FixedLengthElementArrayTest { @Test public void testSetAndGet() { int testValue = 53215; int numBitsPerElement = 17; long bitMask = (1L << numBitsPerElement) - 1; FixedLengthElementArray arr = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 17000000); for(int i=0;i<1000000;i++) { arr.setElementValue(i*numBitsPerElement, numBitsPerElement, testValue); } for(int j=0;j<100;j++) { for(int i=0;i<1000000;i++) { if(testValue != arr.getElementValue(i*numBitsPerElement, numBitsPerElement, bitMask)) Assert.fail(); } } } /** * This test demonstrates that reading a 59 bit wide value will fail when the bit address is unaligned by * 6 or 7 bits (59+6=65, 59+7=66). Previously the FixedLengthElementArray documentation claimed that 60 bit values * were supported. */ @Test public void testGetOverflow() { long testValue = 288_230_376_151_711_744l; // smallest 59 bit number int numBitsPerElement = 59; // Populate ordinals 0-7 FixedLengthElementArray arr = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 64*10); for(int i=0;i<8;i++) { arr.setElementValue(i*numBitsPerElement, numBitsPerElement, testValue); } // Validate address of ordinal 2 is unaligned by 6 bits long offset_ord2 = 2 * numBitsPerElement; if(offset_ord2 % 8 != 6) { Assert.fail(); } // Validate address of ordinal 5 is unaligned by 7 bits long offset_ord5 = 5 * numBitsPerElement; if(offset_ord5 % 8 != 7) { Assert.fail(); } // Show value is incorrect when reading ordinal 2 long value_ord2 = arr.getElementValue(offset_ord2, numBitsPerElement); if(value_ord2 == testValue) { Assert.fail(); } // Show value is incorrect when reading ordinal 5 long value_ord5 = arr.getElementValue(offset_ord2, numBitsPerElement); if(value_ord5 == testValue) { Assert.fail(); } // Show value is correct when reading other ordinals for(int i=0; i<8; i++) { if(i!=2 && i!=5) { long value = arr.getElementValue(i * numBitsPerElement, numBitsPerElement); if (value != testValue) { Assert.fail(); } } } } /** * This test demonstrates that reading 2 values with a single read when the values are 29 bits wide will cause * an overflow when the bit offset is unaligned by 7 bits (29+29+7=65). This technique was previously used in the * HollowListTypeReadStateShard class. */ @Test public void testMultiGetOverflow() { long testValue = 268_435_456l; // smallest 29 bit number int numBitsPerElement = 29; // Populate ordinals 0-5 FixedLengthElementArray arr = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 64*10); for(int i=0;i<6;i++) { arr.setElementValue(i*numBitsPerElement, numBitsPerElement, testValue); } // Validate address of ordinal 3 is unaligned by 7 bits long bitOffset = 3 * numBitsPerElement; if(bitOffset % 8 != 7) { Assert.fail(); } // Read 2 values at once (ordinals 3 and 4) long multiValue = arr.getElementValue(bitOffset, numBitsPerElement*2); // Show second value is incorrect due to overflow when reading 2 values long secondValue = multiValue >> numBitsPerElement; if(secondValue == testValue) { Assert.fail(); } // Show first value is correct when reading single value long firstValue = arr.getElementValue(bitOffset, numBitsPerElement); if(firstValue != testValue) { Assert.fail(); } // Show second value is correct when reading single value secondValue = arr.getElementValue(bitOffset+numBitsPerElement, numBitsPerElement); if(secondValue != testValue) { Assert.fail(); } } /** * This test demonstrates that reading 2 values with a single read when teh values are 27 bits wide will work as * expected, even when the bit offset is unaligned by 7 bits (27+27+7=61). This technique was previously used in the * HollowListTypeReadStateShard class. */ @Test public void testMultiGetNoOverflow() { long testValue = 134_217_727l; // largest 27 bit number int numBitsPerElement = 27; // Populate ordinals 0-7 FixedLengthElementArray arr = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 64*10); for(int i=0;i<8;i++) { arr.setElementValue(i*numBitsPerElement, numBitsPerElement, testValue); } // Validate address of ordinal 5 is unaligned by 7 bits long bitOffset = 5 * numBitsPerElement; if(bitOffset % 8 != 7) { Assert.fail(); } // Read 2 values at once (ordinals 5 and 6) long multiValue = arr.getElementValue(bitOffset, numBitsPerElement*2); // Validate second value is correct (no overflow) long secondValue = multiValue >> numBitsPerElement; if(secondValue != testValue) { Assert.fail(); } } @Test public void testGetEmpty() { FixedLengthElementArray arr = new FixedLengthElementArray( WastefulRecycler.SMALL_ARRAY_RECYCLER, 17000); Assert.assertEquals(0, arr.getElementValue(0, 4)); } @Test public void testSetAndGetLargeValues() { long testValue = 1913684435138312210L; int numBitsPerElement = 61; FixedLengthElementArray arr = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 610000); for(int i=0;i<10000;i++) { arr.setElementValue(i*numBitsPerElement, numBitsPerElement, testValue); } for(int j=0;j<100;j++) { for(int i=0;i<10000;i++) { if(testValue != arr.getLargeElementValue(i*numBitsPerElement, numBitsPerElement)) Assert.fail(); } } } @Test public void testCopyBitRange() { for(int iteration = 0;iteration < 100;iteration++) { if(iteration % 1024 == 1023) System.out.println(iteration); Random rand = new Random(); int totalBitsInArray = rand.nextInt(6400000); int totalBitsInCopyRange = rand.nextInt(totalBitsInArray); int copyFromRangeStartBit = rand.nextInt(totalBitsInArray - totalBitsInCopyRange); int copyToRangeStartBit = rand.nextInt(100000); FixedLengthElementArray source = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, totalBitsInArray + 64); FixedLengthElementArray dest = new FixedLengthElementArray(WastefulRecycler.DEFAULT_INSTANCE, totalBitsInArray + copyToRangeStartBit); int numLongs = (totalBitsInArray >>> 6); for(int i=0;i<=numLongs;i++) { source.set(i, rand.nextLong()); } dest.copyBits(source, copyFromRangeStartBit, copyToRangeStartBit, totalBitsInCopyRange); /// compare the copy range. int compareBitStart = copyFromRangeStartBit; int copyToRangeOffset = copyToRangeStartBit - copyFromRangeStartBit; int numBitsLeftToCompare = totalBitsInCopyRange; while(numBitsLeftToCompare > 0) { int bitsToCompare = numBitsLeftToCompare > 56 ? 56 : numBitsLeftToCompare; long fromLong = source.getElementValue(compareBitStart, bitsToCompare); long toLong = dest.getElementValue(compareBitStart + copyToRangeOffset, bitsToCompare); if(fromLong != toLong) Assert.fail(); numBitsLeftToCompare -= bitsToCompare; compareBitStart += bitsToCompare; } } } @Test public void testCopySmallBitRange() { FixedLengthElementArray arrFrom = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 64); FixedLengthElementArray arrTo = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 128); arrFrom.setElementValue(0, 64, -1L); arrTo.copyBits(arrFrom, 10, 10, 10); Assert.assertEquals(0, arrTo.getElementValue(0, 10)); Assert.assertEquals(1023, arrTo.getElementValue(10, 10)); Assert.assertEquals(0, arrTo.getLargeElementValue(20, 10)); } @Test public void testIncrement() { FixedLengthElementArray arr = new FixedLengthElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER, 1000000); Random rand = new Random(); long startVal = rand.nextInt(Integer.MAX_VALUE); int elementCount = 0; for(int i=0;i<1000000;i+=65) { arr.setElementValue(i, 60, startVal+i); elementCount++; } arr.incrementMany(0, 1000, 65, elementCount); for(int i=0;i<1000000;i+=65) { long val = arr.getElementValue(i, 60); Assert.assertEquals(startVal + i + 1000, val); } arr.incrementMany(0, -2000, 65, elementCount); for(int i=0;i<1000000;i+=65) { long val = arr.getElementValue(i, 60); Assert.assertEquals(startVal + i - 1000, val); } } @Test public void doesNotThrowSIGSEGV() { FixedLengthElementArray arr = new FixedLengthElementArray(new WastefulRecycler(2, 2), 1793); for(int i=0;i<2500;i++) { try { arr.setElementValue(i, 2, 3); } catch(ArrayIndexOutOfBoundsException acceptable) { } } } @Test public void testArrayIndexOutOfBoundsEdgeCase() { FixedLengthElementArray arr = new FixedLengthElementArray(new WastefulRecycler(2, 2), 256); arr.copyBits(arr, 256, 10, 0); } @Test public void convenienceMethodForNumberOfBitsRequiredForValue() { Assert.assertEquals(1, FixedLengthData.bitsRequiredToRepresentValue(0)); Assert.assertEquals(1, FixedLengthData.bitsRequiredToRepresentValue(1)); Assert.assertEquals(2, FixedLengthData.bitsRequiredToRepresentValue(2)); Assert.assertEquals(2, FixedLengthData.bitsRequiredToRepresentValue(3)); Assert.assertEquals(3, FixedLengthData.bitsRequiredToRepresentValue(4)); Assert.assertEquals(5, FixedLengthData.bitsRequiredToRepresentValue(16)); Assert.assertEquals(5, FixedLengthData.bitsRequiredToRepresentValue(31)); Assert.assertEquals(63, FixedLengthData.bitsRequiredToRepresentValue(Long.MAX_VALUE)); } }
8,708
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/encoding/GapEncodedVariableLengthIntegerReaderTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.memory.encoding; import static com.netflix.hollow.core.memory.encoding.GapEncodedVariableLengthIntegerReader.EMPTY_READER; import static org.junit.Assert.assertEquals; import com.netflix.hollow.core.memory.ByteDataArray; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import java.util.function.Supplier; import org.junit.Assert; import org.junit.Test; public class GapEncodedVariableLengthIntegerReaderTest { @Test public void returnsValues() { GapEncodedVariableLengthIntegerReader reader = reader(1, 10, 100, 105, 107, 200); assertValues(reader, 1, 10, 100, 105, 107, 200); reader.reset(); assertValues(reader, 1, 10, 100, 105, 107, 200); } @Test public void testEmpty() { GapEncodedVariableLengthIntegerReader reader = reader(20); Assert.assertFalse(reader.isEmpty()); reader = reader(); Assert.assertTrue(reader.isEmpty()); Assert.assertTrue(EMPTY_READER.isEmpty()); } @Test public void testCombine() { GapEncodedVariableLengthIntegerReader reader1 = reader(1, 10, 100, 105, 107, 200); GapEncodedVariableLengthIntegerReader reader2 = reader(5, 76, 100, 102, 109, 197, 198, 199, 200, 201); GapEncodedVariableLengthIntegerReader combined = GapEncodedVariableLengthIntegerReader.combine(reader1, reader2, WastefulRecycler.SMALL_ARRAY_RECYCLER); assertValues(combined, 1, 5, 10, 76, 100, 102, 105, 107, 109, 197, 198, 199, 200, 201); } @Test public void testJoin() { GapEncodedVariableLengthIntegerReader[] from = new GapEncodedVariableLengthIntegerReader[2]; from[0] = reader(1, 10, 100, 105, 107, 200); from[1] = reader(5, 76, 100, 102, 109, 200, 201); GapEncodedVariableLengthIntegerReader joined = GapEncodedVariableLengthIntegerReader.join(from); assertValues(joined, 2, 11, 20, 153, 200, 201, 205, 210, 214, 219, 400, 401, 403); GapEncodedVariableLengthIntegerReader[] from4 = new GapEncodedVariableLengthIntegerReader[4]; from4[0] = reader(0, 1, 2, 3); from4[1] = null; from4[2] = reader(3); from4[3] = EMPTY_READER; GapEncodedVariableLengthIntegerReader joined4 = GapEncodedVariableLengthIntegerReader.join(from4); assertValues(joined4, 0, 4, 8, 12, 14); // splitOrdinal 3, in splitIndex 2 of numSplits 4 => 3*4+2 GapEncodedVariableLengthIntegerReader[] empties = new GapEncodedVariableLengthIntegerReader[] {EMPTY_READER, EMPTY_READER}; GapEncodedVariableLengthIntegerReader joinedEmpties = GapEncodedVariableLengthIntegerReader.join(empties); assertEquals(EMPTY_READER, joinedEmpties); GapEncodedVariableLengthIntegerReader[] nulls = new GapEncodedVariableLengthIntegerReader[] {null, null}; GapEncodedVariableLengthIntegerReader joinedNulls = GapEncodedVariableLengthIntegerReader.join(nulls); assertEquals(EMPTY_READER, joinedNulls); GapEncodedVariableLengthIntegerReader[] from1 = new GapEncodedVariableLengthIntegerReader[1]; from1[0] = reader(1, 10, 100, 105, 107, 200); GapEncodedVariableLengthIntegerReader joined1 = GapEncodedVariableLengthIntegerReader.join(from1); assertValues(joined1, 1, 10, 100, 105, 107, 200); assertIllegalStateException(() -> GapEncodedVariableLengthIntegerReader.join(null)); } @Test public void testSplit() { GapEncodedVariableLengthIntegerReader reader = reader(1, 10, 100, 105, 107, 200); GapEncodedVariableLengthIntegerReader[] splitBy2 = reader.split(2); assertEquals(2, splitBy2.length); assertValues(splitBy2[0], 5, 50, 100); // (split[i]*numSplits + i) is the original ordinal assertValues(splitBy2[1], 0, 52, 53); GapEncodedVariableLengthIntegerReader[] splitBy256 = reader.split(256); assertEquals(256, splitBy256.length); assertValues(splitBy256[1], 0); assertValues(splitBy256[200], 0); assertEquals(EMPTY_READER, splitBy256[0]); assertEquals(EMPTY_READER, splitBy256[255]); GapEncodedVariableLengthIntegerReader[] splitBy2Empty = EMPTY_READER.split(2); assertEquals(2, splitBy2Empty.length); assertEquals(EMPTY_READER, splitBy2Empty[0]); assertEquals(EMPTY_READER, splitBy2Empty[1]); assertIllegalStateException(() ->reader.split(0)); assertIllegalStateException(() -> reader.split(3)); } private GapEncodedVariableLengthIntegerReader reader(int... values) { ByteDataArray arr = new ByteDataArray(WastefulRecycler.SMALL_ARRAY_RECYCLER); int cur = 0; for(int i=0;i<values.length;i++) { VarInt.writeVInt(arr, values[i] - cur); cur = values[i]; } return new GapEncodedVariableLengthIntegerReader(arr.getUnderlyingArray(), (int) arr.length()); } private void assertValues(GapEncodedVariableLengthIntegerReader reader, int... expectedValues) { for(int i=0;i<expectedValues.length;i++) { assertEquals(expectedValues[i], reader.nextElement()); reader.advance(); } assertEquals(Integer.MAX_VALUE, reader.nextElement()); } private void assertIllegalStateException(Supplier<?> invocation) { try { invocation.get(); Assert.fail(); } catch (IllegalStateException e) { // expected } } }
8,709
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/encoding/FixedLengthMultipleOccurrenceElementArrayTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.memory.encoding; import static org.junit.Assert.assertEquals; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import java.util.List; import java.util.stream.Collectors; import java.util.stream.LongStream; import org.junit.Before; import org.junit.Test; public class FixedLengthMultipleOccurrenceElementArrayTest { private FixedLengthMultipleOccurrenceElementArray array; @Before public void setUp() { array = new FixedLengthMultipleOccurrenceElementArray( WastefulRecycler.SMALL_ARRAY_RECYCLER, 10000L, 5, 4); } @Test public void testAddAndGet_returnsMultipleNoZero() { List<Long> elements = LongStream.range(1, 4).boxed().collect(Collectors.toList()); elements.forEach(v -> array.addElement(0, v)); assertEquals(elements, array.getElements(0)); } @Test public void testAddAndGet_returnsMultipleWithZero() { List<Long> elements = LongStream.range(0, 3).boxed().collect(Collectors.toList()); elements.forEach(v -> array.addElement(0, v)); assertEquals(elements, array.getElements(0)); } @Test public void testAddAndGet_resizes() { List<Long> elements = LongStream.range(1, 4).boxed().collect(Collectors.toList()); elements.forEach(v -> array.addElement(0, v)); assertEquals(elements, array.getElements(0)); } @Test public void testAddAndGet_multipleNodes() { List<Long> values0 = LongStream.range(0, 4).boxed().collect(Collectors.toList()); List<Long> values1 = LongStream.range(2, 15).boxed().collect(Collectors.toList()); List<Long> values2 = LongStream.range(1, 2).boxed().collect(Collectors.toList()); values0.forEach(v -> array.addElement(0, v)); values1.forEach(v -> array.addElement(1, v)); values2.forEach(v -> array.addElement(2, v)); assertEquals(values0, array.getElements(0)); assertEquals(values1, array.getElements(1)); assertEquals(values2, array.getElements(2)); } @Test public void testLargeNumberOfNodes() { LongStream.range(0, 10000).forEach(nodeIndex -> { List<Long> elements = LongStream.range(0, 31).boxed().collect(Collectors.toList()); elements.forEach(ordinal -> array.addElement(nodeIndex, ordinal)); assertEquals("nodeIndex " + nodeIndex + " should have correct elements", elements, array.getElements(nodeIndex)); }); } }
8,710
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/memory/encoding/OnHeapArrayVsOffHeapBufferAcceptanceTest.java
package com.netflix.hollow.core.memory.encoding; import static org.junit.Assert.assertEquals; import com.netflix.hollow.core.memory.EncodedByteBuffer; import com.netflix.hollow.core.memory.SegmentedByteArray; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import com.netflix.hollow.core.read.HollowBlobInput; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Paths; import org.junit.Assert; import org.junit.Test; /** * Tests parity between on-heap and shared-memory consumer mode by reading test data from on-heap arrays vs. off-heap buffers */ public class OnHeapArrayVsOffHeapBufferAcceptanceTest { private static final String SCRATCH_DIR = System.getProperty("java.io.tmpdir"); private static final int TEST_SINGLE_BUFFER_CAPACITY_BYTES = 16; @Test public void testParityBetweenFixedLengthDataModes() throws IOException { // Add some padding bytes at the beginning of file so that longs are written at unaligned locations int numLongsWritten = 14; // adding padding writes the test longs at a non-aligned byte for (int padding = 0; padding < Long.BYTES; padding ++) { // write a File of TEST_SINGLE_BUFFER_CAPACITY_BYTES*4 size, assuming TEST_SINGLE_BUFFER_CAPACITY_BYTES is 32 File testFile = writeTestFileUnaligned("/fixed_length_data_modes", padding); testFile.deleteOnExit(); readUsingFixedLengthDataModes(testFile, padding, numLongsWritten); } } private void readUsingFixedLengthDataModes(File testFile, int padding, int numLongsWritten) throws IOException { // test read parity between FixedLengthElementArray and EncodedLongBuffer for- // aligned long, // unaligned long, // aligned and at spine boundary long, // unaligned and at spine boundary long, // partly out of bounds long but queried bits are within bounds // partly out of bounds long and queried bits are out of bounds // out of bounds long HollowBlobInput hbi1 = HollowBlobInput.serial(new FileInputStream(testFile)); hbi1.skipBytes(padding + 16); // skip past the first 16 bytes of test data written to file FixedLengthElementArray testLongArray = FixedLengthElementArray.newFrom(hbi1, WastefulRecycler.DEFAULT_INSTANCE, numLongsWritten); HollowBlobInput hbi2 = HollowBlobInput.randomAccess(testFile, TEST_SINGLE_BUFFER_CAPACITY_BYTES); hbi2.skipBytes(padding + 16); // skip past the first 16 bytes of test data written to file EncodedLongBuffer testLongBuffer = EncodedLongBuffer.newFrom(hbi2, numLongsWritten); // read each values starting at each bit index for (int i = 0; i< (numLongsWritten - 1) * Long.BYTES * 8; i ++) { // for bit length 1 to 60 for (int j = 1; j < 61; j ++) { assertEquals(testLongArray.getElementValue(i, j), testLongBuffer.getElementValue(i, j)); } // for bit length 1 to 64 for (int j = 1; j <= 64; j ++) { assertEquals(testLongArray.getLargeElementValue(i, j), testLongBuffer.getLargeElementValue(i, j)); } } // partly out of bounds long but queried bits are within bounds // // get a 15-bit element that is in the last 15 bits of the buffer, but it would enforce an 8-byte long read // starting at the last 2 bytes in buffer but extending past the end of the buffer assertEquals(testLongArray.getElementValue(numLongsWritten * Long.BYTES * 8 - 2 * 8, 16), testLongBuffer.getElementValue(numLongsWritten * Long.BYTES * 8 - 2 * 8, 16)); // partly out of bounds long and queried bits are out of bounds // get a 16-bit element that is in the last 15 bits of the buffer try { testLongBuffer.getElementValue(numLongsWritten * Long.BYTES * 8 - 2 * 8, 17); Assert.fail(); } catch (IllegalStateException e) { // this is expected } catch (Exception e) { Assert.fail(); } // out of bounds long try { testLongBuffer.getElementValue(numLongsWritten * Long.BYTES * 8, 60); Assert.fail(); } catch (IllegalStateException e) { // this is expected } catch (Exception e) { Assert.fail(); } } @Test public void testParityBetweenVariableLengthDataModes() throws IOException { // Add some padding bytes at the beginning of file so that longs are written at unaligned locations // adding padding writes the test longs at a non-aligned byte for (int padding = 0; padding < Long.BYTES; padding ++) { File testFile = writeTestFileUnaligned("/variable_length_data_modes", padding); testFile.deleteOnExit(); readUsingVariableLengthDataModes(testFile, padding); } } private void readUsingVariableLengthDataModes(File testFile, int padding) throws IOException { // test read parity between SegmentedByteArray and EncodedByteBuffer for- // aligned byte, // unaligned byte, // out of bounds byte SegmentedByteArray testByteArray = new SegmentedByteArray(WastefulRecycler.DEFAULT_INSTANCE); testByteArray.loadFrom(HollowBlobInput.serial(new FileInputStream(testFile)), testFile.length()); EncodedByteBuffer testByteBuffer = new EncodedByteBuffer(); testByteBuffer.loadFrom(HollowBlobInput.randomAccess(testFile, TEST_SINGLE_BUFFER_CAPACITY_BYTES), testFile.length()); // aligned bytes - BlobByteBuffer vs. SegmentedByteArray assertEquals(testByteArray.get(0 + padding), testByteBuffer.get(0 + padding)); assertEquals(testByteArray.get(8 + padding), testByteBuffer.get(8 + padding)); assertEquals(testByteArray.get(16 + padding), testByteBuffer.get(16 + padding)); assertEquals(testByteArray.get(23 + padding), testByteBuffer.get(23 + padding)); assertEquals(testByteArray.get(1 + padding), testByteBuffer.get(1 + padding)); // unaligned bytes - BlobByteBuffer vs. SegmentedByteArray assertEquals(testByteArray.get(1 + padding), testByteBuffer.get(1 + padding)); assertEquals(testByteArray.get(13 + padding), testByteBuffer.get(13 + padding)); assertEquals(testByteArray.get(127 + padding), testByteBuffer.get(127 + padding)); // out of bounds read try { testByteBuffer.get(testFile.length()); Assert.fail(); } catch (IllegalStateException e) { // this is expected } catch (Exception e) { Assert.fail(); } } // write a File of TEST_SINGLE_BUFFER_CAPACITY_BYTES*4 size, assuming TEST_SINGLE_BUFFER_CAPACITY_BYTES is 32 private File writeTestFileUnaligned(String filename, int padding) throws IOException { File f = new File(Paths.get(SCRATCH_DIR).toString() + filename + ".test"); DataOutputStream out = new DataOutputStream(new FileOutputStream(f)); for (int i=0; i<padding; i++) { out.writeByte((byte) 0xff); } byte[] leadingBytes = new byte[] {0, 1, 0, 1, 0, 1, 0, 1}; // bytes 0-7 for (int i=0; i<leadingBytes.length; i++) { out.writeByte(leadingBytes[i]); } out.writeUTF("abcdef"); long[] values = { 123456789000L, 234567891000L, // bytes 16-31 345678912000L, 456789123000L, // bytes 32-47 567891234000L, 678912345000L, // bytes 48-63 789123456000L, 891234567000L, // bytes 64-79 912345678000L, 123456789000L, // bytes 80-95 234567891000L, 345678912000L, // bytes 96-111 Long.MAX_VALUE, Long.MAX_VALUE, // bytes 112-127 }; for (int i=0; i<values.length; i++) { out.writeLong(values[i]); } out.flush(); out.close(); f.deleteOnExit(); return f; } }
8,711
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/util/RemovedOrdinalIteratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.util; import java.util.BitSet; import org.junit.Assert; import org.junit.Test; public class RemovedOrdinalIteratorTest { private static final BitSet PREVIOUS_ORDINALS = bitSet(1, 2, 3, 4, 6, 7, 9, 10); private static final BitSet CURRENT_ORDINALS = bitSet(1, 3, 4, 5, 7, 8, 9); @Test public void iteratesOverRemovedOrdinals() { RemovedOrdinalIterator iter = new RemovedOrdinalIterator(PREVIOUS_ORDINALS, CURRENT_ORDINALS); Assert.assertEquals(2, iter.next()); Assert.assertEquals(6, iter.next()); Assert.assertEquals(10, iter.next()); Assert.assertEquals(-1, iter.next()); } @Test public void iteratesOverAddedOrdinals() { RemovedOrdinalIterator iterFlip = new RemovedOrdinalIterator(PREVIOUS_ORDINALS, CURRENT_ORDINALS, true); Assert.assertEquals(5, iterFlip.next()); Assert.assertEquals(8, iterFlip.next()); Assert.assertEquals(-1, iterFlip.next()); } private static BitSet bitSet(int... setBits) { BitSet bitSet = new BitSet(); for(int bit : setBits) { bitSet.set(bit); } return bitSet; } }
8,712
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/util/SimultaneousExecutorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.util; import static org.junit.Assert.fail; import java.util.concurrent.Callable; import org.junit.Before; import org.junit.Test; // TODO(timt): tag as MEDIUM test public class SimultaneousExecutorTest { private SimultaneousExecutor subject; @Before public void before() { subject = new SimultaneousExecutor(getClass(), "test"); } @Test public void failsWhenAnyRunnableThrowsException() throws Exception { subject.execute(new Job(false)); subject.execute(new Job(false)); subject.execute(new Job(true)); subject.execute(new Job(false)); try { subject.awaitSuccessfulCompletion(); fail("Should have thrown Exception"); } catch(Exception expected) { } } @Test public void failsWhenAnyCallableThrowsException() throws Exception { StatusEnsuringCallable firstTask = new StatusEnsuringCallable(false); StatusEnsuringCallable secondTask = new StatusEnsuringCallable(false); subject.submit(firstTask); subject.submit(secondTask); try { subject.awaitSuccessfulCompletion(); fail("Should fail"); } catch (final Exception e) { } } @Test public void canBeReused() throws Exception { subject.execute(new Job(false)); subject.execute(new Job(false)); subject.execute(new Job(false)); subject.execute(new Job(false)); subject.awaitSuccessfulCompletionOfCurrentTasks(); subject.execute(new Job(false)); subject.execute(new Job(false)); subject.execute(new Job(false)); subject.execute(new Job(false)); subject.awaitSuccessfulCompletion(); } private class Job implements Runnable { private final boolean fail; public Job(boolean fail) { this.fail = fail; } public void run() { if(fail) throw new RuntimeException("FAIL"); } } private static class StatusEnsuringCallable implements Callable<Void> { private final boolean shouldSucceed; public StatusEnsuringCallable(final boolean shouldSucceed) { this.shouldSucceed = shouldSucceed; } @Override public Void call() throws Exception { if (shouldSucceed) { return null; } else { throw new RuntimeException("Failing as configured"); } } } }
8,713
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/util/HashCodesTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.util; import static com.netflix.hollow.core.HollowConstants.HASH_TABLE_MAX_SIZE; import com.netflix.hollow.core.memory.ByteDataArray; import com.netflix.hollow.core.memory.encoding.HashCodes; import com.netflix.hollow.core.memory.encoding.VarInt; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import java.util.Random; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class HashCodesTest { private Random rand = new Random(); @Test public void testStringHashCode() { for(int i=0;i<10000;i++) { String str = buildRandomString(true, 25); Assert.assertEquals(accurateStringHashCode(str), HashCodes.hashCode(str)); } for(int i=0;i<10000;i++) { String str = buildRandomString(false, 25); Assert.assertEquals(accurateStringHashCode(str), HashCodes.hashCode(str)); } } @Test public void testHashTableSize() { // Current load factor is 10 / 7. If load factor calculation is changed, this test should be updated int N; try { HashCodes.hashTableSize(-1); Assert.fail("exception expected"); } catch (IllegalArgumentException ex) { Assert.assertEquals("cannot be negative; numElements=-1", ex.getMessage()); } Assert.assertEquals(1, HashCodes.hashTableSize(0)); Assert.assertEquals(2, HashCodes.hashTableSize(1)); Assert.assertEquals(4, HashCodes.hashTableSize(2)); // first integer overflow boundary condition (214_748_364) N = Integer.MAX_VALUE / 10; Assert.assertEquals(1 << 29, HashCodes.hashTableSize(N)); Assert.assertEquals(536870912, HashCodes.hashTableSize(N + 1)); // exceeding maximum hash table size (before load factor) N = HASH_TABLE_MAX_SIZE; Assert.assertEquals(1073741824, HashCodes.hashTableSize(N)); try { HashCodes.hashTableSize(N + 1); Assert.fail("exception expected"); } catch (IllegalArgumentException ex) { Assert.assertEquals("exceeds maximum number of buckets; numElements=751619277", ex.getMessage()); } // Note: technically these overflow conditions aren't reachable because max buckets is a lower // threshold. Keeping the assertions to avoid regressions. N = (int)((1L<<31) * 7L / 10L); try { HashCodes.hashTableSize(N); Assert.fail("exception expected"); } catch (IllegalArgumentException ex) {} try { HashCodes.hashTableSize(N + 1); Assert.fail("exception expected"); } catch (IllegalArgumentException ex) {} // max int try { HashCodes.hashTableSize(Integer.MAX_VALUE); Assert.fail("exception expected"); } catch (IllegalArgumentException ex) {} } @Test @Ignore public void testHashTableSize_exhaustively() { int size = HashCodes.hashTableSize(2); for (int N=3; N< HASH_TABLE_MAX_SIZE; ++N) { int s = HashCodes.hashTableSize(N); if (s < size) { StringBuilder sb = new StringBuilder(); sb.append("expected size to grow or stay same; N="); sb.append(N); sb.append(" previous="); sb.append(size); sb.append("(~2^"); sb.append(31 - Integer.numberOfLeadingZeros(size)); sb.append(") size="); sb.append(s); sb.append("(~2^"); sb.append(31 - Integer.numberOfLeadingZeros(s)); sb.append(')'); throw new AssertionFailedError(sb.toString()); } size = s; } } private String buildRandomString(boolean includeMultibyteCharacters, int strLen) { StringBuilder builder = new StringBuilder(); for(int i=0;i<strLen;i++) { builder.append((char)rand.nextInt(includeMultibyteCharacters ? (int)Character.MAX_VALUE : 0x80)); } return builder.toString(); } private int accurateStringHashCode(String str) { ByteDataArray buf = new ByteDataArray(WastefulRecycler.SMALL_ARRAY_RECYCLER); for(int i=0;i<str.length();i++) { VarInt.writeVInt(buf, str.charAt(i)); } return HashCodes.hashCode(buf.getUnderlyingArray(), 0, (int)buf.length()); } }
8,714
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/util/VersionsTest.java
package com.netflix.hollow.core.util; import static com.netflix.hollow.core.HollowConstants.VERSION_LATEST; import static com.netflix.hollow.core.HollowConstants.VERSION_NONE; import org.junit.Assert; import org.junit.Test; public class VersionsTest { @Test public void testPrettyPrint() { Assert.assertEquals(Versions.PRETTY_VERSION_NONE, Versions.prettyVersion(VERSION_NONE)); Assert.assertEquals(Versions.PRETTY_VERSION_LATEST, Versions.prettyVersion(VERSION_LATEST)); Assert.assertEquals("123", Versions.prettyVersion(123l)); } }
8,715
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/util/HollowWriteStateCreatorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.util; import static com.netflix.hollow.core.HollowStateEngine.HEADER_TAG_METRIC_CYCLE_START; import static com.netflix.hollow.core.HollowStateEngine.HEADER_TAG_PRODUCER_TO_VERSION; import static org.junit.Assert.assertEquals; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowShardLargeType; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import com.netflix.hollow.tools.checksum.HollowChecksum; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowWriteStateCreatorTest { @Test public void recreatesUsingReadEngine() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new Integer(1)); writeEngine.addHeaderTag("CopyTag", "copied"); writeEngine.addHeaderTag(HEADER_TAG_METRIC_CYCLE_START, String.valueOf(System.currentTimeMillis())); String toVersion = String.valueOf(System.currentTimeMillis()); writeEngine.addHeaderTag(HEADER_TAG_PRODUCER_TO_VERSION, toVersion); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); String cycleStartTime = readEngine.getHeaderTag(HEADER_TAG_METRIC_CYCLE_START); String readEngineToVersion = readEngine.getHeaderTag(HEADER_TAG_PRODUCER_TO_VERSION); HollowWriteStateEngine recreatedWriteEngine = HollowWriteStateCreator.recreateAndPopulateUsingReadEngine(readEngine); assertEquals(cycleStartTime, recreatedWriteEngine.getPreviousHeaderTags().get(HEADER_TAG_METRIC_CYCLE_START)); assertEquals(readEngineToVersion, recreatedWriteEngine.getPreviousHeaderTags().get(HEADER_TAG_PRODUCER_TO_VERSION)); HollowReadStateEngine recreatedReadEngine = StateEngineRoundTripper.roundTripSnapshot(recreatedWriteEngine); assertEquals(HollowChecksum.forStateEngine(readEngine), HollowChecksum.forStateEngine(recreatedReadEngine)); assertEquals("copied", recreatedReadEngine.getHeaderTag("CopyTag")); assertEquals(readEngine.getCurrentRandomizedTag(), recreatedReadEngine.getCurrentRandomizedTag()); } @Test public void throwsExceptionIfWriteStateIsPopulated() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new Integer(1)); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); try { HollowWriteStateCreator.populateUsingReadEngine(writeEngine, readEngine); Assert.fail(); } catch(IllegalStateException expected) { } } @Test public void populatesOnlyPreviouslyExistingFieldsWhenSchemaIsAddedTo() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new Integer(1)); mapper.add(new Integer(2)); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); HollowWriteStateEngine repopulatedWriteStateEngine = new HollowWriteStateEngine(); new HollowObjectMapper(repopulatedWriteStateEngine).initializeTypeState(IntegerWithMoreThanOneField.class); HollowWriteStateCreator.populateUsingReadEngine(repopulatedWriteStateEngine, readEngine); repopulatedWriteStateEngine.prepareForNextCycle(); repopulatedWriteStateEngine.addAllObjectsFromPreviousCycle(); new HollowObjectMapper(repopulatedWriteStateEngine).add(new IntegerWithMoreThanOneField(3)); HollowReadStateEngine recreatedReadEngine = StateEngineRoundTripper.roundTripSnapshot(repopulatedWriteStateEngine); GenericHollowObject one = new GenericHollowObject(recreatedReadEngine, "Integer", 0); assertEquals(1, one.getInt("value")); Assert.assertNull(one.getString("anotherValue")); GenericHollowObject two = new GenericHollowObject(recreatedReadEngine, "Integer", 1); assertEquals(2, two.getInt("value")); Assert.assertNull(two.getString("anotherValue")); GenericHollowObject three = new GenericHollowObject(recreatedReadEngine, "Integer", 2); assertEquals(3, three.getInt("value")); assertEquals("3", three.getString("anotherValue")); } @Test public void populatesPreviouslyExistingFieldsWhenSchemaFieldsAreRemoved() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new IntegerWithMoreThanOneField(1)); mapper.add(new IntegerWithMoreThanOneField(2)); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); HollowWriteStateEngine repopulatedWriteStateEngine = new HollowWriteStateEngine(); new HollowObjectMapper(repopulatedWriteStateEngine).initializeTypeState(Integer.class); HollowWriteStateCreator.populateUsingReadEngine(repopulatedWriteStateEngine, readEngine); repopulatedWriteStateEngine.prepareForNextCycle(); repopulatedWriteStateEngine.addAllObjectsFromPreviousCycle(); new HollowObjectMapper(repopulatedWriteStateEngine).add(new Integer(3)); HollowReadStateEngine recreatedReadEngine = StateEngineRoundTripper.roundTripSnapshot(repopulatedWriteStateEngine); HollowObjectSchema schema = (HollowObjectSchema)recreatedReadEngine.getSchema("Integer"); assertEquals(1, schema.numFields()); assertEquals("value", schema.getFieldName(0)); GenericHollowObject one = new GenericHollowObject(recreatedReadEngine, "Integer", 0); assertEquals(1, one.getInt("value")); GenericHollowObject two = new GenericHollowObject(recreatedReadEngine, "Integer", 1); assertEquals(2, two.getInt("value")); GenericHollowObject three = new GenericHollowObject(recreatedReadEngine, "Integer", 2); assertEquals(3, three.getInt("value")); } @Test public void repopulationFailsIfShardsAreIncorrectlyPreconfigured() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new Integer(1)); mapper.add(new Integer(2)); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); HollowWriteStateEngine repopulatedWriteStateEngine = new HollowWriteStateEngine(); new HollowObjectMapper(repopulatedWriteStateEngine).initializeTypeState(IntegerWithWrongShardConfiguration.class); try { HollowWriteStateCreator.populateUsingReadEngine(repopulatedWriteStateEngine, readEngine); Assert.fail(); } catch(Exception expected) { } } @Test public void testReadSchemaFileIntoWriteState() throws Exception { HollowWriteStateEngine engine = new HollowWriteStateEngine(); assertEquals("Should have no type states", 0, engine.getOrderedTypeStates().size()); HollowWriteStateCreator.readSchemaFileIntoWriteState("schema1.txt", engine); assertEquals("Should now have types", 2, engine.getOrderedTypeStates().size()); } @SuppressWarnings("unused") @HollowTypeName(name="Integer") private static class IntegerWithMoreThanOneField { private final int value; @HollowInline private final String anotherValue; public IntegerWithMoreThanOneField(int value) { this.value = value; this.anotherValue = String.valueOf(value); } } @SuppressWarnings("unused") @HollowTypeName(name="Integer") @HollowShardLargeType(numShards=4) private static class IntegerWithWrongShardConfiguration { private int value; } }
8,716
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/util/ThreadsTest.java
package com.netflix.hollow.core.util; import static com.netflix.hollow.core.util.Threads.daemonThread; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; // TODO(timt): tag as MEDIUM test public class ThreadsTest { @Test public void named() { Thread thread = daemonThread(() -> {}, "Thready McThreadson"); assertEquals("Thready McThreadson", thread.getName()); assertTrue(thread.isDaemon()); // TODO(timt): invariant } @Test public void described() { Thread thread = daemonThread(() -> {}, getClass(), "howdy"); assertEquals("hollow | ThreadsTest | howdy", thread.getName()); assertTrue(thread.isDaemon()); } @Test public void described_customPlatform() { Thread thread = daemonThread(() -> {}, "solid", getClass(), "howdy"); assertEquals("solid | ThreadsTest | howdy", thread.getName()); assertTrue(thread.isDaemon()); } @Test public void nullName() { try { daemonThread(() -> {}, null); fail("expected an exception"); } catch (NullPointerException e) { assertEquals("name required", e.getMessage()); } } @Test public void nullPlatform() { try { daemonThread(() -> {}, null, getClass(), "boom"); fail("expected an exception"); } catch (NullPointerException e) { assertEquals("platform required", e.getMessage()); } } @Test public void nullRunnable() { try { daemonThread(null, getClass(), "boom"); fail("expected an exception"); } catch (NullPointerException e) { assertEquals("runnable required", e.getMessage()); } } @Test public void nullContext() { try { daemonThread(() -> {}, null, "boom"); fail("expected an exception"); } catch (NullPointerException e) { assertEquals("context required", e.getMessage()); } } @Test public void nullDescription() { try { daemonThread(() -> {}, getClass(), null); fail("expected an exception"); } catch (NullPointerException e) { assertEquals("description required", e.getMessage()); } } }
8,717
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/util/BitSetIteratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.core.util; import java.util.BitSet; import org.junit.Assert; import org.junit.Test; public class BitSetIteratorTest { @Test public void testEmpty() { BitSetIterator it = new BitSetIterator(new BitSet()); Assert.assertFalse(it.hasNext()); Assert.assertNull(it.next()); } @Test public void testNormal() { BitSet bs = new BitSet(); for (int i = 0; i < 5; i++) { bs.set(i * 2); } int count = 0; BitSetIterator it = new BitSetIterator(bs); while (it.hasNext()) { Integer value = it.next(); Assert.assertTrue(bs.get(value)); count++; } Assert.assertEquals(bs.cardinality(), count); } @Test public void testRange() { BitSet bs = new BitSet(); for (int i = 0; i < 20; i++) { bs.set(i * 2); } assertRange(bs, null, null); assertRange(bs, null, 10); assertRange(bs, 0, null); assertRange(bs, bs.cardinality() / 2, null); assertRange(bs, 0, 10); assertRange(bs, 5, 10); assertRange(bs, 15, 100); assertRange(bs, 30, 100); } private void assertRange(BitSet bs, Integer start, Integer limit) { int count = 0; BitSetIterator it = new BitSetIterator(bs, start, limit); while (it.hasNext()) { Integer value = it.next(); Assert.assertTrue(bs.get(value)); count++; } if (limit == null) { int expected = (start == null || start==0) ? bs.cardinality() : (bs.cardinality() - start)+1; Assert.assertEquals(expected, count); } else { int max = Math.min(limit, bs.cardinality()); int expected = (start == null || start==0) ? max : Math.min((bs.cardinality() - start)+1, max); if (expected<0) expected=0; Assert.assertEquals(expected, count); } } }
8,718
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/HollowBlobHeaderTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowBlobHeaderTest { private static final String VERSION_NAME = "version"; private static final String VERSION_VALUE = "1234"; private static final String JAR_VERSION_NAME = "jarversion"; private static final String JAR_VERSION_VALUE = "12.34"; private static final String HEADER_VAL2 = "val2"; private static final String HEADER_VAL1 = "val1"; private static final String HEADER_NAME1 = "name1"; private static final String HEADER_NAME2 = "name2"; private HollowWriteStateEngine writeStateEngine; private HollowBlobWriter blobWriter; private ByteArrayOutputStream baos; private HollowReadStateEngine readStateEngine; private HollowBlobReader blobReader; @Before public void setUp() { writeStateEngine = new HollowWriteStateEngine(); writeStateEngine.addHeaderTag(VERSION_NAME, VERSION_VALUE); writeStateEngine.addHeaderTag(JAR_VERSION_NAME, JAR_VERSION_VALUE); blobWriter = new HollowBlobWriter(writeStateEngine); baos = new ByteArrayOutputStream(); readStateEngine = new HollowReadStateEngine(); blobReader = new HollowBlobReader(readStateEngine); } @Test public void writeAndReadHeadersForSnapshot() throws IOException { roundTripSnapshot(); Assert.assertEquals(VERSION_VALUE, readStateEngine.getHeaderTag(VERSION_NAME)); Assert.assertEquals(JAR_VERSION_VALUE, readStateEngine.getHeaderTag(JAR_VERSION_NAME)); } @Test public void writeAndReadHeadersForDelta() throws IOException { roundTripDelta(); Assert.assertEquals(VERSION_VALUE, readStateEngine.getHeaderTag(VERSION_NAME)); Assert.assertEquals(JAR_VERSION_VALUE, readStateEngine.getHeaderTag(JAR_VERSION_NAME)); } @Test public void writeAndReadHeaderMapForSnapshot() throws IOException { Map<String, String> headerTags = new HashMap<String, String>(); headerTags.put(HEADER_NAME1, HEADER_VAL1); headerTags.put(HEADER_NAME2, HEADER_VAL2); writeStateEngine.addHeaderTags(headerTags); roundTripSnapshot(); Assert.assertEquals(VERSION_VALUE, readStateEngine.getHeaderTag(VERSION_NAME)); Assert.assertEquals(JAR_VERSION_VALUE, readStateEngine.getHeaderTag(JAR_VERSION_NAME)); Assert.assertEquals(HEADER_VAL1, readStateEngine.getHeaderTag(HEADER_NAME1)); Assert.assertEquals(HEADER_VAL2, readStateEngine.getHeaderTag(HEADER_NAME2)); } private void roundTripSnapshot() throws IOException { blobWriter.writeSnapshot(baos); writeStateEngine.prepareForNextCycle(); blobReader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); baos.reset(); } private void roundTripDelta() throws IOException { blobWriter.writeSnapshot(baos); writeStateEngine.prepareForNextCycle(); blobReader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); baos.reset(); blobWriter.writeDelta(baos); writeStateEngine.prepareForNextCycle(); blobReader.applyDelta(HollowBlobInput.serial(baos.toByteArray())); baos.reset(); } }
8,719
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/HollowReadFilterTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.read.filter.HollowFilterConfig; import com.netflix.hollow.core.schema.HollowListSchema; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowListTypeWriteState; import com.netflix.hollow.core.write.HollowListWriteRecord; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowReadFilterTest extends AbstractStateEngineTest { HollowObjectSchema objSchema; HollowListSchema listSchema; HollowSetSchema setSchema; HollowMapSchema mapSchema; HollowObjectSchema elementSchema; @Before public void setUp() { objSchema = new HollowObjectSchema("TestObject", 5); objSchema.addField("field1", FieldType.STRING); objSchema.addField("field2", FieldType.INT); objSchema.addField("field3", FieldType.STRING); objSchema.addField("field4", FieldType.DOUBLE); objSchema.addField("field5", FieldType.FLOAT); listSchema = new HollowListSchema("TestList", "TestElement"); setSchema = new HollowSetSchema("TestSet", "TestElement"); mapSchema = new HollowMapSchema("TestMap", "TestElement", "TestElement"); elementSchema = new HollowObjectSchema("TestElement", 1); elementSchema.addField("field", FieldType.INT); super.setUp(); } @Test public void testIgnoredObject() throws IOException { readFilter = new HollowFilterConfig(true); readFilter.addType(objSchema.getName()); runThroughTheMotions(); Assert.assertNull(readStateEngine.getTypeState(objSchema.getName())); } @Test public void testIgnoredList() throws IOException { readFilter = new HollowFilterConfig(true); readFilter.addType(listSchema.getName()); runThroughTheMotions(); Assert.assertNull(readStateEngine.getTypeState(listSchema.getName())); } @Test public void testIgnoredSet() throws IOException { readFilter = new HollowFilterConfig(true); readFilter.addType(setSchema.getName()); runThroughTheMotions(); Assert.assertNull(readStateEngine.getTypeState(setSchema.getName())); } @Test public void testIgnoredMap() throws IOException { readFilter = new HollowFilterConfig(true); readFilter.addType(mapSchema.getName()); runThroughTheMotions(); Assert.assertNull(readStateEngine.getTypeState(mapSchema.getName())); } @Test public void testMultipleIgnoredTypes() throws Exception { readFilter = new HollowFilterConfig(true); readFilter.addType(listSchema.getName()); readFilter.addType(setSchema.getName()); readFilter.addType(mapSchema.getName()); runThroughTheMotions(); Assert.assertNull(readStateEngine.getTypeState(listSchema.getName())); Assert.assertNull(readStateEngine.getTypeState(setSchema.getName())); Assert.assertNull(readStateEngine.getTypeState(mapSchema.getName())); } @Test public void testExcludedObjectFields() throws Exception { readFilter = new HollowFilterConfig(true); readFilter.addField(objSchema.getName(), "field2"); readFilter.addField(objSchema.getName(), "field3"); readFilter.addField(objSchema.getName(), "field5"); runThroughTheMotions(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(objSchema.getName()); HollowObjectSchema filteredSchema = typeState.getSchema(); Assert.assertEquals("field1", filteredSchema.getFieldName(0)); Assert.assertEquals("field4", filteredSchema.getFieldName(1)); Assert.assertEquals("obj1", typeState.readString(0, 0)); Assert.assertEquals("OBJECT number two", typeState.readString(1, 0)); Assert.assertEquals("#3", typeState.readString(2, 0)); Assert.assertEquals("number four!", typeState.readString(3, 0)); Assert.assertEquals(1.01D, typeState.readDouble(0, 1), 0); Assert.assertEquals(2.02D, typeState.readDouble(1, 1), 0); Assert.assertEquals(3.03D, typeState.readDouble(2, 1), 0); Assert.assertEquals(4.04D, typeState.readDouble(3, 1), 0); } @Test public void testIncludedObjectFields() throws Exception { readFilter = new HollowFilterConfig(); readFilter.addField(objSchema.getName(), "field2"); readFilter.addField(objSchema.getName(), "field3"); readFilter.addField(objSchema.getName(), "field5"); runThroughTheMotions(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(objSchema.getName()); HollowObjectSchema filteredSchema = typeState.getSchema(); Assert.assertEquals("field2", filteredSchema.getFieldName(0)); Assert.assertEquals("field3", filteredSchema.getFieldName(1)); Assert.assertEquals("field5", filteredSchema.getFieldName(2)); Assert.assertEquals(1000, typeState.readInt(0, 0)); Assert.assertEquals(2000, typeState.readInt(1, 0)); Assert.assertEquals(3000, typeState.readInt(2, 0)); Assert.assertEquals(4000, typeState.readInt(3, 0)); Assert.assertEquals("ONE", typeState.readString(0, 1)); Assert.assertEquals("TWO", typeState.readString(1, 1)); Assert.assertEquals("THREE", typeState.readString(2, 1)); Assert.assertEquals("FOUR", typeState.readString(3, 1)); Assert.assertEquals(1.1F, typeState.readFloat(0, 2), 0); Assert.assertEquals(2.2F, typeState.readFloat(1, 2), 0); Assert.assertEquals(3.3F, typeState.readFloat(2, 2), 0); Assert.assertEquals(4.4F, typeState.readFloat(3, 2), 0); } private void runThroughTheMotions() throws IOException { addState1Data(); roundTripSnapshot(); addState2Data(); roundTripDelta(); } private void addState1Data() { addTestObject("obj1", 1000, "ONE", 1.01D, 1.1F); addTestObject("OBJECT number two", 2000, "TWO", 2.02D, 2.2F); addTestObject("#3", 3000, "THREE", 3.03D, 3.3F); addTestList(1, 3); addTestList(1, 2, 3, 4); addTestList(2, 4); addTestSet(1, 3); addTestSet(1, 2, 3, 4); addTestSet(2, 4); addTestMap(1, 3); addTestMap(1, 2, 3, 4); addTestMap(2, 4); addTestEntry(0); addTestEntry(1); addTestEntry(2); addTestEntry(3); addTestEntry(4); } private void addState2Data() { addTestObject("obj1", 1000, "ONE", 1.01D, 1.1F); addTestObject("#3", 3000, "THREE", 3.03D, 3.3F); addTestObject("number four!", 4000, "FOUR", 4.04D, 4.4F); addTestList(0, 3); addTestList(0, 2, 3, 4, 5); addTestList(2, 4); addTestSet(0, 3); addTestSet(0, 2, 3, 4, 5); addTestSet(2, 4); addTestMap(0, 3); addTestMap(0, 2, 3, 5); addTestMap(2, 4); addTestEntry(1); addTestEntry(2); addTestEntry(3); addTestEntry(4); addTestEntry(5); } private void addTestObject(String f1, int f2, String f3, double f4, float f5) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(objSchema); rec.setString("field1", f1); rec.setInt("field2", f2); rec.setString("field3", f3); rec.setDouble("field4", f4); rec.setFloat("field5", f5); writeStateEngine.add(objSchema.getName(), rec); } private void addTestList(int... elementOrdinals) { HollowListWriteRecord rec = new HollowListWriteRecord(); for(int ordinal : elementOrdinals) rec.addElement(ordinal); writeStateEngine.add(listSchema.getName(), rec); } private void addTestSet(int... elementOrdinals) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int ordinal : elementOrdinals) rec.addElement(ordinal); writeStateEngine.add(setSchema.getName(), rec); } private void addTestMap(int... keyAndValueOrdinals) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<keyAndValueOrdinals.length; i+= 2) rec.addEntry(keyAndValueOrdinals[i], keyAndValueOrdinals[i+1]); writeStateEngine.add(mapSchema.getName(), rec); } private void addTestEntry(int data) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(elementSchema); rec.setInt("field", data); writeStateEngine.add(elementSchema.getName(), rec); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(objSchema)); writeStateEngine.addTypeState(new HollowListTypeWriteState(listSchema)); writeStateEngine.addTypeState(new HollowSetTypeWriteState(setSchema)); writeStateEngine.addTypeState(new HollowMapTypeWriteState(mapSchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(elementSchema)); } }
8,720
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/HollowTypeStateListenerTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.BitSet; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowTypeStateListenerTest { HollowWriteStateEngine writeStateEngine; HollowBlobWriter blobWriter; ByteArrayOutputStream baos; HollowObjectSchema schema; HollowReadStateEngine readStateEngine; HollowBlobReader blobReader; PopulatedOrdinalListener listener; @Before public void setUp() { listener = new PopulatedOrdinalListener(); writeStateEngine = new HollowWriteStateEngine(); blobWriter = new HollowBlobWriter(writeStateEngine); baos = new ByteArrayOutputStream(); schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); readStateEngine = new HollowReadStateEngine(); readStateEngine.addTypeListener("TestObject", listener); blobReader = new HollowBlobReader(readStateEngine); } @Test public void test() throws IOException { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); addRecord(writeState, 1, "one"); addRecord(writeState, 2, "two"); addRecord(writeState, 3, "three"); roundTripSnapshot(); addRecord(writeState, 1, "one"); addRecord(writeState, 3, "three"); addRecord(writeState, 1000, "one thousand"); addRecord(writeState, 0, "zero"); roundTripDelta(); BitSet populatedBitSet = listener.getPopulatedOrdinals(); Assert.assertEquals(4, populatedBitSet.cardinality()); Assert.assertTrue(populatedBitSet.get(0)); Assert.assertTrue(populatedBitSet.get(2)); Assert.assertTrue(populatedBitSet.get(3)); Assert.assertTrue(populatedBitSet.get(4)); } private void addRecord(HollowObjectTypeWriteState writeState, int intVal, String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", intVal); rec.setString("f2", strVal); writeState.add(rec); } private void roundTripSnapshot() throws IOException { writeStateEngine.prepareForWrite(); blobWriter.writeSnapshot(baos); writeStateEngine.prepareForNextCycle(); blobReader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); baos.reset(); } private void roundTripDelta() throws IOException { writeStateEngine.prepareForWrite(); blobWriter.writeDelta(baos); writeStateEngine.prepareForNextCycle(); blobReader.applyDelta(HollowBlobInput.serial(baos.toByteArray())); baos.reset(); } }
8,721
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/SnapshotPopulatedOrdinalsReaderTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read; import com.netflix.hollow.core.memory.ThreadSafeBitSet; import com.netflix.hollow.core.read.engine.HollowTypeStateListener; import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener; import com.netflix.hollow.core.read.engine.SnapshotPopulatedOrdinalsReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.BitSet; import org.junit.Assert; import org.junit.Test; public class SnapshotPopulatedOrdinalsReaderTest { @Test public void test() throws IOException { PopulatedOrdinalListener listener = new PopulatedOrdinalListener(); ThreadSafeBitSet bitSet = new ThreadSafeBitSet(); for(int i=0;i<10000;i+=10) bitSet.set(i); DataInputStream dis = serializeToStream(bitSet); SnapshotPopulatedOrdinalsReader.readOrdinals(HollowBlobInput.serial(dis), new HollowTypeStateListener[] { listener }); BitSet populatedOrdinals = listener.getPopulatedOrdinals(); Assert.assertEquals(1000, populatedOrdinals.cardinality()); for(int i=0;i<10000;i+=10) Assert.assertTrue(populatedOrdinals.get(i)); } private DataInputStream serializeToStream(ThreadSafeBitSet bitSet) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); bitSet.serializeBitsTo(dos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DataInputStream dis = new DataInputStream(bais); return dis; } }
8,722
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/HollowBlobInputTest.java
package com.netflix.hollow.core.read; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.core.memory.MemoryMode; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class HollowBlobInputTest { private static final String SCRATCH_DIR = System.getProperty("java.io.tmpdir"); @Mock HollowConsumer.Blob mockBlob; @Mock InputStream mockInputStream; @Mock File mockFile; Path testFile; byte[] leadingBytes; @Before public void setup() throws IOException { MockitoAnnotations.initMocks(this); testFile = Files.createTempFile(Paths.get(SCRATCH_DIR), "blobfile", "snapshot"); // The test file looks like: // First 8 bytes for testing reading byte, short, and long // Then to test reading UTF, 2 bytes for UTF length (containing unsigned short value of 1) and then the string "test" leadingBytes = new byte[] {0, 1, 0, 1, 0, 1, 0, 1}; Files.write(testFile, leadingBytes); byte[] utfLen = new byte[] {0, 1}; // bytes corresponding to a short of value 1 Files.write(testFile, utfLen, StandardOpenOption.APPEND); Files.write(testFile, "test".getBytes(), StandardOpenOption.APPEND); when(mockBlob.getInputStream()).thenReturn(new FileInputStream(testFile.toFile())); when(mockBlob.getFile()).thenReturn(testFile.toFile()); } @Test public void testModeBasedSelector() throws IOException { assertTrue((HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob)).getInput() instanceof DataInputStream); assertTrue((HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob)).getInput() instanceof RandomAccessFile); assertNotNull((HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob)).getBuffer()); } @Test public void testRead() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(0, inStream.read()); // first byte is 0 assertEquals(1, inStream.read()); // second byte is 1 HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); assertEquals(0, inBuffer.read()); // first byte is 0 assertEquals(1, inBuffer.read()); // second byte is 1 } @Test public void testReadBytes() throws IOException { byte[] result = new byte[8]; HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob).read(result, 0, 8); assertTrue(Arrays.equals(leadingBytes, result)); HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob).read(result, 0, 8); assertTrue(Arrays.equals(leadingBytes, result)); } @Test public void testSeek() throws IOException { try (HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob)) { inStream.seek(3); fail(); } catch (UnsupportedOperationException e) { // pass } catch (Exception e) { fail(); } HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); inBuffer.seek(3); assertEquals(3, inBuffer.getFilePointer()); // first byte is 0 } @Test public void testGetFilePointer() throws IOException { try (HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob)) { inStream.getFilePointer(); fail(); } catch (UnsupportedOperationException e) { // pass } catch (Exception e) { fail(); } HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); assertEquals(0, inBuffer.getFilePointer()); // first byte is 0 } @Test public void testReadShort() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(1, inStream.readShort()); // first short is 1 assertEquals(1, inStream.readShort()); // second short is 1 HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); assertEquals(1, inBuffer.readShort()); // first short is 1 assertEquals(1, inBuffer.readShort()); // second short is 1 } @Test public void testReadInt() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(65537, inStream.readInt()); // first int HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); assertEquals(65537, inBuffer.readInt()); // first int } @Test public void testReadLong() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(281479271743489l, inStream.readLong()); // first long HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); assertEquals(281479271743489l, inBuffer.readLong()); // first long } @Test public void testReadUTF() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); inStream.readLong(); // skip 8 bytes assertEquals("t", inStream.readUTF()); // first UTF HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); inBuffer.seek(8); assertEquals("t", inBuffer.readUTF()); // first UTF } @Test public void testSkipBytes() throws IOException { HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob); assertEquals(1l, inStream.skipBytes(1)); assertEquals(1, inStream.read()); // next byte read is 1 assertEquals(2000, inStream.skipBytes(2000)); // successfully skips past end of file for FileInputStream HollowBlobInput inBuffer = HollowBlobInput.modeBasedSelector(MemoryMode.SHARED_MEMORY_LAZY, mockBlob); assertEquals(1l, inBuffer.skipBytes(1)); assertEquals(1, inBuffer.read()); // next byte read is 1 assertEquals(12, inBuffer.skipBytes(2000)); // stops at end of file for RandomAccessFile } }
8,723
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/HollowBlobRandomizedTagTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read; import static org.junit.Assert.assertEquals; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowBlobRandomizedTagTest { byte snapshot[]; byte delta1[]; byte delta2[]; byte reversedelta1[]; byte reversedelta2[]; byte snapshot2[]; @Before public void setUp() throws IOException { HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); HollowBlobWriter writer = new HollowBlobWriter(stateEngine); stateEngine.prepareForWrite(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); snapshot = baos.toByteArray(); stateEngine.prepareForNextCycle(); stateEngine.prepareForWrite(); baos = new ByteArrayOutputStream(); writer.writeDelta(baos); delta1 = baos.toByteArray(); baos = new ByteArrayOutputStream(); writer.writeReverseDelta(baos); reversedelta1 = baos.toByteArray(); stateEngine.prepareForNextCycle(); stateEngine.prepareForNextCycle(); stateEngine.prepareForNextCycle(); stateEngine.prepareForWrite(); stateEngine.prepareForWrite(); baos = new ByteArrayOutputStream(); writer.writeDelta(baos); delta2 = baos.toByteArray(); baos = new ByteArrayOutputStream(); writer.writeReverseDelta(baos); reversedelta2 = baos.toByteArray(); baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); snapshot2 = baos.toByteArray(); } @Test public void applyingIncorrectDeltaFails() throws IOException { HollowReadStateEngine stateEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(stateEngine); reader.readSnapshot(HollowBlobInput.serial(snapshot)); reader.applyDelta(HollowBlobInput.serial(delta1)); try { reader.applyDelta(HollowBlobInput.serial(delta1)); Assert.fail("Should have refused to apply delta to incorrect state"); } catch(IOException expected) { } reader.applyDelta(HollowBlobInput.serial(delta2)); } @Test public void applyingReverseDeltaToIncorrectStateFails() throws IOException { HollowReadStateEngine stateEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(stateEngine); reader.readSnapshot(HollowBlobInput.serial(snapshot2)); try { reader.applyDelta(HollowBlobInput.serial(reversedelta1)); Assert.fail("Should have refused to apply reverse delta to incorrect state"); } catch(IOException expected) { } reader.applyDelta(HollowBlobInput.serial(reversedelta2)); reader.applyDelta(HollowBlobInput.serial(reversedelta1)); try { reader.applyDelta(HollowBlobInput.serial(delta2)); Assert.fail("Should have refused to apply delta to incorrect state"); } catch(IOException expected) { } reader.applyDelta(HollowBlobInput.serial(delta1)); reader.applyDelta(HollowBlobInput.serial(delta2)); } @Test public void originRandomizedTagPresence() throws IOException { HollowReadStateEngine stateEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(stateEngine); reader.readSnapshot(HollowBlobInput.serial(snapshot)); assertEquals(-1, stateEngine.getOriginRandomizedTag()); long tag = stateEngine.getCurrentRandomizedTag(); reader.applyDelta(HollowBlobInput.serial(delta1)); assertEquals(tag, stateEngine.getOriginRandomizedTag()); tag = stateEngine.getCurrentRandomizedTag(); reader.applyDelta(HollowBlobInput.serial(reversedelta1)); assertEquals(tag, stateEngine.getOriginRandomizedTag()); } }
8,724
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/HollowBlobOptionalPartTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.HollowConsumer.DoubleSnapshotConfig; import com.netflix.hollow.api.consumer.fs.HollowFilesystemBlobRetriever; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.ProducerOptionalBlobPartConfig; import com.netflix.hollow.api.producer.fs.HollowFilesystemPublisher; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.memory.MemoryMode; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.filter.TypeFilter; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.TypeA; import com.netflix.hollow.core.write.objectmapper.TypeB; import com.netflix.hollow.core.write.objectmapper.TypeC; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Test; public class HollowBlobOptionalPartTest { @Test public void optionalPartsAreAvailableInLowLevelAPI() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeA.class); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); ByteArrayOutputStream mainPart = new ByteArrayOutputStream(); ByteArrayOutputStream bPart = new ByteArrayOutputStream(); ByteArrayOutputStream cPart = new ByteArrayOutputStream(); ProducerOptionalBlobPartConfig partConfig = newPartConfig(); ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart); partStreams.addOutputStream("C", cPart); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart, partStreams); HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(readEngine); HollowBlobInput mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart.toByteArray())); InputStream bPartInput = new ByteArrayInputStream(bPart.toByteArray()); // HollowBlobInput cPartInput = HollowBlobInput.serial(new ByteArrayInputStream(cPart.toByteArray())); OptionalBlobPartInput optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); reader.readSnapshot(mainPartInput, optionalPartInput, TypeFilter.newTypeFilter().build()); GenericHollowObject obj = new GenericHollowObject(readEngine, "TypeA", 1); Assert.assertEquals("2", obj.getObject("a1").getString("value")); Assert.assertEquals(2, obj.getInt("a2")); Assert.assertEquals(2L, obj.getObject("b").getLong("b2")); Assert.assertNull(readEngine.getTypeState("TypeC")); } @Test public void optionalPartsAreAvailableInHighLevelAPI() throws IOException { InMemoryBlobStore blobStore = new InMemoryBlobStore(Collections.singleton("B")); HollowInMemoryBlobStager stager = new HollowInMemoryBlobStager(newPartConfig()); HollowProducer producer = HollowProducer .withPublisher(blobStore) .withNumStatesBetweenSnapshots(2) .withBlobStager(stager) .build(); producer.initializeDataModel(TypeA.class); producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); }); producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); // state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); state.add(new TypeA("4", 4, new TypeB((short)4, 4L, 4f, new char[] {'4'}, new byte[] { 4 }), Collections.singleton(new TypeC('4', null)))); }); HollowConsumer consumer = HollowConsumer.newHollowConsumer() .withBlobRetriever(blobStore) .build(); consumer.triggerRefresh(); GenericHollowObject obj = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 3); Assert.assertEquals("4", obj.getObject("a1").getString("value")); Assert.assertEquals(4, obj.getInt("a2")); Assert.assertEquals(4L, obj.getObject("b").getLong("b2")); Assert.assertFalse(consumer.getStateEngine().getTypeState("TypeB").getPopulatedOrdinals().get(1)); Assert.assertNull(consumer.getStateEngine().getTypeState("TypeC")); } @Test public void refusesToApplyIncorrectPartSnapshot() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeA.class); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); ByteArrayOutputStream mainPart = new ByteArrayOutputStream(); ByteArrayOutputStream bPart = new ByteArrayOutputStream(); ByteArrayOutputStream cPart = new ByteArrayOutputStream(); ProducerOptionalBlobPartConfig partConfig = newPartConfig(); ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart); partStreams.addOutputStream("C", cPart); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart, partStreams); writeEngine.prepareForNextCycle(); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); mapper.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); ByteArrayOutputStream mainPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream bPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream cPart2 = new ByteArrayOutputStream(); partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart2); partStreams.addOutputStream("C", cPart2); writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart2, partStreams); HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(readEngine); HollowBlobInput mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart.toByteArray())); InputStream bPartInput = new ByteArrayInputStream(bPart.toByteArray()); InputStream cPartInput = new ByteArrayInputStream(cPart2.toByteArray()); /// wrong part state OptionalBlobPartInput optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); optionalPartInput.addInput("C", cPartInput); try { reader.readSnapshot(mainPartInput, optionalPartInput, TypeFilter.newTypeFilter().build()); Assert.fail("Should have thrown Exception"); } catch(IllegalArgumentException ex) { Assert.assertEquals("Optional blob part C does not appear to be matched with the main input", ex.getMessage()); } } @Test public void testFilesystemBlobRetriever() throws IOException { File localBlobStore = createLocalDir(); HollowFilesystemPublisher publisher = new HollowFilesystemPublisher(localBlobStore.toPath()); HollowInMemoryBlobStager stager = new HollowInMemoryBlobStager(newPartConfig()); HollowProducer producer = HollowProducer.withPublisher(publisher).withBlobStager(stager).build(); producer.initializeDataModel(TypeA.class); long v1 = producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); }); long v2 = producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); state.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); }); HollowFilesystemBlobRetriever blobRetriever = new HollowFilesystemBlobRetriever(localBlobStore.toPath(), new HashSet<>(Arrays.asList("B", "C"))); HollowConsumer consumer = HollowConsumer.newHollowConsumer() .withBlobRetriever(blobRetriever) .withDoubleSnapshotConfig(new DoubleSnapshotConfig() { @Override public int maxDeltasBeforeDoubleSnapshot() { return Integer.MAX_VALUE; } @Override public boolean allowDoubleSnapshot() { return false; } }).build(); consumer.triggerRefreshTo(v1); consumer.triggerRefreshTo(v2); consumer.triggerRefreshTo(v1); } @Test public void refusesToApplyIncorrectPartDelta() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeA.class); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); ByteArrayOutputStream mainPart = new ByteArrayOutputStream(); ByteArrayOutputStream bPart = new ByteArrayOutputStream(); ByteArrayOutputStream cPart = new ByteArrayOutputStream(); ProducerOptionalBlobPartConfig partConfig = newPartConfig(); ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart); partStreams.addOutputStream("C", cPart); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); writer.writeSnapshot(mainPart, partStreams); writeEngine.prepareForNextCycle(); mapper.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); mapper.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); ByteArrayOutputStream mainPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream bPart2 = new ByteArrayOutputStream(); ByteArrayOutputStream cPart2 = new ByteArrayOutputStream(); partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart2); partStreams.addOutputStream("C", cPart2); writer = new HollowBlobWriter(writeEngine); writer.writeDelta(mainPart2, partStreams); writeEngine.prepareForNextCycle(); mapper.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); mapper.add(new TypeA("4", 4, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); mapper.add(new TypeA("5", 5, new TypeB((short)5, 5L, 5f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('5', null)))); ByteArrayOutputStream mainPart3 = new ByteArrayOutputStream(); ByteArrayOutputStream bPart3 = new ByteArrayOutputStream(); ByteArrayOutputStream cPart3 = new ByteArrayOutputStream(); partStreams = partConfig.newStreams(); partStreams.addOutputStream("B", bPart3); partStreams.addOutputStream("C", cPart3); writer = new HollowBlobWriter(writeEngine); writer.writeDelta(mainPart3, partStreams); /// read snapshot HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(readEngine); HollowBlobInput mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart.toByteArray())); InputStream bPartInput = new ByteArrayInputStream(bPart.toByteArray()); InputStream cPartInput = new ByteArrayInputStream(cPart.toByteArray()); OptionalBlobPartInput optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); optionalPartInput.addInput("C", cPartInput); reader.readSnapshot(mainPartInput, optionalPartInput, TypeFilter.newTypeFilter().build()); /// apply delta mainPartInput = HollowBlobInput.serial(new ByteArrayInputStream(mainPart2.toByteArray())); bPartInput = new ByteArrayInputStream(bPart3.toByteArray()); /// wrong part state cPartInput = new ByteArrayInputStream(cPart2.toByteArray()); optionalPartInput = new OptionalBlobPartInput(); optionalPartInput.addInput("B", bPartInput); optionalPartInput.addInput("C", cPartInput); try { reader.applyDelta(mainPartInput, optionalPartInput); Assert.fail("Should have thrown Exception"); } catch(IllegalArgumentException ex) { Assert.assertEquals("Optional blob part B does not appear to be matched with the main input", ex.getMessage()); } } @Test public void optionalPartsWithSharedMemoryLazy() throws IOException { File localBlobStore = createLocalDir(); HollowFilesystemPublisher publisher = new HollowFilesystemPublisher(localBlobStore.toPath()); HollowInMemoryBlobStager stager = new HollowInMemoryBlobStager(newPartConfig()); HollowProducer producer = HollowProducer .withPublisher(publisher) .withNumStatesBetweenSnapshots(2) .withBlobStager(stager) .build(); producer.initializeDataModel(TypeA.class); producer.runCycle(state -> { state.add(new TypeA("1", 1, new TypeB((short)1, 1L, 1f, new char[] {'1'}, new byte[] { 1 }), Collections.singleton(new TypeC('1', null)))); state.add(new TypeA("2", 2, new TypeB((short)2, 2L, 2f, new char[] {'2'}, new byte[] { 2 }), Collections.singleton(new TypeC('2', null)))); state.add(new TypeA("3", 3, new TypeB((short)3, 3L, 3f, new char[] {'3'}, new byte[] { 3 }), Collections.singleton(new TypeC('3', null)))); }); HollowConsumer consumer = HollowConsumer.newHollowConsumer() .withBlobRetriever(new HollowFilesystemBlobRetriever(localBlobStore.toPath(), Collections.singleton("B"))) .withMemoryMode(MemoryMode.SHARED_MEMORY_LAZY) .build(); consumer.triggerRefresh(); GenericHollowObject obj = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 1); Assert.assertEquals("2", obj.getObject("a1").getString("value")); Assert.assertEquals(2, obj.getInt("a2")); Assert.assertEquals(2L, obj.getObject("b").getLong("b2")); Assert.assertNull(consumer.getStateEngine().getTypeState("TypeC")); } private ProducerOptionalBlobPartConfig newPartConfig() { ProducerOptionalBlobPartConfig partConfig = new ProducerOptionalBlobPartConfig(); partConfig.addTypesToPart("B", "TypeB"); partConfig.addTypesToPart("C", "SetOfTypeC", "TypeC", "MapOfStringToListOfInteger", "ListOfInteger", "Integer"); return partConfig; } static File createLocalDir() throws IOException { File localDir = Files.createTempDirectory("hollow").toFile(); localDir.deleteOnExit(); return localDir; } }
8,725
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/missing/FakeMissingHollowRecord.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.missing; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.delegate.HollowRecordDelegate; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; import com.netflix.hollow.core.schema.HollowSchema; public class FakeMissingHollowRecord implements HollowRecord { private final HollowTypeDataAccess dataAccess; private final int ordinal; public FakeMissingHollowRecord(HollowTypeDataAccess dataAccess, int ordinal) { this.dataAccess = dataAccess; this.ordinal = ordinal; } @Override public int getOrdinal() { return ordinal; } @Override public HollowSchema getSchema() { return dataAccess.getSchema(); } @Override public HollowTypeDataAccess getTypeDataAccess() { return dataAccess; } @Override public HollowRecordDelegate getDelegate() { throw new UnsupportedOperationException(); } }
8,726
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/missing/MissingObjectFieldDefaultsTests.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.missing; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Before; import org.junit.Test; public class MissingObjectFieldDefaultsTests extends AbstractStateEngineTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); super.setUp(); } @Test public void testDefaultMissingObjectValue() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); roundTripSnapshot(); GenericHollowObject obj = (GenericHollowObject) GenericHollowRecordHelper.instantiate(readStateEngine, "TestObject", 1); assertEquals(2, obj.getInt("f1")); assertEquals("two", obj.getString("f2")); assertEquals(Long.MIN_VALUE, obj.getLong("f3")); assertEquals(Integer.MIN_VALUE, obj.getInt("f4")); assertTrue(Float.isNaN(obj.getFloat("f5"))); assertTrue(Double.isNaN(obj.getDouble("f6"))); assertEquals(null, obj.getString("f7")); assertFalse(obj.isStringFieldEqual("f7", "not-null")); assertTrue(obj.isStringFieldEqual("f7", null)); assertEquals(null, obj.getBytes("f8")); assertTrue(obj.isNull("f9")); assertFalse(obj.getBoolean("f10")); } private void addRecord(int intVal, String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", intVal); rec.setString("f2", strVal); writeStateEngine.add("TestObject", rec); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,727
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/missing/MissingMapTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.missing; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowMap; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.missing.HollowObjectMissingDataAccess; import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchema; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.junit.Assert; import org.junit.Test; public class MissingMapTest extends AbstractStateEngineTest { @Test public void testCompletelyMissingMap() throws IOException { roundTripSnapshot(); readStateEngine.setMissingDataHandler(new FakeMissingDataHandler()); GenericHollowMap map = (GenericHollowMap) GenericHollowRecordHelper.instantiate(readStateEngine, "MissingMap", 0); Assert.assertEquals(2, map.size()); Assert.assertTrue(map.containsKey(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 2))); Assert.assertEquals(300, map.get(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 3)).getOrdinal()); Assert.assertFalse(map.containsKey(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 0))); Assert.assertNull(map.get(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 4))); Iterator<Map.Entry<HollowRecord, HollowRecord>> rec = map.entrySet().iterator(); Assert.assertTrue(rec.hasNext()); Map.Entry<HollowRecord, HollowRecord> next = rec.next(); Assert.assertEquals(2, next.getKey().getOrdinal()); Assert.assertEquals("MissingObject", next.getKey().getSchema().getName()); Assert.assertEquals(200, next.getValue().getOrdinal()); Assert.assertEquals("MissingObject", next.getValue().getSchema().getName()); Assert.assertTrue(rec.hasNext()); next = rec.next(); Assert.assertEquals(3, next.getKey().getOrdinal()); Assert.assertEquals("MissingObject", next.getKey().getSchema().getName()); Assert.assertEquals(300, next.getValue().getOrdinal()); Assert.assertEquals("MissingObject", next.getValue().getSchema().getName()); Assert.assertEquals(300, map.get(next.getKey()).getOrdinal()); Assert.assertEquals("MissingObject", map.get(next.getKey()).getSchema().getName()); Assert.assertFalse(rec.hasNext()); } private class FakeMissingDataHandler extends DefaultMissingDataHandler { @Override public HollowSchema handleSchema(String type) { if("MissingMap".equals(type)) return new HollowMapSchema("MissingMap", "MissingObject", "MissingObject"); if("MissingObject".equals(type)) return new HollowObjectSchema("MissingObject", 0); return null; } @Override public int handleMapSize(String type, int ordinal) { return 2; } @Override public HollowMapEntryOrdinalIterator handleMapOrdinalIterator(String type, int ordinal) { return new HollowMapEntryOrdinalIterator() { private final int keys[] = { 2, 3 }; private final int values[] = { 200, 300 }; private int counter = -1; @Override public boolean next() { return ++counter < keys.length; } @Override public int getValue() { return values[counter]; } @Override public int getKey() { return keys[counter]; } }; } @Override public HollowMapEntryOrdinalIterator handleMapPotentialMatchOrdinalIterator(String type, int ordinal, int keyHashCode) { return handleMapOrdinalIterator(type, ordinal); } @Override public int handleMapGet(String type, int ordinal, int keyOrdinal, int keyOrdinalHashCode) { if(ordinal == 2) return 200; if(ordinal == 3) return 300; return -1; } } @Override protected void initializeTypeStates() { } }
8,728
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/missing/MissingSetTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.missing; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.api.objects.generic.GenericHollowSet; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.missing.HollowObjectMissingDataAccess; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSetSchema; import java.io.IOException; import java.util.Iterator; import org.junit.Assert; import org.junit.Test; public class MissingSetTest extends AbstractStateEngineTest { @Test public void testCompletelyMissingSet() throws IOException { roundTripSnapshot(); readStateEngine.setMissingDataHandler(new FakeMissingDataHandler()); GenericHollowSet set = (GenericHollowSet) GenericHollowRecordHelper.instantiate(readStateEngine, "MissingSet", 0); Assert.assertEquals(2, set.size()); Assert.assertTrue(set.contains(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 2))); Assert.assertFalse(set.contains(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 0))); Iterator<HollowRecord> rec = set.iterator(); Assert.assertTrue(rec.hasNext()); HollowRecord next = rec.next(); Assert.assertEquals(2, next.getOrdinal()); Assert.assertEquals("MissingObject", next.getSchema().getName()); Assert.assertTrue(rec.hasNext()); next = rec.next(); Assert.assertEquals(3, next.getOrdinal()); Assert.assertEquals("MissingObject", next.getSchema().getName()); Assert.assertFalse(rec.hasNext()); } private class FakeMissingDataHandler extends DefaultMissingDataHandler { @Override public HollowSchema handleSchema(String type) { if("MissingSet".equals(type)) return new HollowSetSchema("MissingSet", "MissingObject"); if("MissingObject".equals(type)) return new HollowObjectSchema("MissingObject", 0); return null; } @Override public int handleSetSize(String type, int ordinal) { return 2; } @Override public boolean handleSetContainsElement(String type, int ordinal, int elementOrdinal, int elementOrdinalHashCode) { return elementOrdinal == 2 || elementOrdinal == 3; } @Override public HollowOrdinalIterator handleSetPotentialMatchIterator(String type, int ordinal, int hashCode) { return handleSetIterator(type, ordinal); } @Override public HollowOrdinalIterator handleSetIterator(String type, int ordinal) { return new HollowOrdinalIterator() { private final int ordinals[] = {2, 3}; private int currentOrdinal = 0; @Override public int next() { if(currentOrdinal >= ordinals.length) return NO_MORE_ORDINALS; return ordinals[currentOrdinal++]; } }; } } @Override protected void initializeTypeStates() { } }
8,729
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/missing/MissingListTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.missing; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowList; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.missing.HollowObjectMissingDataAccess; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.schema.HollowListSchema; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchema; import java.io.IOException; import java.util.Iterator; import org.junit.Assert; import org.junit.Test; public class MissingListTest extends AbstractStateEngineTest { @Test public void testCompletelyMissingList() throws IOException { roundTripSnapshot(); readStateEngine.setMissingDataHandler(new FakeMissingDataHandler()); GenericHollowList list = (GenericHollowList) GenericHollowRecordHelper.instantiate(readStateEngine, "MissingList", 0); Assert.assertEquals(2, list.size()); Assert.assertTrue(list.contains(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 2))); Assert.assertFalse(list.contains(new FakeMissingHollowRecord(new HollowObjectMissingDataAccess(readStateEngine, "MissingObject"), 0))); Iterator<HollowRecord> rec = list.iterator(); Assert.assertTrue(rec.hasNext()); HollowRecord next = rec.next(); Assert.assertEquals(2, next.getOrdinal()); Assert.assertEquals("MissingObject", next.getSchema().getName()); Assert.assertTrue(rec.hasNext()); next = rec.next(); Assert.assertEquals(3, next.getOrdinal()); Assert.assertEquals("MissingObject", next.getSchema().getName()); Assert.assertFalse(rec.hasNext()); } private class FakeMissingDataHandler extends DefaultMissingDataHandler { @Override public HollowSchema handleSchema(String type) { if("MissingList".equals(type)) return new HollowListSchema("MissingList", "MissingObject"); if("MissingObject".equals(type)) return new HollowObjectSchema("MissingObject", 0); return null; } @Override public int handleListSize(String type, int ordinal) { return 2; } @Override public int handleListElementOrdinal(String type, int ordinal, int idx) { return idx + 2; } @Override public HollowOrdinalIterator handleListIterator(String type, int ordinal) { return new HollowOrdinalIterator() { private final int ordinals[] = {2, 3}; private int currentOrdinal = 0; @Override public int next() { if(currentOrdinal >= ordinals.length) return NO_MORE_ORDINALS; return ordinals[currentOrdinal++]; } }; } } @Override protected void initializeTypeStates() { } }
8,730
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/map/HollowMapHashKeyTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.map; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowMap; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowHashKey; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; public class HollowMapHashKeyTest { @Test public void testMapHashKeys() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.useDefaultHashKeys(); mapper.add(new TestTopLevelObject(1, new Obj(1, "New York", "US", 100), new Obj(2, "Ottawa", "CA", 200), new Obj(3, "Rome", "IT", 300), new Obj(4, "London", "GB", 400), new Obj(5, "Turin", "IT", 500))); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); GenericHollowObject obj = new GenericHollowObject(readEngine, "TestTopLevelObject", 0); GenericHollowObject key = (GenericHollowObject) obj.getMap("mapById").findKey(1); Assert.assertEquals("US", key.getObject("country").getString("value")); key = (GenericHollowObject) obj.getMap("mapById").findKey(2); Assert.assertEquals("CA", key.getObject("country").getString("value")); key = (GenericHollowObject) obj.getMap("mapById").findKey(3); Assert.assertEquals("IT", key.getObject("country").getString("value")); key = (GenericHollowObject) obj.getMap("mapById").findKey(4); Assert.assertEquals("GB", key.getObject("country").getString("value")); key = (GenericHollowObject) obj.getMap("mapById").findKey(5); Assert.assertEquals("IT", key.getObject("country").getString("value")); key = (GenericHollowObject)obj.getMap("mapByIdCountry").findKey(1, "US"); Assert.assertEquals(1, key.getInt("id")); key = (GenericHollowObject)obj.getMap("mapByIdCountry").findKey(2, "CA"); Assert.assertEquals(2, key.getInt("id")); key = (GenericHollowObject)obj.getMap("mapByIdCountry").findKey(3, "IT"); Assert.assertEquals(3, key.getInt("id")); key = (GenericHollowObject)obj.getMap("mapByIdCountry").findKey(4, "GB"); Assert.assertEquals(4, key.getInt("id")); key = (GenericHollowObject)obj.getMap("mapByIdCountry").findKey(5, "IT"); Assert.assertEquals(5, key.getInt("id")); key = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findKey(1, "New York", "US"); Assert.assertEquals(1, key.getInt("id")); key = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findKey(2, "Ottawa", "CA"); Assert.assertEquals(2, key.getInt("id")); key = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findKey(3, "Rome", "IT"); Assert.assertEquals(3, key.getInt("id")); key = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findKey(4, "London", "GB"); Assert.assertEquals(4, key.getInt("id")); key = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findKey(5, "Turin", "IT"); Assert.assertEquals(5, key.getInt("id")); GenericHollowObject value = (GenericHollowObject) obj.getMap("mapById").findValue(1); Assert.assertEquals(100, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapById").findValue(2); Assert.assertEquals(200, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapById").findValue(3); Assert.assertEquals(300, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapById").findValue(4); Assert.assertEquals(400, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapById").findValue(5); Assert.assertEquals(500, value.getInt("value")); value = (GenericHollowObject)obj.getMap("mapByIdCountry").findValue(1, "US"); Assert.assertEquals(100, value.getInt("value")); value = (GenericHollowObject)obj.getMap("mapByIdCountry").findValue(2, "CA"); Assert.assertEquals(200, value.getInt("value")); value = (GenericHollowObject)obj.getMap("mapByIdCountry").findValue(3, "IT"); Assert.assertEquals(300, value.getInt("value")); value = (GenericHollowObject)obj.getMap("mapByIdCountry").findValue(4, "GB"); Assert.assertEquals(400, value.getInt("value")); value = (GenericHollowObject)obj.getMap("mapByIdCountry").findValue(5, "IT"); Assert.assertEquals(500, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findValue(1, "New York", "US"); Assert.assertEquals(100, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findValue(2, "Ottawa", "CA"); Assert.assertEquals(200, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findValue(3, "Rome", "IT"); Assert.assertEquals(300, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findValue(4, "London", "GB"); Assert.assertEquals(400, value.getInt("value")); value = (GenericHollowObject) obj.getMap("mapByIdCityCountry").findValue(5, "Turin", "IT"); Assert.assertEquals(500, value.getInt("value")); Map.Entry<HollowRecord, HollowRecord> entry = obj.getMap("mapById").findEntry(1); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(1, key.getInt("id")); Assert.assertEquals(100, value.getInt("value")); entry = obj.getMap("mapById").findEntry(2); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(2, key.getInt("id")); Assert.assertEquals(200, value.getInt("value")); entry = obj.getMap("mapById").findEntry(3); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(3, key.getInt("id")); Assert.assertEquals(300, value.getInt("value")); entry = obj.getMap("mapById").findEntry(4); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(4, key.getInt("id")); Assert.assertEquals(400, value.getInt("value")); entry = obj.getMap("mapById").findEntry(5); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(5, key.getInt("id")); Assert.assertEquals(500, value.getInt("value")); entry = obj.getMap("mapByIdCountry").findEntry(1, "US"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(1, key.getInt("id")); Assert.assertEquals(100, value.getInt("value")); entry = obj.getMap("mapByIdCountry").findEntry(2, "CA"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(2, key.getInt("id")); Assert.assertEquals(200, value.getInt("value")); entry = obj.getMap("mapByIdCountry").findEntry(3, "IT"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(3, key.getInt("id")); Assert.assertEquals(300, value.getInt("value")); entry = obj.getMap("mapByIdCountry").findEntry(4, "GB"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(4, key.getInt("id")); Assert.assertEquals(400, value.getInt("value")); entry = obj.getMap("mapByIdCountry").findEntry(5, "IT"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(5, key.getInt("id")); Assert.assertEquals(500, value.getInt("value")); entry = obj.getMap("mapByIdCityCountry").findEntry(1, "New York", "US"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(1, key.getInt("id")); Assert.assertEquals(100, value.getInt("value")); entry = obj.getMap("mapByIdCityCountry").findEntry(2, "Ottawa", "CA"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(2, key.getInt("id")); Assert.assertEquals(200, value.getInt("value")); entry = obj.getMap("mapByIdCityCountry").findEntry(3, "Rome", "IT"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(3, key.getInt("id")); Assert.assertEquals(300, value.getInt("value")); entry = obj.getMap("mapByIdCityCountry").findEntry(4, "London", "GB"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(4, key.getInt("id")); Assert.assertEquals(400, value.getInt("value")); entry = obj.getMap("mapByIdCityCountry").findEntry(5, "Turin", "IT"); key = (GenericHollowObject) entry.getKey(); value = (GenericHollowObject) entry.getValue(); Assert.assertEquals(5, key.getInt("id")); Assert.assertEquals(500, value.getInt("value")); value = (GenericHollowObject)obj.getMap("intMap").findValue(1); Assert.assertEquals(100, value.getInt("value")); value = (GenericHollowObject)obj.getMap("intMap").findValue(2); Assert.assertEquals(200, value.getInt("value")); value = (GenericHollowObject)obj.getMap("intMap").findValue(3); Assert.assertEquals(300, value.getInt("value")); value = (GenericHollowObject)obj.getMap("intMap").findValue(4); Assert.assertEquals(400, value.getInt("value")); value = (GenericHollowObject)obj.getMap("intMap").findValue(5); Assert.assertEquals(500, value.getInt("value")); } @SuppressWarnings("unused") private static class TestTopLevelObject { int id; @HollowTypeName(name="MapById") @HollowHashKey(fields="id") Map<Obj, Integer> mapById; @HollowTypeName(name="MapByIdCountry") @HollowHashKey(fields={"id", "country.value"}) Map<Obj, Integer> mapByIdCountry; @HollowTypeName(name="MapByIdCityCountry") @HollowHashKey(fields={"id", "city", "country.value"}) Map<Obj, Integer> mapByIdCityCountry; Map<Integer, Integer> intMap; public TestTopLevelObject(int id, Obj... elements) { this.id = id; this.mapById = new HashMap<Obj, Integer>(); this.mapByIdCountry = new HashMap<Obj, Integer>(); this.mapByIdCityCountry = new HashMap<>(); this.intMap = new HashMap<Integer, Integer>(); for(int i=0;i<elements.length;i++) { mapById.put(elements[i], (int)elements[i].extraValue); mapByIdCountry.put(elements[i], (int)elements[i].extraValue); mapByIdCityCountry.put(elements[i], (int)elements[i].extraValue); intMap.put(elements[i].id, (int)elements[i].extraValue); } } } @SuppressWarnings("unused") private static class Obj { int id; @HollowInline String city; String country; long extraValue; public Obj(int id, String city, String country, long extraValue) { this.id = id; this.city = city; this.country = country; this.extraValue = extraValue; } } @Test public void testLookupOfLongKey() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeWithLongMap.class); TypeWithLongMap top = new TypeWithLongMap(); long longValue = (long)Integer.MAX_VALUE+1; top.longMap.put(longValue, 100L); mapper.add(top); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); GenericHollowMap map = new GenericHollowMap(readEngine, "MapOfLongToLong", 0); GenericHollowObject value = new GenericHollowObject(readEngine, "Long", map.findValue(longValue).getOrdinal()); Assert.assertEquals(100L, value.getLong("value")); } private static class TypeWithLongMap { Map<Long, Long> longMap = new HashMap<>(); } }
8,731
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/map/HollowMapShardedTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.map; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import java.io.IOException; import java.util.BitSet; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowMapShardedTest extends AbstractStateEngineTest { @Before public void setUp() { super.setUp(); } @Test public void testShardedData() throws IOException { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<2000;i++) { rec.reset(); rec.addEntry(i, i+1); rec.addEntry(i+2, i+3); rec.addEntry(i+4, i+5); writeStateEngine.add("TestMap", rec); } roundTripSnapshot(); Assert.assertEquals(8, readStateEngine.getTypeState("TestMap").numShards()); HollowMapTypeDataAccess mapDataAccess = (HollowMapTypeDataAccess) readStateEngine.getTypeDataAccess("TestMap"); for(int i=0;i<1000;i++) { Assert.assertEquals(3, mapDataAccess.size(i)); Assert.assertEquals(i+1, mapDataAccess.get(i, i)); Assert.assertEquals(i+3, mapDataAccess.get(i, i+2)); Assert.assertEquals(i+5, mapDataAccess.get(i, i+4)); } for(int i=0;i<2000;i++) { rec.reset(); rec.addEntry(i*2, i*2+1); rec.addEntry(i*2+2, i*2+3); rec.addEntry(i*2+4, i*2+5); writeStateEngine.add("TestMap", rec); } roundTripDelta(); int expectedValue = 0; BitSet populatedOrdinals = readStateEngine.getTypeState("TestMap").getPopulatedOrdinals(); int ordinal = populatedOrdinals.nextSetBit(0); while(ordinal != -1) { Assert.assertEquals(3, mapDataAccess.size(ordinal)); Assert.assertEquals(expectedValue+1, mapDataAccess.get(ordinal, expectedValue)); Assert.assertEquals(expectedValue+3, mapDataAccess.get(ordinal, expectedValue+2)); Assert.assertEquals(expectedValue+5, mapDataAccess.get(ordinal, expectedValue+4)); expectedValue += 2; ordinal = populatedOrdinals.nextSetBit(ordinal+1); } } @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(4096); writeStateEngine.addTypeState(new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestKey", "TestValue"))); } }
8,732
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/map/HollowMapDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.map; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.map.HollowMapTypeReadState; import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowMapDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(10, 20, 30, 40); addRecord(40, 50, 60, 70); addRecord(70, 80, 90, 100); roundTripSnapshot(); addRecord(10, 20, 30, 40); addRecord(70, 80, 90, 100); addRecord(100, 200, 300, 400, 500, 600, 700, 800); addRecord(1, 2, 3, 4); roundTripDelta(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); assertMap(typeState, 0, 10, 20, 30, 40); assertMap(typeState, 1, 40, 50, 60, 70); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertMap(typeState, 2, 70, 80, 90, 100); assertMap(typeState, 3, 100, 200, 300, 400, 500, 600, 700, 800); assertMap(typeState, 4, 1, 2, 3, 4); Assert.assertEquals(4, typeState.maxOrdinal()); roundTripDelta(); assertMap(typeState, 0, 10, 20, 30, 40); /// all maps were "removed", but again hang around until the following cycle. assertMap(typeState, 1); /// this map should now be disappeared. assertMap(typeState, 2, 70, 80, 90, 100); /// "ghost" assertMap(typeState, 3, 100, 200, 300, 400, 500, 600, 700, 800); /// "ghost" assertMap(typeState, 4, 1, 2, 3, 4); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(634, 54732); addRecord(1, 2, 3, 4); roundTripDelta(); Assert.assertEquals(1, typeState.maxOrdinal()); assertMap(typeState, 0, 634, 54732); /// now, since all maps were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertMap(typeState, 1, 1, 2, 3, 4); /// even though 1, 2, 3 had an equivalent map in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } @Test public void testShrinkingMapEntrySize() throws IOException { addRecord(1, 1000, 2, 2000); roundTripSnapshot(); addRecord(1, 1000, 2, 200); roundTripDelta(); addRecord(1, 1000, 2, 200); addRecord(1, 1001, 2, 201); roundTripDelta(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); assertMap(typeState, 1, 1, 1000, 2, 200); } @Test public void testSingleEmptyMap() throws IOException { addRecord(); roundTripSnapshot(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); Assert.assertEquals(0, typeState.maxOrdinal()); Assert.assertEquals(0, typeState.size(0)); } @Test public void testSingleMapWith0KeyValueOrdinals() throws IOException { addRecord(0,0); roundTripSnapshot(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); Assert.assertEquals(0, typeState.maxOrdinal()); Assert.assertEquals(1, typeState.size(0)); HollowMapEntryOrdinalIterator ordinalIterator = typeState.ordinalIterator(0); Assert.assertTrue(ordinalIterator.next()); Assert.assertEquals(0, ordinalIterator.getKey()); Assert.assertEquals(0, ordinalIterator.getValue()); Assert.assertFalse(ordinalIterator.next()); } @Test public void testStaleReferenceException() throws IOException { addRecord(0, 0); roundTripSnapshot(); readStateEngine.invalidate(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); try { assertMap(typeState, 0, 0, 0); Assert.fail("Should have thrown Exception"); } catch(NullPointerException expected) { } } private void addRecord(int... ordinals) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<ordinals.length;i+=2) { rec.addEntry(ordinals[i], ordinals[i+1]); } writeStateEngine.add("TestMap", rec); } private void assertMap(HollowMapTypeReadState readState, int ordinal, int... elements) { Assert.assertEquals(elements.length / 2, readState.size(ordinal)); for(int i=0;i<elements.length;i+=2) { Assert.assertEquals(elements[i+1], readState.get(ordinal, elements[i])); } } @Override protected void initializeTypeStates() { HollowMapTypeWriteState writeState = new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestKey", "TestValue")); writeStateEngine.addTypeState(writeState); } }
8,733
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/map/HollowMapCollectionTest.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.map; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowMap; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.stream.IntStream; import org.junit.Assert; import org.junit.Test; public class HollowMapCollectionTest { @Test public void testEntryIterator() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new Top(1, 2, 3)); HollowReadStateEngine rse = new HollowReadStateEngine(); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, rse); GenericHollowMap m = new GenericHollowMap(rse, "MapOfIntegerToInteger", 0); List<Integer> keys = m.entrySet().stream().map(Map.Entry::getKey) .map(r -> (GenericHollowObject) r) .map(o -> o.getInt("value")) .sorted() .collect(toList()); Assert.assertEquals(Arrays.asList(1, 2, 3), keys); Iterator<Map.Entry<HollowRecord, HollowRecord>> iterator = m.entrySet().iterator(); iterator.forEachRemaining(e -> {}); Assert.assertFalse(iterator.hasNext()); try { iterator.next(); Assert.fail(); } catch (NoSuchElementException e) { } } @Test public void testEquals() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new Top(1, 2, 3)); mapper.add(new Top(1, 2, 4)); mapper.add(new Top(1, 2, 3, 4)); HollowReadStateEngine rse = new HollowReadStateEngine(); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, rse); GenericHollowMap m1 = new GenericHollowMap(rse, "MapOfStringToString", 0); GenericHollowMap m2 = new GenericHollowMap(rse, "MapOfStringToString", 0); GenericHollowMap m3 = new GenericHollowMap(rse, "MapOfStringToString", 1); GenericHollowMap m4 = new GenericHollowMap(rse, "MapOfStringToString", 2); GenericHollowMap m5 = new GenericHollowMap(rse, "MapOfIntegerToInteger", 0); assertMapEquals(m1, m1, true); assertMapEquals(m1, m2, true); assertMapEquals(m1, new HashMap<>(m1), true); assertMapEquals(m1, m3, false); assertMapEquals(m1, m4, false); assertMapEquals(m1, m5, false); Assert.assertNotEquals(m1, new ArrayList<>(m1.keySet())); } static void assertMapEquals(Map<?, ?> a, Map<?, ?> b, boolean equal) { if (equal) { Assert.assertEquals(a.hashCode(), b.hashCode()); Assert.assertEquals(a, b); Assert.assertTrue(equalsUsingContains(a, b)); Assert.assertEquals(b, a); Assert.assertTrue(equalsUsingContains(b, a)); } else { Assert.assertNotEquals(a, b); Assert.assertFalse(equalsUsingContains(a, b)); Assert.assertNotEquals(b, a); Assert.assertFalse(equalsUsingContains(b, a)); } } static class Top { Map<Integer, Integer> ints; Map<String, String> strings; Top(int... vs) { this.ints = IntStream.of(vs).boxed().collect(toMap(e -> e, e -> e)); this.strings = IntStream.of(vs).mapToObj(Integer::toString).collect(toMap(e -> e, e -> e)); } } static boolean equalsUsingContains(Map<?, ?> a, Map<?, ?> b) { if (a.size() != b.size()) { return false; } return a.entrySet().containsAll(b.entrySet()); } }
8,734
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/map/HollowMapFastDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.map; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.map.HollowMapTypeReadState; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowMapFastDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(10, 20, 30, 40); addRecord(20, 30, 40, 50); addRecord(30, 40, 50, 60); addRecord(40, 50, 60, 70); addRecord(50, 60, 70, 80); addRecord(60, 70, 80, 90); addRecord(70, 80, 90, 100); addRecord(80, 90, 100, 110); addRecord(90, 100, 110, 120); addRecord(100, 110, 120, 130, 140, 150, 160, 170); addRecord(110, 120, 130, 140, 150, 160); addRecord(120, 130, 140, 150); addRecord(130, 140, 150, 160); addRecord(140, 150, 160, 170); addRecord(150, 160, 170, 180); addRecord(160, 170, 180, 190); roundTripSnapshot(); addRecord(10, 20, 30, 40); addRecord(20, 30, 40, 50); addRecord(30, 40, 50, 60); addRecord(40, 50, 60, 70); addRecord(50, 60, 70, 80); addRecord(60, 70, 80, 90); addRecord(70, 80, 90, 100); addRecord(80, 90, 100, 110); addRecord(90, 100, 110, 120); addRecord(101, 111, 121, 131, 141, 151, 161, 171); addRecord(110, 120, 130, 140, 150, 160); addRecord(120, 130, 140, 150); addRecord(130, 140, 150, 160); addRecord(140, 150, 160, 170); addRecord(150, 160, 170, 180); addRecord(160, 170, 180, 190); roundTripDelta(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); assertMap(typeState, 0, 10, 20, 30, 40); assertMap(typeState, 1, 20, 30, 40, 50); assertMap(typeState, 2, 30, 40, 50, 60); assertMap(typeState, 3, 40, 50, 60, 70); assertMap(typeState, 4, 50, 60, 70, 80); assertMap(typeState, 5, 60, 70, 80, 90); assertMap(typeState, 6, 70, 80, 90, 100); assertMap(typeState, 7, 80, 90, 100, 110); assertMap(typeState, 8, 90, 100, 110, 120); assertMap(typeState, 9, 100, 110, 120, 130, 140, 150, 160, 170); // ghost assertMap(typeState, 10, 110, 120, 130, 140, 150, 160); assertMap(typeState, 11, 120, 130, 140, 150); assertMap(typeState, 12, 130, 140, 150, 160); assertMap(typeState, 13, 140, 150, 160, 170); assertMap(typeState, 14, 150, 160, 170, 180); assertMap(typeState, 15, 160, 170, 180, 190); assertMap(typeState, 16, 101, 111, 121, 131, 141, 151, 161, 171); addRecord(10, 20, 30, 40); addRecord(20, 30, 40, 50); addRecord(30, 40, 50, 60); addRecord(40, 50, 60, 70); addRecord(50, 60, 70, 80); addRecord(70, 80, 90, 100); addRecord(80, 90, 100, 110); addRecord(90, 100, 110, 120); addRecord(101, 111, 121, 131, 141, 151, 161, 171); addRecord(111, 121, 131, 141, 151, 161); addRecord(120, 130, 140, 150); addRecord(130, 140, 150, 160); addRecord(140, 150, 160, 170); addRecord(150, 160, 170, 180); addRecord(160, 170, 180, 190); roundTripDelta(); assertMap(typeState, 0, 10, 20, 30, 40); assertMap(typeState, 1, 20, 30, 40, 50); assertMap(typeState, 2, 30, 40, 50, 60); assertMap(typeState, 3, 40, 50, 60, 70); assertMap(typeState, 4, 50, 60, 70, 80); assertMap(typeState, 5, 60, 70, 80, 90); // ghost assertMap(typeState, 6, 70, 80, 90, 100); assertMap(typeState, 7, 80, 90, 100, 110); assertMap(typeState, 8, 90, 100, 110, 120); assertMap(typeState, 9, 111, 121, 131, 141, 151, 161); assertMap(typeState, 10, 110, 120, 130, 140, 150, 160); // ghost assertMap(typeState, 11, 120, 130, 140, 150); assertMap(typeState, 12, 130, 140, 150, 160); assertMap(typeState, 13, 140, 150, 160, 170); assertMap(typeState, 14, 150, 160, 170, 180); assertMap(typeState, 15, 160, 170, 180, 190); assertMap(typeState, 16, 101, 111, 121, 131, 141, 151, 161, 171); addRecord(10, 20, 30, 40); addRecord(20, 30, 40, 50); addRecord(31, 41, 51, 61); addRecord(40, 50, 60, 70); addRecord(50, 60, 70, 80); addRecord(70, 80, 90, 100); addRecord(80, 90, 100, 110); addRecord(90, 100, 110, 120); addRecord(101, 111, 121, 131, 141, 151, 161, 171); addRecord(111, 121, 131, 141, 151, 161); addRecord(120, 130, 140, 150); addRecord(130, 140, 150, 160); addRecord(140, 150, 160, 170); addRecord(150, 160, 170, 180); addRecord(160, 170, 180, 190); roundTripDelta(); assertMap(typeState, 0, 10, 20, 30, 40); assertMap(typeState, 1, 20, 30, 40, 50); assertMap(typeState, 2, 30, 40, 50, 60); // ghost assertMap(typeState, 3, 40, 50, 60, 70); assertMap(typeState, 4, 50, 60, 70, 80); assertMap(typeState, 5, 31, 41, 51, 61); assertMap(typeState, 6, 70, 80, 90, 100); assertMap(typeState, 7, 80, 90, 100, 110); assertMap(typeState, 8, 90, 100, 110, 120); assertMap(typeState, 9, 111, 121, 131, 141, 151, 161); assertMap(typeState, 10); assertMap(typeState, 11, 120, 130, 140, 150); assertMap(typeState, 12, 130, 140, 150, 160); assertMap(typeState, 13, 140, 150, 160, 170); assertMap(typeState, 14, 150, 160, 170, 180); assertMap(typeState, 15, 160, 170, 180, 190); assertMap(typeState, 16, 101, 111, 121, 131, 141, 151, 161, 171); } private void addRecord(int... ordinals) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<ordinals.length;i+=2) { rec.addEntry(ordinals[i], ordinals[i+1]); } writeStateEngine.add("TestMap", rec); } private void assertMap(HollowMapTypeReadState readState, int ordinal, int... elements) { Assert.assertEquals(elements.length / 2, readState.size(ordinal)); for(int i=0;i<elements.length;i+=2) { Assert.assertEquals(elements[i+1], readState.get(ordinal, elements[i])); } } @Override protected void initializeTypeStates() { HollowMapTypeWriteState writeState = new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestKey", "TestValue")); writeStateEngine.addTypeState(writeState); } }
8,735
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/map/HollowMapLargeTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.map; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.map.HollowMapTypeReadState; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class HollowMapLargeTest extends AbstractStateEngineTest { @Before public void setUp() { super.setUp(); } @Test public void testSnapshotSmall() throws IOException { testSnapshot(1 << 9, 1 << 8, 1 << 22); } @Ignore @Test // This test configuration can use up lots of memory public void testSnapshotLarge() throws IOException { testSnapshot(1 << 9, 1 << 16, 1 << 22); } void testSnapshot(int nMaps, int maxOrdinal, int initialValue) throws IOException { for (int n = 0; n < nMaps; n++) { int v = initialValue - n; HollowMapWriteRecord rec = new HollowMapWriteRecord(); for (int i = 0; i < maxOrdinal; i++, v--) { rec.addEntry(i, v); } writeStateEngine.add("TestMap", rec); } roundTripSnapshot(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); for (int n = 0; n < nMaps; n++) { int l = typeState.size(n); Assert.assertEquals(maxOrdinal, l); int v = initialValue - n; for (int i = 0; i < maxOrdinal; i++, v--) { Assert.assertEquals(n + " " + i, v, typeState.get(n, i)); } } } @Test public void testDeltaSmall() throws IOException { testDelta(1 << 9, 1 << 8, 1 << 22); } @Ignore @Test // This test configuration can use up lots of memory public void testDeltaLarge() throws IOException { testDelta(1 << 9, 1 << 16, 1 << 22); } void testDelta(int nMaps, int maxOrdinal, int initialValue) throws IOException { { int v = initialValue; HollowMapWriteRecord rec = new HollowMapWriteRecord(); for (int i = 0; i < maxOrdinal; i++, v--) { rec.addEntry(i, v); } } roundTripSnapshot(); for (int n = 0; n < nMaps; n++) { int v = initialValue - n; HollowMapWriteRecord rec = new HollowMapWriteRecord(); for (int i = 0; i < maxOrdinal; i++, v--) { rec.addEntry(i, v); } writeStateEngine.add("TestMap", rec); } roundTripDelta(); HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); for (int n = 0; n < nMaps; n++) { int l = typeState.size(n); Assert.assertEquals(maxOrdinal, l); int v = initialValue - n; for (int i = 0; i < maxOrdinal; i++, v--) { Assert.assertEquals(n + " " + i, v, typeState.get(n, i)); } } } @Override protected void initializeTypeStates() { HollowMapTypeWriteState writeState = new HollowMapTypeWriteState( new HollowMapSchema("TestMap", "TestKey", "TestValue")); writeStateEngine.addTypeState(writeState); } }
8,736
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectReverseDeltaVarLengthFieldTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.HollowBlobInput; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowObjectReverseDeltaVarLengthFieldTest extends AbstractStateEngineTest { @Test public void test() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add("one"); mapper.add("two"); mapper.add("three"); mapper.add("four"); roundTripSnapshot(); mapper.add("one"); mapper.add("four"); roundTripSnapshot(); mapper.add("one"); byte reverseDelta1[] = getReverseDelta(); roundTripDelta(); mapper.add("one"); mapper.add("two"); byte reverseDelta2[] = getReverseDelta(); roundTripDelta(); HollowBlobReader reader = new HollowBlobReader(readStateEngine); reader.applyDelta(HollowBlobInput.serial(reverseDelta2)); reader.applyDelta(HollowBlobInput.serial(reverseDelta1)); Assert.assertEquals("four", ((HollowObjectTypeReadState)readStateEngine.getTypeState("String")).readString(3, 0)); } private byte[] getReverseDelta() throws IOException { ByteArrayOutputStream reverseDelta = new ByteArrayOutputStream(); HollowBlobWriter writer = new HollowBlobWriter(writeStateEngine); writer.writeReverseDelta(reverseDelta); return reverseDelta.toByteArray(); } @Override protected void initializeTypeStates() { new HollowObjectMapper(writeStateEngine).initializeTypeState(String.class); } }
8,737
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectLargeFieldTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectLargeFieldTest extends AbstractStateEngineTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 3); schema.addField("longField", FieldType.LONG); schema.addField("intField", FieldType.INT); schema.addField("doubleField", FieldType.DOUBLE); super.setUp(); } @Test public void test() throws IOException { addRecord(1, 1, 2.53D); addRecord(100, 100, 3523456.3252352456346D); roundTripSnapshot(); addRecord(100, 100, 3523456.3252352456346D); addRecord(Long.MIN_VALUE, Integer.MIN_VALUE, Double.MIN_VALUE); addRecord(200, 200, 1.00003D); roundTripDelta(); assertObject(1, 100, 100, 3523456.3252352456346D); assertObject(2, Long.MIN_VALUE, Integer.MIN_VALUE, Double.MIN_VALUE); assertObject(3, 200, 200, 1.00003D); addRecord(Long.MAX_VALUE, Integer.MAX_VALUE, Double.MAX_VALUE); addRecord(100, 100, 3523456.3252352456346D); addRecord(Long.MIN_VALUE, Integer.MIN_VALUE, Double.MIN_VALUE); addRecord(200, 200, 1.00003D); roundTripDelta(); assertObject(0, Long.MAX_VALUE, Integer.MAX_VALUE, Double.MAX_VALUE); assertObject(1, 100, 100, 3523456.3252352456346D); assertObject(2, Long.MIN_VALUE, Integer.MIN_VALUE, Double.MIN_VALUE); assertObject(3, 200, 200, 1.00003D); } private void addRecord(long l, int i, double d) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setLong("longField", l); rec.setInt("intField", i); rec.setDouble("doubleField", d); writeStateEngine.add("TestObject", rec); } private void assertObject(int ordinal, long l, int i, double d) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(l, obj.getLong("longField")); Assert.assertEquals(i, obj.getInt("intField")); Assert.assertTrue(d == obj.getDouble("doubleField")); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); } }
8,738
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectNullStringValueTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectNullStringValueTest extends AbstractStateEngineTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); super.setUp(); } @Test public void test() throws IOException { addRecord(0, "zero"); addRecord(1, null); addRecord(2, "two"); roundTripSnapshot(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); assertObject(typeState, 0, 0, "zero"); assertObject(typeState, 1, 1, null); assertObject(typeState, 2, 2, "two"); } private void addRecord(int intVal, String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", intVal); rec.setString("f2", strVal); writeStateEngine.add("TestObject", rec); } private void assertObject(HollowObjectTypeReadState readState, int ordinal, int intVal, String strVal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); Assert.assertEquals(intVal, obj.getInt("f1")); Assert.assertEquals(strVal, obj.getString("f2")); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,739
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectLargeFieldSizeTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Test; public class HollowObjectLargeFieldSizeTest { @Test public void preserveNullValueWhenFieldSizeIsLargeInSnapshot() { InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = producer.runCycle(state -> { state.add(new Long(1L)); state.add(new Long(0L)); state.add(new Long(2L)); state.add(new Long(-1L)); state.add(new Long(3L)); state.add(new Long(Long.MIN_VALUE)); state.add(new Long(4L)); state.add(new Long(Long.MAX_VALUE)); state.add(new Long(5L)); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v1); assertValues(consumer, 1L, 0L, 2L, -1L, 3L, Long.MIN_VALUE, 4L, Long.MAX_VALUE, 5L); } @Test public void preserveNullValueWhenFieldSizeBecomesLargeInDelta() { InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .noIntegrityCheck() .build(); long v1 = producer.runCycle(state -> { state.add(new Long(1L)); state.add(new Long(0L)); state.add(new Long(2L)); state.add(new Long(-1L)); state.add(new Long(3L)); state.add(new Long(4L)); state.add(new Long(5L)); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v1); assertValues(consumer, 1L, 0L, 2L, -1L, 3L, 4L, 5L); long v2 = producer.runCycle(state -> { state.add(new Long(1L)); state.add(new Long(0L)); state.add(new Long(2L)); state.add(new Long(-1L)); state.add(new Long(3L)); state.add(new Long(4L)); state.add(new Long(5L)); state.add(new Long(Long.MIN_VALUE)); state.add(new Long(Long.MAX_VALUE)); }); consumer.triggerRefreshTo(v2); assertValues(consumer, 1L, 0L, 2L, -1L, 3L, 4L, 5L, Long.MIN_VALUE, Long.MAX_VALUE); } private void assertValues(HollowConsumer consumer, long... values) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState)consumer.getStateEngine().getTypeState("Long"); for(int i=0;i<values.length;i++) { Assert.assertEquals(values[i], typeState.readLong(i, 0)); } } }
8,740
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectVarLengthFieldRemovalTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectVarLengthFieldRemovalTest extends AbstractStateEngineTest { private HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); super.setUp(); } @Test public void test() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); roundTripSnapshot(); addRecord(1, "one"); addRecord(3, "three"); addRecord(1000, "one thousand"); roundTripDelta(); addRecord(1, "one"); addRecord(3, "three"); addRecord(4, "four"); addRecord(1000, "one thousand"); roundTripDelta(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); Assert.assertEquals(3, typeState.maxOrdinal()); assertObject(typeState, 0, 1, "one"); assertObject(typeState, 1, 4, "four"); assertObject(typeState, 2, 3, "three"); assertObject(typeState, 3, 1000, "one thousand"); } private void addRecord(int intVal, String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", intVal); rec.setString("f2", strVal); writeStateEngine.add("TestObject", rec); } private void assertObject(HollowObjectTypeReadState readState, int ordinal, int intVal, String strVal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); Assert.assertEquals(intVal, obj.getInt("f1")); Assert.assertEquals(strVal, obj.getString("f2")); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,741
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectExactBitBoundaryEdgeCaseTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Before; import org.junit.Test; public class HollowObjectExactBitBoundaryEdgeCaseTest extends AbstractStateEngineTest { private HollowObjectSchema schema; private HollowObjectSchema schema2; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 3); schema.addField("float1", FieldType.FLOAT); schema.addField("float2", FieldType.FLOAT); schema.addField("unpopulatedField", FieldType.INT); schema2 = new HollowObjectSchema("TestObject2", 3); schema2.addField("int1", FieldType.INT); schema2.addField("int2", FieldType.INT); schema2.addField("unpopulatedField", FieldType.INT); super.setUp(); } @Test public void unpopulatedFieldOnSegmentBoundary() throws IOException { for(int i=0;i<4094;i++) { addRecord((float)i); } for(int i=0;i<992;i++) { addRecord(i); } roundTripSnapshot(); for(int i=0;i<4096;i++) { addRecord((float)i); } for(int i=0;i<993;i++) { addRecord(i); } roundTripDelta(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState)readStateEngine.getTypeDataAccess("TestObject"); typeState.readInt(4096, 2); typeState = (HollowObjectTypeReadState)readStateEngine.getTypeDataAccess("TestObject2"); typeState.readInt(992, 2); } private void addRecord(float value) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setFloat("float1", value); rec.setFloat("float2", value); writeStateEngine.add("TestObject", rec); } private void addRecord(int value) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema2); rec.setInt("int1", value); rec.setInt("int2", 1047552); writeStateEngine.add("TestObject2", rec); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema2)); } }
8,742
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectShardedTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import java.util.BitSet; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectShardedTest extends AbstractStateEngineTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 3); schema.addField("longField", FieldType.LONG); schema.addField("intField", FieldType.INT); schema.addField("doubleField", FieldType.DOUBLE); super.setUp(); } @Test public void testShardedData() throws IOException { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); for(int i=0;i<1000;i++) { rec.reset(); rec.setLong("longField", i); rec.setInt("intField", i); rec.setDouble("doubleField", i); writeStateEngine.add("TestObject", rec); } roundTripSnapshot(); Assert.assertEquals(4, readStateEngine.getTypeState("TestObject").numShards()); for(int i=0;i<1000;i++) { GenericHollowObject obj = new GenericHollowObject(readStateEngine, "TestObject", i); Assert.assertEquals(i, obj.getLong("longField")); Assert.assertEquals(i, obj.getInt("intField")); Assert.assertEquals((double)i, obj.getDouble("doubleField"), 0); } for(int i=0;i<1000;i++) { rec.reset(); rec.setLong("longField", i*2); rec.setInt("intField", i*2); rec.setDouble("doubleField", i*2); writeStateEngine.add("TestObject", rec); } roundTripDelta(); int expectedValue = 0; BitSet populatedOrdinals = readStateEngine.getTypeState("TestObject").getPopulatedOrdinals(); int ordinal = populatedOrdinals.nextSetBit(0); while(ordinal != -1) { GenericHollowObject obj = new GenericHollowObject(readStateEngine, "TestObject", ordinal); Assert.assertEquals(expectedValue, obj.getLong("longField")); Assert.assertEquals(expectedValue, obj.getInt("intField")); Assert.assertEquals(expectedValue, obj.getDouble("doubleField"), 0); expectedValue += 2; ordinal = populatedOrdinals.nextSetBit(ordinal+1); } } @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(4096); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); } }
8,743
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectDeltaTest extends AbstractStateEngineTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); super.setUp(); } @Test public void test() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); roundTripSnapshot(); addRecord(1, "one"); addRecord(3, "three"); addRecord(1000, "ten thousand"); addRecord(0, "zero"); writeStateEngine.resetToLastPrepareForNextCycle(); writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(1, "one"); addRecord(3, "three"); addRecord(1000, "one thousand"); addRecord(0, "zero"); roundTripDelta(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 0, 1, "one"); assertObject(typeState, 1, 2, "two"); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 2, 3, "three"); assertObject(typeState, 3, 1000, "one thousand"); assertObject(typeState, 4, 0, "zero"); roundTripDelta(); assertObject(typeState, 0, 1, "one"); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, 2, ""); /// this record should now be disappeared. assertObject(typeState, 2, 3, "three"); /// "ghost" assertObject(typeState, 3, 1000, "one thousand"); /// "ghost" assertObject(typeState, 4, 0, "zero"); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(634, "six hundred thirty four"); addRecord(0, "zero"); roundTripDelta(); Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, 634, "six hundred thirty four"); /// now, since all records were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertObject(typeState, 1, 0, "zero"); /// even though "zero" had an equivalent record in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } @Test public void allStringFieldsNullTest() throws IOException { addRecord(1, null); addRecord(2, null); roundTripSnapshot(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); assertObject(typeState, 0, 1, null); assertObject(typeState, 1, 2, null); } @Test public void testStaleReferenceException() throws IOException { addRecord(0, null); roundTripSnapshot(); readStateEngine.invalidate(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); try { assertObject(typeState, 0, 0, null); Assert.fail("Should have thrown Exception"); } catch(NullPointerException expected) { } } private void addRecord(int intVal, String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", intVal); rec.setString("f2", strVal); writeStateEngine.add("TestObject", rec); } private void assertObject(HollowObjectTypeReadState readState, int ordinal, int intVal, String strVal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); Assert.assertEquals(intVal, obj.getInt("f1")); Assert.assertEquals(strVal, obj.getString("f2")); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,744
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectRemovalTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectRemovalTest extends AbstractStateEngineTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.INT); super.setUp(); } @Test public void removeRecordWithLargeFieldValueAtEndOfRecord() throws IOException { addRecord(10, 251); addRecord(15, 15); addRecord(20, 1021); addRecord(30, 251); roundTripSnapshot(); addRecord(10, 251); addRecord(30, 251); roundTripDelta(); addRecord(10, 251); addRecord(30, 251); addRecord(1, 1); roundTripDelta(); assertObject(0, 10, 251); assertObject(3, 30, 251); } private void assertObject(int ordinal, int int1, int int2) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(int1, obj.getInt("f1")); Assert.assertEquals(int2, obj.getInt("f2")); } private void addRecord(int int1, int int2) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", int1); rec.setInt("f2", int2); writeStateEngine.add("TestObject", rec); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,745
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectStringEqualityTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectStringEqualityTest extends AbstractStateEngineTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 1); schema.addField("str", FieldType.STRING); super.setUp(); } @Test public void testStringEquality() throws Exception { addRecord("test"); roundTripSnapshot(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState)readStateEngine.getTypeState("TestObject"); Assert.assertFalse(typeState.isStringFieldEqual(0, 0, "tes")); Assert.assertTrue(typeState.isStringFieldEqual(0, 0, "test")); Assert.assertFalse(typeState.isStringFieldEqual(0, 0, "testt")); } private void addRecord(String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setString("str", strVal); writeStateEngine.add("TestObject", rec); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,746
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/object/HollowObjectReverseDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.object; import com.netflix.hollow.core.read.HollowBlobInput; import com.netflix.hollow.core.read.engine.HollowBlobReader; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectReverseDeltaTest { HollowObjectSchema schema; HollowWriteStateEngine writeEngine; HollowReadStateEngine readEngine; @Before public void setUp() { schema = new HollowObjectSchema("test", 1); schema.addField("field", FieldType.INT); HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeEngine = new HollowWriteStateEngine(); writeEngine.addTypeState(writeState); readEngine = new HollowReadStateEngine(); } @Test public void test() throws IOException { addWriteRecord(100); addWriteRecord(101); addWriteRecord(102); addWriteRecord(103); writeEngine.prepareForWrite(); writeEngine.prepareForNextCycle(); addWriteRecord(100); addWriteRecord(101); addWriteRecord(103); writeEngine.prepareForWrite(); byte reverseDelta3[] = createReverseDelta(); writeEngine.prepareForNextCycle(); addWriteRecord(101); writeEngine.prepareForWrite(); byte reverseDelta2[] = createReverseDelta(); writeEngine.prepareForNextCycle(); addWriteRecord(100); addWriteRecord(101); writeEngine.prepareForWrite(); byte reverseDelta1[] = createReverseDelta(); byte snapshot[] = createSnapshot(); HollowBlobReader reader = new HollowBlobReader(readEngine); reader.readSnapshot(HollowBlobInput.serial(snapshot)); assertState(100, 101); reader.applyDelta(HollowBlobInput.serial(reverseDelta1)); assertState(-100, 101); reader.applyDelta(HollowBlobInput.serial(reverseDelta2)); assertState(100, 101, -1, 103); reader.applyDelta(HollowBlobInput.serial(reverseDelta3)); assertState(100, 101, 102, 103); } private void assertState(int... expectedValuesInOrdinalPosition) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readEngine.getTypeState("test"); PopulatedOrdinalListener listener = typeState.getListener(PopulatedOrdinalListener.class); Assert.assertEquals(expectedValuesInOrdinalPosition.length, listener.getPopulatedOrdinals().length()); for(int i=0;i<expectedValuesInOrdinalPosition.length;i++) { if(expectedValuesInOrdinalPosition[i] != -1) { if(expectedValuesInOrdinalPosition[i] < 0) Assert.assertFalse(listener.getPopulatedOrdinals().get(i)); else Assert.assertTrue(listener.getPopulatedOrdinals().get(i)); int expectedValue = Math.abs(expectedValuesInOrdinalPosition[i]); Assert.assertEquals(expectedValue, typeState.readInt(i, 0)); } } } private void addWriteRecord(int value) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("field", value); writeEngine.add("test", rec); } private byte[] createReverseDelta() throws IOException { HollowBlobWriter writer = new HollowBlobWriter(writeEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeReverseDelta(baos); return baos.toByteArray(); } private byte[] createSnapshot() throws IOException { HollowBlobWriter writer = new HollowBlobWriter(writeEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); return baos.toByteArray(); } }
8,747
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/list/HollowListCollectionTest.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.list; import static java.util.stream.Collectors.toList; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowList; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.stream.IntStream; import org.junit.Assert; import org.junit.Test; public class HollowListCollectionTest { static class Top { List<Integer> ints; List<String> strings; Top(int... vs) { this.ints = IntStream.of(vs).boxed().collect(toList()); this.strings = IntStream.of(vs).mapToObj(Integer::toString).collect(toList()); } } @Test public void testIterator() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new Top(1, 2, 3)); HollowReadStateEngine rse = new HollowReadStateEngine(); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, rse); GenericHollowList l = new GenericHollowList(rse, "ListOfInteger", 0); List<Integer> keys = l.stream() .map(r -> (GenericHollowObject) r) .map(o -> o.getInt("value")) .collect(toList()); Assert.assertEquals(Arrays.asList(1, 2, 3), keys); Iterator<HollowRecord> iterator = l.iterator(); iterator.forEachRemaining(e -> {}); Assert.assertFalse(iterator.hasNext()); try { iterator.next(); Assert.fail(); } catch (NoSuchElementException e) { } } @Test public void testEquals() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new Top(1, 2, 3)); mapper.add(new Top(1, 2, 4)); mapper.add(new Top(1, 2, 3, 4)); HollowReadStateEngine rse = new HollowReadStateEngine(); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, rse); GenericHollowList l1 = new GenericHollowList(rse, "ListOfString", 0); GenericHollowList l2 = new GenericHollowList(rse, "ListOfString", 0); GenericHollowList l3 = new GenericHollowList(rse, "ListOfString", 1); GenericHollowList l4 = new GenericHollowList(rse, "ListOfString", 2); GenericHollowList l5 = new GenericHollowList(rse, "ListOfInteger", 0); assertListEquals(l1, l1, true); assertListEquals(l1, l2, true); assertListEquals(l1, new ArrayList<>(l1), true); assertListEquals(l1, l3, false); assertListEquals(l1, l4, false); assertListEquals(l1, l5, false); Assert.assertNotEquals(l1, new HashSet<>(l1)); } static void assertListEquals(List<?> a, List<?> b, boolean equal) { if (equal) { Assert.assertEquals(a.hashCode(), b.hashCode()); Assert.assertEquals(a, b); Assert.assertTrue(equalsUsingIterator(a, b)); Assert.assertEquals(b, a); Assert.assertTrue(equalsUsingIterator(b, a)); } else { Assert.assertNotEquals(a, b); Assert.assertFalse(equalsUsingIterator(a, b)); Assert.assertNotEquals(b, a); Assert.assertFalse(equalsUsingIterator(b, a)); } } static boolean equalsUsingIterator(List<?> a, List<?> b) { ListIterator<?> ia = a.listIterator(); ListIterator<?> ib = b.listIterator(); while (ia.hasNext() && ib.hasNext()) { if (!Objects.equals(ia.next(), ib.next())) { return false; } } return !(ia.hasNext() || ib.hasNext()); } }
8,748
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/list/HollowListDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.list; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.list.HollowListTypeReadState; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.schema.HollowListSchema; import com.netflix.hollow.core.write.HollowListTypeWriteState; import com.netflix.hollow.core.write.HollowListWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowListDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(10, 20, 30); addRecord(40, 50, 60); addRecord(70, 80, 90); roundTripSnapshot(); addRecord(10, 20, 30); addRecord(70, 80, 90); addRecord(100, 200, 300, 400, 500, 600, 700); addRecord(1, 2, 3); roundTripDelta(); HollowListTypeReadState typeState = (HollowListTypeReadState) readStateEngine.getTypeState("TestList"); assertList(typeState, 0, 10, 20, 30); assertList(typeState, 1, 40, 50, 60); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertList(typeState, 2, 70, 80, 90); assertList(typeState, 3, 100, 200, 300, 400, 500, 600, 700); assertList(typeState, 4, 1, 2, 3); Assert.assertEquals(4, typeState.maxOrdinal()); roundTripDelta(); assertList(typeState, 0, 10, 20, 30); /// all lists were "removed", but again hang around until the following cycle. assertList(typeState, 1); /// this list should now be disappeared. assertList(typeState, 2, 70, 80, 90); /// "ghost" assertList(typeState, 3, 100, 200, 300, 400, 500, 600, 700); /// "ghost" assertList(typeState, 4, 1, 2, 3); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(634, 54732); addRecord(1, 2, 3); roundTripDelta(); Assert.assertEquals(1, typeState.maxOrdinal()); assertList(typeState, 0, 634, 54732); /// now, since all lists were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertList(typeState, 1, 1, 2, 3); /// even though 1, 2, 3 had an equivalent list in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } @Test public void testSingleEmptyList() throws IOException { addRecord(); roundTripSnapshot(); HollowListTypeReadState typeState = (HollowListTypeReadState) readStateEngine.getTypeState("TestList"); assertList(typeState, 0); } @Test public void testSingleListWith0Ordinal() throws IOException { addRecord(0); roundTripSnapshot(); HollowListTypeReadState typeState = (HollowListTypeReadState) readStateEngine.getTypeState("TestList"); assertList(typeState, 0, 0); } @Test public void testStaleReferenceException() throws IOException { addRecord(0); roundTripSnapshot(); readStateEngine.invalidate(); HollowListTypeReadState typeState = (HollowListTypeReadState) readStateEngine.getTypeState("TestList"); try { assertList(typeState, 0, 0); Assert.fail("Should have thrown Exception"); } catch(NullPointerException expected) { } } private void addRecord(int... ordinals) { HollowListWriteRecord rec = new HollowListWriteRecord(); for(int i=0;i<ordinals.length;i++) { rec.addElement(ordinals[i]); } writeStateEngine.add("TestList", rec); } private void assertList(HollowListTypeReadState readState, int ordinal, int... elements) { HollowOrdinalIterator iter = readState.ordinalIterator(ordinal); for(int i=0;i<elements.length;i++) { Assert.assertEquals(elements[i], iter.next()); } Assert.assertEquals(HollowOrdinalIterator.NO_MORE_ORDINALS, iter.next()); } @Override protected void initializeTypeStates() { HollowListTypeWriteState writeState = new HollowListTypeWriteState(new HollowListSchema("TestList", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,749
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/list/HollowListFastDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.list; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.list.HollowListTypeReadState; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.schema.HollowListSchema; import com.netflix.hollow.core.write.HollowListTypeWriteState; import com.netflix.hollow.core.write.HollowListWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowListFastDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(); addRecord(30, 40, 50); addRecord(40, 50, 60); addRecord(50, 60, 70); addRecord(60, 70, 80, 90, 100, 110, 120); addRecord(70, 80, 90, 100); addRecord(80, 90, 100); addRecord(90, 100, 110); addRecord(100, 110, 120); addRecord(110, 120, 130); addRecord(120, 130, 140); roundTripSnapshot(); addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(); addRecord(30, 40, 50); addRecord(40, 50, 60); addRecord(50, 60, 70); addRecord(60, 70, 80, 90, 100, 110, 120); addRecord(71, 81, 91, 101); addRecord(80, 90, 100); addRecord(90, 100, 110); addRecord(100, 110, 120); addRecord(110, 120, 130); addRecord(120, 130, 140); roundTripDelta(); HollowListTypeReadState typeState = (HollowListTypeReadState) readStateEngine.getTypeState("TestList"); assertList(typeState, 0, 10, 20, 30); assertList(typeState, 1, 20, 30, 40); assertList(typeState, 2); assertList(typeState, 3, 30, 40, 50); assertList(typeState, 4, 40, 50, 60); assertList(typeState, 5, 50, 60, 70); assertList(typeState, 6, 60, 70, 80, 90, 100, 110, 120); assertList(typeState, 7, 70, 80, 90, 100); // ghost assertList(typeState, 8, 80, 90, 100); assertList(typeState, 9, 90, 100, 110); assertList(typeState, 10, 100, 110, 120); assertList(typeState, 11, 110, 120, 130); assertList(typeState, 12, 120, 130, 140); assertList(typeState, 13, 71, 81, 91, 101); Assert.assertEquals(13, typeState.maxOrdinal()); addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(); addRecord(40, 50, 60); addRecord(50, 60, 70); addRecord(61, 71, 81, 91, 101, 111, 121); addRecord(71, 81, 91, 101); addRecord(80, 90, 100); addRecord(90, 100, 110); addRecord(100, 110, 120); addRecord(110, 120, 130); addRecord(120, 130, 140); roundTripDelta(); assertList(typeState, 0, 10, 20, 30); assertList(typeState, 1, 20, 30, 40); assertList(typeState, 2); assertList(typeState, 3, 30, 40, 50); // ghost assertList(typeState, 4, 40, 50, 60); assertList(typeState, 5, 50, 60, 70); assertList(typeState, 6, 60, 70, 80, 90, 100, 110, 120); assertList(typeState, 7, 61, 71, 81, 91, 101, 111, 121); assertList(typeState, 8, 80, 90, 100); assertList(typeState, 9, 90, 100, 110); assertList(typeState, 10, 100, 110, 120); assertList(typeState, 11, 110, 120, 130); assertList(typeState, 12, 120, 130, 140); assertList(typeState, 13, 71, 81, 91, 101); Assert.assertEquals(13, typeState.maxOrdinal()); } private void addRecord(int... ordinals) { HollowListWriteRecord rec = new HollowListWriteRecord(); for(int i=0;i<ordinals.length;i++) { rec.addElement(ordinals[i]); } writeStateEngine.add("TestList", rec); } private void assertList(HollowListTypeReadState readState, int ordinal, int... elements) { HollowOrdinalIterator iter = readState.ordinalIterator(ordinal); for(int i=0;i<elements.length;i++) { Assert.assertEquals(elements[i], iter.next()); } Assert.assertEquals(HollowOrdinalIterator.NO_MORE_ORDINALS, iter.next()); } @Override protected void initializeTypeStates() { HollowListTypeWriteState writeState = new HollowListTypeWriteState(new HollowListSchema("TestList", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,750
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/list/HollowListShardedTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.list; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.HollowListTypeDataAccess; import com.netflix.hollow.core.schema.HollowListSchema; import com.netflix.hollow.core.write.HollowListTypeWriteState; import com.netflix.hollow.core.write.HollowListWriteRecord; import java.io.IOException; import java.util.BitSet; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowListShardedTest extends AbstractStateEngineTest { @Before public void setUp() { super.setUp(); } @Test public void testShardedData() throws IOException { HollowListWriteRecord rec = new HollowListWriteRecord(); for(int i=0;i<2000;i++) { rec.reset(); rec.addElement(i); rec.addElement(i+1); rec.addElement(i+2); writeStateEngine.add("TestList", rec); } roundTripSnapshot(); Assert.assertEquals(4, readStateEngine.getTypeState("TestList").numShards()); HollowListTypeDataAccess listDataAccess = (HollowListTypeDataAccess) readStateEngine.getTypeDataAccess("TestList"); for(int i=0;i<1000;i++) { Assert.assertEquals(i, listDataAccess.getElementOrdinal(i, 0)); Assert.assertEquals(i+1, listDataAccess.getElementOrdinal(i, 1)); Assert.assertEquals(i+2, listDataAccess.getElementOrdinal(i, 2)); } for(int i=0;i<2000;i++) { rec.reset(); rec.addElement(i*2); rec.addElement(i*2+1); rec.addElement(i*2+2); writeStateEngine.add("TestList", rec); } roundTripDelta(); int expectedValue = 0; BitSet populatedOrdinals = readStateEngine.getTypeState("TestList").getPopulatedOrdinals(); int ordinal = populatedOrdinals.nextSetBit(0); while(ordinal != -1) { Assert.assertEquals(expectedValue, listDataAccess.getElementOrdinal(ordinal, 0)); Assert.assertEquals(expectedValue+1, listDataAccess.getElementOrdinal(ordinal, 1)); Assert.assertEquals(expectedValue+2, listDataAccess.getElementOrdinal(ordinal, 2)); expectedValue += 2; ordinal = populatedOrdinals.nextSetBit(ordinal+1); } } @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(4096); writeStateEngine.addTypeState(new HollowListTypeWriteState(new HollowListSchema("TestList", "TestObject"))); } }
8,751
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/filter/HollowFilterConfigTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.filter; import org.junit.Assert; import org.junit.Test; public class HollowFilterConfigTest { @Test public void includeFilterSpecifiesTypesAndFields() { HollowFilterConfig conf = new HollowFilterConfig(); conf.addType("TypeA"); conf.addField("TypeB", "b1"); conf.addField("TypeB", "b2"); Assert.assertTrue(conf.doesIncludeType("TypeA")); Assert.assertTrue(conf.getObjectTypeConfig("TypeA").includesField("anyGivenField")); Assert.assertTrue(conf.doesIncludeType("TypeB")); Assert.assertTrue(conf.getObjectTypeConfig("TypeB").includesField("b1")); Assert.assertFalse(conf.getObjectTypeConfig("TypeB").includesField("b3")); Assert.assertFalse(conf.doesIncludeType("TypeC")); Assert.assertFalse(conf.getObjectTypeConfig("TypeC").includesField("asdf")); } @Test public void excludeFilterSpecifiesTypesAndFields() { HollowFilterConfig conf = new HollowFilterConfig(true); conf.addType("TypeA"); conf.addField("TypeB", "b1"); conf.addField("TypeB", "b2"); Assert.assertFalse(conf.doesIncludeType("TypeA")); Assert.assertFalse(conf.getObjectTypeConfig("TypeA").includesField("anyGivenField")); Assert.assertTrue(conf.doesIncludeType("TypeB")); Assert.assertFalse(conf.getObjectTypeConfig("TypeB").includesField("b1")); Assert.assertTrue(conf.getObjectTypeConfig("TypeB").includesField("b3")); Assert.assertTrue(conf.doesIncludeType("TypeC")); Assert.assertTrue(conf.getObjectTypeConfig("TypeC").includesField("anyGivenField")); } @Test public void serializesAndDeserializes() { HollowFilterConfig conf = new HollowFilterConfig(true); conf.addType("TypeA"); conf.addField("TypeB", "b1"); conf.addField("TypeB", "b2"); String configStr = conf.toString(); conf = HollowFilterConfig.fromString(configStr); System.out.println(configStr); Assert.assertFalse(conf.doesIncludeType("TypeA")); Assert.assertFalse(conf.getObjectTypeConfig("TypeA").includesField("anyGivenField")); Assert.assertTrue(conf.doesIncludeType("TypeB")); Assert.assertFalse(conf.getObjectTypeConfig("TypeB").includesField("b1")); Assert.assertTrue(conf.getObjectTypeConfig("TypeB").includesField("b3")); Assert.assertTrue(conf.doesIncludeType("TypeC")); Assert.assertTrue(conf.getObjectTypeConfig("TypeC").includesField("anyGivenField")); } }
8,752
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/filter/TypeFilterTest.java
package com.netflix.hollow.core.read.filter; import static com.netflix.hollow.core.read.filter.TypeFilter.newTypeFilter; import static com.netflix.hollow.core.schema.HollowSchema.SchemaType.OBJECT; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.UnaryOperator; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; public class TypeFilterTest { private static final Collection<Object[]> typeCases = asList( // includeAll() is the default c("include all: object", l(Charlie.class), f -> f, l("Charlie")), c("include all: subclass", l(Beta.class), f -> f, l("Beta", "Charlie", "Long")), c("include all: hierarchy", l(Alpha.class), f -> f, l("Alpha", "Beta", "Charlie", "Long")), c("include all: disjoint", l(Charlie.class, Echo.class), f -> f, l("Charlie", "Echo")), c("include all: collections", l(Omega.class), f -> f, l("Omega", "ListOfLE", "LE", "LERef", "SetOfSE", "SE", "SERef", "MapOfKToV", "K", "KRef", "V", "VRef")), c("exclude all: hierarchy", l(Alpha.class), f -> f.excludeAll(), none()), c("exclude all: collections", l(Omega.class), f -> f.excludeAll(), none()), c("include: hierarchy", l(Alpha.class), f -> f.excludeAll().include("Alpha"), l("Alpha")), c("include: collections", l(Omega.class), f -> f.excludeAll().include("Omega"), l("Omega")), c("recursive include: hierarchy", l(Alpha.class), f -> f.excludeAll() .includeRecursive("Alpha"), l("Alpha", "Beta", "Charlie", "Long")), c("recursive include: collections", l(Omega.class), f -> f.excludeAll() .includeRecursive("Omega"), l("Omega", "ListOfLE", "LE", "LERef", "SetOfSE", "SE", "SERef", "MapOfKToV", "K", "KRef", "V", "VRef")), c("exclude: hierarchy", l(Alpha.class), f -> f.exclude("Beta"), l("Alpha", "Charlie", "Long")), c("exclude: collections #1", l(Omega.class), f -> f.exclude("Omega"), l("ListOfLE", "LE", "LERef", "SetOfSE", "SE", "SERef", "MapOfKToV", "K", "KRef", "V", "VRef")), c("exclude: collections #2", l(Omega.class), f -> f.exclude("ListOfLE") .exclude("SetOfSE") .exclude("MapOfKToV"), l("Omega", "LE", "LERef", "SE", "SERef", "K", "KRef", "V", "VRef")), c("recursive exclude: hierarchy", l(Alpha.class), f -> f.excludeRecursive("Beta"), l("Alpha")), c("recursive exclude: collections #1", l(Omega.class), f -> f.excludeRecursive("Omega"), none()), c("recursive exclude: collections #2", l(Omega.class), f -> f.excludeRecursive("ListOfLE") .excludeRecursive("SetOfSE") .excludeRecursive("MapOfKToV"), l("Omega")), c("re-include: hierarchy", l(Alpha.class), f -> f.excludeRecursive("Beta") .include("Long"), l("Alpha", "Long")), c("re-include: collections", l(Omega.class), f -> f.excludeRecursive("Omega") .include("ListOfLE") .include("SetOfSE") .include("MapOfKToV"), l("ListOfLE", "SetOfSE", "MapOfKToV")), c("recursive re-include: collections", l(Omega.class), f -> f.excludeRecursive("Omega") .includeRecursive("ListOfLE") .includeRecursive("SetOfSE") .includeRecursive("MapOfKToV"), l("ListOfLE", "LE", "LERef", "SetOfSE", "SE", "SERef", "MapOfKToV", "K", "KRef", "V", "VRef")) ); private static final Collection<Object[]> typeAndFieldCases = asList( /* * Field-specific inclusions/exclusions not fully supported. * * For now: * * • type inclusions always include all fields * • type exclusions always exclude all fields * • field-specific inclusions are resolved equivalent to a type inclusion * • field-specific exclusions do nothing */ c("type include", l(Charlie.class), f -> f.excludeAll() .include("Charlie"), l("Charlie", "Charlie.i", "Charlie.l", "Charlie.s")), c("type exclude", l(Beta.class), f -> f.exclude("Beta") .exclude("Long"), l("Charlie", "Charlie.i", "Charlie.l", "Charlie.s")), c("include inline fields", l(Charlie.class), f -> f.excludeAll() .include("Charlie", "l"), l("Charlie", "Charlie.l")), c("include scalar ref field", l(Beta.class), f -> f.excludeAll() .include("Beta", "l"), l("Beta", "Beta.l")), c("include object ref field", l(Beta.class), f -> f.excludeAll() .include("Beta", "charlie"), l("Beta", "Beta.charlie")), c("recursive include scalar ref field", l(Beta.class), f -> f.excludeAll() .includeRecursive("Beta", "l"), l("Beta", "Beta.l", "Long", "Long.value")), c("recursive include object ref field", l(Beta.class), f -> f.excludeAll() .includeRecursive("Beta", "charlie"), l("Beta", "Beta.charlie", "Charlie", "Charlie.i", "Charlie.l", "Charlie.s")) ); @RunWith(Parameterized.class) public static class TypeOnly extends AbstractTypeFilterTest { private final List<Class<?>> models; private final UnaryOperator<TypeFilter.Builder> filteredBy; private final List<String> expected; @Parameterized.Parameters(name = "{index}: {0}{1} ➡︎ {4}") public static Collection<Object[]> cases() { return typeCases; } public TypeOnly(String skip, String msg, List<Class<?>> models, UnaryOperator<TypeFilter.Builder> filteredBy, List<String> expected) { super(skip); this.models = models; this.filteredBy = filteredBy; this.expected = expected; } @Test public void verify() { if (skip) return; List<HollowSchema> schemas = generateSchema(models); TypeFilter subject = filteredBy .apply(newTypeFilter()) .resolve(schemas); Set<String> included = schemas.stream() .map(HollowSchema::getName) .filter(name -> subject.includes(name)) .collect(toSet()); if (expected.isEmpty()) { assertThat(included).isEmpty(); } else { assertThat(included).containsOnly(expected.toArray(new String[0])); } } } @RunWith(Parameterized.class) public static class TypeAndField extends AbstractTypeFilterTest { private final List<Class<?>> models; private final UnaryOperator<TypeFilter.Builder> filteredBy; private final List<String> expected; @Parameterized.Parameters(name = "{index}: {0}{1} ➡︎ {4}") public static Collection<Object[]> cases() { return typeAndFieldCases; } public TypeAndField(String skip, String msg, List<Class<?>> models, UnaryOperator<TypeFilter.Builder> filteredBy, List<String> expected) { super(skip); this.models = models; this.filteredBy = filteredBy; this.expected = expected; } @Test public void verify() { if (skip) return; List<HollowSchema> schemas = generateSchema(models); TypeFilter subject = filteredBy .apply(newTypeFilter()) .resolve(schemas); Set<String> included = schemas .stream() .flatMap(schema -> { String typeName = schema.getName(); Stream<String> typeStream = subject.includes(typeName) ? Stream.of(typeName) : Stream.empty(); if (schema.getSchemaType() == OBJECT) { HollowObjectSchema os = (HollowObjectSchema) schema; Set<String> fields = IntStream.range(0, os.numFields()) .mapToObj(os::getFieldName) .filter(f -> subject.includes(typeName, f)) .map(f -> typeName + "." + f) .collect(toSet()); return fields.isEmpty() ? Stream.empty() : Stream.concat(typeStream, fields.stream()); } else { return typeStream; } }) .collect(toSet()); if (this.expected.isEmpty()) { assertThat(included).isEmpty(); } else { assertThat(included).containsOnly(this.expected.toArray(new String[0])); } } } private static abstract class AbstractTypeFilterTest extends TypeFilterTest { static final String SKIP = "SKIP:"; protected final boolean skip; protected AbstractTypeFilterTest(String skip) { this.skip = skip == SKIP; } } private static Object[] c(String msg, List<Class<?>> models, UnaryOperator<TypeFilter.Builder> filteredBy, List<String> expected) { return new Object[] { "", msg, models, filteredBy, expected }; } private static Object[] skip(String msg, List<Class<?>> models, UnaryOperator<TypeFilter.Builder> filteredBy, List<String> expected) { return new Object[] { AbstractTypeFilterTest.SKIP, msg, models, filteredBy, expected }; } private static <T> List<T> none() { return emptyList(); } private static <T> List<T> l(T...items) { assert items.length > 0; return Arrays.asList(items); } private static List<HollowSchema> generateSchema(List<Class<?>> models) { HollowWriteStateEngine wse = new HollowWriteStateEngine(); HollowObjectMapper om = new HollowObjectMapper(wse); for (Class<?> model : models) { om.initializeTypeState(model); } return wse.getSchemas(); } } @SuppressWarnings("unused") class Alpha { int i; Beta beta; } @SuppressWarnings("unused") class Beta { @HollowInline String s; Long l; Charlie charlie; } @SuppressWarnings("unused") class Charlie { int i; long l; @HollowInline String s; } @SuppressWarnings("unused") class Echo { long l; } @SuppressWarnings("unused") class Omega { List<LE> list; Set<SE> set; Map<K,V> map; static class LE { LERef ref; } static class LERef { int i; } static class SE { SERef ref; } static class SERef { int i; } static class K { KRef ref; } static class KRef { int i; } static class V { VRef ref; } static class VRef { int i; } }
8,753
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/set/HollowSetFastDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.set; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.set.HollowSetTypeReadState; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowSetFastDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(10, 20, 30); addRecord(40, 50, 60, 70); addRecord(70, 80, 90); roundTripSnapshot(); addRecord(10, 20, 30); addRecord(40, 50, 61, 70); addRecord(70, 80, 90); addRecord(1, 2, 3); roundTripDelta(); HollowSetTypeReadState typeState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); assertSet(typeState, 0, 10, 20, 30); assertSet(typeState, 1, 40, 50, 60, 70); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertSet(typeState, 2, 70, 80, 90); assertSet(typeState, 3, 40, 50, 61, 70); assertSet(typeState, 4, 1, 2, 3); Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(10, 30); addRecord(40, 50, 61, 70); addRecord(70, 80, 90); addRecord(1, 2, 3); roundTripDelta(); assertSet(typeState, 0, 10, 20, 30); assertSet(typeState, 1, 10, 30); assertSet(typeState, 2, 70, 80, 90); assertSet(typeState, 3, 40, 50, 61, 70); assertSet(typeState, 4, 1, 2, 3); Assert.assertEquals(4, typeState.maxOrdinal()); } private void assertSet(HollowSetTypeReadState readState, int ordinal, int... elements) { Assert.assertEquals(elements.length, readState.size(ordinal)); for(int i=0;i<elements.length;i++) { Assert.assertTrue(readState.contains(ordinal, elements[i])); } } private void addRecord(int... ordinals) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int i=0;i<ordinals.length;i++) { rec.addElement(ordinals[i]); } writeStateEngine.add("TestSet", rec); } @Override protected void initializeTypeStates() { HollowSetTypeWriteState writeState = new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,754
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/set/HollowSetShardedTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.set; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import java.io.IOException; import java.util.BitSet; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowSetShardedTest extends AbstractStateEngineTest { @Before public void setUp() { super.setUp(); } @Test public void testShardedData() throws IOException { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int i=0;i<2000;i++) { rec.reset(); rec.addElement(i); rec.addElement(i+1); rec.addElement(i+2); writeStateEngine.add("TestSet", rec); } roundTripSnapshot(); Assert.assertEquals(4, readStateEngine.getTypeState("TestSet").numShards()); HollowSetTypeDataAccess setDataAccess = (HollowSetTypeDataAccess) readStateEngine.getTypeDataAccess("TestSet"); for(int i=0;i<1000;i++) { Assert.assertEquals(3, setDataAccess.size(i)); Assert.assertTrue(setDataAccess.contains(i, i)); Assert.assertTrue(setDataAccess.contains(i, i+1)); Assert.assertTrue(setDataAccess.contains(i, i+2)); } for(int i=0;i<2000;i++) { rec.reset(); rec.addElement(i*2); rec.addElement(i*2+1); rec.addElement(i*2+2); writeStateEngine.add("TestSet", rec); } roundTripDelta(); int expectedValue = 0; BitSet populatedOrdinals = readStateEngine.getTypeState("TestSet").getPopulatedOrdinals(); int ordinal = populatedOrdinals.nextSetBit(0); while(ordinal != -1) { Assert.assertEquals(3, setDataAccess.size(ordinal)); Assert.assertTrue(setDataAccess.contains(ordinal, expectedValue)); Assert.assertTrue(setDataAccess.contains(ordinal, expectedValue+1)); Assert.assertTrue(setDataAccess.contains(ordinal, expectedValue+2)); expectedValue += 2; ordinal = populatedOrdinals.nextSetBit(ordinal+1); } } @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(4096); writeStateEngine.addTypeState(new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject"))); } }
8,755
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/set/HollowSetDeltaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.set; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.set.HollowSetTypeReadState; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowSetDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(10, 20, 30); addRecord(40, 50, 60); addRecord(70, 80, 90); roundTripSnapshot(); addRecord(10, 20, 30); addRecord(70, 80, 90); addRecord(100, 200, 300, 400, 500, 600, 700); addRecord(1, 2, 3); roundTripDelta(); HollowSetTypeReadState typeState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); assertSet(typeState, 0, 10, 20, 30); assertSet(typeState, 1, 40, 50, 60); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertSet(typeState, 2, 70, 80, 90); assertSet(typeState, 3, 100, 200, 300, 400, 500, 600, 700); assertSet(typeState, 4, 1, 2, 3); Assert.assertEquals(4, typeState.maxOrdinal()); roundTripDelta(); assertSet(typeState, 0, 10, 20, 30); /// all sets were "removed", but again hang around until the following cycle. assertSet(typeState, 1); /// this set should now be disappeared. assertSet(typeState, 2, 70, 80, 90); /// "ghost" assertSet(typeState, 3, 100, 200, 300, 400, 500, 600, 700); /// "ghost" assertSet(typeState, 4, 1, 2, 3); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(634, 54732); addRecord(1, 2, 3); roundTripDelta(); Assert.assertEquals(1, typeState.maxOrdinal()); assertSet(typeState, 0, 634, 54732); /// now, since all sets were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertSet(typeState, 1, 1, 2, 3); /// even though 1, 2, 3 had an equivalent set in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } private void addRecord(int... ordinals) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int i=0;i<ordinals.length;i++) { rec.addElement(ordinals[i]); } writeStateEngine.add("TestSet", rec); } private void assertSet(HollowSetTypeReadState readState, int ordinal, int... elements) { Assert.assertEquals(elements.length, readState.size(ordinal)); for(int i=0;i<elements.length;i++) { Assert.assertTrue(readState.contains(ordinal, elements[i])); } } @Override protected void initializeTypeStates() { HollowSetTypeWriteState writeState = new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,756
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/set/HollowSetHashKeyTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.set; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowHashKey; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class HollowSetHashKeyTest { @Test public void testSetHashKeys() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.useDefaultHashKeys(); mapper.add(new TestTopLevelObject(1, new Obj(1, "US", 100), new Obj(2, "CA", 200), new Obj(3, "IT", 300), new Obj(4, "GB", 400), new Obj(5, "IT", 500))); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); GenericHollowObject obj = new GenericHollowObject(readEngine, "TestTopLevelObject", 0); GenericHollowObject element = (GenericHollowObject) obj.getSet("setById").findElement(1); Assert.assertEquals("US", element.getObject("country").getString("value")); element = (GenericHollowObject) obj.getSet("setById").findElement(2); Assert.assertEquals("CA", element.getObject("country").getString("value")); element = (GenericHollowObject) obj.getSet("setById").findElement(3); Assert.assertEquals("IT", element.getObject("country").getString("value")); element = (GenericHollowObject) obj.getSet("setById").findElement(4); Assert.assertEquals("GB", element.getObject("country").getString("value")); element = (GenericHollowObject) obj.getSet("setById").findElement(5); Assert.assertEquals("IT", element.getObject("country").getString("value")); element = (GenericHollowObject)obj.getSet("setByIdCountry").findElement(1, "US"); Assert.assertEquals(1, element.getInt("id")); element = (GenericHollowObject)obj.getSet("setByIdCountry").findElement(2, "CA"); Assert.assertEquals(2, element.getInt("id")); element = (GenericHollowObject)obj.getSet("setByIdCountry").findElement(3, "IT"); Assert.assertEquals(3, element.getInt("id")); element = (GenericHollowObject)obj.getSet("setByIdCountry").findElement(4, "GB"); Assert.assertEquals(4, element.getInt("id")); element = (GenericHollowObject)obj.getSet("setByIdCountry").findElement(5, "IT"); Assert.assertEquals(5, element.getInt("id")); element = (GenericHollowObject)obj.getSet("intSet").findElement(100); Assert.assertEquals(100, element.getInt("value")); element = (GenericHollowObject)obj.getSet("intSet").findElement(200); Assert.assertEquals(200, element.getInt("value")); element = (GenericHollowObject)obj.getSet("intSet").findElement(300); Assert.assertEquals(300, element.getInt("value")); element = (GenericHollowObject)obj.getSet("intSet").findElement(400); Assert.assertEquals(400, element.getInt("value")); element = (GenericHollowObject)obj.getSet("intSet").findElement(500); Assert.assertEquals(500, element.getInt("value")); } @SuppressWarnings("unused") private static class TestTopLevelObject { int id; @HollowTypeName(name="SetById") @HollowHashKey(fields="id") Set<Obj> setById; @HollowTypeName(name="SetByIdCountry") @HollowHashKey(fields={"id", "country.value"}) Set<Obj> setByIdCountry; Set<Integer> intSet; public TestTopLevelObject(int id, Obj... elements) { this.id = id; this.setById = new HashSet<Obj>(); this.setByIdCountry = new HashSet<Obj>(); this.intSet = new HashSet<Integer>(); for(int i=0;i<elements.length;i++) { setById.add(elements[i]); setByIdCountry.add(elements[i]); intSet.add((int)elements[i].extraValue); } } } @SuppressWarnings("unused") private static class Obj { int id; String country; long extraValue; public Obj(int id, String country, long extraValue) { this.id = id; this.country = country; this.extraValue = extraValue; } } }
8,757
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/set/HollowSetTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.set; import static com.netflix.hollow.core.read.iterator.HollowOrdinalIterator.NO_MORE_ORDINALS; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.set.HollowSetTypeReadState; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowSetTest extends AbstractStateEngineTest { @Test public void testContains() throws IOException { addRecord(10, 20, 30); roundTripSnapshot(); HollowSetTypeReadState typeState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); HollowOrdinalIterator iter = typeState.potentialMatchOrdinalIterator(0, 20); boolean foundValue = false; int ordinal = iter.next(); while(ordinal != NO_MORE_ORDINALS) { if(ordinal == 20) foundValue = true; ordinal = iter.next(); } if(!foundValue) Assert.fail("Did not find value in PotentialMatchOrdinalIterator"); } @Test public void testSingleEmptySet() throws IOException { addRecord(); roundTripSnapshot(); HollowSetTypeReadState typeState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); Assert.assertEquals(0, typeState.size(0)); Assert.assertEquals(0, typeState.maxOrdinal()); } @Test public void testSingleElementWith0Ordinal() throws IOException { addRecord(0); roundTripSnapshot(); HollowSetTypeReadState typeState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); Assert.assertEquals(1, typeState.size(0)); Assert.assertEquals(0, typeState.maxOrdinal()); HollowOrdinalIterator iter = typeState.ordinalIterator(0); Assert.assertEquals(0, iter.next()); Assert.assertEquals(NO_MORE_ORDINALS, iter.next()); } @Test public void testStaleReferenceException() throws IOException { roundTripSnapshot(); readStateEngine.invalidate(); HollowSetTypeReadState typeState = (HollowSetTypeReadState) readStateEngine.getTypeState("TestSet"); try { Assert.assertEquals(0, typeState.size(100)); Assert.fail("Should have thrown Exception"); } catch(NullPointerException expected) { } } private void addRecord(int... ordinals) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int i=0;i<ordinals.length;i++) { rec.addElement(ordinals[i]); } writeStateEngine.add("TestSet", rec); } @Override protected void initializeTypeStates() { HollowSetTypeWriteState writeState = new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject")); writeStateEngine.addTypeState(writeState); } }
8,758
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/set/HollowSetCollectionTest.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.read.set; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.objects.generic.GenericHollowSet; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.stream.IntStream; import org.junit.Assert; import org.junit.Test; public class HollowSetCollectionTest { static class Top { Set<Integer> ints; Set<String> strings; Top(int... vs) { this.ints = IntStream.of(vs).boxed().collect(toSet()); this.strings = IntStream.of(vs).mapToObj(Integer::toString).collect(toSet()); } } @Test public void testIterator() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new Top(1, 2, 3)); HollowReadStateEngine rse = new HollowReadStateEngine(); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, rse); GenericHollowSet s = new GenericHollowSet(rse, "SetOfInteger", 0); List<Integer> keys = s.stream() .map(r -> (GenericHollowObject) r) .map(o -> o.getInt("value")) .sorted() .collect(toList()); Assert.assertEquals(Arrays.asList(1, 2, 3), keys); Iterator<HollowRecord> iterator = s.iterator(); iterator.forEachRemaining(e -> {}); Assert.assertFalse(iterator.hasNext()); try { iterator.next(); Assert.fail(); } catch (NoSuchElementException e) { } } @Test public void testEquals() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new Top(1, 2, 3)); mapper.add(new Top(1, 2, 4)); mapper.add(new Top(1, 2, 3, 4)); HollowReadStateEngine rse = new HollowReadStateEngine(); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, rse); GenericHollowSet s1 = new GenericHollowSet(rse, "SetOfString", 0); GenericHollowSet s2 = new GenericHollowSet(rse, "SetOfString", 0); GenericHollowSet s3 = new GenericHollowSet(rse, "SetOfString", 1); GenericHollowSet s4 = new GenericHollowSet(rse, "SetOfString", 2); GenericHollowSet s5 = new GenericHollowSet(rse, "SetOfInteger", 0); assertSetEquals(s1, s1, true); assertSetEquals(s1, s2, true); assertSetEquals(s1, new HashSet<>(s1), true); assertSetEquals(s1, s3, false); assertSetEquals(s1, s4, false); assertSetEquals(s1, s5, false); Assert.assertNotEquals(s1, new ArrayList<>(s1)); } static void assertSetEquals(Set<?> a, Set<?> b, boolean equal) { if (equal) { Assert.assertEquals(a.hashCode(), b.hashCode()); Assert.assertEquals(a, b); Assert.assertTrue(equalsUsingContains(a, b)); Assert.assertEquals(b, a); Assert.assertTrue(equalsUsingContains(b, a)); } else { Assert.assertNotEquals(a, b); Assert.assertFalse(equalsUsingContains(a, b)); Assert.assertNotEquals(b, a); Assert.assertFalse(equalsUsingContains(b, a)); } } static boolean equalsUsingContains(Set<?> a, Set<?> b) { if (a.size() != b.size()) { return false; } try { return a.containsAll(b); } catch (Exception e) { return false; } } }
8,759
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine/object/AbstractHollowObjectTypeDataElementsSplitJoinTest.java
package com.netflix.hollow.core.read.engine.object; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.filter.HollowFilterConfig; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import org.junit.Before; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class AbstractHollowObjectTypeDataElementsSplitJoinTest extends AbstractStateEngineTest { protected HollowObjectSchema schema; @Mock protected HollowObjectTypeReadState mockObjectTypeState; @Before public void setUp() { schema = new HollowObjectSchema("TestObject", 4); schema.addField("longField", HollowObjectSchema.FieldType.LONG); schema.addField("stringField", HollowObjectSchema.FieldType.STRING); schema.addField("intField", HollowObjectSchema.FieldType.INT); schema.addField("doubleField", HollowObjectSchema.FieldType.DOUBLE); MockitoAnnotations.initMocks(this); HollowObjectTypeDataElements[] fakeDataElements = new HollowObjectTypeDataElements[5]; when(mockObjectTypeState.currentDataElements()).thenReturn(fakeDataElements); super.setUp(); } @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(4096); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); } private void populateWriteStateEngine(int numRecords) { initWriteStateEngine(); HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); for(int i=0;i<numRecords;i++) { rec.reset(); rec.setLong("longField", i); rec.setString("stringField", "Value" + i); rec.setInt("intField", i); rec.setDouble("doubleField", i); writeStateEngine.add("TestObject", rec); } } private void populateWriteStateEngine(int[] recordIds) { initWriteStateEngine(); HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); for(int recordId : recordIds) { rec.reset(); rec.setLong("longField", recordId); rec.setString("stringField", "Value" + recordId); rec.setInt("intField", recordId); rec.setDouble("doubleField", recordId); writeStateEngine.add("TestObject", rec); } } protected HollowObjectTypeReadState populateTypeStateWith(int numRecords) throws IOException { populateWriteStateEngine(numRecords); roundTripSnapshot(); return (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); } protected HollowObjectTypeReadState populateTypeStateWith(int[] recordIds) throws IOException { populateWriteStateEngine(recordIds); roundTripSnapshot(); return (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); } protected HollowObjectTypeReadState populateTypeStateWithFilter(int numRecords) throws IOException { populateWriteStateEngine(numRecords); readStateEngine = new HollowReadStateEngine(); HollowFilterConfig readFilter = new HollowFilterConfig(true); readFilter.addField("TestObject", "intField"); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine, readFilter); return (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); } protected void assertDataUnchanged(int numRecords) { assertDataUnchanged((HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"), numRecords); } protected void assertDataUnchanged(HollowObjectTypeReadState typeState, int numRecords) { for(int i=0;i<numRecords;i++) { GenericHollowObject obj = new GenericHollowObject(typeState, i); assertEquals(i, obj.getLong("longField")); assertEquals("Value"+i, obj.getString("stringField")); assertEquals((double)i, obj.getDouble("doubleField"), 0); if (typeState.getSchema().numFields() == 4) { // filtered assertEquals(i, obj.getInt("intField")); } } } }
8,760
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine/object/HollowObjectTypeReadStateTest.java
package com.netflix.hollow.core.read.engine.object; import static com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState.shardingFactor; import static junit.framework.TestCase.assertEquals; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.memory.MemoryMode; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import java.util.Random; import java.util.function.Supplier; import org.junit.Assert; import org.junit.Test; public class HollowObjectTypeReadStateTest extends AbstractHollowObjectTypeDataElementsSplitJoinTest { @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(4 * 100 * 1024); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); } @Test public void testMappingAnOrdinalToAShardAndBack() { int maxOrdinal = 1000; int numShards = 4; int minRecordLocationsPerShard = (maxOrdinal + 1) / numShards; int[][] shardOrdinals = new int[numShards][]; for(int i=0;i<numShards;i++) { int maxShardOrdinal = (i < ((maxOrdinal + 1) & (numShards - 1))) ? minRecordLocationsPerShard : minRecordLocationsPerShard - 1; shardOrdinals[i] = new int[maxShardOrdinal + 1]; } int shardNumberMask = numShards - 1; int shardOrdinalShift = 31 - Integer.numberOfLeadingZeros(numShards); for (int ordinal=0; ordinal<=maxOrdinal; ordinal++) { int shardIndex = ordinal & shardNumberMask; int shardOrdinal = ordinal >> shardOrdinalShift; shardOrdinals[shardIndex][shardOrdinal] = ordinal; } for (int shardIndex=0; shardIndex<numShards; shardIndex++) { for (int shardOrdinal=0; shardOrdinal<shardOrdinals[shardIndex].length; shardOrdinal++) { int ordinal = (shardOrdinal * numShards) + shardIndex; assertEquals(shardOrdinals[shardIndex][shardOrdinal], ordinal); } } } @Test public void testShardingFactor() { assertEquals(2, shardingFactor(1, 2)); assertEquals(2, shardingFactor(2, 1)); assertEquals(2, shardingFactor(4, 2)); assertEquals(2, shardingFactor(2, 4)); assertEquals(16, shardingFactor(1, 16)); assertEquals(16, shardingFactor(32, 2)); assertIllegalStateException(() -> shardingFactor(0, 1)); assertIllegalStateException(() -> shardingFactor(2, 0)); assertIllegalStateException(() -> shardingFactor(1, 1)); assertIllegalStateException(() -> shardingFactor(1, -1)); assertIllegalStateException(() -> shardingFactor(2, 3)); } @Test public void testResharding() throws Exception { for (int shardingFactor : new int[]{2, 4, 8, 16}) // 32, 64, 128, 256, 512, 1024... { for(int numRecords=1;numRecords<=100000;numRecords+=new Random().nextInt(1000)) { HollowObjectTypeReadState objectTypeReadState = populateTypeStateWith(numRecords); assertDataUnchanged(objectTypeReadState, numRecords); // Splitting shards { int prevShardCount = objectTypeReadState.numShards(); int newShardCount = shardingFactor * prevShardCount; objectTypeReadState.reshard(newShardCount); assertEquals(newShardCount, objectTypeReadState.numShards()); assertEquals(newShardCount, shardingFactor * prevShardCount); } assertDataUnchanged(objectTypeReadState, numRecords); // Joining shards { int prevShardCount = objectTypeReadState.numShards(); int newShardCount = prevShardCount / shardingFactor; objectTypeReadState.reshard(newShardCount); assertEquals(newShardCount, objectTypeReadState.numShards()); assertEquals(shardingFactor * newShardCount, prevShardCount); } assertDataUnchanged(objectTypeReadState, numRecords); } } } @Test public void testReshardingWithFilter() throws Exception { for (int shardingFactor : new int[]{2, 64}) { for(int numRecords=1;numRecords<=100000;numRecords+=new Random().nextInt(10000)) { HollowObjectTypeReadState objectTypeReadState = populateTypeStateWithFilter(numRecords); assertDataUnchanged(objectTypeReadState, numRecords); // Splitting shards { int prevShardCount = objectTypeReadState.numShards(); int newShardCount = shardingFactor * prevShardCount; objectTypeReadState.reshard(newShardCount); assertEquals(newShardCount, objectTypeReadState.numShards()); assertEquals(newShardCount, shardingFactor * prevShardCount); } assertDataUnchanged(objectTypeReadState, numRecords); // Joining shards { int prevShardCount = objectTypeReadState.numShards(); int newShardCount = prevShardCount / shardingFactor; objectTypeReadState.reshard(newShardCount); assertEquals(newShardCount, objectTypeReadState.numShards()); assertEquals(shardingFactor * newShardCount, prevShardCount); } assertDataUnchanged(objectTypeReadState, numRecords); } } } @Test public void testReshardingIntermediateStages_expandWithOriginalDataElements() throws Exception { for (int shardingFactor : new int[]{2, 4}) { for(int numRecords=1;numRecords<=100000;numRecords+=new Random().nextInt(5000)) { HollowObjectTypeReadState expectedTypeState = populateTypeStateWith(numRecords); HollowObjectTypeReadState.ShardsHolder original = expectedTypeState.shardsVolatile; HollowObjectTypeReadState.ShardsHolder expanded = expectedTypeState.expandWithOriginalDataElements(original, shardingFactor); HollowObjectTypeReadState actualTypeState = new HollowObjectTypeReadState(readStateEngine, MemoryMode.ON_HEAP, schema, schema); actualTypeState.shardsVolatile = expanded; assertEquals(shardingFactor * expectedTypeState.numShards(), actualTypeState.numShards()); assertDataUnchanged(actualTypeState, numRecords); } } } @Test public void testReshardingIntermediateStages_splitDataElementsForOneShard() throws Exception { for (int shardingFactor : new int[]{2, 4}) { for(int numRecords=1;numRecords<=100000;numRecords+=new Random().nextInt(5000)) { HollowObjectTypeReadState typeState = populateTypeStateWith(numRecords); HollowObjectTypeReadState.ShardsHolder originalShardsHolder = typeState.shardsVolatile; int originalNumShards = typeState.numShards(); // expand shards typeState.shardsVolatile = typeState.expandWithOriginalDataElements(originalShardsHolder, shardingFactor); for(int i=0; i<originalNumShards; i++) { HollowObjectTypeDataElements originalDataElements = typeState.shardsVolatile.shards[i].dataElements; typeState.shardsVolatile = typeState.splitDataElementsForOneShard(typeState.shardsVolatile, i, originalNumShards, shardingFactor); assertEquals(shardingFactor * originalNumShards, typeState.numShards()); assertDataUnchanged(typeState, numRecords); // as each original shard is processed originalDataElements.destroy(); } } } } @Test public void testReshardingIntermediateStages_joinDataElementsForOneShard() throws Exception { for (int shardingFactor : new int[]{2, 4, 8}) { for (int numRecords = 75000; numRecords <= 100000; numRecords += new Random().nextInt(1000)) { HollowObjectTypeReadState typeState = populateTypeStateWith(numRecords); HollowObjectTypeReadState.ShardsHolder originalShardsHolder = typeState.shardsVolatile; int originalNumShards = typeState.numShards(); assertEquals(8, originalNumShards); int newNumShards = originalNumShards / shardingFactor; for (int i=0; i<newNumShards; i++) { HollowObjectTypeDataElements dataElementsToJoin[] = new HollowObjectTypeDataElements[shardingFactor]; for (int j=0; j<shardingFactor; j++) { dataElementsToJoin[j] = originalShardsHolder.shards[i + (newNumShards*j)].dataElements; }; typeState.shardsVolatile = typeState.joinDataElementsForOneShard(typeState.shardsVolatile, i, shardingFactor); for (int j = 0; j < shardingFactor; j ++) { dataElementsToJoin[j].destroy(); }; assertEquals(originalNumShards, typeState.numShards()); // numShards remains unchanged assertDataUnchanged(typeState, numRecords); // as each original shard is processed } } } } private void assertIllegalStateException(Supplier<Integer> invocation) { try { invocation.get(); Assert.fail(); } catch (IllegalStateException e) { // expected } } }
8,761
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine/object/HollowObjectTypeDataElementsSplitJoinTest.java
package com.netflix.hollow.core.read.engine.object; import static org.junit.Assert.assertEquals; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.fs.HollowFilesystemBlobRetriever; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.tools.checksum.HollowChecksum; import java.io.IOException; import java.nio.file.Paths; import java.util.BitSet; import org.junit.Test; public class HollowObjectTypeDataElementsSplitJoinTest extends AbstractHollowObjectTypeDataElementsSplitJoinTest { @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(4 * 1000 * 1024); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); } @Test public void testSplitThenJoin() throws IOException { HollowObjectTypeDataElementsSplitter splitter = new HollowObjectTypeDataElementsSplitter(); HollowObjectTypeDataElementsJoiner joiner = new HollowObjectTypeDataElementsJoiner(); for (int numRecords=0;numRecords<1*1000;numRecords++) { HollowObjectTypeReadState typeReadState = populateTypeStateWith(numRecords); assertEquals(1, typeReadState.numShards()); assertDataUnchanged(typeReadState, numRecords); for (int numSplits : new int[]{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}) { HollowObjectTypeDataElements[] splitElements = splitter.split(typeReadState.currentDataElements()[0], numSplits); HollowObjectTypeDataElements joinedElements = joiner.join(splitElements); HollowObjectTypeReadState resultTypeReadState = new HollowObjectTypeReadState(typeReadState.getSchema(), joinedElements); assertDataUnchanged(resultTypeReadState, numRecords); assertChecksumUnchanged(resultTypeReadState, typeReadState, typeReadState.getPopulatedOrdinals()); } } } private void assertChecksumUnchanged(HollowObjectTypeReadState newTypeState, HollowObjectTypeReadState origTypeState, BitSet populatedOrdinals) { HollowChecksum origCksum = new HollowChecksum(); HollowChecksum newCksum = new HollowChecksum(); for(int i=0;i<origTypeState.numShards();i++) { origTypeState.shardsVolatile.shards[i].applyShardToChecksum(origCksum, origTypeState.getSchema(), populatedOrdinals, i, origTypeState.shardsVolatile.shardNumberMask); } for(int i=0;i<newTypeState.numShards();i++) { newTypeState.shardsVolatile.shards[i].applyShardToChecksum(newCksum, newTypeState.getSchema(), populatedOrdinals, i, newTypeState.shardsVolatile.shardNumberMask); } assertEquals(newCksum, origCksum); } @Test public void testSplitThenJoinWithFilter() throws IOException { HollowObjectTypeDataElementsSplitter splitter = new HollowObjectTypeDataElementsSplitter(); HollowObjectTypeDataElementsJoiner joiner = new HollowObjectTypeDataElementsJoiner(); int numSplits = 2; for (int numRecords=0;numRecords<1*1000;numRecords++) { HollowObjectTypeReadState typeReadState = populateTypeStateWithFilter(numRecords); assertEquals(1, typeReadState.numShards()); assertDataUnchanged(typeReadState, numRecords); HollowObjectTypeDataElements[] splitElements = splitter.split(typeReadState.currentDataElements()[0], numSplits); HollowObjectTypeDataElements joinedElements = joiner.join(splitElements); HollowObjectTypeReadState resultTypeReadState = new HollowObjectTypeReadState(typeReadState.getSchema(), joinedElements); assertDataUnchanged(resultTypeReadState, numRecords); assertChecksumUnchanged(resultTypeReadState, typeReadState, typeReadState.getPopulatedOrdinals()); } } @Test public void testSplitThenJoinWithEmptyJoin() throws IOException { HollowObjectTypeDataElementsSplitter splitter = new HollowObjectTypeDataElementsSplitter(); HollowObjectTypeReadState typeReadState = populateTypeStateWith(1); assertEquals(1, typeReadState.numShards()); HollowObjectTypeDataElements[] splitBy4 = splitter.split(typeReadState.currentDataElements()[0], 4); assertEquals(-1, splitBy4[1].maxOrdinal); assertEquals(-1, splitBy4[3].maxOrdinal); HollowObjectTypeDataElementsJoiner joiner = new HollowObjectTypeDataElementsJoiner(); HollowObjectTypeDataElements joined = joiner.join(new HollowObjectTypeDataElements[]{splitBy4[1], splitBy4[3]}); assertEquals(-1, joined.maxOrdinal); } // manually invoked // @Test public void testSplittingAndJoiningWithSnapshotBlob() throws Exception { String blobPath = null; // dir where snapshot blob exists for e.g. "/tmp/"; long v = 0l; // snapshot version for e.g. 20230915162636001l; String objectTypeWithOneShard = null; // type name corresponding to an Object type with single shard for e.g. "Movie"; int numSplits = 2; if (blobPath==null || v==0l || objectTypeWithOneShard==null) { throw new IllegalArgumentException("These arguments need to be specified"); } HollowFilesystemBlobRetriever hollowBlobRetriever = new HollowFilesystemBlobRetriever(Paths.get(blobPath)); HollowConsumer c = HollowConsumer.withBlobRetriever(hollowBlobRetriever).build(); c.triggerRefreshTo(v); HollowReadStateEngine readStateEngine = c.getStateEngine(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(objectTypeWithOneShard); HollowSchema origSchema = typeState.getSchema(); assertEquals(1, typeState.numShards()); HollowObjectTypeDataElementsSplitter splitter = new HollowObjectTypeDataElementsSplitter(); HollowObjectTypeDataElements[] splitElements = splitter.split(typeState.currentDataElements()[0], numSplits); HollowObjectTypeDataElementsJoiner joiner = new HollowObjectTypeDataElementsJoiner(); HollowObjectTypeDataElements joinedElements = joiner.join(splitElements); HollowObjectTypeReadState resultTypeState = new HollowObjectTypeReadState(typeState.getSchema(), joinedElements); assertChecksumUnchanged(resultTypeState, typeState, typeState.getPopulatedOrdinals()); } }
8,762
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine/object/HollowObjectTypeDataElementsSplitterTest.java
package com.netflix.hollow.core.read.engine.object; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowObjectTypeDataElementsSplitterTest extends AbstractHollowObjectTypeDataElementsSplitJoinTest { @Test public void testSplit() throws IOException { HollowObjectTypeDataElementsSplitter splitter = new HollowObjectTypeDataElementsSplitter(); HollowObjectTypeReadState typeReadState = populateTypeStateWith(5); assertEquals(1, typeReadState.numShards()); assertDataUnchanged(typeReadState, 5); HollowObjectTypeDataElements[] result1 = splitter.split(typeReadState.currentDataElements()[0], 1); typeReadState = new HollowObjectTypeReadState(typeReadState.getSchema(), result1[0]); assertDataUnchanged(typeReadState, 5); HollowObjectTypeDataElements[] result8 = splitter.split(typeReadState.currentDataElements()[0], 8); assertEquals(0, result8[0].maxOrdinal); // for index that landed one record after split assertEquals(-1, result8[7].maxOrdinal); // for index that landed no records after split try { splitter.split(typeReadState.currentDataElements()[0], 3); // numSplits=3 Assert.fail(); } catch (IllegalStateException e) { // expected, numSplits should be a power of 2 } try { splitter.split(typeReadState.currentDataElements()[0], 0); // numSplits=0 Assert.fail(); } catch (IllegalStateException e) { // expected, numSplits should be a power of 2 } } }
8,763
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/read/engine/object/HollowObjectTypeDataElementsJoinerTest.java
package com.netflix.hollow.core.read.engine.object; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.test.InMemoryBlobStore; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowObjectTypeDataElementsJoinerTest extends AbstractHollowObjectTypeDataElementsSplitJoinTest { @Override protected void initializeTypeStates() { writeStateEngine.setTargetMaxTypeShardSize(16); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); } @Test public void testJoin() throws IOException { HollowObjectTypeDataElementsJoiner joiner = new HollowObjectTypeDataElementsJoiner(); HollowObjectTypeReadState typeReadState = populateTypeStateWith(1); assertEquals(1, typeReadState.numShards()); HollowObjectTypeReadState typeReadStateSharded = populateTypeStateWith(5); assertDataUnchanged(typeReadStateSharded, 5); assertEquals(8, typeReadStateSharded.numShards()); HollowObjectTypeDataElements joinedDataElements = joiner.join(typeReadStateSharded.currentDataElements()); typeReadState = new HollowObjectTypeReadState(typeReadState.getSchema(), joinedDataElements); assertDataUnchanged(typeReadState, 5); try { joiner.join(mockObjectTypeState.currentDataElements()); Assert.fail(); } catch (IllegalStateException e) { // expected, numSplits should be a power of 2 } } @Test public void testJoinDifferentFieldWidths() throws IOException { HollowObjectTypeDataElementsJoiner joiner = new HollowObjectTypeDataElementsJoiner(); HollowObjectTypeReadState typeReadStateSmall = populateTypeStateWith(new int[] {1}); assertEquals(1, typeReadStateSmall.numShards()); HollowObjectTypeDataElements dataElementsSmall = typeReadStateSmall.currentDataElements()[0]; int intFieldPosSmall = dataElementsSmall.schema.getPosition("intField"); int widthSmall = dataElementsSmall.bitsPerField[intFieldPosSmall]; long valSmall = dataElementsSmall.fixedLengthData.getElementValue(dataElementsSmall.bitOffsetPerField[intFieldPosSmall], widthSmall); HollowObjectTypeReadState typeReadStateBig = populateTypeStateWith(new int[] {2}); assertEquals(1, typeReadStateBig.numShards()); HollowObjectTypeDataElements dataElementsBig = typeReadStateBig.currentDataElements()[0]; int intFieldPosBig = dataElementsBig.schema.getPosition("intField"); int widthBig = dataElementsBig.bitsPerField[intFieldPosBig]; long valBig = dataElementsBig.fixedLengthData.getElementValue(dataElementsBig.bitOffsetPerField[intFieldPosBig], widthBig); assertTrue(widthBig > widthSmall); HollowObjectTypeDataElements dataElementsJoined = joiner.join(new HollowObjectTypeDataElements[] {dataElementsSmall, dataElementsBig}); int intFieldPosJoined = dataElementsJoined.schema.getPosition("intField"); int widthJoined = dataElementsJoined.bitsPerField[intFieldPosJoined]; long val0 = dataElementsJoined.fixedLengthData.getElementValue(dataElementsJoined.bitOffsetPerField[intFieldPosJoined], widthJoined); long val1 = dataElementsJoined.fixedLengthData.getElementValue(dataElementsJoined.bitsPerRecord + dataElementsJoined.bitOffsetPerField[intFieldPosJoined], widthJoined); assertEquals(widthBig, widthJoined); assertEquals(valSmall, val0); assertEquals(valBig, val1); } // TODO: manually invoked, depends on producer side changes for supporting changing numShards in a delta chain // @Test // public void testLopsidedShards() { // InMemoryBlobStore blobStore = new InMemoryBlobStore(); // HollowProducer p = HollowProducer.withPublisher(blobStore) // .withBlobStager(new HollowInMemoryBlobStager()) // .build(); // // p.initializeDataModel(schema); // int targetSize = 64; // p.getWriteEngine().setTargetMaxTypeShardSize(targetSize); // long v1 = oneRunCycle(p, new int[] {0, 1, 2, 3, 4, 5, 6, 7}); // // HollowConsumer c = HollowConsumer // .withBlobRetriever(blobStore) // .withDoubleSnapshotConfig(new HollowConsumer.DoubleSnapshotConfig() { // @Override // public boolean allowDoubleSnapshot() { // return false; // } // // @Override // public int maxDeltasBeforeDoubleSnapshot() { // return Integer.MAX_VALUE; // } // }) // .withSkipTypeShardUpdateWithNoAdditions() // .build(); // c.triggerRefreshTo(v1); // // assertEquals(2, c.getStateEngine().getTypeState("TestObject").numShards()); // assertEquals(true, c.getStateEngine().isSkipTypeShardUpdateWithNoAdditions()); // // long v2 = oneRunCycle(p, new int[] {0, 1, 2, 3, 5, 7}); // c.triggerRefreshTo(v2); // assertEquals(2, c.getStateEngine().getTypeState("TestObject").numShards()); // // long v3 = oneRunCycle(p, new int[] { 0, 1, 3, 5}); // drop to 1 ordinal per shard, skipTypeShardWithNoAdds will make it so that maxOrdinal is adjusted // c.triggerRefreshTo(v3); // assertEquals(2, c.getStateEngine().getTypeState("TestObject").numShards()); // // long v4 = oneRunCycle(p, new int[] { 0, 1, 2, 3}); // now add another ordinal to one shard, maxOrdinals will be lopsided // c.triggerRefreshTo(v4); // assertEquals(2, c.getStateEngine().getTypeState("TestObject").numShards()); // // readStateEngine = c.getStateEngine(); // assertDataUnchanged(3); // // long v5 = oneRunCycle(p, new int[] {0, 1}); // // // assert lopsided shards before join // assertEquals(2, ((HollowObjectTypeReadState) c.getStateEngine().getTypeState("TestObject")).shardsVolatile.shards[0].dataElements.maxOrdinal); // assertEquals(3, ((HollowObjectTypeReadState) c.getStateEngine().getTypeState("TestObject")).shardsVolatile.shards[1].dataElements.maxOrdinal); // c.triggerRefreshTo(v5); // assertEquals(1, c.getStateEngine().getTypeState("TestObject").numShards()); // joined to 1 shard // readStateEngine = c.getStateEngine(); // assertDataUnchanged(2); // // long v6 = oneRunCycle(p, new int[] {0, 1, 2, 3, 4, 5 }); // c.triggerRefreshTo(v6); // assertEquals(2, c.getStateEngine().getTypeState("TestObject").numShards()); // split to 2 shards // // long v7 = oneRunCycle(p, new int[] {8, 9}); // c.triggerRefreshTo(v7); // assertEquals(4, c.getStateEngine().getTypeState("TestObject").numShards()); // still 2 shards // // long v8 = oneRunCycle(p, new int[] {8}); // c.triggerRefreshTo(v8); // assertEquals(2, c.getStateEngine().getTypeState("TestObject").numShards()); // down to 1 shard // // c.triggerRefreshTo(v1); // assertEquals(v1, c.getCurrentVersionId()); // // c.triggerRefreshTo(v8); // assertEquals(v8, c.getCurrentVersionId()); // } private long oneRunCycle(HollowProducer p, int recordIds[]) { return p.runCycle(state -> { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); for(int recordId : recordIds) { rec.reset(); rec.setLong("longField", recordId); rec.setString("stringField", "Value" + recordId); rec.setInt("intField", recordId); rec.setDouble("doubleField", recordId); state.getStateEngine().add("TestObject", rec); } }); } }
8,764
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/schema/HollowSchemaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.schema; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.netflix.hollow.core.schema.HollowSchema.SchemaType; import org.junit.Assert; import org.junit.Test; public class HollowSchemaTest { @Test public void isNullableObjectEquals() { Assert.assertTrue(HollowSchema.isNullableObjectEquals(null, null)); Assert.assertTrue(HollowSchema.isNullableObjectEquals("S1", "S1")); Assert.assertTrue(HollowSchema.isNullableObjectEquals(1, 1)); Assert.assertFalse(HollowSchema.isNullableObjectEquals(null, 1)); Assert.assertFalse(HollowSchema.isNullableObjectEquals(null, "S1")); Assert.assertFalse(HollowSchema.isNullableObjectEquals("S1", null)); Assert.assertFalse(HollowSchema.isNullableObjectEquals("S1", "")); Assert.assertFalse(HollowSchema.isNullableObjectEquals("S1", "S2")); Assert.assertFalse(HollowSchema.isNullableObjectEquals("S1", 1)); } @Test public void fromTypeId() { Assert.assertEquals(SchemaType.OBJECT, SchemaType.fromTypeId(0)); Assert.assertEquals(SchemaType.OBJECT, SchemaType.fromTypeId(6)); Assert.assertNotEquals(SchemaType.OBJECT, SchemaType.fromTypeId(1)); Assert.assertEquals(SchemaType.LIST, SchemaType.fromTypeId(2)); Assert.assertEquals(SchemaType.SET, SchemaType.fromTypeId(1)); Assert.assertEquals(SchemaType.SET, SchemaType.fromTypeId(4)); Assert.assertEquals(SchemaType.MAP, SchemaType.fromTypeId(3)); Assert.assertEquals(SchemaType.MAP, SchemaType.fromTypeId(5)); } @Test public void hasKey() { Assert.assertTrue(SchemaType.hasKey(4)); Assert.assertTrue(SchemaType.hasKey(5)); Assert.assertTrue(SchemaType.hasKey(6)); } @Test public void invalidName() { try { new HollowObjectSchema("", 1); fail(); } catch (IllegalArgumentException ex) { assertEquals("Type name in Hollow Schema was an empty string", ex.getMessage()); } try { new HollowObjectSchema(null, 1); fail(); } catch (IllegalArgumentException ex) { assertEquals("Type name in Hollow Schema was null", ex.getMessage()); } } }
8,765
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/schema/HollowSchemaSorterTest.java
package com.netflix.hollow.core.schema; import com.netflix.hollow.core.util.HollowWriteStateCreator; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import java.util.List; import org.junit.Assert; import org.junit.Test; public class HollowSchemaSorterTest { @Test public void schemasAreSortedBasedOnDependencies() throws IOException { String schemasText = "TypeB {" + " ListOfString str;" + "}" + "" + "String {" + " string value;" + "}" + "" + "ListOfString List<String>;" + "" + "TypeA {" + " TypeB b;" + " String str;" + "}"; List<HollowSchema> schemas = HollowSchemaParser.parseCollectionOfSchemas(schemasText); List<HollowSchema> sortedSchemas = HollowSchemaSorter.dependencyOrderedSchemaList(schemas); Assert.assertEquals(4, sortedSchemas.size()); Assert.assertEquals("String", sortedSchemas.get(0).getName()); Assert.assertEquals("ListOfString", sortedSchemas.get(1).getName()); Assert.assertEquals("TypeB", sortedSchemas.get(2).getName()); Assert.assertEquals("TypeA", sortedSchemas.get(3).getName()); } @Test public void sortsSchemasEvenIfDependencyTypesNotPresent() throws IOException { String schemasText = "TypeA { TypeB b; }" + "TypeB { TypeC c; }"; List<HollowSchema> schemas = HollowSchemaParser.parseCollectionOfSchemas(schemasText); List<HollowSchema> sortedSchemas = HollowSchemaSorter.dependencyOrderedSchemaList(schemas); Assert.assertEquals(2, sortedSchemas.size()); Assert.assertEquals("TypeB", sortedSchemas.get(0).getName()); Assert.assertEquals("TypeA", sortedSchemas.get(1).getName()); } @Test public void determinesIfSchemasAreTransitivelyDependent() throws IOException { String schemasText = "TypeA { TypeB b; }" + "TypeB { TypeC c; }" + "TypeC { TypeD d; }"; List<HollowSchema> schemas = HollowSchemaParser.parseCollectionOfSchemas(schemasText); HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); HollowWriteStateCreator.populateStateEngineWithTypeWriteStates(stateEngine, schemas); Assert.assertTrue(HollowSchemaSorter.typeIsTransitivelyDependent(stateEngine, "TypeA", "TypeB")); Assert.assertTrue(HollowSchemaSorter.typeIsTransitivelyDependent(stateEngine, "TypeA", "TypeC")); Assert.assertTrue(HollowSchemaSorter.typeIsTransitivelyDependent(stateEngine, "TypeB", "TypeC")); Assert.assertFalse(HollowSchemaSorter.typeIsTransitivelyDependent(stateEngine, "TypeC", "TypeB")); Assert.assertFalse(HollowSchemaSorter.typeIsTransitivelyDependent(stateEngine, "TypeB", "TypeA")); Assert.assertFalse(HollowSchemaSorter.typeIsTransitivelyDependent(stateEngine, "TypeC", "TypeA")); } }
8,766
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/schema/HollowSetSchemaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.schema; import com.netflix.hollow.core.index.key.PrimaryKey; import org.junit.Assert; import org.junit.Test; public class HollowSetSchemaTest { @Test public void testEquals() { { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA"); HollowSetSchema s2 = new HollowSetSchema("Test", "TypeA"); Assert.assertEquals(s1, s2); } { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA"); HollowSetSchema s2 = new HollowSetSchema("Test2", "TypeA"); Assert.assertNotEquals(s1, s2); } { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA"); HollowSetSchema s2 = new HollowSetSchema("Test", "TypeB"); Assert.assertNotEquals(s1, s2); } } @Test public void testEqualsWithKeys() { { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA", "f1"); HollowSetSchema s2 = new HollowSetSchema("Test", "TypeA", "f1"); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getHashKey(), s2.getHashKey()); Assert.assertEquals(new PrimaryKey("TypeA", "f1"), s2.getHashKey()); } { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA", "f1", "f2"); HollowSetSchema s2 = new HollowSetSchema("Test", "TypeA", "f1", "f2"); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getHashKey(), s2.getHashKey()); Assert.assertEquals(new PrimaryKey("TypeA", "f1", "f2"), s2.getHashKey()); } { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA"); HollowSetSchema s2 = new HollowSetSchema("Test", "TypeA", "f1"); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getHashKey(), s2.getHashKey()); } { HollowSetSchema s1 = new HollowSetSchema("Test", "TypeA", "f1"); HollowSetSchema s2 = new HollowSetSchema("Test", "TypeA", "f1", "f2"); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getHashKey(), s2.getHashKey()); } } }
8,767
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/schema/HollowSchemaHashTest.java
package com.netflix.hollow.core.schema; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.test.HollowReadStateEngineBuilder; import java.util.Arrays; import java.util.Map; import org.junit.Test; public class HollowSchemaHashTest { @HollowPrimaryKey(fields = "id") class Movie { int id; Map<Integer, String> aMap; } @Test public void schemaHashTest() { SimpleHollowDataset dataset = SimpleHollowDataset.fromClassDefinitions(Long.class, Movie.class); HollowReadStateEngine readState = new HollowReadStateEngineBuilder(Arrays.asList(Long.class, Movie.class)).build(); HollowSchemaHash hollowSchemaHash1 = new HollowSchemaHash(dataset.getSchemas()); HollowSchemaHash hollowSchemaHash2 = new HollowSchemaHash(readState.getSchemas()); assertEquals(hollowSchemaHash1, hollowSchemaHash2); assertNotNull(hollowSchemaHash1.getHash()); assertNotEquals("", hollowSchemaHash1.getHash()); } }
8,768
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/schema/HollowSchemaParserTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.schema; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import org.junit.Assert; import org.junit.Test; public class HollowSchemaParserTest { @Test public void parsesObjectSchema() throws IOException { String objectSchema = "/* This is a comment\n" + " consisting of multiple lines */\n" + " TypeA {\n" + " int a1;\n" + " \tstring a2; //This is a comment\n" + " String a3;\n" + "}\n"; HollowObjectSchema schema = (HollowObjectSchema) HollowSchemaParser.parseSchema(objectSchema); Assert.assertEquals("TypeA", schema.getName()); Assert.assertEquals(3, schema.numFields()); Assert.assertEquals(FieldType.INT, schema.getFieldType(0)); Assert.assertEquals("a1", schema.getFieldName(0)); Assert.assertEquals(FieldType.STRING, schema.getFieldType(1)); Assert.assertEquals("a2", schema.getFieldName(1)); Assert.assertEquals(FieldType.REFERENCE, schema.getFieldType(2)); Assert.assertEquals("String", schema.getReferencedType(2)); Assert.assertEquals("a3", schema.getFieldName(2)); // HollowObjectSchame.toString is parsed properly Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesObjectSchemaWithKey() throws IOException { String objectSchema = " TypeA @PrimaryKey(a1) {\n" + " int a1;\n" + " string a2;\n" + " String a3;\n" + "}\n"; HollowObjectSchema schema = (HollowObjectSchema) HollowSchemaParser.parseSchema(objectSchema); Assert.assertEquals("TypeA", schema.getName()); Assert.assertEquals(3, schema.numFields()); Assert.assertEquals(FieldType.INT, schema.getFieldType(0)); Assert.assertEquals("a1", schema.getFieldName(0)); Assert.assertEquals(FieldType.STRING, schema.getFieldType(1)); Assert.assertEquals("a2", schema.getFieldName(1)); Assert.assertEquals(FieldType.REFERENCE, schema.getFieldType(2)); Assert.assertEquals("String", schema.getReferencedType(2)); Assert.assertEquals("a3", schema.getFieldName(2)); // Make sure primary key and HollowObjectSchame.toString is parsed properly Assert.assertEquals(new PrimaryKey("TypeA", "a1"), schema.getPrimaryKey()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesObjectSchemaMultipleWithKey() throws IOException { String objectSchema = " TypeA @PrimaryKey(a1, a3.value) {\n" + " int a1;\n" + " string a2;\n" + " String a3;\n" + "}\n"; HollowObjectSchema schema = (HollowObjectSchema) HollowSchemaParser.parseSchema(objectSchema); Assert.assertEquals("TypeA", schema.getName()); Assert.assertEquals(3, schema.numFields()); Assert.assertEquals(FieldType.INT, schema.getFieldType(0)); Assert.assertEquals("a1", schema.getFieldName(0)); Assert.assertEquals(FieldType.STRING, schema.getFieldType(1)); Assert.assertEquals("a2", schema.getFieldName(1)); Assert.assertEquals(FieldType.REFERENCE, schema.getFieldType(2)); Assert.assertEquals("String", schema.getReferencedType(2)); Assert.assertEquals("a3", schema.getFieldName(2)); // Make sure primary key and HollowObjectSchame.toString is parsed properly Assert.assertEquals(new PrimaryKey("TypeA", "a1", "a3.value"), schema.getPrimaryKey()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesListSchema() throws IOException { String listSchema = "ListOfTypeA List<TypeA>;\n"; HollowListSchema schema = (HollowListSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("ListOfTypeA", schema.getName()); Assert.assertEquals("TypeA", schema.getElementType()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesSetSchema() throws IOException { String listSchema = "SetOfTypeA Set<TypeA>;\n"; HollowSetSchema schema = (HollowSetSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("SetOfTypeA", schema.getName()); Assert.assertEquals("TypeA", schema.getElementType()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesSetSchemaWithKey() throws IOException { String listSchema = "SetOfTypeA Set<TypeA> @HashKey(id.value);\n"; HollowSetSchema schema = (HollowSetSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("SetOfTypeA", schema.getName()); Assert.assertEquals("TypeA", schema.getElementType()); Assert.assertEquals(new PrimaryKey("TypeA", "id.value"), schema.getHashKey()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesSetSchemaWithMultiFieldKey() throws IOException { String listSchema = "SetOfTypeA Set<TypeA> @HashKey(id.value, region.country.id, key);\n"; HollowSetSchema schema = (HollowSetSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("SetOfTypeA", schema.getName()); Assert.assertEquals("TypeA", schema.getElementType()); Assert.assertEquals(new PrimaryKey("TypeA", "id.value", "region.country.id", "key"), schema.getHashKey()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesMapSchema() throws IOException { String listSchema = "MapOfStringToTypeA Map<String, TypeA>;\n"; HollowMapSchema schema = (HollowMapSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("MapOfStringToTypeA", schema.getName()); Assert.assertEquals("String", schema.getKeyType()); Assert.assertEquals("TypeA", schema.getValueType()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesMapSchemaWithPrimaryKey() throws IOException { String listSchema = "MapOfStringToTypeA Map<String, TypeA> @HashKey(value);\n"; HollowMapSchema schema = (HollowMapSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("MapOfStringToTypeA", schema.getName()); Assert.assertEquals("String", schema.getKeyType()); Assert.assertEquals("TypeA", schema.getValueType()); Assert.assertEquals(new PrimaryKey("String", "value"), schema.getHashKey()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesMapSchemaWithMultiFieldPrimaryKey() throws IOException { String listSchema = "MapOfStringToTypeA Map<String, TypeA> @HashKey(id.value, region.country.id, key);\n"; HollowMapSchema schema = (HollowMapSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("MapOfStringToTypeA", schema.getName()); Assert.assertEquals("String", schema.getKeyType()); Assert.assertEquals("TypeA", schema.getValueType()); Assert.assertEquals(new PrimaryKey("String", "id.value", "region.country.id", "key"), schema.getHashKey()); Assert.assertEquals(schema, HollowSchemaParser.parseSchema(schema.toString())); } @Test public void parsesManySchemas() throws IOException { String manySchemas = "/* This is a comment\n" + " consisting of multiple lines */\n" + " TypeA {\n" + " int a1;\n" + " \tstring a2; //This is a comment\n" + " String a3;\n" + "}\n\n"+ "MapOfStringToTypeA Map<String, TypeA>;\n"+ "ListOfTypeA List<TypeA>;\n"+ "TypeB { float b1; double b2; boolean b3; }"; List<HollowSchema> schemas = HollowSchemaParser.parseCollectionOfSchemas(manySchemas); Assert.assertEquals(4, schemas.size()); } @Test public void testParseCollectionOfSchemas_reader() throws Exception { InputStream input = null; try { input = getClass().getResourceAsStream("/schema1.txt"); List<HollowSchema> schemas = HollowSchemaParser.parseCollectionOfSchemas(new BufferedReader(new InputStreamReader(input))); Assert.assertEquals("Should have two schemas", 2, schemas.size()); Assert.assertEquals("Should have Minion schema", "Minion", schemas.get(0).getName()); Assert.assertEquals("Should have String schema", "String", schemas.get(1).getName()); } finally { if (input != null) { input.close(); } } } }
8,769
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/schema/HollowMapSchemaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.schema; import com.netflix.hollow.core.index.key.PrimaryKey; import org.junit.Assert; import org.junit.Test; public class HollowMapSchemaTest { @Test public void testEquals() { { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB"); HollowMapSchema s2 = new HollowMapSchema("Test", "TypeA", "TypeB"); Assert.assertEquals(s1, s2); } { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB"); HollowMapSchema s2 = new HollowMapSchema("Test2", "TypeA", "TypeB"); Assert.assertNotEquals(s1, s2); } { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB"); HollowMapSchema s2 = new HollowMapSchema("Test", "TypeB", "TypeB"); Assert.assertNotEquals(s1, s2); } { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB"); HollowMapSchema s2 = new HollowMapSchema("Test", "TypeA", "TypeC"); Assert.assertNotEquals(s1, s2); } } @Test public void testEqualsWithKeys() { { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB", "f1"); HollowMapSchema s2 = new HollowMapSchema("Test", "TypeA", "TypeB", "f1"); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getHashKey(), s2.getHashKey()); Assert.assertEquals(new PrimaryKey("TypeA", "f1"), s2.getHashKey()); } { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB", "f1", "f2"); HollowMapSchema s2 = new HollowMapSchema("Test", "TypeA", "TypeB", "f1", "f2"); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getHashKey(), s2.getHashKey()); Assert.assertEquals(new PrimaryKey("TypeA", "f1", "f2"), s2.getHashKey()); } { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB"); HollowMapSchema s2 = new HollowMapSchema("Test", "TypeA", "TypeB", "f1"); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getHashKey(), s2.getHashKey()); } { HollowMapSchema s1 = new HollowMapSchema("Test", "TypeA", "TypeB", "f1"); HollowMapSchema s2 = new HollowMapSchema("Test", "TypeA", "TypeB", "f1", "f2"); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getHashKey(), s2.getHashKey()); } } }
8,770
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/schema/HollowObjectSchemaTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.schema; import com.netflix.hollow.api.error.IncompatibleSchemaException; import com.netflix.hollow.core.read.filter.HollowFilterConfig; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import org.junit.Assert; import org.junit.Test; public class HollowObjectSchemaTest { @Test public void findsCommonSchemas() { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F2"); s2.addField("F2", FieldType.LONG); s2.addField("F3", FieldType.STRING); HollowObjectSchema commonSchema = s1.findCommonSchema(s2); Assert.assertEquals(1, commonSchema.numFields()); Assert.assertEquals("F2", commonSchema.getFieldName(0)); Assert.assertEquals(FieldType.LONG, commonSchema.getFieldType(0)); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); Assert.assertEquals(s1.getPrimaryKey(), commonSchema.getPrimaryKey()); { HollowObjectSchema s3 = new HollowObjectSchema("Test", 2, "F3"); s3.addField("F2", FieldType.LONG); s3.addField("F3", FieldType.STRING); HollowObjectSchema c3 = s1.findCommonSchema(s3); Assert.assertNotEquals(s1.getPrimaryKey(), s3.getPrimaryKey()); Assert.assertNotEquals(s1.getPrimaryKey(), c3.getPrimaryKey()); Assert.assertNull(c3.getPrimaryKey()); } } @Test public void findCommonSchema_incompatible() { try { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F1"); s1.addField("F1", FieldType.INT); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1"); s2.addField("F1", FieldType.STRING); s1.findCommonSchema(s2); Assert.fail("Expected IncompatibleSchemaException"); } catch (IncompatibleSchemaException e) { Assert.assertEquals("Test", e.getTypeName()); Assert.assertEquals("F1", e.getFieldName()); } } @Test public void findsUnionSchemas() { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F2"); s2.addField("F2", FieldType.LONG); s2.addField("F3", FieldType.STRING); HollowObjectSchema unionSchema = s1.findUnionSchema(s2); Assert.assertEquals(3, unionSchema.numFields()); Assert.assertEquals("F1", unionSchema.getFieldName(0)); Assert.assertEquals(FieldType.INT, unionSchema.getFieldType(0)); Assert.assertEquals("F2", unionSchema.getFieldName(1)); Assert.assertEquals(FieldType.LONG, unionSchema.getFieldType(1)); Assert.assertEquals("F3", unionSchema.getFieldName(2)); Assert.assertEquals(FieldType.STRING, unionSchema.getFieldType(2)); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); Assert.assertEquals(s1.getPrimaryKey(), unionSchema.getPrimaryKey()); { HollowObjectSchema s3 = new HollowObjectSchema("Test", 2, "F3"); s3.addField("F2", FieldType.LONG); s3.addField("F3", FieldType.STRING); HollowObjectSchema u3 = s1.findUnionSchema(s3); Assert.assertNotEquals(s1.getPrimaryKey(), u3.getPrimaryKey()); Assert.assertNotEquals(s1.getPrimaryKey(), u3.getPrimaryKey()); Assert.assertNull(u3.getPrimaryKey()); } } @Test public void filterSchema() { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); Assert.assertEquals(2, s1.numFields()); HollowFilterConfig filter = new HollowFilterConfig(); filter.addField("Test", "F2"); HollowObjectSchema s2 = s1.filterSchema(filter); Assert.assertEquals(1, s2.numFields()); Assert.assertEquals("F2", s2.getFieldName(0)); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } @Test public void testEquals() { { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertEquals(s1, s2); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 1); s2.addField("F1", FieldType.INT); Assert.assertNotEquals(s1, s2); } } @Test public void testEqualsWithPrimaryKey() { { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F2"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F1", "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1", "F2"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F1", "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } } }
8,771
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/HollowHashIndexLongevityTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.test.HollowWriteStateEngineBuilder; import com.netflix.hollow.test.consumer.TestBlobRetriever; import com.netflix.hollow.test.consumer.TestHollowConsumer; import java.io.IOException; import java.util.Collections; import java.util.Set; import java.util.stream.IntStream; import org.assertj.core.api.Condition; import org.junit.Test; @SuppressWarnings("unused") public class HollowHashIndexLongevityTest { @Test public void testIndexSurvives3Updates() throws IOException { TestHollowConsumer longConsumer = createHollowConsumer(true); TestHollowConsumer shortConsumer = createHollowConsumer(false); HollowWriteStateEngine snapshotEngine = createSnapshot(0, 5, "snapshot"); longConsumer.applySnapshot(0, snapshotEngine); shortConsumer.applySnapshot(0, snapshotEngine); //If we were using listeners, we would have access to the ReadStateEngine + API. So we'll just use API to //simulate that. //Auto discover the keys HollowHashIndex longSnapshot0 = new HollowHashIndex(longConsumer.getAPI().getDataAccess(), "TypeA", "", "key"); HollowHashIndex shortSnapshot0 = new HollowHashIndex(shortConsumer.getAPI().getDataAccess(), "TypeA", "", "key"); int longOrd0 = getOnlyOrdinal(longSnapshot0.findMatches(0)); int longOrd1 = getOnlyOrdinal(longSnapshot0.findMatches(1)); int longOrd2 = getOnlyOrdinal(longSnapshot0.findMatches(2)); int shortOrd0 = getOnlyOrdinal(longSnapshot0.findMatches(0)); int shortOrd1 = getOnlyOrdinal(longSnapshot0.findMatches(1)); int shortOrd2 = getOnlyOrdinal(longSnapshot0.findMatches(2)); HollowAPI longSnapshotApi = longConsumer.getAPI(); //All of these return non-null results. That verifies the index worked as of this snapshot. assertThat(longSnapshot0.findMatches(0)).is(exactlyOrdinal(longOrd0)); assertThat(longSnapshot0.findMatches(1)).is(exactlyOrdinal(longOrd1)); assertThat(longSnapshot0.findMatches(2)).is(exactlyOrdinal(longOrd2)); assertThat(shortSnapshot0.findMatches(0)).is(exactlyOrdinal(shortOrd0)); assertThat(shortSnapshot0.findMatches(1)).is(exactlyOrdinal(shortOrd1)); assertThat(shortSnapshot0.findMatches(2)).is(exactlyOrdinal(shortOrd2)); //Now we do a delta. Both indexes should work HollowWriteStateEngine delta1Engine = createSnapshot(0, 5, "delta1"); longConsumer.applyDelta(1, delta1Engine); shortConsumer.applyDelta(1, delta1Engine); HollowHashIndex longDelta1 = new HollowHashIndex(longConsumer.getAPI().getDataAccess(), "TypeA", "", "key"); HollowHashIndex shortDelta1 = new HollowHashIndex(shortConsumer.getAPI().getDataAccess(), "TypeA", "", "key"); assertThat(longConsumer.getAPI()).isNotSameAs(longSnapshotApi); //The ordinals should all change because every record was updated. assertThat(longDelta1.findMatches(0)).is(notOrdinal(longOrd0)); assertThat(longDelta1.findMatches(1)).is(notOrdinal(longOrd1)); assertThat(longDelta1.findMatches(2)).is(notOrdinal(longOrd2)); assertThatOrdinalsAreNotEqual(shortDelta1.findMatches(0), shortSnapshot0.findMatches(0)); assertThatOrdinalsAreNotEqual(shortDelta1.findMatches(1), shortSnapshot0.findMatches(1)); assertThatOrdinalsAreNotEqual(shortDelta1.findMatches(2), shortSnapshot0.findMatches(2)); //All of these should continue to work. assertThat(longSnapshot0.findMatches(0)).is(exactlyOrdinal(longOrd0)); assertThat(longSnapshot0.findMatches(1)).is(exactlyOrdinal(longOrd1)); assertThat(longSnapshot0.findMatches(2)).is(exactlyOrdinal(longOrd2)); assertThat(shortSnapshot0.findMatches(0)).is(exactlyOrdinal(shortOrd0)); assertThat(shortSnapshot0.findMatches(1)).is(exactlyOrdinal(shortOrd1)); assertThat(shortSnapshot0.findMatches(2)).is(exactlyOrdinal(shortOrd2)); //Do another delta. The long index should work. The short index should not. HollowWriteStateEngine delta2Engine = createSnapshot(4, 10, "delta1"); longConsumer.applyDelta(2, delta2Engine); shortConsumer.applyDelta(2, delta2Engine); HollowHashIndex longDelta2 = new HollowHashIndex(longConsumer.getAPI().getDataAccess(), "TypeA", "", "key"); HollowHashIndex shortDelta2 = new HollowHashIndex(shortConsumer.getAPI().getDataAccess(), "TypeA", "", "key"); assertThat(longConsumer.getAPI()).isNotSameAs(longSnapshotApi); assertThat(longDelta2.findMatches(0)).isNull(); assertThat(longDelta2.findMatches(1)).isNull(); assertThat(longDelta2.findMatches(2)).isNull(); assertThat(longDelta2.findMatches(5)).is(exactlyOneOrdinal()); assertThat(shortDelta2.findMatches(0)).isNull(); assertThat(shortDelta2.findMatches(1)).isNull(); assertThat(shortDelta2.findMatches(2)).isNull(); assertThat(shortDelta2.findMatches(5)).is(exactlyOneOrdinal()); //Long should keep working, short should not. assertThat(longSnapshot0.findMatches(0)).is(exactlyOrdinal(longOrd0)).is(exactlyOneOrdinal()); assertThat(longSnapshot0.findMatches(1)).is(exactlyOrdinal(longOrd1)).is(exactlyOneOrdinal()); assertThat(longSnapshot0.findMatches(2)).is(exactlyOrdinal(longOrd2)).is(exactlyOneOrdinal()); //We changed the id range to exclude 0-2 to ensure we don't end up with a "new" object squatting on an old ordinal //and the index accidentally matching. assertThat(shortSnapshot0.findMatches(0)).isNull(); assertThat(shortSnapshot0.findMatches(1)).isNull(); assertThat(shortSnapshot0.findMatches(2)).isNull(); } private static void assertThatOrdinalsAreNotEqual(HollowHashIndexResult actual, HollowHashIndexResult expected) { Set<Integer> expectedOrdinals = toOrdinals(expected); assertThat(expectedOrdinals).isNotEmpty(); assertThat(toOrdinals(actual)) .isNotEmpty() .isNotEqualTo(expectedOrdinals); } private static Set<Integer> toOrdinals(HollowHashIndexResult result) { if(result != null) { return result.stream().boxed().collect(toSet()); } else { return Collections.emptySet(); } } private static Condition<HollowHashIndexResult> notOrdinal(int expectedOrdinal) { return new Condition<HollowHashIndexResult>("HollowHashIndexResult must have 1 result and it must NOT be " + expectedOrdinal) { @Override public boolean matches(HollowHashIndexResult matches) { if(matches.numResults()!=1) { describedAs("HollowHashIndexResult has " + matches.numResults() + " results. Expected only 1."); return false; } int actualOrdinal = matches.iterator().next(); if(actualOrdinal == expectedOrdinal) { describedAs("HollowHashIndexResult returned ordinal " + actualOrdinal + ". Returned ordinal must be any other value."); return false; } return true; } }; } private static Condition<HollowHashIndexResult> exactlyOrdinal(int expectedOrdinal) { return new Condition<HollowHashIndexResult>("HollowHashIndexResult must have 1 result and it must be " + expectedOrdinal) { @Override public boolean matches(HollowHashIndexResult matches) { if(matches.numResults()!=1) { describedAs("HollowHashIndexResult has " + matches.numResults() + " results. Expected only 1."); return false; } int actualOrdinal = matches.iterator().next(); if(actualOrdinal != expectedOrdinal) { describedAs("HollowHashIndexResult returned ordinal " + actualOrdinal + ". Expected ordinal " + expectedOrdinal + "."); return false; } return true; } }; } private static Condition<HollowHashIndexResult> exactlyOneOrdinal() { return new Condition<HollowHashIndexResult>("HollowHashIndexResult must have at least one result.") { @Override public boolean matches(HollowHashIndexResult matches) { if(matches.numResults()==0) { describedAs("HollowHashIndexResult has " + matches.numResults() + " results. Expected at least one."); return false; } return true; } }; } private static int getOnlyOrdinal(HollowHashIndexResult matches) { assertThat(matches.numResults()).isEqualTo(1); return matches.iterator().next(); } @SuppressWarnings("FieldCanBeLocal") @HollowPrimaryKey(fields = {"key"}) private static class TypeA { private final int key; private final String value; public TypeA(int key, String value) { this.key = key; this.value = value; } } private static HollowWriteStateEngine createSnapshot(int start, int end, String value) { Object[] objects = IntStream.range(start, end) .mapToObj(id -> new TypeA(id, value)) .toArray(); return new HollowWriteStateEngineBuilder(Collections.singleton(TypeA.class)).add(objects).build(); } private static TestHollowConsumer createHollowConsumer(boolean longevity) { return new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .withObjectLongevityConfig( new HollowConsumer.ObjectLongevityConfig() { public long usageDetectionPeriodMillis() { return 1_000L; } public long gracePeriodMillis() { return HOURS.toMillis(2); } public boolean forceDropData() { return true; } public boolean enableLongLivedObjectSupport() { return longevity; } public boolean enableExpiredUsageStackTraces() { return false; } public boolean dropDataAutomatically() { return true; } }) .build(); } }
8,772
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/PrimaryKeyTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @SuppressWarnings("unused") public class PrimaryKeyTest { HollowWriteStateEngine writeEngine; @Before public void setUp() { writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeWithTraversablePrimaryKey.class); } @Test public void automaticallyTraversesSomeIncompletelyDefinedFieldPaths() { HollowObjectSchema schema = (HollowObjectSchema) writeEngine.getTypeState("TypeWithTraversablePrimaryKey").getSchema(); PrimaryKey traversablePrimaryKey = schema.getPrimaryKey(); Assert.assertEquals(2, traversablePrimaryKey.getFieldPathIndex(writeEngine, 0).length); Assert.assertEquals(3, traversablePrimaryKey.getFieldPathIndex(writeEngine, 1).length); Assert.assertEquals(1, traversablePrimaryKey.getFieldPathIndex(writeEngine, 2).length); PrimaryKey anotherTraversablePrimaryKey = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType.id"); Assert.assertEquals(3, anotherTraversablePrimaryKey.getFieldPathIndex(writeEngine, 0).length); PrimaryKey hardStopPrimaryKey = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType.id!"); Assert.assertEquals(2, hardStopPrimaryKey.getFieldPathIndex(writeEngine, 0).length); PrimaryKey hardStopPrimaryKey2 = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType2!"); Assert.assertEquals(1, hardStopPrimaryKey2.getFieldPathIndex(writeEngine, 0).length); PrimaryKey hardStopPrimaryKey3 = new PrimaryKey("TypeWithTraversablePrimaryKey", "strList!"); Assert.assertEquals(1, hardStopPrimaryKey3.getFieldPathIndex(writeEngine, 0).length); } @Test public void throwsMeaningfulExceptions() { try { PrimaryKey invalidFieldDefinition = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType.nofield"); invalidFieldDefinition.getFieldPathIndex(writeEngine, 0); Assert.fail("IllegalArgumentException expected"); } catch (FieldPaths.FieldPathException expected) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_FOUND, expected.error); Assert.assertEquals(1, expected.fieldSegments.size()); Assert.assertEquals(1, expected.segmentIndex); Assert.assertEquals("SubTypeWithTraversablePrimaryKey", expected.enclosingSchema.getName()); } try { PrimaryKey invalidFieldDefinition = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType.id.value.alldone"); invalidFieldDefinition.getFieldPathIndex(writeEngine, 0); Assert.fail("IllegalArgumentException expected"); } catch (FieldPaths.FieldPathException expected) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_TRAVERSABLE, expected.error); Assert.assertEquals(3, expected.fieldSegments.size()); Assert.assertEquals(2, expected.segmentIndex); Assert.assertEquals("value", expected.fieldSegments.get(2).getName()); Assert.assertEquals("String", expected.enclosingSchema.getName()); } try { PrimaryKey invalidFieldDefinition = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType2"); invalidFieldDefinition.getFieldPathIndex(writeEngine, 0); Assert.fail("IllegalArgumentException expected"); } catch (FieldPaths.FieldPathException expected) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_EXPANDABLE, expected.error); Assert.assertEquals(1, expected.fieldSegments.size()); Assert.assertEquals("subType2", expected.fieldSegments.get(0).getName()); Assert.assertEquals("SubTypeWithNonTraversablePrimaryKey", expected.enclosingSchema.getName()); } try { PrimaryKey invalidFieldDefinition = new PrimaryKey("TypeWithTraversablePrimaryKey", "strList.element.value"); invalidFieldDefinition.getFieldPathIndex(writeEngine, 0); Assert.fail("IllegalArgumentException expected"); } catch (FieldPaths.FieldPathException expected) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_TRAVERSABLE, expected.error); Assert.assertEquals(1, expected.fieldSegments.size()); Assert.assertEquals(1, expected.segmentIndex); Assert.assertEquals("element", expected.segments[expected.segmentIndex]); Assert.assertEquals("ListOfString", expected.enclosingSchema.getName()); } try { PrimaryKey invalidFieldDefinition = new PrimaryKey("UnknownType", "id"); invalidFieldDefinition.getFieldPathIndex(writeEngine, 0); Assert.fail("IllegalArgumentException expected"); } catch (FieldPaths.FieldPathException expected) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_BINDABLE, expected.error); Assert.assertEquals(0, expected.fieldSegments.size()); Assert.assertEquals(0, expected.segmentIndex); Assert.assertEquals("UnknownType", expected.rootType); } } @Test public void testAutoExpand() { { // verify fieldPath auto expand PrimaryKey autoExpandPK = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType"); Assert.assertEquals(FieldType.STRING, autoExpandPK.getFieldType(writeEngine, 0)); Assert.assertEquals(null, autoExpandPK.getFieldSchema(writeEngine, 0)); } { // verify disabled fieldPath auto expand with ending "!" PrimaryKey autoExpandPK = new PrimaryKey("TypeWithTraversablePrimaryKey", "subType!"); Assert.assertNotEquals(FieldType.STRING, autoExpandPK.getFieldType(writeEngine, 0)); Assert.assertEquals(FieldType.REFERENCE, autoExpandPK.getFieldType(writeEngine, 0)); Assert.assertEquals("SubTypeWithTraversablePrimaryKey", autoExpandPK.getFieldSchema(writeEngine, 0).getName()); } } @HollowPrimaryKey(fields={"pk1", "subType", "intId"}) private static class TypeWithTraversablePrimaryKey { String pk1; SubTypeWithTraversablePrimaryKey subType; SubTypeWithNonTraversablePrimaryKey subType2; int intId; List<String> strList; } @HollowPrimaryKey(fields="id") private static class SubTypeWithTraversablePrimaryKey { String id; int anotherField; } @HollowPrimaryKey(fields={"id1", "id2"}) private static class SubTypeWithNonTraversablePrimaryKey { long id1; float id2; } }
8,773
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/HollowUniqueKeyIndexTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.memory.pool.ArraySegmentRecycler; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.io.IOException; import org.junit.Assert; import org.junit.Test; @SuppressWarnings("unused") public class HollowUniqueKeyIndexTest extends HollowPrimaryKeyIndexTest { protected TestableUniqueKeyIndex createIndex(String type, String ... fieldPaths) { return new HollowUniqueKeyIndex(readStateEngine, type, fieldPaths); } protected TestableUniqueKeyIndex createIndex(ArraySegmentRecycler memoryRecycler, String type, String ... fieldPaths) { return new HollowUniqueKeyIndex(readStateEngine, memoryRecycler, type, fieldPaths); } @Test public void testSnapshotAndDelta() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); roundTripSnapshot(); // Auto Discover fieldPaths from @HollowPrimaryKey // UniqueKeyIndex idx = createIndex("TypeA", "a1", "a2", "ab.b1.value"); TestableUniqueKeyIndex idx = createIndex("TypeA"); idx.listenForDeltaUpdates(); int ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); int ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); int ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); Assert.assertEquals(0, ord0); Assert.assertEquals(1, ord1); Assert.assertEquals(2, ord2); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); // mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); mapper.add(new TypeA(3, 3.3d, new TypeB("three"))); roundTripDelta(); ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); int ord3 = idx.getMatchingOrdinal(3, 3.3d, "three"); Assert.assertEquals(0, ord0); Assert.assertEquals(-1, ord1); Assert.assertEquals(2, ord2); Assert.assertEquals(3, ord3); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); // it is a ghost record (marked deleted but it is available) assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); assertEquals(idx.getRecordKey(3), 3, 3.3d, "three"); } @Test public void indicatesWhetherOrNotDuplicateKeysExist() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); roundTripSnapshot(); // Auto Discover fieldPaths from @HollowPrimaryKey //UniqueKeyIndex idx = createIndex("TypeA", "a1", "a2", "ab.b1.value"); TestableUniqueKeyIndex idx = createIndex("TypeA"); idx.listenForDeltaUpdates(); Assert.assertFalse(idx.containsDuplicates()); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two", true))); roundTripDelta(); Assert.assertEquals(1, idx.getDuplicateKeys().size()); Assert.assertTrue(idx.containsDuplicates()); } @Test public void handlesEmptyTypes() throws IOException { HollowObjectSchema testSchema = new HollowObjectSchema("Test", 1); testSchema.addField("test1", FieldType.INT); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(testSchema)); roundTripSnapshot(); TestableUniqueKeyIndex idx = createIndex("Test", "test1"); Assert.assertEquals(-1, idx.getMatchingOrdinal(100)); Assert.assertFalse(idx.containsDuplicates()); } @Test public void testSnapshotAndDeltaWithStateEngineMemoryRecycler() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); roundTripSnapshot(); TestableUniqueKeyIndex idx = createIndex(readStateEngine.getMemoryRecycler(), "TypeA", "a1", "a2", "ab.b1.value"); idx.listenForDeltaUpdates(); int ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); int ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); int ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); Assert.assertEquals(0, ord0); Assert.assertEquals(1, ord1); Assert.assertEquals(2, ord2); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); // mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); mapper.add(new TypeA(3, 3.3d, new TypeB("three"))); roundTripDelta(); ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); int ord3 = idx.getMatchingOrdinal(3, 3.3d, "three"); Assert.assertEquals(0, ord0); Assert.assertEquals(-1, ord1); Assert.assertEquals(2, ord2); Assert.assertEquals(3, ord3); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); // it is a ghost record (marked deleted but it is available) assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); assertEquals(idx.getRecordKey(3), 3, 3.3d, "three"); } @Test public void testDups() throws IOException { String typeA = "TypeA"; int numOfItems = 1000; int a1ValueStart = 1; double a2Value = 1; addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); roundTripSnapshot(); int a1Pos = ((HollowObjectSchema) readStateEngine.getTypeState(typeA).getSchema()).getPosition("a1"); int a2Pos = ((HollowObjectSchema) readStateEngine.getTypeState(typeA).getSchema()).getPosition("a2"); TestableUniqueKeyIndex idx = createIndex("TypeA", "a1"); idx.listenForDeltaUpdates(); Assert.assertFalse(idx.containsDuplicates()); // add dups int numOfDups = (int) (numOfItems * 0.2); int a1dupValueStart = 2; int a1dupValueEnd = a1dupValueStart + numOfDups; double a2dupValues = 2; { // Add dups addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); addDataForDupTesting(writeStateEngine, a1dupValueStart, a2dupValues, numOfDups); roundTripDelta(); Assert.assertEquals(true, idx.containsDuplicates()); // Make sure there is dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); double a2Val = readTypeState.readDouble(ordinal, a2Pos); //System.out.println("a1=" + a1Val + "\ta2=" + a2Val); if (isInDupRange) { // Not deterministic Assert.assertTrue(a2Val == a2Value || a2Val == a2dupValues); } else { Assert.assertTrue(a2Val == a2Value); } } } { // remove dups addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); roundTripDelta(); Assert.assertFalse(idx.containsDuplicates()); // Make sure there is no dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); double a2Val = readTypeState.readDouble(ordinal, a2Pos); // System.out.println("a1=" + a1Val + "\ta2=" + a2Val); // Should be equal to base value Assert.assertTrue(a2Val == a2Value); } } { // create dups addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); addDataForDupTesting(writeStateEngine, a1dupValueStart, a2dupValues, numOfDups); roundTripDelta(); Assert.assertEquals(true, idx.containsDuplicates()); // Make sure there is dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); double a2Val = readTypeState.readDouble(ordinal, a2Pos); //System.out.println("a1=" + a1Val + "\ta2=" + a2Val); if (isInDupRange) { // Not deterministic Assert.assertTrue(a2Val == a2Value || a2Val == a2dupValues); } else { Assert.assertTrue(a2Val == a2Value); } } } { // remove original addDataForDupTesting(writeStateEngine, a1dupValueStart, a2dupValues, numOfDups); roundTripDelta(); Assert.assertFalse(idx.containsDuplicates()); // Make sure there is no dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); if (!isInDupRange) { // should not be found if not in dup range Assert.assertTrue(ordinal < 0); continue; } double a2Val = readTypeState.readDouble(ordinal, a2Pos); // System.out.println("a1=" + a1Val + "\ta2=" + a2Val); // Make sure value is the Dup Values Assert.assertTrue(a2Val == a2dupValues); } } } private static void addDataForDupTesting(HollowWriteStateEngine writeStateEngine, int a1Start, double a2, int size) { TypeB typeB = new TypeB("commonTypeB"); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); int max = a1Start + size; for (int a1 = a1Start; a1 < max; a1++) { mapper.add(new TypeA(a1, a2, typeB)); } } private static void assertEquals(Object[] actual, Object... expected) { Assert.assertEquals(actual.length, expected.length); for (int i = 0; i < actual.length; i++) { Assert.assertEquals(expected[i], actual[i]); } } @HollowPrimaryKey(fields = { "a1", "a2", "ab.b1" }) private static class TypeA { private final int a1; private final double a2; private final TypeB ab; public TypeA(int a1, double a2, TypeB ab) { this.a1 = a1; this.a2 = a2; this.ab = ab; } } private static class TypeB { private final String b1; private final boolean isDuplicate; public TypeB(String b1) { this(b1, false); } public TypeB(String b1, boolean isDuplicate) { this.b1 = b1; this.isDuplicate = isDuplicate; } } @Override protected void initializeTypeStates() { } }
8,774
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/MultiLinkedElementArrayTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import org.junit.Assert; import org.junit.Test; public class MultiLinkedElementArrayTest { @Test public void testIterators() { MultiLinkedElementArray arr = new MultiLinkedElementArray(WastefulRecycler.SMALL_ARRAY_RECYCLER); Assert.assertEquals(0, arr.newList()); arr.add(0, 100); arr.add(0, 200); arr.add(0, 300); Assert.assertEquals(1, arr.newList()); arr.add(1, 101); Assert.assertEquals(2, arr.newList()); arr.add(2, 102); Assert.assertEquals(3, arr.newList()); arr.add(0, 400); arr.add(0, 500); arr.add(2, 202); arr.add(3, 103); arr.add(3, 203); arr.add(3, 303); Assert.assertEquals(4, arr.newList()); arr.add(4, 0); Assert.assertEquals(5, arr.newList()); arr.add(5, 0); arr.add(5, 0); Assert.assertEquals(6, arr.newList()); arr.add(6, 0); arr.add(6, 0); arr.add(6, 0); arr.add(0, 600); assertIteratorContents(arr.iterator(0), 600, 500, 400, 300, 200, 100); assertIteratorContents(arr.iterator(1), 101); assertIteratorContents(arr.iterator(2), 202, 102); assertIteratorContents(arr.iterator(3), 303, 203, 103); assertIteratorContents(arr.iterator(4), 0); assertIteratorContents(arr.iterator(5), 0, 0); assertIteratorContents(arr.iterator(6), 0, 0, 0); } private void assertIteratorContents(HollowOrdinalIterator iter, int... expectedOrdinals) { for(int i=0;i<expectedOrdinals.length;i++) { Assert.assertEquals(expectedOrdinals[i], iter.next()); } Assert.assertEquals(HollowOrdinalIterator.NO_MORE_ORDINALS, iter.next()); } }
8,775
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/HollowPrefixIndexTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Test for Hollow Prefix Index. */ public class HollowPrefixIndexTest { private HollowWriteStateEngine writeStateEngine; private HollowReadStateEngine readStateEngine; private HollowObjectMapper objectMapper; @Before public void beforeTestSetup() { writeStateEngine = new HollowWriteStateEngine(); readStateEngine = new HollowReadStateEngine(); objectMapper = new HollowObjectMapper(writeStateEngine); } @Test public void testSimple() throws Exception { test(getSimpleList(), "SimpleMovie", "name");// also tests, if field path auto expands to name.value. } @Test public void testInline() throws Exception { test(getInlineList(), "MovieInlineName", "name"); } @Test public void testReference() throws Exception { test(getReferenceList(), "MovieWithReferenceName", "name.n.value"); } @Test public void testReferenceInline() throws Exception { test(getReferenceToInlineList(), "MovieWithReferenceToInlineName", "name.n"); } @Test public void testFindKeysWithPrefix() throws Exception { for (Movie movie : getSimpleList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowTokenizedPrefixIndex tokenizedPrefixIndex = new HollowTokenizedPrefixIndex(readStateEngine, "SimpleMovie", "name.value", false); Set<Integer> ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("th")); Assert.assertTrue(ordinals.size() == 3); ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("matrix")); Assert.assertTrue(ordinals.size() == 3); ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("re")); Assert.assertTrue(ordinals.size() == 2); ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("the "));// note the whitespace in findKeysWithPrefix string. // expected result ordinals size is 0, since entire movie is not indexed. movie name is split by whitespace. Assert.assertTrue(ordinals.size() == 0); ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("")); Assert.assertTrue(ordinals.size() == 6); } @Test public void testLongestPrefixMatch() throws Exception { // "The Matrix" // "Blood Diamond" // "Rush" // "Rocky" // "The Matrix Reloaded" // "The Matrix Resurrections" for (Movie movie : getSimpleList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowTokenizedPrefixIndex tokenizedPrefixIndex = new HollowTokenizedPrefixIndex(readStateEngine, "SimpleMovie", "name.value", false); List<Integer> match; match = tokenizedPrefixIndex.findLongestMatch("rush"); Assert.assertTrue(match.get(0) > -1); match = tokenizedPrefixIndex.findLongestMatch("rushing"); Assert.assertTrue(match.get(0) > -1); match = tokenizedPrefixIndex.findLongestMatch("the"); Assert.assertTrue(match.get(0) > -1); match = tokenizedPrefixIndex.findLongestMatch("doesnotexist"); Assert.assertTrue(match.size() == 0); match = tokenizedPrefixIndex.findLongestMatch("resurrect"); Assert.assertTrue(match.size() == 0); match = tokenizedPrefixIndex.findLongestMatch(""); // empty string is not indexed in prefix index but supported in hollow type state Assert.assertTrue(match.size() == 0); match = tokenizedPrefixIndex.findLongestMatch(null); // null value is not supported in hollow type state Assert.assertTrue(match.size() == 0); } @Test public void testPrefixIndexCaseSensitivity() throws Exception { for (Movie movie : getSimpleList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowTokenizedPrefixIndex tokenizedPrefixIndex = new HollowTokenizedPrefixIndex(readStateEngine, "SimpleMovie", "name.value", true); Set<Integer> ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("th")); Assert.assertTrue(ordinals.size() == 0); ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("Th")); Assert.assertTrue(ordinals.size() == 3); ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("matrix")); Assert.assertTrue(ordinals.size() == 0); ordinals = toSet(tokenizedPrefixIndex.findKeysWithPrefix("Matrix")); Assert.assertTrue(ordinals.size() == 3); List<Integer> match; match = tokenizedPrefixIndex.findLongestMatch("rush"); Assert.assertTrue(match.size() == 0); match = tokenizedPrefixIndex.findLongestMatch("Rush"); Assert.assertTrue(match.get(0) > -1); } @Test public void testDeltaChange() throws Exception { List<Movie> movies = getSimpleList(); ((SimpleMovie) movies.get(0)).updateName("007 James Bond");// test numbers ((SimpleMovie) movies.get(1)).updateName("龍爭虎鬥");// "Enter The Dragon" for (Movie movie : movies) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, "SimpleMovie", "name"); prefixIndex.listenForDeltaUpdates(); Set<Integer> ordinals = toSet(prefixIndex.findKeysWithPrefix("龍")); Set<String> movieNames = getMovieNames(ordinals, "SimpleMovie", "name"); Assert.assertTrue(ordinals.size() == 1); Assert.assertTrue(movieNames.contains("龍爭虎鬥")); ordinals = toSet(prefixIndex.findKeysWithPrefix("00")); movieNames = getMovieNames(ordinals, "SimpleMovie", "name"); Assert.assertTrue(ordinals.size() == 1); Assert.assertTrue(movieNames.contains("007 James Bond")); // update one movie ((SimpleMovie) (movies.get(3))).updateName("Rocky 2"); // add new movie Movie m = new SimpleMovie(5, "As Good as It Gets", 1997); movies.add(m); m = new SimpleMovie(6, "0 dark thirty", 1997); movies.add(m); for (Movie movie : movies) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripDelta(writeStateEngine, readStateEngine); ordinals = toSet(prefixIndex.findKeysWithPrefix("as")); movieNames = getMovieNames(ordinals, "SimpleMovie", "name"); Assert.assertTrue(ordinals.size() == 1); Assert.assertTrue(movieNames.contains("As Good as It Gets")); ordinals = toSet(prefixIndex.findKeysWithPrefix("R")); movieNames = getMovieNames(ordinals, "SimpleMovie", "name"); Assert.assertEquals(ordinals.size(), 2); Assert.assertTrue(movieNames.contains("Rocky 2")); Assert.assertTrue(movieNames.contains("Rush")); ordinals = toSet(prefixIndex.findKeysWithPrefix("rocky 2")); movieNames = getMovieNames(ordinals, "SimpleMovie", "name"); Assert.assertTrue(ordinals.size() == 1); Assert.assertTrue(movieNames.contains("Rocky 2")); ordinals = toSet(prefixIndex.findKeysWithPrefix("0")); movieNames = getMovieNames(ordinals, "SimpleMovie", "name"); Assert.assertTrue(ordinals.size() == 2); Assert.assertTrue(movieNames.contains("007 James Bond")); Assert.assertTrue(movieNames.contains("0 dark thirty")); prefixIndex.detachFromDeltaUpdates(); } @Test public void testListReference() throws Exception { MovieListReference movieListReference = new MovieListReference(1, 1999, "The Matrix", Arrays.asList("Keanu Reeves", "Laurence Fishburne", "Carrie-Anne Moss")); objectMapper.add(movieListReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, "MovieListReference", "actors.element.value"); Set<Integer> ordinals = toSet(prefixIndex.findKeysWithPrefix("kea")); Assert.assertTrue(ordinals.size() == 1); } @Test public void testSetReference() throws Exception { MovieSetReference movieSetReference = new MovieSetReference(1, 1999, "The Matrix", new HashSet<String>(Arrays.asList("Keanu Reeves", "Laurence Fishburne", "Carrie-Anne Moss"))); objectMapper.add(movieSetReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, "MovieSetReference", "actors.element"); Set<Integer> ordinals = toSet(prefixIndex.findKeysWithPrefix("kea")); Assert.assertTrue(ordinals.size() == 1); } @Test public void testMovieActorReference() throws Exception { List<Actor> actors = Arrays.asList(new Actor("Keanu Reeves"), new Actor("Laurence Fishburne"), new Actor("Carrie-Anne Moss")); MovieActorReference movieSetReference = new MovieActorReference(1, 1999, "The Matrix", actors); objectMapper.add(movieSetReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, "MovieActorReference", "actors.element"); Set<Integer> ordinals = toSet(prefixIndex.findKeysWithPrefix("kea")); Assert.assertTrue(ordinals.size() == 1); } @Test public void testMovieActorReference_duplicatesInList() throws Exception { List<Actor> actors = Collections.singletonList(new Actor("Keanu Reeves")); int numMovies = 10; IntStream.range(0, numMovies).mapToObj(index -> new MovieActorReference(index, 1999 + index, "The Matrix " + index, actors)) .forEach(objectMapper::add); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, "MovieActorReference", "actors.element"); Assert.assertEquals(numMovies, toSet(prefixIndex.findKeysWithPrefix("kea")).size()); } @Test public void testMovieMapReference() throws Exception { Map<Integer, String> idActorMap = new HashMap<>(); idActorMap.put(1, "Keanu Reeves"); idActorMap.put(2, "Laurence Fishburne"); idActorMap.put(3, "Carrie-Anne Moss"); MovieMapReference movieMapReference = new MovieMapReference(1, 1999, "The Matrix", idActorMap); objectMapper.add(movieMapReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, "MovieMapReference", "idActorNameMap.value"); Set<Integer> ordinals = toSet(prefixIndex.findKeysWithPrefix("kea")); Assert.assertTrue(ordinals.size() == 1); } @Test public void testMovieActorMapReference() throws Exception { Map<Integer, Actor> idActorMap = new HashMap<>(); idActorMap.put(1, new Actor("Keanu Reeves")); idActorMap.put(2, new Actor("Laurence Fishburne")); idActorMap.put(3, new Actor("Carrie-Anne Moss")); MovieActorMapReference movieActorMapReference = new MovieActorMapReference(1, 1999, "The Matrix", idActorMap); objectMapper.add(movieActorMapReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, "MovieActorMapReference", "idActorNameMap.value"); Set<Integer> ordinals = toSet(prefixIndex.findKeysWithPrefix("carr")); Assert.assertTrue(ordinals.size() == 1); ordinals = toSet(prefixIndex.findKeysWithPrefix("aaa")); Assert.assertTrue(ordinals.size() == 0); } @Test(expected = IllegalArgumentException.class) public void testInvalidType() throws Exception { for (Movie movie : getSimpleList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // random type which does not exists in read state engine. new HollowPrefixIndex(readStateEngine, "randomType", "id"); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldPath() throws Exception { for (Movie movie : getSimpleList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // test invalid field path, basically field path does not lead to a string value. new HollowPrefixIndex(readStateEngine, "SimpleMovie", "id"); } @Test(expected = IllegalArgumentException.class) public void testInvalidFieldPathReference() throws Exception { for (Movie movie : getReferenceList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // test invalid field path, in this case reference type is referring toa field which is not present. // PrimaryKey class helps in catching this. new HollowPrefixIndex(readStateEngine, "MovieWithReferenceName", "name.randomField"); } @Test public void testAutoExpandFieldPath() throws Exception { for (Movie movie : getReferenceList()) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex index = new HollowPrefixIndex(readStateEngine, "MovieWithReferenceName", "name.n");// no.value appended, it should work Set<Integer> ordinals = toSet(index.findKeysWithPrefix("the")); Assert.assertTrue(ordinals.size() == 3); } private void test(List<Movie> movies, String type, String fieldPath) throws Exception { for (Movie movie : movies) { objectMapper.add(movie); } StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowPrefixIndex prefixIndex = new HollowPrefixIndex(readStateEngine, type, fieldPath); Set<Integer> ordinals = toSet(prefixIndex.findKeysWithPrefix("R")); Assert.assertEquals(ordinals.size(), 2); ordinals = toSet(prefixIndex.findKeysWithPrefix("R")); Assert.assertEquals(ordinals.size(), 2); ordinals = toSet(prefixIndex.findKeysWithPrefix("th")); Assert.assertEquals(ordinals.size(), 3); ordinals = toSet(prefixIndex.findKeysWithPrefix("ttt")); Assert.assertEquals(ordinals.size(), 0); ordinals = toSet(prefixIndex.findKeysWithPrefix("the")); Assert.assertEquals(ordinals.size(), 3); ordinals = toSet(prefixIndex.findKeysWithPrefix("blOO")); Assert.assertEquals(ordinals.size(), 1); } public List<Movie> getSimpleList() { List<Movie> movies = new ArrayList<>(); movies.add(new SimpleMovie(1, "The Matrix", 1999)); movies.add(new SimpleMovie(2, "Blood Diamond", 2006)); movies.add(new SimpleMovie(3, "Rush", 2013)); movies.add(new SimpleMovie(4, "Rocky", 1976)); movies.add(new SimpleMovie(5, "The Matrix Reloaded", 2003)); movies.add(new SimpleMovie(6, "The Matrix Resurrections", 2021)); return movies; } public List<Movie> getInlineList() { List<Movie> movies = new ArrayList<>(); movies.add(new MovieInlineName(1, "The Matrix", 1999)); movies.add(new MovieInlineName(2, "Blood Diamond", 2006)); movies.add(new MovieInlineName(3, "Rush", 2013)); movies.add(new MovieInlineName(4, "Rocky", 1976)); movies.add(new MovieInlineName(5, "The Matrix Reloaded", 2003)); movies.add(new MovieInlineName(6, "The Matrix Resurrections", 2021)); return movies; } public List<Movie> getReferenceList() { List<Movie> movies = new ArrayList<>(); movies.add(new MovieWithReferenceName(1, "The Matrix", 1999)); movies.add(new MovieWithReferenceName(2, "Blood Diamond", 2006)); movies.add(new MovieWithReferenceName(3, "Rush", 2013)); movies.add(new MovieWithReferenceName(4, "Rocky", 1976)); movies.add(new MovieWithReferenceName(5, "The Matrix Reloaded", 2003)); movies.add(new MovieWithReferenceName(6, "The Matrix Resurrections", 2021)); return movies; } public List<Movie> getReferenceToInlineList() { List<Movie> movies = new ArrayList<>(); movies.add(new MovieWithReferenceToInlineName(1, "The Matrix", 1999)); movies.add(new MovieWithReferenceToInlineName(2, "Blood Diamond", 2006)); movies.add(new MovieWithReferenceToInlineName(3, "Rush", 2013)); movies.add(new MovieWithReferenceToInlineName(4, "Rocky", 1976)); movies.add(new MovieWithReferenceToInlineName(5, "The Matrix Reloaded", 2003)); movies.add(new MovieWithReferenceToInlineName(6, "The Matrix Resurrections", 2021)); return movies; } private Set<Integer> toSet(HollowOrdinalIterator iterator) { Set<Integer> ordinals = new HashSet<>(); int ordinal = iterator.next(); while (ordinal != HollowOrdinalIterator.NO_MORE_ORDINALS) { ordinals.add(ordinal); ordinal = iterator.next(); } return ordinals; } private Set<String> getMovieNames(Set<Integer> ordinals, String type, String field) { Set<String> movieNames = new HashSet<>(); HollowObjectTypeReadState movieReadState = (HollowObjectTypeReadState) readStateEngine.getTypeState(type); HollowObjectTypeReadState nameReadState = (HollowObjectTypeReadState) readStateEngine.getTypeState("String"); int nameField = movieReadState.getSchema().getPosition(field); int valueField = nameReadState.getSchema().getPosition("value"); for (int ordinal : ordinals) { int nameOrdinal = movieReadState.readOrdinal(ordinal, nameField); movieNames.add(nameReadState.readString(nameOrdinal, valueField)); } return movieNames; } /** * Custom prefix index for splitting the key by white space. */ private static class HollowTokenizedPrefixIndex extends HollowPrefixIndex { public HollowTokenizedPrefixIndex(HollowReadStateEngine readStateEngine, String type, String fieldPath, boolean caseSensitive) { super(readStateEngine, type, fieldPath, 1, caseSensitive); } @Override public String[] getKeys(int ordinal, boolean caseSensitive) { // split the key by " "; String[] keys = super.getKeys(ordinal, caseSensitive); List<String> tokens = new ArrayList<>(); for (String key : keys) { String[] splits = key.split(" "); for (String split : splits) tokens.add(split); } return tokens.toArray(new String[tokens.size()]); } } /** * Abstract Movie class for testing purposes. */ private static abstract class Movie { private int id; private int yearRelease; public Movie(int id, int year) { this.id = id; this.yearRelease = year; } } /** * Movie class with String reference for movie name. */ private static class SimpleMovie extends Movie { private String name; public SimpleMovie(int id, String name, int yearRelease) { super(id, yearRelease); this.name = name; } public void updateName(String n) { this.name = n; } } /** * Movie class with HollowInline attribute for movie name. */ private static class MovieInlineName extends Movie { @HollowInline private String name; public MovieInlineName(int id, String name, int yearRelease) { super(id, yearRelease); this.name = name; } } /** * Movie class with name attribute being reference to another class with String reference. */ private static class MovieWithReferenceName extends Movie { private Name name; public MovieWithReferenceName(int id, String name, int yearRelease) { super(id, yearRelease); this.name = new Name(name); } } private static class Name { String n; public Name(String n) { this.n = n; } } /** * Movie class with name attribute being reference to another class with HollowInline string value */ private static class MovieWithReferenceToInlineName extends Movie { private NameInline name; public MovieWithReferenceToInlineName(int id, String name, int yearRelease) { super(id, yearRelease); this.name = new NameInline(name); } } private static class NameInline { @HollowInline String n; public NameInline(String n) { this.n = n; } } /** * Movie class with list of actors */ private static class MovieListReference extends Movie { List<String> actors; String name; public MovieListReference(int id, int yearRelease, String name, List<String> actors) { super(id, yearRelease); this.name = name; this.actors = actors; } } /** * Movie class with set of actors */ private static class MovieSetReference extends Movie { Set<String> actors; String name; public MovieSetReference(int id, int yearRelease, String name, Set<String> actors) { super(id, yearRelease); this.name = name; this.actors = actors; } } /** * Movie class with reference to List of Actor */ private static class MovieActorReference extends Movie { List<Actor> actors; String name; public MovieActorReference(int id, int yearRelease, String name, List<Actor> actors) { super(id, yearRelease); this.actors = actors; this.name = name; } } private static class Actor { private String name; public Actor(String name) { this.name = name; } } private static class MovieMapReference extends Movie { private Map<Integer, String> idActorNameMap; private String name; public MovieMapReference(int id, int yearRelease, String name, Map<Integer, String> idActorMap) { super(id, yearRelease); this.name = name; this.idActorNameMap = idActorMap; } } private static class MovieActorMapReference extends Movie { private Map<Integer, Actor> idActorNameMap; private String name; public MovieActorMapReference(int id, int yearRelease, String name, Map<Integer, Actor> idActorMap) { super(id, yearRelease); this.name = name; this.idActorNameMap = idActorMap; } } }
8,776
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/HollowHashIndexTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.IntStream; import org.junit.Assert; import org.junit.Test; public class HollowHashIndexTest extends AbstractStateEngineTest { private HollowObjectMapper mapper; @Override protected void initializeTypeStates() { mapper = new HollowObjectMapper(writeStateEngine); } @Test public void testBasicHashIndexFunctionality() throws Exception { mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); mapper.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); mapper.add(new TypeA(4, 4.4d, new TypeB("four"))); mapper.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeA", "a1", new String[]{"a1", "ab.element.b1.value"}); Assert.assertNull("An entry that doesn't have any matches has a null iterator", index.findMatches(0, "notfound")); assertIteratorContainsAll(index.findMatches(1, "one").iterator(), 0); assertIteratorContainsAll(index.findMatches(1, "1").iterator(), 1); assertIteratorContainsAll(index.findMatches(2, "two").iterator(), 2); assertIteratorContainsAll(index.findMatches(2, "twenty").iterator(), 2); assertIteratorContainsAll(index.findMatches(2, "two hundred").iterator(), 2); assertIteratorContainsAll(index.findMatches(3, "three").iterator(), 3); assertIteratorContainsAll(index.findMatches(3, "thirty").iterator(), 3); assertIteratorContainsAll(index.findMatches(3, "three hundred").iterator(), 3); assertIteratorContainsAll(index.findMatches(4, "four").iterator(), 4, 5); assertIteratorContainsAll(index.findMatches(4, "forty").iterator(), 5); } @Test public void testIndexingStringTypeFieldWithNullValues() throws Exception { mapper.add(new TypeB(null)); mapper.add(new TypeB("onez:")); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeB", "", "b1.value"); Assert.assertNull(index.findMatches("one:")); assertIteratorContainsAll(index.findMatches("onez:").iterator(), 1); } @Test public void testIndexingBytesTypeFieldWithNullValues() throws Exception { byte[] bytes = {-120,0,0,0}; mapper.add(new TypeBytes(null)); mapper.add(new TypeBytes(bytes)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeBytes", "", "data"); byte[] nonExistingBytes = {1}; Assert.assertNull(index.findMatches(nonExistingBytes)); assertIteratorContainsAll(index.findMatches(bytes).iterator(), 1); } @Test public void testIndexingStringTypeFieldsWithNullValues() throws Exception { mapper.add(new TypeTwoStrings(null, "onez:")); mapper.add(new TypeTwoStrings("onez:", "onez:")); mapper.add(new TypeTwoStrings(null, null)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeTwoStrings", "", "b1.value", "b2.value"); Assert.assertNull(index.findMatches("one")); Assert.assertNull(index.findMatches("one", "onez:")); assertIteratorContainsAll(index.findMatches("onez:", "onez:").iterator(), 1); } @Test public void testIndexingStringTypeFieldsWithNullValuesInDifferentOrder() throws Exception { mapper.add(new TypeTwoStrings(null, null)); mapper.add(new TypeTwoStrings(null, "onez:")); mapper.add(new TypeTwoStrings("onez:", "onez:")); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeTwoStrings", "", "b1.value", "b2.value"); Assert.assertNull(index.findMatches("one")); Assert.assertNull(index.findMatches("one", "onez:")); assertIteratorContainsAll(index.findMatches("onez:", "onez:").iterator(), 2); } @Test public void testIndexingBooleanTypeFieldWithNullValues() throws Exception { mapper.add(new TypeBoolean(null)); mapper.add(new TypeBoolean(true)); mapper.add(new TypeBoolean(false)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeBoolean", "", "data.value"); assertIteratorContainsAll(index.findMatches(Boolean.FALSE).iterator(), 2); assertIteratorContainsAll(index.findMatches(Boolean.TRUE).iterator(), 1); } @Test public void testIndexingInlinedStringTypeFieldWithNullValues() throws Exception { mapper.add(new TypeInlinedString(null)); mapper.add(new TypeInlinedString("onez:")); mapper.add(new TypeInlinedString(null)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeInlinedString", "", "data"); Assert.assertNull(index.findMatches("one:")); assertIteratorContainsAll(index.findMatches("onez:").iterator(), 1); } @Test public void testIndexingLongTypeFieldWithNullValues() throws Exception { mapper.add(new TypeLong(null)); mapper.add(new TypeLong(3L)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeLong", "", "data.value"); Assert.assertNull(index.findMatches(2L)); assertIteratorContainsAll(index.findMatches(3L).iterator(), 1); } @Test public void testIndexingDoubleTypeFieldWithNullValues() throws Exception { mapper.add(new TypeDouble(null)); mapper.add(new TypeDouble(-8.0)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeDouble", "", "data.value"); Assert.assertNull(index.findMatches(2.0)); assertIteratorContainsAll(index.findMatches(-8.0).iterator(), 1); } @Test public void testIndexingIntegerTypeFieldWithNullValues() throws Exception { mapper.add(new TypeInteger(null)); mapper.add(new TypeInteger(-1)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeInteger", "", "data.value"); Assert.assertNull(index.findMatches(2)); assertIteratorContainsAll(index.findMatches(-1).iterator(), 1); } @Test public void testIndexingFloatTypeFieldWithNullValues() throws Exception { mapper.add(new TypeFloat(null)); mapper.add(new TypeFloat(-1.0f)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeFloat", "", "data.value"); Assert.assertNull(index.findMatches(2.0f)); assertIteratorContainsAll(index.findMatches(-1.0f).iterator(), 1); } @Test public void testIndexingReferenceTypeFieldWithNullValues() throws Exception { mapper.add(new TypeC(null)); mapper.add(new TypeC(new TypeD(null))); mapper.add(new TypeC(new TypeD("one"))); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeC", "", "cd.d1.value"); Assert.assertNull(index.findMatches("none")); assertIteratorContainsAll(index.findMatches("one").iterator(), 2); } @Test public void testIndexingListTypeField() throws Exception { mapper.add(new TypeList("A", "B", "C", "D", "A", "B", "C", "D")); mapper.add(new TypeList("B", "C", "D", "E")); mapper.add(new TypeList("X", "Y", "Z")); mapper.add(new TypeList()); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeList", "", "data.element.value"); Assert.assertNull(index.findMatches("M")); Assert.assertNull(index.findMatches("")); assertIteratorContainsAll(index.findMatches("A").iterator(), 0); assertIteratorContainsAll(index.findMatches("B").iterator(), 0, 1); assertIteratorContainsAll(index.findMatches("X").iterator(), 2); } @Test public void testIndexingSetTypeField() throws Exception { mapper.add(new TypeSet("A", "B", "C", "D")); mapper.add(new TypeSet("B", "C", "D", "E")); mapper.add(new TypeSet("X", "Y", "Z")); mapper.add(new TypeSet()); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeSet", "", "data.element.value"); Assert.assertNull(index.findMatches("M")); Assert.assertNull(index.findMatches("")); assertIteratorContainsAll(index.findMatches("A").iterator(), 0); assertIteratorContainsAll(index.findMatches("B").iterator(), 0, 1); assertIteratorContainsAll(index.findMatches("X").iterator(), 2); } @Test public void testIndexingListOfIntTypeField() throws Exception { mapper.add(new TypeListOfTypeString(10, 20, 30, 40, 10, 12)); mapper.add(new TypeListOfTypeString(10, 20, 30)); mapper.add(new TypeListOfTypeString(50, 51, 52)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeListOfTypeString", "", "data.element.data.value"); Assert.assertNull(index.findMatches(10000)); Assert.assertNull(index.findMatches(-1)); assertIteratorContainsAll(index.findMatches(40).iterator(), 0); assertIteratorContainsAll(index.findMatches(10).iterator(), 0, 1); assertIteratorContainsAll(index.findMatches(50).iterator(), 2); } @Test(expected = IllegalArgumentException.class) public void testFindingMatchForNullQueryValue() throws Exception { mapper.add(new TypeB("one:")); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeB", "", "b1.value"); index.findMatches(new Object[]{null}); Assert.fail("exception expected"); } @Test public void testUpdateListener() throws Exception { mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); mapper.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); mapper.add(new TypeA(4, 4.4d, new TypeB("four"))); mapper.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeA", "", "a1"); index.listenForDeltaUpdates(); // spot check initial mapper state Assert.assertNull("An entry that doesn't have any matches has a null iterator", index.findMatches(0)); assertIteratorContainsAll(index.findMatches(1).iterator(), 1, 0); assertIteratorContainsAll(index.findMatches(2).iterator(), 2); assertIteratorContainsAll(index.findMatches(3).iterator(), 3); assertIteratorContainsAll(index.findMatches(4).iterator(), 4, 5); HollowOrdinalIterator preUpdateIterator = index.findMatches(4).iterator(); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); mapper.add(new TypeA(4, 4.4d, new TypeB("four"), new TypeB("fore"))); mapper.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("fourfour"))); mapper.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); // run a round trip roundTripDelta(); // verify the ordinals we get from the index match our new expected ones. assertIteratorContainsAll(index.findMatches(1).iterator(), 1, 0); Assert.assertNull("A removed entry that doesn't have any matches", index.findMatches(2)); assertIteratorContainsAll(index.findMatches(3).iterator(), 3); assertIteratorContainsAll(index.findMatches(4).iterator(), 5, 6, 7); // an iterator doesn't update itself if it was retrieved prior to an update being applied assertIteratorContainsAll(preUpdateIterator, 4, 5); } @Test public void testGettingPropertiesValues() throws Exception { mapper.add(new TypeInlinedString(null)); mapper.add(new TypeInlinedString("onez:")); mapper.add(new TypeInlinedString(null)); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeInlinedString", "", "data"); Assert.assertEquals(index.getMatchFields().length, 1); Assert.assertEquals(index.getMatchFields()[0], "data"); Assert.assertEquals(index.getType(), "TypeInlinedString"); Assert.assertEquals(index.getSelectField(), ""); } private void assertIteratorContainsAll(HollowOrdinalIterator iter, int... expectedOrdinals) { Set<Integer> ordinalSet = new HashSet<>(); int ordinal = iter.next(); while (ordinal != HollowOrdinalIterator.NO_MORE_ORDINALS) { ordinalSet.add(ordinal); ordinal = iter.next(); } Set<Integer> expectedSet = IntStream.of(expectedOrdinals).boxed().collect(toSet()); Assert.assertEquals(expectedSet, ordinalSet); } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeA { private final int a1; private final double a2; private final List<TypeB> ab; public TypeA(int a1, double a2, TypeB... ab) { this.a1 = a1; this.a2 = a2; this.ab = Arrays.asList(ab); } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeB { private final String b1; private final boolean isDuplicate; public TypeB(String b1) { this(b1, false); } public TypeB(String b1, boolean isDuplicate) { this.b1 = b1; this.isDuplicate = isDuplicate; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeC { private final TypeD cd; public TypeC(TypeD cd) { this.cd = cd; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeD { private final String d1; public TypeD(String d1) { this.d1 = d1; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeTwoStrings { private final String b1; private final String b2; public TypeTwoStrings(String b1, String b2) { this.b1 = b1; this.b2 = b2; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeBoolean { private final Boolean data; public TypeBoolean(Boolean data) { this.data = data; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeInlinedString { @HollowInline private final String data; public TypeInlinedString(String data) { this.data = data; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeLong { private final Long data; public TypeLong(Long data) { this.data = data; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeDouble { private final Double data; public TypeDouble(Double data) { this.data = data; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeInteger { private final Integer data; public TypeInteger(Integer data) { this.data = data; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeFloat { private final Float data; public TypeFloat(Float data) { this.data = data; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeBytes { private final byte[] data; public TypeBytes(byte[] data) { this.data = data; } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeList { private final List<String> data; public TypeList(String ... data) { this.data = Arrays.asList(data); } } @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static class TypeListOfTypeString { private final List<TypeInteger> data; public TypeListOfTypeString(Integer ... data) { this.data = stream(data).map(TypeInteger::new).collect(toList()); } } @SuppressWarnings({"unused", "FieldCanBeLocal", "MismatchedQueryAndUpdateOfCollection"}) private static class TypeSet { private final Set<String> data; public TypeSet(String ... data) { this.data = new HashSet<>(Arrays.asList(data)); } } }
8,777
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndexLongevityTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import static java.util.concurrent.TimeUnit.HOURS; import static org.assertj.core.api.Assertions.assertThat; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.test.HollowWriteStateEngineBuilder; import com.netflix.hollow.test.consumer.TestBlobRetriever; import com.netflix.hollow.test.consumer.TestHollowConsumer; import java.io.IOException; import java.util.Collections; import java.util.stream.IntStream; import org.junit.Test; @SuppressWarnings("unused") public class HollowPrimaryKeyIndexLongevityTest { @Test public void testIndexSurvives3Updates() throws IOException { TestHollowConsumer longConsumer = createHollowConsumer(true); TestHollowConsumer shortConsumer = createHollowConsumer(false); HollowWriteStateEngine snapshotEngine = createSnapshot(0,5, "snapshot"); longConsumer.applySnapshot(0, snapshotEngine); shortConsumer.applySnapshot(0, snapshotEngine); //If we were using listeners, we would have access to the ReadStateEngine + API. So we'll just use API to //simulate that. //Auto discover the keys HollowUniqueKeyIndex longSnapshot0 = new HollowUniqueKeyIndex(longConsumer.getAPI().getDataAccess(), "TypeA"); HollowUniqueKeyIndex shortSnapshot0 = new HollowUniqueKeyIndex(shortConsumer.getAPI().getDataAccess(), "TypeA"); int longOrd0 = longSnapshot0.getMatchingOrdinal(0); int longOrd1 = longSnapshot0.getMatchingOrdinal(1); int longOrd2 = longSnapshot0.getMatchingOrdinal(2); HollowAPI longSnapshotApi = longConsumer.getAPI(); //All of these return non-null results. That verifies the index worked as of this snapshot. assertThat(longSnapshot0.getMatchingOrdinal(0)).isEqualTo(longOrd0).isNotEqualTo(-1); assertThat(longSnapshot0.getMatchingOrdinal(1)).isEqualTo(longOrd1).isNotEqualTo(-1); assertThat(longSnapshot0.getMatchingOrdinal(2)).isEqualTo(longOrd2).isNotEqualTo(-1); assertThat(shortSnapshot0.getMatchingOrdinal(0)).isNotEqualTo(-1); assertThat(shortSnapshot0.getMatchingOrdinal(1)).isNotEqualTo(-1); assertThat(shortSnapshot0.getMatchingOrdinal(2)).isNotEqualTo(-1); //Now we do a delta. Both indexes should work HollowWriteStateEngine delta1Engine = createSnapshot(0,5, "delta1"); longConsumer.applyDelta(1, delta1Engine); shortConsumer.applyDelta(1, delta1Engine); HollowUniqueKeyIndex longDelta1 = new HollowUniqueKeyIndex(longConsumer.getAPI().getDataAccess(), "TypeA"); HollowUniqueKeyIndex shortDelta1 = new HollowUniqueKeyIndex(shortConsumer.getAPI().getDataAccess(), "TypeA"); assertThat(longConsumer.getAPI()).isNotSameAs(longSnapshotApi); //The ordinals should all change because every record was updated. assertThat(longDelta1.getMatchingOrdinal(0)).isNotEqualTo(longOrd0).isNotEqualTo(-1); assertThat(longDelta1.getMatchingOrdinal(1)).isNotEqualTo(longOrd1).isNotEqualTo(-1); assertThat(longDelta1.getMatchingOrdinal(2)).isNotEqualTo(longOrd2).isNotEqualTo(-1); assertThat(shortDelta1.getMatchingOrdinal(0)).isNotEqualTo(shortSnapshot0.getMatchingOrdinal(0)).isNotEqualTo(-1); assertThat(shortDelta1.getMatchingOrdinal(1)).isNotEqualTo(shortSnapshot0.getMatchingOrdinal(1)).isNotEqualTo(-1); assertThat(shortDelta1.getMatchingOrdinal(2)).isNotEqualTo(shortSnapshot0.getMatchingOrdinal(2)).isNotEqualTo(-1); //All of these should continue to work. assertThat(longSnapshot0.getMatchingOrdinal(0)).isEqualTo(longOrd0); assertThat(longSnapshot0.getMatchingOrdinal(1)).isEqualTo(longOrd1); assertThat(longSnapshot0.getMatchingOrdinal(2)).isEqualTo(longOrd2); assertThat(shortSnapshot0.getMatchingOrdinal(0)).isNotEqualTo(-1); assertThat(shortSnapshot0.getMatchingOrdinal(1)).isNotEqualTo(-1); assertThat(shortSnapshot0.getMatchingOrdinal(2)).isNotEqualTo(-1); //Do another delta. The long index should work. The short index should not. HollowWriteStateEngine delta2Engine = createSnapshot(4,10, "delta1"); longConsumer.applyDelta(2, delta2Engine); shortConsumer.applyDelta(2, delta2Engine); HollowUniqueKeyIndex longDelta2 = new HollowUniqueKeyIndex(longConsumer.getAPI().getDataAccess(), "TypeA"); HollowUniqueKeyIndex shortDelta2 = new HollowUniqueKeyIndex(shortConsumer.getAPI().getDataAccess(), "TypeA"); assertThat(longConsumer.getAPI()).isNotSameAs(longSnapshotApi); assertThat(longDelta2.getMatchingOrdinal(0)).isEqualTo(-1); assertThat(longDelta2.getMatchingOrdinal(1)).isEqualTo(-1); assertThat(longDelta2.getMatchingOrdinal(2)).isEqualTo(-1); assertThat(longDelta2.getMatchingOrdinal(5)).isNotEqualTo(-1); assertThat(shortDelta2.getMatchingOrdinal(0)).isEqualTo(-1); assertThat(shortDelta2.getMatchingOrdinal(1)).isEqualTo(-1); assertThat(shortDelta2.getMatchingOrdinal(2)).isEqualTo(-1); assertThat(shortDelta2.getMatchingOrdinal(5)).isNotEqualTo(-1); //Long should keep working, short should not. assertThat(longSnapshot0.getMatchingOrdinal(0)).isEqualTo(longOrd0).isNotEqualTo(-1); assertThat(longSnapshot0.getMatchingOrdinal(1)).isEqualTo(longOrd1).isNotEqualTo(-1); assertThat(longSnapshot0.getMatchingOrdinal(2)).isEqualTo(longOrd2).isNotEqualTo(-1); //We changed the id range to exclude 0-2 to ensure we don't end up with a "new" object squatting on an old ordinal //and the index accidentally matching. assertThat(shortSnapshot0.getMatchingOrdinal(0)).isEqualTo(-1); assertThat(shortSnapshot0.getMatchingOrdinal(1)).isEqualTo(-1); assertThat(shortSnapshot0.getMatchingOrdinal(2)).isEqualTo(-1); } @SuppressWarnings("FieldCanBeLocal") @HollowPrimaryKey(fields = {"key"}) private static class TypeA { private final int key; private final String value; public TypeA(int key, String value) { this.key = key; this.value = value; } } private static HollowWriteStateEngine createSnapshot(int start, int end, String value) { Object[] objects = IntStream.range(start, end) .mapToObj(id -> new TypeA(id, value)) .toArray(); return new HollowWriteStateEngineBuilder(Collections.singleton(TypeA.class)).add(objects).build(); } private static TestHollowConsumer createHollowConsumer(boolean longevity) { return new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .withObjectLongevityConfig( new HollowConsumer.ObjectLongevityConfig() { public long usageDetectionPeriodMillis() { return 1_000L; } public long gracePeriodMillis() { return HOURS.toMillis(2); } public boolean forceDropData() { return true; } public boolean enableLongLivedObjectSupport() { return longevity; } public boolean enableExpiredUsageStackTraces() { return false; } public boolean dropDataAutomatically() { return true; } }) .build(); } }
8,778
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/GrowingSegmentedLongArrayTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import org.junit.Assert; import org.junit.Test; public class GrowingSegmentedLongArrayTest { @Test public void growsToFit() { GrowingSegmentedLongArray arr = new GrowingSegmentedLongArray(WastefulRecycler.SMALL_ARRAY_RECYCLER); for(int i=0;i<100000;i++) { Assert.assertEquals(0, arr.get(i)); } for(int i=0;i<100000;i++) { arr.set(i, i); } for(int i=0;i<100000;i++) { Assert.assertEquals(i, arr.get(i)); } arr.destroy(); } }
8,779
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/HollowSparseIntegerSetTest.java
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Unit tests for HollowSparseIntegerSet. */ public class HollowSparseIntegerSetTest { private HollowWriteStateEngine writeStateEngine; private HollowReadStateEngine readStateEngine; private HollowObjectMapper objectMapper; @Before public void beforeTestSetup() { writeStateEngine = new HollowWriteStateEngine(); readStateEngine = new HollowReadStateEngine(); objectMapper = new HollowObjectMapper(writeStateEngine); } @Test public void testEmptyAndDelta() throws Exception { List<Movie> emptyMovies = new ArrayList<>(); objectMapper.initializeTypeState(Movie.class); for (Movie movie : emptyMovies) objectMapper.add(movie); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowSparseIntegerSet hollowIntSet = new HollowSparseIntegerSet(readStateEngine, "Movie", "id.value", getPredicate()); Assert.assertEquals(0, hollowIntSet.cardinality()); hollowIntSet.listenForDeltaUpdates(); for (Movie m : getMovies()) objectMapper.add(m); objectMapper.add(new Movie(new Video(8192), "Random", 2009)); StateEngineRoundTripper.roundTripDelta(writeStateEngine, readStateEngine); Assert.assertEquals(11, hollowIntSet.cardinality());// 11 movies released in 2009 as per predicate } @Test public void test() throws Exception { List<Movie> movies = getMovies(); for (Movie movie : movies) objectMapper.add(movie); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); HollowSparseIntegerSet hollowIntSet = new HollowSparseIntegerSet(readStateEngine, "Movie", "id.value", getPredicate()); Assert.assertFalse(hollowIntSet.get(1)); Assert.assertFalse(hollowIntSet.get(2)); Assert.assertFalse(hollowIntSet.get(3)); Assert.assertFalse(hollowIntSet.get(4)); Assert.assertTrue(hollowIntSet.get(77)); Assert.assertTrue(hollowIntSet.get(66)); Assert.assertTrue(hollowIntSet.get(55)); Assert.assertTrue(hollowIntSet.get(512)); Assert.assertTrue(hollowIntSet.get(513)); Assert.assertTrue(hollowIntSet.get(Integer.MAX_VALUE)); Assert.assertTrue(hollowIntSet.get(40)); Assert.assertTrue(hollowIntSet.get(28)); Assert.assertTrue(hollowIntSet.get(30)); // listen for delta updates hollowIntSet.listenForDeltaUpdates(); // apply delta Movie movie = movies.get(5);// change the movie release year for Avatar to 1999 movie.releaseYear = 1999; for (Movie m : movies) objectMapper.add(m); StateEngineRoundTripper.roundTripDelta(writeStateEngine, readStateEngine); // now Avatar should not be there in index. Assert.assertFalse(hollowIntSet.get(512)); } // this predicate only indexes movie released in 2009 private HollowSparseIntegerSet.IndexPredicate getPredicate() { return new HollowSparseIntegerSet.IndexPredicate() { @Override public boolean shouldIndex(int ordinal) { HollowObjectTypeDataAccess objectTypeDataAccess = (HollowObjectTypeDataAccess) readStateEngine.getTypeDataAccess("Movie"); int yearReleasedFieldPosition = objectTypeDataAccess.getSchema().getPosition("releaseYear"); int yearReleased = objectTypeDataAccess.readInt(ordinal, yearReleasedFieldPosition); if (yearReleased == 2009) return true; return false; } }; } private List<Movie> getMovies() { List<Movie> movies = new ArrayList<>(); movies.add(new Movie(new Video(1), "The Matrix", 1999)); movies.add(new Movie(new Video(2), "Blood Diamond", 2006)); movies.add(new Movie(new Video(3), "Rush", 2013)); movies.add(new Movie(new Video(4), "Rocky", 1976)); movies.add(new Movie(new Video(40), "Inglourious Basterds", 2009)); movies.add(new Movie(new Video(512), "Avatar", 2009)); movies.add(new Movie(new Video(513), "Harry Potter and the Half-Blood Prince", 2009)); movies.add(new Movie(new Video(0), "The Hangover", 2009)); movies.add(new Movie(new Video(Integer.MAX_VALUE), "Sherlock Holmes", 2009)); movies.add(new Movie(new Video(28), "Up", 2009)); movies.add(new Movie(new Video(30), "The Girl with the Dragon Tattoo", 2009)); movies.add(new Movie(new Video(77), "District 9", 2009)); movies.add(new Movie(new Video(66), "Law Abiding Citizen", 2009)); movies.add(new Movie(new Video(55), "Moon", 2009)); return movies; } private static class Movie { private Video id; private String name; private int releaseYear; public Movie(Video id, String name, int releaseYear) { this.id = id; this.name = name; this.releaseYear = releaseYear; } } private static class Video { private int value; public Video(int id) { this.value = id; } } }
8,780
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/HollowPrimaryKeyIndexTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.memory.pool.ArraySegmentRecycler; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.io.IOException; import org.junit.Assert; import org.junit.Test; @SuppressWarnings("unused") public class HollowPrimaryKeyIndexTest extends AbstractStateEngineTest { protected TestableUniqueKeyIndex createIndex(String type, String ... fieldPaths) { return new HollowPrimaryKeyIndex(readStateEngine, type, fieldPaths); } protected TestableUniqueKeyIndex createIndex(ArraySegmentRecycler memoryRecycler, String type, String ... fieldPaths) { return new HollowPrimaryKeyIndex(readStateEngine, memoryRecycler, type, fieldPaths); } @Test public void testSnapshotAndDelta() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); roundTripSnapshot(); // Auto Discover fieldPaths from @HollowPrimaryKey // UniqueKeyIndex idx = createIndex("TypeA", "a1", "a2", "ab.b1.value"); TestableUniqueKeyIndex idx = createIndex("TypeA"); idx.listenForDeltaUpdates(); int ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); int ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); int ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); Assert.assertEquals(0, ord0); Assert.assertEquals(1, ord1); Assert.assertEquals(2, ord2); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); // mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); mapper.add(new TypeA(3, 3.3d, new TypeB("three"))); roundTripDelta(); ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); int ord3 = idx.getMatchingOrdinal(3, 3.3d, "three"); Assert.assertEquals(0, ord0); Assert.assertEquals(-1, ord1); Assert.assertEquals(2, ord2); Assert.assertEquals(3, ord3); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); // it is a ghost record (marked deleted but it is available) assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); assertEquals(idx.getRecordKey(3), 3, 3.3d, "three"); } @Test public void indicatesWhetherOrNotDuplicateKeysExist() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); roundTripSnapshot(); // Auto Discover fieldPaths from @HollowPrimaryKey //UniqueKeyIndex idx = createIndex("TypeA", "a1", "a2", "ab.b1.value"); TestableUniqueKeyIndex idx = createIndex("TypeA"); idx.listenForDeltaUpdates(); Assert.assertFalse(idx.containsDuplicates()); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two", true))); roundTripDelta(); Assert.assertEquals(1, idx.getDuplicateKeys().size()); Assert.assertTrue(idx.containsDuplicates()); } @Test public void handlesEmptyTypes() throws IOException { HollowObjectSchema testSchema = new HollowObjectSchema("Test", 1); testSchema.addField("test1", FieldType.INT); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(testSchema)); roundTripSnapshot(); TestableUniqueKeyIndex idx = createIndex("Test", "test1"); Assert.assertEquals(-1, idx.getMatchingOrdinal(100)); Assert.assertFalse(idx.containsDuplicates()); } @Test public void testSnapshotAndDeltaWithStateEngineMemoryRecycler() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); roundTripSnapshot(); TestableUniqueKeyIndex idx = createIndex(readStateEngine.getMemoryRecycler(), "TypeA", "a1", "a2", "ab.b1.value"); idx.listenForDeltaUpdates(); int ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); int ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); int ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); Assert.assertEquals(0, ord0); Assert.assertEquals(1, ord1); Assert.assertEquals(2, ord2); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); mapper.add(new TypeA(1, 1.1d, new TypeB("one"))); // mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); mapper.add(new TypeA(2, 2.2d, new TypeB("two"))); mapper.add(new TypeA(3, 3.3d, new TypeB("three"))); roundTripDelta(); ord0 = idx.getMatchingOrdinal(1, 1.1d, "one"); ord1 = idx.getMatchingOrdinal(1, 1.1d, "1"); ord2 = idx.getMatchingOrdinal(2, 2.2d, "two"); int ord3 = idx.getMatchingOrdinal(3, 3.3d, "three"); Assert.assertEquals(0, ord0); Assert.assertEquals(-1, ord1); Assert.assertEquals(2, ord2); Assert.assertEquals(3, ord3); assertEquals(idx.getRecordKey(0), 1, 1.1d, "one"); assertEquals(idx.getRecordKey(1), 1, 1.1d, "1"); // it is a ghost record (marked deleted but it is available) assertEquals(idx.getRecordKey(2), 2, 2.2d, "two"); assertEquals(idx.getRecordKey(3), 3, 3.3d, "three"); } @Test public void testDups() throws IOException { String typeA = "TypeA"; int numOfItems = 1000; int a1ValueStart = 1; double a2Value = 1; addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); roundTripSnapshot(); int a1Pos = ((HollowObjectSchema) readStateEngine.getTypeState(typeA).getSchema()).getPosition("a1"); int a2Pos = ((HollowObjectSchema) readStateEngine.getTypeState(typeA).getSchema()).getPosition("a2"); TestableUniqueKeyIndex idx = createIndex("TypeA", "a1"); idx.listenForDeltaUpdates(); Assert.assertFalse(idx.containsDuplicates()); // add dups int numOfDups = (int) (numOfItems * 0.2); int a1dupValueStart = 2; int a1dupValueEnd = a1dupValueStart + numOfDups; double a2dupValues = 2; { // Add dups addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); addDataForDupTesting(writeStateEngine, a1dupValueStart, a2dupValues, numOfDups); roundTripDelta(); Assert.assertEquals(true, idx.containsDuplicates()); // Make sure there is dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); double a2Val = readTypeState.readDouble(ordinal, a2Pos); //System.out.println("a1=" + a1Val + "\ta2=" + a2Val); if (isInDupRange) { // Not deterministic Assert.assertTrue(a2Val == a2Value || a2Val == a2dupValues); } else { Assert.assertTrue(a2Val == a2Value); } } } { // remove dups addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); roundTripDelta(); Assert.assertFalse(idx.containsDuplicates()); // Make sure there is no dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); double a2Val = readTypeState.readDouble(ordinal, a2Pos); // System.out.println("a1=" + a1Val + "\ta2=" + a2Val); // Should be equal to base value Assert.assertTrue(a2Val == a2Value); } } { // create dups addDataForDupTesting(writeStateEngine, a1ValueStart, a2Value, numOfItems); addDataForDupTesting(writeStateEngine, a1dupValueStart, a2dupValues, numOfDups); roundTripDelta(); Assert.assertEquals(true, idx.containsDuplicates()); // Make sure there is dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); double a2Val = readTypeState.readDouble(ordinal, a2Pos); //System.out.println("a1=" + a1Val + "\ta2=" + a2Val); if (isInDupRange) { // Not deterministic Assert.assertTrue(a2Val == a2Value || a2Val == a2dupValues); } else { Assert.assertTrue(a2Val == a2Value); } } } { // remove original addDataForDupTesting(writeStateEngine, a1dupValueStart, a2dupValues, numOfDups); roundTripDelta(); Assert.assertFalse(idx.containsDuplicates()); // Make sure there is no dups HollowObjectTypeReadState readTypeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(typeA); for (int i = 0; i < readTypeState.maxOrdinal(); i++) { int a1Val = readTypeState.readInt(i, a1Pos); boolean isInDupRange = a1dupValueStart <= a1Val && a1Val < a1dupValueEnd; int ordinal = idx.getMatchingOrdinal(a1Val); if (!isInDupRange) { // should not be found if not in dup range Assert.assertTrue(ordinal < 0); continue; } double a2Val = readTypeState.readDouble(ordinal, a2Pos); // System.out.println("a1=" + a1Val + "\ta2=" + a2Val); // Make sure value is the Dup Values Assert.assertTrue(a2Val == a2dupValues); } } } private static void addDataForDupTesting(HollowWriteStateEngine writeStateEngine, int a1Start, double a2, int size) { TypeB typeB = new TypeB("commonTypeB"); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); int max = a1Start + size; for (int a1 = a1Start; a1 < max; a1++) { mapper.add(new TypeA(a1, a2, typeB)); } } private static void assertEquals(Object[] actual, Object... expected) { Assert.assertEquals(actual.length, expected.length); for (int i = 0; i < actual.length; i++) { Assert.assertEquals(expected[i], actual[i]); } } @HollowPrimaryKey(fields = { "a1", "a2", "ab.b1" }) private static class TypeA { private final int a1; private final double a2; private final TypeB ab; public TypeA(int a1, double a2, TypeB ab) { this.a1 = a1; this.a2 = a2; this.ab = ab; } } private static class TypeB { private final String b1; private final boolean isDuplicate; public TypeB(String b1) { this(b1, false); } public TypeB(String b1, boolean isDuplicate) { this.b1 = b1; this.isDuplicate = isDuplicate; } } @Override protected void initializeTypeStates() { } }
8,781
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/FieldPathTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Test cases for FieldPath class. */ public class FieldPathTest { private HollowWriteStateEngine writeStateEngine; private HollowReadStateEngine readStateEngine; private HollowObjectMapper objectMapper; @Before public void beforeTestSetup() { writeStateEngine = new HollowWriteStateEngine(); readStateEngine = new HollowReadStateEngine(); objectMapper = new HollowObjectMapper(writeStateEngine); } private static class SimpleValue { int id; } private static class IntegerReference { Integer id; } private static class ObjectReference { IntegerReference reference; } @Test public void testSimpleValue() throws Exception { SimpleValue simpleValue = new SimpleValue(); simpleValue.id = 3; objectMapper.add(simpleValue); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // with auto-expand feature on FieldPath fieldPath = new FieldPath(readStateEngine, "SimpleValue", "id"); Object[] values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); Object value = fieldPath.findValue(0); Assert.assertEquals(3, (int) value); // with auto-expand feature off fieldPath = new FieldPath(readStateEngine, "SimpleValue", "id", false); values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); } @Test public void testSimpleReference() throws Exception { IntegerReference integerReference = new IntegerReference(); integerReference.id = 3; objectMapper.add(integerReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); //with auto expand FieldPath fieldPath = new FieldPath(readStateEngine, "IntegerReference", "id"); Object[] values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); Object value = fieldPath.findValue(0); Assert.assertEquals(3, (int) value); // with auto expand but giving full field path fieldPath = new FieldPath(readStateEngine, "IntegerReference", "id.value"); values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); // without auto expand feature fieldPath = new FieldPath(readStateEngine, "IntegerReference", "id.value"); values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); } @Test(expected = IllegalArgumentException.class) public void testSimpleReferenceWithoutAutoExpand() throws Exception { IntegerReference integerReference = new IntegerReference(); integerReference.id = 3; objectMapper.add(integerReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); //with auto expand try { new FieldPath(readStateEngine, "IntegerReference", "id", false); } catch (FieldPaths.FieldPathException e) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_FULL, e.error); Assert.assertEquals(1, e.fieldSegments.size()); Assert.assertEquals("Integer", e.fieldSegments.get(0).getTypeName()); Assert.assertEquals("id", e.fieldSegments.get(0).getName()); throw e; } } @Test public void testObjectReference() throws Exception { IntegerReference integerReference = new IntegerReference(); integerReference.id = 3; ObjectReference ref = new ObjectReference(); ref.reference = integerReference; objectMapper.add(ref); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); //with auto expand -> this case works because there is only one path possible leading to a scalar value. FieldPath fieldPath = new FieldPath(readStateEngine, "ObjectReference", "reference"); Object[] values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); Object value = fieldPath.findValue(0); Assert.assertEquals(3, (int) value); // with partial auto-expand fieldPath = new FieldPath(readStateEngine, "ObjectReference", "reference.id"); values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); // with auto-expand but complete path fieldPath = new FieldPath(readStateEngine, "ObjectReference", "reference.id.value"); values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); // without auto-expand but complete path fieldPath = new FieldPath(readStateEngine, "ObjectReference", "reference.id.value"); values = fieldPath.findValues(0); Assert.assertEquals(3, (int) values[0]); } @Test(expected = IllegalArgumentException.class) public void testObjectReferenceWithoutAutoExpand() throws Exception { IntegerReference integerReference = new IntegerReference(); integerReference.id = 3; ObjectReference ref = new ObjectReference(); ref.reference = integerReference; objectMapper.add(ref); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // with partial path try { new FieldPath(readStateEngine, "ObjectReference", "reference.id", false); } catch (FieldPaths.FieldPathException e) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_FULL, e.error); Assert.assertEquals(2, e.fieldSegments.size()); Assert.assertEquals("Integer", e.fieldSegments.get(1).getTypeName()); Assert.assertEquals("id", e.fieldSegments.get(1).getName()); throw e; } } private static class MultiValue { int id; IntegerReference intRef; } private static class ObjectReferenceToMultiValue { int refId; MultiValue multiValue; } @Test public void testMultiFieldReference() throws Exception { IntegerReference simpleValue = new IntegerReference(); simpleValue.id = 3; MultiValue multiValue = new MultiValue(); multiValue.id = 2; multiValue.intRef = simpleValue; ObjectReferenceToMultiValue referenceToMultiValue = new ObjectReferenceToMultiValue(); referenceToMultiValue.multiValue = multiValue; referenceToMultiValue.refId = 1; objectMapper.add(referenceToMultiValue); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // with auto-expand FieldPath fieldPath = new FieldPath(readStateEngine, "ObjectReferenceToMultiValue", "multiValue.intRef"); Object[] values = fieldPath.findValues(0); Assert.assertEquals(3, ((int) values[0])); fieldPath = new FieldPath(readStateEngine, "ObjectReferenceToMultiValue", "multiValue.intRef.id.value"); values = fieldPath.findValues(0); Assert.assertEquals(3, ((int) values[0])); //without auto-complete but full path given fieldPath = new FieldPath(readStateEngine, "ObjectReferenceToMultiValue", "multiValue.intRef.id.value", false); values = fieldPath.findValues(0); Assert.assertEquals(3, ((int) values[0])); } @Test(expected = IllegalArgumentException.class) public void testMultiFieldReferenceIncomplete() throws Exception { IntegerReference simpleValue = new IntegerReference(); simpleValue.id = 3; MultiValue multiValue = new MultiValue(); multiValue.id = 2; multiValue.intRef = simpleValue; ObjectReferenceToMultiValue referenceToMultiValue = new ObjectReferenceToMultiValue(); referenceToMultiValue.multiValue = multiValue; referenceToMultiValue.refId = 1; objectMapper.add(referenceToMultiValue); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // with auto-expand but incomplete, since reference has two fields, cannot auto-expand try { new FieldPath(readStateEngine, "ObjectReferenceToMultiValue", "multiValue"); } catch (FieldPaths.FieldPathException e) { Assert.assertEquals(FieldPaths.FieldPathException.ErrorKind.NOT_EXPANDABLE, e.error); Assert.assertEquals("MultiValue", e.enclosingSchema.getName()); Assert.assertEquals(1, e.fieldSegments.size()); Assert.assertEquals("multiValue", e.fieldSegments.get(0).getName()); throw e; } } // ------- unit tests for LIST type ------- private static class ListType { List<Integer> intValues; } private static class ListObjectReference { List<SimpleValue> intValues; } @Test public void testListIntegerReference() throws Exception { ListType listType = new ListType(); listType.intValues = Arrays.asList(1, 2, 3); objectMapper.add(listType); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); FieldPath fieldPath; Object[] values; //with partial auto expand fieldPath = new FieldPath(readStateEngine, "ListType", "intValues.element"); values = fieldPath.findValues(0); Assert.assertEquals(1, (int) values[0]); Assert.assertEquals(2, (int) values[1]); Assert.assertEquals(3, (int) values[2]); //with auto expand but full path given fieldPath = new FieldPath(readStateEngine, "ListType", "intValues.element.value"); values = fieldPath.findValues(0); Assert.assertEquals(1, (int) values[0]); Assert.assertEquals(2, (int) values[1]); Assert.assertEquals(3, (int) values[2]); //without auto expand but full path given fieldPath = new FieldPath(readStateEngine, "ListType", "intValues.element.value", false); values = fieldPath.findValues(0); Assert.assertEquals(1, (int) values[0]); Assert.assertEquals(2, (int) values[1]); Assert.assertEquals(3, (int) values[2]); } @Test public void testListObjectReference() throws Exception { ListObjectReference listType = new ListObjectReference(); SimpleValue val1 = new SimpleValue(); val1.id = 1; SimpleValue val2 = new SimpleValue(); val2.id = 2; listType.intValues = Arrays.asList(val1, val2); objectMapper.add(listType); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); FieldPath fieldPath; Object[] values; //with partial auto expand fieldPath = new FieldPath(readStateEngine, "ListObjectReference", "intValues.element"); values = fieldPath.findValues(0); Assert.assertEquals(1, (int) values[0]); Assert.assertEquals(2, (int) values[1]); //without auto expand fieldPath = new FieldPath(readStateEngine, "ListObjectReference", "intValues.element.id"); values = fieldPath.findValues(0); Assert.assertEquals(1, (int) values[0]); Assert.assertEquals(2, (int) values[1]); } // ------- unit tests for SET type ------- private static class SetType { Set<Integer> intValues; } @Test public void testSetIntegerReference() throws Exception { SetType setType = new SetType(); setType.intValues = new HashSet<>(Arrays.asList(1, 2, 3)); objectMapper.add(setType); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); FieldPath fieldPath; Object[] values; Set<Integer> valuesAsSet; //with partial auto expand fieldPath = new FieldPath(readStateEngine, "SetType", "intValues.element"); values = fieldPath.findValues(0); Assert.assertEquals(3, values.length); valuesAsSet = new HashSet<>(); for (Object v : values) valuesAsSet.add((int) v); Assert.assertTrue(valuesAsSet.contains(1)); Assert.assertTrue(valuesAsSet.contains(2)); Assert.assertTrue(valuesAsSet.contains(3)); //without auto expand fieldPath = new FieldPath(readStateEngine, "SetType", "intValues.element.value"); values = fieldPath.findValues(0); Assert.assertEquals(3, values.length); valuesAsSet = new HashSet<>(); for (Object v : values) valuesAsSet.add((int) v); Assert.assertTrue(valuesAsSet.contains(1)); Assert.assertTrue(valuesAsSet.contains(2)); Assert.assertTrue(valuesAsSet.contains(3)); } // ------- unit tests for MAP type ------- private static class MapReference { Map<Integer, String> mapValues; } @Test public void testMapReference() throws Exception { Map<Integer, String> map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); MapReference mapReference = new MapReference(); mapReference.mapValues = map; objectMapper.add(mapReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // no auto-expand for a map FieldPath fieldPath = new FieldPath(readStateEngine, "MapReference", "mapValues.value"); Object[] values = fieldPath.findValues(0); Assert.assertEquals(2, values.length); Set<String> valuesAsSet = new HashSet<>(); for (Object v : values) valuesAsSet.add((String) v); Assert.assertTrue(valuesAsSet.contains("one")); Assert.assertTrue(valuesAsSet.contains("two")); } private static class MapObjectReference { Map<Integer, MapValue> mapValues; } private static class MapValue { String val; } @Test public void testMapObjectValueReference() throws Exception { MapValue val1 = new MapValue(); val1.val = "one"; MapValue val2 = new MapValue(); val2.val = "two"; Map<Integer, MapValue> map = new HashMap<>(); map.put(1, val1); map.put(2, val2); MapObjectReference mapObjectReference = new MapObjectReference(); mapObjectReference.mapValues = map; objectMapper.add(mapObjectReference); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); // for values FieldPath fieldPath = new FieldPath(readStateEngine, "MapObjectReference", "mapValues.value"); Object[] values = fieldPath.findValues(0); Assert.assertEquals(2, values.length); Set<String> valuesAsSet = new HashSet<>(); for (Object v : values) valuesAsSet.add((String) v); Assert.assertTrue(valuesAsSet.contains("one")); Assert.assertTrue(valuesAsSet.contains("two")); // for keys fieldPath = new FieldPath(readStateEngine, "MapObjectReference", "mapValues.key"); values = fieldPath.findValues(0); Assert.assertEquals(2, values.length); Set<Integer> keysAsSet = new HashSet<>(); for (Object v : values) keysAsSet.add((int) v); Assert.assertTrue(keysAsSet.contains(1)); Assert.assertTrue(keysAsSet.contains(2)); } // Map key is a list private static class MapKeyReferenceAsList { Map<ListType, Integer> mapValues; } @Test public void testMapKeyReferenceToList() throws Exception { ListType listType = new ListType(); listType.intValues = Arrays.asList(1, 2, 3); Map<ListType, Integer> map = new HashMap<>(); map.put(listType, 1); MapKeyReferenceAsList mapKeyReferenceAsList = new MapKeyReferenceAsList(); mapKeyReferenceAsList.mapValues = map; objectMapper.add(mapKeyReferenceAsList); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine); FieldPath fieldPath; Object[] values; fieldPath = new FieldPath(readStateEngine, "MapKeyReferenceAsList", "mapValues.key.intValues.element.value"); values = fieldPath.findValues(0); Assert.assertEquals(3, values.length); } }
8,782
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/PrimaryKeyIndexDeltaIndexTest.java
package com.netflix.hollow.core.index; import static java.util.stream.Collectors.toList; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.IntStream; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Test; public class PrimaryKeyIndexDeltaIndexTest { @HollowPrimaryKey(fields = "id") static class X { final int id; X(int id) { this.id = id; } } @Test public void testRemoval() { InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowProducer p = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); p.initializeDataModel(X.class); // Add all ordinals for first cycle // Size appropriately so the addition and removal keep within the same hash code table size int upper = (1 << 11) + 512; long version = p.runCycle(ws -> { IntStream.range(0, upper).parallel(). forEach(i -> { ws.add(new X(i)); }); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); HollowPrimaryKeyIndex index = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "X", "id"); index.listenForDeltaUpdates(); List<Integer> indexes = IntStream.range(0, upper).boxed().collect(toList()); for (int j = 0; j < 10; j++) { Collections.shuffle(indexes); // Remove 8% of ordinals, selected randomly, to keep within the threshold for a delta update int lower = upper * 92 / 100; int[] ordinalsToKeep = indexes.stream().limit(lower).mapToInt(i -> i).toArray(); version = p.runCycle(ws -> { IntStream.of(ordinalsToKeep).parallel(). forEach(i -> { ws.add(new X(i)); }); }); consumer.triggerRefreshTo(version); int[] matches = IntStream.range(0, upper) .filter(i -> index.getMatchingOrdinal(i) != -1) .sorted() .toArray(); Arrays.sort(ordinalsToKeep); Assert.assertArrayEquals(ordinalsToKeep, matches); Assert.assertFalse(index.containsDuplicates()); // Add all ordinals back version = p.runCycle(ws -> { IntStream.range(0, upper).parallel(). forEach(i -> { ws.add(new X(i)); }); }); consumer.triggerRefreshTo(version); matches = IntStream.range(0, upper) .filter(i -> index.getMatchingOrdinal(i) != -1) .sorted() .toArray(); Assert.assertEquals(upper, matches.length); Assert.assertFalse(index.containsDuplicates()); } } }
8,783
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/SparseBitSetTest.java
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index; import com.netflix.hollow.core.util.SimultaneousExecutor; import java.util.HashSet; import java.util.Random; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** * Unit tests for SparseBitSet implementation defined in HollowSparseIntegerSet. */ public class SparseBitSetTest { HollowSparseIntegerSet.SparseBitSet sparseBitSet; @Test public void testRandom() { int maxValue = 5000000; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); Random random = new Random(); Set<Integer> intIndexed = new HashSet<>(); for (int i = 0; i < 100000; i++) { int r = random.nextInt(maxValue); while (intIndexed.contains(r)) r = random.nextInt(maxValue); sparseBitSet.set(r); intIndexed.add(r); } Assert.assertEquals(100000, sparseBitSet.cardinality()); Assert.assertTrue(sparseBitSet.estimateBitsUsed() > 0); for (int i = 0; i < maxValue; i++) { if (intIndexed.contains(i)) Assert.assertTrue("Expected in set, but not found the int " + i, sparseBitSet.get(i)); else Assert.assertFalse("Not expected in set, but found the int " + i, sparseBitSet.get(i)); } } @Test public void testEvenNumbersMultipleThread() { for (int j = 0; j < 10; j++) { int maxValue = 500000; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); SimultaneousExecutor executor = new SimultaneousExecutor(getClass(), "test"); int parallelism = executor.getMaximumPoolSize(); int taskSize = maxValue / parallelism; for (int i = 0; i < parallelism; i++) { int from = i * taskSize; int to = (from + taskSize) - 1; if (i == (parallelism - 1)) to = maxValue; executor.submit(new Task(sparseBitSet, from, to)); } executor.awaitUninterruptibly(); HollowSparseIntegerSet.SparseBitSet.compact(sparseBitSet); Assert.assertTrue(sparseBitSet.cardinality() == 250001); } } private static class Task implements Runnable { HollowSparseIntegerSet.SparseBitSet set; int from; int to; public Task(HollowSparseIntegerSet.SparseBitSet set, int from, int to) { this.set = set; this.from = from; this.to = to; } @Override public void run() { for (int i = from; i <= to; i++) { if ((i % 2) == 0) set.set(i); } } } @Test public void testInsertLongInBuckets() { int maxValue = 8192; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); sparseBitSet.set(8000);// 1st bit in long for bucket 1 sparseBitSet.set(8001);// 1st bit in long for bucket 1 sparseBitSet.set(8002);// 1st bit in long for bucket 1 sparseBitSet.set(8167);// 3rd bit in long for bucket 1 sparseBitSet.set(8067);// 2nd bit in long for bucket 1 sparseBitSet.set(0);// 1st bit in long for bucket 0 sparseBitSet.set(512);// 8th bit in long for bucket 0 sparseBitSet.set(69);// 2nd bit in long for bucket 0 sparseBitSet.set(2047); // bit in long for bucket 0 sparseBitSet.set(4095);// bit in long for bucket 0 Assert.assertTrue(sparseBitSet.get(8000)); Assert.assertTrue(sparseBitSet.get(8001)); Assert.assertTrue(sparseBitSet.get(8002)); Assert.assertTrue(sparseBitSet.get(8167)); Assert.assertTrue(sparseBitSet.get(8067)); Assert.assertTrue(sparseBitSet.get(0)); Assert.assertTrue(sparseBitSet.get(4095)); Assert.assertTrue(sparseBitSet.get(512)); Assert.assertFalse(sparseBitSet.get(8003)); Assert.assertFalse(sparseBitSet.get(8063)); Assert.assertFalse(sparseBitSet.get(7999)); Assert.assertFalse(sparseBitSet.get(8168)); Assert.assertFalse(sparseBitSet.get(8191)); } @Test public void testRemoveLongInBuckets() { int maxValue = 8192; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); sparseBitSet.set(8000);// 1st bit in long for bucket 1 sparseBitSet.set(8001);// 1st bit in long for bucket 1 sparseBitSet.set(8002);// 1st bit in long for bucket 1 sparseBitSet.set(8167);// 3rd bit in long for bucket 1 sparseBitSet.set(8067);// 2nd bit in long for bucket 1 sparseBitSet.clear(8000); // not long removal, plain clear test Assert.assertFalse(sparseBitSet.get(8000)); Assert.assertTrue(sparseBitSet.get(8001)); Assert.assertTrue(sparseBitSet.get(8002)); Assert.assertTrue(sparseBitSet.get(8067)); Assert.assertTrue(sparseBitSet.get(8167)); sparseBitSet.clear(8001); sparseBitSet.clear(8002);// now first long should be removed from buckets Assert.assertFalse(sparseBitSet.get(8001)); Assert.assertFalse(sparseBitSet.get(8002)); Assert.assertTrue(sparseBitSet.get(8067)); Assert.assertTrue(sparseBitSet.get(8167)); // add them back sparseBitSet.set(8000); sparseBitSet.set(8001); sparseBitSet.set(8002); // removing long from between other longs in bucket sparseBitSet.clear(8067); Assert.assertTrue(sparseBitSet.get(8000)); Assert.assertTrue(sparseBitSet.get(8001)); Assert.assertTrue(sparseBitSet.get(8002)); Assert.assertTrue(sparseBitSet.get(8167)); Assert.assertFalse(sparseBitSet.get(8067)); // removing the last long sparseBitSet.set(8067); sparseBitSet.clear(8167); Assert.assertTrue(sparseBitSet.get(8000)); Assert.assertTrue(sparseBitSet.get(8001)); Assert.assertTrue(sparseBitSet.get(8002)); Assert.assertTrue(sparseBitSet.get(8067)); Assert.assertFalse(sparseBitSet.get(8167)); // removing all longs sparseBitSet.clear(8000); sparseBitSet.clear(8001); sparseBitSet.clear(8002); sparseBitSet.clear(8167); sparseBitSet.clear(8067); Assert.assertFalse(sparseBitSet.get(8000)); Assert.assertFalse(sparseBitSet.get(8001)); Assert.assertFalse(sparseBitSet.get(8002)); Assert.assertFalse(sparseBitSet.get(8067)); Assert.assertFalse(sparseBitSet.get(8167)); sparseBitSet.set(8000); sparseBitSet.set(8001); sparseBitSet.set(8002); sparseBitSet.set(8067); sparseBitSet.set(8167); Assert.assertTrue(sparseBitSet.get(8000)); Assert.assertTrue(sparseBitSet.get(8001)); Assert.assertTrue(sparseBitSet.get(8002)); Assert.assertTrue(sparseBitSet.get(8167)); Assert.assertTrue(sparseBitSet.get(8067)); } @Test public void testFindMaxValue() { int maxValue = 8192; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); sparseBitSet.set(8000); sparseBitSet.set(8001); sparseBitSet.set(8002); Assert.assertEquals(8002, sparseBitSet.findMaxValue()); sparseBitSet.set(8067); Assert.assertEquals(8067, sparseBitSet.findMaxValue()); sparseBitSet.set(8167); Assert.assertEquals(8167, sparseBitSet.findMaxValue()); sparseBitSet.clear(8167); Assert.assertEquals(8067, sparseBitSet.findMaxValue()); } @Test(expected = IllegalArgumentException.class) public void testNegativeValue() { int maxValue = 8192; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); sparseBitSet.set(-1); } @Test public void testCompaction() { int maxValue = 8192; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); sparseBitSet.set(0);// 1st bit in long for bucket 0 sparseBitSet.set(512);// 8th bit in long for bucket 0 sparseBitSet.set(69);// 2nd bit in long for bucket 0 sparseBitSet.set(2047); // bit in long for bucket 0 sparseBitSet.set(4095);// bit in long for bucket 0 Assert.assertTrue(sparseBitSet.get(0)); Assert.assertTrue(sparseBitSet.get(4095)); Assert.assertTrue(sparseBitSet.get(512)); HollowSparseIntegerSet.SparseBitSet compactSparseBitSet = HollowSparseIntegerSet.SparseBitSet.compact(sparseBitSet); Assert.assertTrue(compactSparseBitSet.get(0)); Assert.assertTrue(compactSparseBitSet.get(4095)); Assert.assertTrue(compactSparseBitSet.get(512)); boolean addedValueGreaterThanMax = true; try { compactSparseBitSet.set(4096); } catch (Exception e) { addedValueGreaterThanMax = false; } if (addedValueGreaterThanMax) Assert.fail("Should not be ale to set a value greater than max value in compacted bit set."); } @Test public void testResize() { int maxValue = 8192; sparseBitSet = new HollowSparseIntegerSet.SparseBitSet(maxValue); sparseBitSet.set(0);// 1st bit in long for bucket 0 sparseBitSet.set(512);// 8th bit in long for bucket 0 sparseBitSet.set(69);// 2nd bit in long for bucket 0 sparseBitSet.set(2047); // bit in long for bucket 0 sparseBitSet.set(4095);// bit in long for bucket 0 Assert.assertTrue(sparseBitSet.get(0)); Assert.assertTrue(sparseBitSet.get(4095)); Assert.assertTrue(sparseBitSet.get(512)); HollowSparseIntegerSet.SparseBitSet compactSparseBitSet = HollowSparseIntegerSet.SparseBitSet.compact(sparseBitSet); boolean addedValueGreaterThanMax = true; try { compactSparseBitSet.set(4096); } catch (Exception e) { addedValueGreaterThanMax = false; } if (addedValueGreaterThanMax) Assert.fail("Should not be ale to set a value greater than max value in compacted bit set."); HollowSparseIntegerSet.SparseBitSet resizedSparsedBitSet = HollowSparseIntegerSet.SparseBitSet.resize(compactSparseBitSet, 8192); resizedSparsedBitSet.set(4096); Assert.assertTrue(resizedSparsedBitSet.get(0)); Assert.assertTrue(resizedSparsedBitSet.get(0)); Assert.assertTrue(resizedSparsedBitSet.get(4095)); Assert.assertTrue(resizedSparsedBitSet.get(512)); } }
8,784
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/traversal/HollowIndexTraversalTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index.traversal; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.TypeA; import com.netflix.hollow.core.write.objectmapper.TypeB; import com.netflix.hollow.core.write.objectmapper.TypeC; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.junit.Test; public class HollowIndexTraversalTest extends AbstractStateEngineTest { @Test public void test() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA("two", 2, new TypeB((short)20, 20000000L, 2.2f, "two".toCharArray(), new byte[] { 2, 2, 2 }), Collections.<TypeC>emptySet())); mapper.add(new TypeA("one", 1, new TypeB((short)10, 10000000L, 1.1f, "one".toCharArray(), new byte[] { 1, 1, 1 }), new HashSet<TypeC>(Arrays.asList( new TypeC('d', map("one.1", 1, "one.2", 1, 1, "one.3", 1, 2, 3)), new TypeC('e', map("one.x", 1, "one.y", 1, 1, "one.z", 1, 2, 3)) )))); roundTripSnapshot(); TraversalTreeBuilder builder = new TraversalTreeBuilder(readStateEngine, "TypeA", new String[] {"a1.value", "b.b3", "cList.element.c1", "cList.element.map.value.element"}); HollowIndexerTraversalNode root = builder.buildTree(); root.traverse(1); System.out.println(builder.getFieldMatchLists()[0].size()); System.out.println(builder.getFieldMatchLists()[0].get(0)); System.out.println(builder.getFieldMatchLists()[0].get(1)); System.out.println(builder.getFieldMatchLists()[1].size()); System.out.println(builder.getFieldMatchLists()[1].get(0)); System.out.println(builder.getFieldMatchLists()[1].get(1)); System.out.println(builder.getFieldMatchLists()[2].size()); System.out.println(builder.getFieldMatchLists()[2].get(0)); System.out.println(builder.getFieldMatchLists()[2].get(1)); } private Map<String, List<Integer>> map(Object... keyValues) { Map<String, List<Integer>> map = new HashMap<String, List<Integer>>(); int i = 0; while(i < keyValues.length) { String key = (String)keyValues[i]; List<Integer> values = new ArrayList<Integer>(); i++; while(i < keyValues.length && keyValues[i] instanceof Integer) { values.add((Integer)keyValues[i]); i++; } map.put(key, values); } return map; } @Override protected void initializeTypeStates() { } }
8,785
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/index/traversal/HollowIndexerValueTraverserTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.index.traversal; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.schema.HollowListSchema; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowListTypeWriteState; import com.netflix.hollow.core.write.HollowListWriteRecord; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowSetWriteRecord; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowIndexerValueTraverserTest extends AbstractStateEngineTest { private HollowObjectSchema aSchema; private HollowListSchema bSchema; private HollowMapSchema cSchema; private HollowObjectSchema dSchema; private HollowObjectSchema eSchema; private HollowSetSchema fSchema; private HollowObjectSchema gSchema; @Before public void setUp() { aSchema = new HollowObjectSchema("A", 3); aSchema.addField("a", FieldType.INT); aSchema.addField("b", FieldType.REFERENCE, "B"); aSchema.addField("c", FieldType.REFERENCE, "C"); bSchema = new HollowListSchema("B", "D"); cSchema = new HollowMapSchema("C", "E", "F"); dSchema = new HollowObjectSchema("D", 2); dSchema.addField("d1", FieldType.STRING); dSchema.addField("d2", FieldType.BOOLEAN); eSchema = new HollowObjectSchema("E", 1); eSchema.addField("e", FieldType.STRING); fSchema = new HollowSetSchema("F", "G"); gSchema = new HollowObjectSchema("G", 1); gSchema.addField("g", FieldType.FLOAT); super.setUp(); } @Test public void iteratesValues() throws IOException { a(1, b( d("1", true), d("2", false), d("3", true) ), c( e("one"), f(g(1.1f), g(1.2f), g(1.3f)), e("two"), f(g(2.1f)), e("three"), f(g(3.1f)) ) ); roundTripSnapshot(); HollowIndexerValueTraverser traverser = new HollowIndexerValueTraverser(readStateEngine, "A", "a", "b.element.d1", "b.element.d2", "c.key.e", "c.value.element.g"); traverser.traverse(0); for(int i=0;i<traverser.getNumMatches();i++) { for(int j=0;j<traverser.getNumFieldPaths();j++) { System.out.print(traverser.getMatchedValue(i, j) + ", "); } System.out.println(); } Assert.assertEquals(15, traverser.getNumMatches()); assertValueTraverserContainsEntry(traverser, 1, "1", true, "three", 3.1f); assertValueTraverserContainsEntry(traverser, 1, "2", false, "two", 2.1f); assertValueTraverserContainsEntry(traverser, 1, "3", true, "two", 2.1f); assertValueTraverserContainsEntry(traverser, 1, "3", true, "one", 1.1f); assertValueTraverserContainsEntry(traverser, 1, "3", true, "one", 1.2f); assertValueTraverserContainsEntry(traverser, 1, "1", true, "one", 1.3f); } private void assertValueTraverserContainsEntry(HollowIndexerValueTraverser traverser, Object... values) { for(int i=0;i<traverser.getNumMatches();i++) { boolean allMatched = true; for(int j=0;j<traverser.getNumFieldPaths();j++) { if(!values[j].equals(traverser.getMatchedValue(i, j))) allMatched = false; } if(allMatched) return; } Assert.fail("entry not found"); } private int a(int a, int b, int c) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(aSchema); rec.setInt("a", a); rec.setReference("b", b); rec.setReference("c", c); return writeStateEngine.add("A", rec); } private int b(int... values) { HollowListWriteRecord rec = new HollowListWriteRecord(); for(int i=0;i<values.length;i++) { rec.addElement(values[i]); } return writeStateEngine.add("B", rec); } private int c(int... keyValuePairs) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<keyValuePairs.length;i+=2) { rec.addEntry(keyValuePairs[i], keyValuePairs[i+1]); } return writeStateEngine.add("C", rec); } private int d(String d1, boolean d2) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(dSchema); rec.setString("d1", d1); rec.setBoolean("d2", d2); return writeStateEngine.add("D", rec); } private int e(String value) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(eSchema); rec.setString("e", value); return writeStateEngine.add("E", rec); } private int f(int... values) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int i=0;i<values.length;i++) { rec.addElement(values[i]); } return writeStateEngine.add("F", rec); } private int g(float value) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(gSchema); rec.setFloat("g", value); return writeStateEngine.add("G", rec); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(aSchema)); writeStateEngine.addTypeState(new HollowListTypeWriteState(bSchema)); writeStateEngine.addTypeState(new HollowMapTypeWriteState(cSchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(dSchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(eSchema)); writeStateEngine.addTypeState(new HollowSetTypeWriteState(fSchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(gSchema)); } }
8,786
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardPrimaryKeyIndex.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.index.AbstractHollowUniqueKeyIndex; import com.netflix.hollow.api.consumer.index.HollowUniqueKeyIndex; import com.netflix.hollow.core.schema.HollowObjectSchema; /** * @deprecated see {@link com.netflix.hollow.api.consumer.index.UniqueKeyIndex} which can be built as follows: * <pre>{@code * UniqueKeyIndex<Award, K> uki = UniqueKeyIndex.from(consumer, Award.class) * .usingBean(k); * Award m = uki.findMatch(k); * }</pre> * where {@code K} is a class declaring key field paths members, annotated with * {@link com.netflix.hollow.api.consumer.index.FieldPath}, and {@code k} is an instance of * {@code K} that is the key to find the unique {@code Award} object. */ @Deprecated @SuppressWarnings("all") public class AwardPrimaryKeyIndex extends AbstractHollowUniqueKeyIndex<AwardsAPI, Award> implements HollowUniqueKeyIndex<Award> { public AwardPrimaryKeyIndex(HollowConsumer consumer) { this(consumer, true); } public AwardPrimaryKeyIndex(HollowConsumer consumer, boolean isListenToDataRefresh) { this(consumer, isListenToDataRefresh, ((HollowObjectSchema)consumer.getStateEngine().getNonNullSchema("Award")).getPrimaryKey().getFieldPaths()); } public AwardPrimaryKeyIndex(HollowConsumer consumer, String... fieldPaths) { this(consumer, true, fieldPaths); } public AwardPrimaryKeyIndex(HollowConsumer consumer, boolean isListenToDataRefresh, String... fieldPaths) { super(consumer, "Award", isListenToDataRefresh, fieldPaths); } @Override public Award findMatch(Object... keys) { int ordinal = idx.getMatchingOrdinal(keys); if(ordinal == -1) return null; return api.getAward(ordinal); } }
8,787
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/MovieDelegateLookupImpl.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.objects.delegate.HollowObjectAbstractDelegate; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.schema.HollowObjectSchema; @SuppressWarnings("all") public class MovieDelegateLookupImpl extends HollowObjectAbstractDelegate implements MovieDelegate { private final MovieTypeAPI typeAPI; public MovieDelegateLookupImpl(MovieTypeAPI typeAPI) { this.typeAPI = typeAPI; } public long getId(int ordinal) { return typeAPI.getId(ordinal); } public Long getIdBoxed(int ordinal) { return typeAPI.getIdBoxed(ordinal); } public String getTitle(int ordinal) { ordinal = typeAPI.getTitleOrdinal(ordinal); return ordinal == -1 ? null : typeAPI.getAPI().getStringTypeAPI().getValue(ordinal); } public boolean isTitleEqual(int ordinal, String testValue) { ordinal = typeAPI.getTitleOrdinal(ordinal); return ordinal == -1 ? testValue == null : typeAPI.getAPI().getStringTypeAPI().isValueEqual(ordinal, testValue); } public int getTitleOrdinal(int ordinal) { return typeAPI.getTitleOrdinal(ordinal); } public int getYear(int ordinal) { return typeAPI.getYear(ordinal); } public Integer getYearBoxed(int ordinal) { return typeAPI.getYearBoxed(ordinal); } public MovieTypeAPI getTypeAPI() { return typeAPI; } @Override public HollowObjectSchema getSchema() { return typeAPI.getTypeDataAccess().getSchema(); } @Override public HollowObjectTypeDataAccess getTypeDataAccess() { return typeAPI.getTypeDataAccess(); } }
8,788
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardsAPIFactory.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.client.HollowAPIFactory; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.objects.provider.HollowFactory; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; import java.util.Collections; import java.util.Set; @SuppressWarnings("all") public class AwardsAPIFactory implements HollowAPIFactory { private final Set<String> cachedTypes; public AwardsAPIFactory() { this(Collections.<String>emptySet()); } public AwardsAPIFactory(Set<String> cachedTypes) { this.cachedTypes = cachedTypes; } @Override public HollowAPI createAPI(HollowDataAccess dataAccess) { return new AwardsAPI(dataAccess, cachedTypes); } @Override public HollowAPI createAPI(HollowDataAccess dataAccess, HollowAPI previousCycleAPI) { if (!(previousCycleAPI instanceof AwardsAPI)) { throw new ClassCastException(previousCycleAPI.getClass() + " not instance of AwardsAPI"); } return new AwardsAPI(dataAccess, cachedTypes, Collections.<String, HollowFactory<?>>emptyMap(), (AwardsAPI) previousCycleAPI); } }
8,789
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardDataAccessor.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.data.AbstractHollowDataAccessor; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; @SuppressWarnings("all") public class AwardDataAccessor extends AbstractHollowDataAccessor<Award> { public static final String TYPE = "Award"; private AwardsAPI api; public AwardDataAccessor(HollowConsumer consumer) { super(consumer, TYPE); this.api = (AwardsAPI)consumer.getAPI(); } public AwardDataAccessor(HollowReadStateEngine rStateEngine, AwardsAPI api) { super(rStateEngine, TYPE); this.api = api; } public AwardDataAccessor(HollowReadStateEngine rStateEngine, AwardsAPI api, String ... fieldPaths) { super(rStateEngine, TYPE, fieldPaths); this.api = api; } public AwardDataAccessor(HollowReadStateEngine rStateEngine, AwardsAPI api, PrimaryKey primaryKey) { super(rStateEngine, TYPE, primaryKey); this.api = api; } @Override public Award getRecord(int ordinal){ return api.getAward(ordinal); } }
8,790
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/MovieDelegateCachedImpl.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowTypeAPI; import com.netflix.hollow.api.objects.delegate.HollowCachedDelegate; import com.netflix.hollow.api.objects.delegate.HollowObjectAbstractDelegate; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.schema.HollowObjectSchema; @SuppressWarnings("all") public class MovieDelegateCachedImpl extends HollowObjectAbstractDelegate implements HollowCachedDelegate, MovieDelegate { private final Long id; private final String title; private final int titleOrdinal; private final Integer year; private MovieTypeAPI typeAPI; public MovieDelegateCachedImpl(MovieTypeAPI typeAPI, int ordinal) { this.id = typeAPI.getIdBoxed(ordinal); this.titleOrdinal = typeAPI.getTitleOrdinal(ordinal); int titleTempOrdinal = titleOrdinal; this.title = titleTempOrdinal == -1 ? null : typeAPI.getAPI().getStringTypeAPI().getValue(titleTempOrdinal); this.year = typeAPI.getYearBoxed(ordinal); this.typeAPI = typeAPI; } public long getId(int ordinal) { if(id == null) return Long.MIN_VALUE; return id.longValue(); } public Long getIdBoxed(int ordinal) { return id; } public String getTitle(int ordinal) { return title; } public boolean isTitleEqual(int ordinal, String testValue) { if(testValue == null) return title == null; return testValue.equals(title); } public int getTitleOrdinal(int ordinal) { return titleOrdinal; } public int getYear(int ordinal) { if(year == null) return Integer.MIN_VALUE; return year.intValue(); } public Integer getYearBoxed(int ordinal) { return year; } @Override public HollowObjectSchema getSchema() { return typeAPI.getTypeDataAccess().getSchema(); } @Override public HollowObjectTypeDataAccess getTypeDataAccess() { return typeAPI.getTypeDataAccess(); } public MovieTypeAPI getTypeAPI() { return typeAPI; } public void updateTypeAPI(HollowTypeAPI typeAPI) { this.typeAPI = (MovieTypeAPI) typeAPI; } }
8,791
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardsAPIHashIndex.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.data.AbstractHollowOrdinalIterable; import com.netflix.hollow.api.consumer.index.AbstractHollowHashIndex; import com.netflix.hollow.core.index.HollowHashIndexResult; import com.netflix.hollow.core.type.HString; import java.util.Collections; /** * @deprecated see {@link com.netflix.hollow.api.consumer.index.HashIndex} which can be built as follows: * <pre>{@code * HashIndex<HString, K> uki = HashIndex.from(consumer, HString.class) * .usingBean(k); * Stream<HString> results = uki.findMatches(k); * }</pre> * where {@code K} is a class declaring key field paths members, annotated with * {@link com.netflix.hollow.api.consumer.index.FieldPath}, and {@code k} is an instance of * {@code K} that is the query to find the matching {@code HString} objects. */ @Deprecated @SuppressWarnings("all") public class AwardsAPIHashIndex extends AbstractHollowHashIndex<AwardsAPI> { public AwardsAPIHashIndex(HollowConsumer consumer, String queryType, String selectFieldPath, String... matchFieldPaths) { super(consumer, true, queryType, selectFieldPath, matchFieldPaths); } public AwardsAPIHashIndex(HollowConsumer consumer, boolean isListenToDataRefresh, String queryType, String selectFieldPath, String... matchFieldPaths) { super(consumer, isListenToDataRefresh, queryType, selectFieldPath, matchFieldPaths); } public Iterable<HString> findStringMatches(Object... keys) { HollowHashIndexResult matches = idx.findMatches(keys); if(matches == null) return Collections.emptySet(); return new AbstractHollowOrdinalIterable<HString>(matches.iterator()) { public HString getData(int ordinal) { return api.getHString(ordinal); } }; } public Iterable<Movie> findMovieMatches(Object... keys) { HollowHashIndexResult matches = idx.findMatches(keys); if(matches == null) return Collections.emptySet(); return new AbstractHollowOrdinalIterable<Movie>(matches.iterator()) { public Movie getData(int ordinal) { return api.getMovie(ordinal); } }; } public Iterable<SetOfMovie> findSetOfMovieMatches(Object... keys) { HollowHashIndexResult matches = idx.findMatches(keys); if(matches == null) return Collections.emptySet(); return new AbstractHollowOrdinalIterable<SetOfMovie>(matches.iterator()) { public SetOfMovie getData(int ordinal) { return api.getSetOfMovie(ordinal); } }; } public Iterable<Award> findAwardMatches(Object... keys) { HollowHashIndexResult matches = idx.findMatches(keys); if(matches == null) return Collections.emptySet(); return new AbstractHollowOrdinalIterable<Award>(matches.iterator()) { public Award getData(int ordinal) { return api.getAward(ordinal); } }; } }
8,792
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/MovieTypeAPI.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowObjectTypeAPI; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.type.StringTypeAPI; @SuppressWarnings("all") public class MovieTypeAPI extends HollowObjectTypeAPI { private final MovieDelegateLookupImpl delegateLookupImpl; public MovieTypeAPI(AwardsAPI api, HollowObjectTypeDataAccess typeDataAccess) { super(api, typeDataAccess, new String[] { "id", "title", "year" }); this.delegateLookupImpl = new MovieDelegateLookupImpl(this); } public long getId(int ordinal) { if(fieldIndex[0] == -1) return missingDataHandler().handleLong("Movie", ordinal, "id"); return getTypeDataAccess().readLong(ordinal, fieldIndex[0]); } public Long getIdBoxed(int ordinal) { long l; if(fieldIndex[0] == -1) { l = missingDataHandler().handleLong("Movie", ordinal, "id"); } else { boxedFieldAccessSampler.recordFieldAccess(fieldIndex[0]); l = getTypeDataAccess().readLong(ordinal, fieldIndex[0]); } if(l == Long.MIN_VALUE) return null; return Long.valueOf(l); } public int getTitleOrdinal(int ordinal) { if(fieldIndex[1] == -1) return missingDataHandler().handleReferencedOrdinal("Movie", ordinal, "title"); return getTypeDataAccess().readOrdinal(ordinal, fieldIndex[1]); } public StringTypeAPI getTitleTypeAPI() { return getAPI().getStringTypeAPI(); } public int getYear(int ordinal) { if(fieldIndex[2] == -1) return missingDataHandler().handleInt("Movie", ordinal, "year"); return getTypeDataAccess().readInt(ordinal, fieldIndex[2]); } public Integer getYearBoxed(int ordinal) { int i; if(fieldIndex[2] == -1) { i = missingDataHandler().handleInt("Movie", ordinal, "year"); } else { boxedFieldAccessSampler.recordFieldAccess(fieldIndex[2]); i = getTypeDataAccess().readInt(ordinal, fieldIndex[2]); } if(i == Integer.MIN_VALUE) return null; return Integer.valueOf(i); } public MovieDelegateLookupImpl getDelegateLookupImpl() { return delegateLookupImpl; } @Override public AwardsAPI getAPI() { return (AwardsAPI) api; } }
8,793
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardDelegate.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.objects.delegate.HollowObjectDelegate; @SuppressWarnings("all") public interface AwardDelegate extends HollowObjectDelegate { public long getId(int ordinal); public Long getIdBoxed(int ordinal); public int getWinnerOrdinal(int ordinal); public int getNomineesOrdinal(int ordinal); public AwardTypeAPI getTypeAPI(); }
8,794
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/MovieDelegate.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.objects.delegate.HollowObjectDelegate; @SuppressWarnings("all") public interface MovieDelegate extends HollowObjectDelegate { public long getId(int ordinal); public Long getIdBoxed(int ordinal); public String getTitle(int ordinal); public boolean isTitleEqual(int ordinal, String testValue); public int getTitleOrdinal(int ordinal); public int getYear(int ordinal); public Integer getYearBoxed(int ordinal); public MovieTypeAPI getTypeAPI(); }
8,795
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardTypeAPI.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowObjectTypeAPI; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; @SuppressWarnings("all") public class AwardTypeAPI extends HollowObjectTypeAPI { private final AwardDelegateLookupImpl delegateLookupImpl; public AwardTypeAPI(AwardsAPI api, HollowObjectTypeDataAccess typeDataAccess) { super(api, typeDataAccess, new String[] { "id", "winner", "nominees" }); this.delegateLookupImpl = new AwardDelegateLookupImpl(this); } public long getId(int ordinal) { if(fieldIndex[0] == -1) return missingDataHandler().handleLong("Award", ordinal, "id"); return getTypeDataAccess().readLong(ordinal, fieldIndex[0]); } public Long getIdBoxed(int ordinal) { long l; if(fieldIndex[0] == -1) { l = missingDataHandler().handleLong("Award", ordinal, "id"); } else { boxedFieldAccessSampler.recordFieldAccess(fieldIndex[0]); l = getTypeDataAccess().readLong(ordinal, fieldIndex[0]); } if(l == Long.MIN_VALUE) return null; return Long.valueOf(l); } public int getWinnerOrdinal(int ordinal) { if(fieldIndex[1] == -1) return missingDataHandler().handleReferencedOrdinal("Award", ordinal, "winner"); return getTypeDataAccess().readOrdinal(ordinal, fieldIndex[1]); } public MovieTypeAPI getWinnerTypeAPI() { return getAPI().getMovieTypeAPI(); } public int getNomineesOrdinal(int ordinal) { if(fieldIndex[2] == -1) return missingDataHandler().handleReferencedOrdinal("Award", ordinal, "nominees"); return getTypeDataAccess().readOrdinal(ordinal, fieldIndex[2]); } public SetOfMovieTypeAPI getNomineesTypeAPI() { return getAPI().getSetOfMovieTypeAPI(); } public AwardDelegateLookupImpl getDelegateLookupImpl() { return delegateLookupImpl; } @Override public AwardsAPI getAPI() { return (AwardsAPI) api; } }
8,796
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/SetOfMovieTypeAPI.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowSetTypeAPI; import com.netflix.hollow.api.objects.delegate.HollowSetLookupDelegate; import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess; @SuppressWarnings("all") public class SetOfMovieTypeAPI extends HollowSetTypeAPI { private final HollowSetLookupDelegate delegateLookupImpl; public SetOfMovieTypeAPI(AwardsAPI api, HollowSetTypeDataAccess dataAccess) { super(api, dataAccess); this.delegateLookupImpl = new HollowSetLookupDelegate(this); } public MovieTypeAPI getElementAPI() { return getAPI().getMovieTypeAPI(); } public AwardsAPI getAPI() { return (AwardsAPI)api; } public HollowSetLookupDelegate getDelegateLookupImpl() { return delegateLookupImpl; } }
8,797
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardHollowFactory.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowTypeAPI; import com.netflix.hollow.api.objects.provider.HollowFactory; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; @SuppressWarnings("all") public class AwardHollowFactory<T extends Award> extends HollowFactory<T> { @Override public T newHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) { return (T)new Award(((AwardTypeAPI)typeAPI).getDelegateLookupImpl(), ordinal); } @Override public T newCachedHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) { return (T)new Award(new AwardDelegateCachedImpl((AwardTypeAPI)typeAPI, ordinal), ordinal); } }
8,798
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/SetOfMovie.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.objects.HollowSet; import com.netflix.hollow.api.objects.delegate.HollowSetDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; @SuppressWarnings("all") public class SetOfMovie extends HollowSet<Movie> { public SetOfMovie(HollowSetDelegate delegate, int ordinal) { super(delegate, ordinal); } @Override public Movie instantiateElement(int ordinal) { return (Movie) api().getMovie(ordinal); } @Override public boolean equalsElement(int elementOrdinal, Object testObject) { return GenericHollowRecordHelper.equalObject(getSchema().getElementType(), elementOrdinal, testObject); } public AwardsAPI api() { return typeApi().getAPI(); } public SetOfMovieTypeAPI typeApi() { return (SetOfMovieTypeAPI) delegate.getTypeAPI(); } }
8,799