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-zenoadapter/src/main/java/com/netflix/hollow
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow/zenoadapter/HollowSerializationFramework.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.zenoadapter; 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.HollowSchema; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import com.netflix.hollow.core.write.HollowListTypeWriteState; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowSetTypeWriteState; import com.netflix.hollow.core.write.HollowTypeWriteState; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.zenoadapter.util.ObjectIdentityOrdinalMap; import com.netflix.hollow.zenoadapter.util.ObjectIdentityOrdinalMap.Entry; import com.netflix.zeno.fastblob.record.schema.FastBlobSchema; import com.netflix.zeno.fastblob.record.schema.FieldDefinition; import com.netflix.zeno.fastblob.record.schema.MapFieldDefinition; import com.netflix.zeno.fastblob.record.schema.TypedFieldDefinition; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializationFramework; import com.netflix.zeno.serializer.SerializerFactory; import com.netflix.zeno.serializer.common.ListSerializer; import com.netflix.zeno.serializer.common.MapSerializer; import com.netflix.zeno.serializer.common.SetSerializer; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class HollowSerializationFramework extends SerializationFramework { private final HollowWriteStateEngine stateEngine; private final ConcurrentHashMap<String, ObjectIdentityOrdinalMap> objectIdentityOrdinalMaps; public HollowSerializationFramework(SerializerFactory serializerFactory, HollowObjectHashCodeFinder hashCodeFinder) { super(serializerFactory); this.frameworkSerializer = new HollowFrameworkSerializer(this, hashCodeFinder); this.stateEngine = new HollowWriteStateEngine(hashCodeFinder); this.objectIdentityOrdinalMaps = new ConcurrentHashMap<String, ObjectIdentityOrdinalMap>(); populateStateEngineTypes(); } public HollowObjectHashCodeFinder getHollowObjectHasher() { return ((HollowFrameworkSerializer)getFrameworkSerializer()).hasher; } public void prepareForNextCycle() { stateEngine.prepareForNextCycle(); objectIdentityOrdinalMaps.clear(); } public int add(String type, Object o) { ObjectIdentityOrdinalMap identityOrdinalMap = getIdentityOrdinalMap(type); Entry entry = identityOrdinalMap.getEntry(o); if(entry != null) { return entry.getOrdinal(); } NFTypeSerializer<Object> serializer = getSerializer(type); int ordinal = add(type, o, serializer); identityOrdinalMap.put(o, ordinal); return ordinal; } private int add(String type, Object o, NFTypeSerializer<Object> serializer) { if(serializer instanceof ListSerializer) { return addList(type, o, serializer); } else if(serializer instanceof SetSerializer) { return addSet(type, o, serializer); } else if(serializer instanceof MapSerializer) { return addMap(type, o, serializer); } else { return addObject(type, o, serializer); } } @SuppressWarnings({ "unchecked", "rawtypes" }) private int addList(String type, Object o, NFTypeSerializer<Object> serializer) { int ordinal; String elementType = ((TypedFieldDefinition)serializer.getFastBlobSchema().getFieldDefinition(0)).getSubType(); ordinal = frameworkSerializer().serializeList(getRec(type), elementType, (Collection)o); return ordinal; } @SuppressWarnings({ "unchecked", "rawtypes" }) private int addSet(String type, Object o, NFTypeSerializer<Object> serializer) { int ordinal; String elementType = ((TypedFieldDefinition)serializer.getFastBlobSchema().getFieldDefinition(0)).getSubType(); ordinal = frameworkSerializer().serializeSet(getRec(type), elementType, (Set)o); return ordinal; } @SuppressWarnings({ "unchecked", "rawtypes" }) private int addMap(String type, Object o, NFTypeSerializer<Object> serializer) { int ordinal; String keyType = ((MapFieldDefinition)serializer.getFastBlobSchema().getFieldDefinition(0)).getKeyType(); String valueType = ((MapFieldDefinition)serializer.getFastBlobSchema().getFieldDefinition(0)).getValueType(); ordinal = frameworkSerializer().serializeMap(getRec(type), keyType, valueType, (Map)o); return ordinal; } private int addObject(String type, Object o, NFTypeSerializer<Object> serializer) { int ordinal; HollowSerializationRecord rec = getRec(type); serializer.serialize(o, rec); ordinal = stateEngine.add(type, rec.getHollowWriteRecord()); return ordinal; } private HollowSerializationRecord getRec(String type) { HollowSerializationRecord rec = frameworkSerializer().getRec(type); rec.reset(); return rec; } private HollowFrameworkSerializer frameworkSerializer() { return (HollowFrameworkSerializer)frameworkSerializer; } public HollowWriteStateEngine getStateEngine() { return stateEngine; } public HollowSchema getHollowSchema(String schemaName) { return stateEngine.getSchema(schemaName); } private void populateStateEngineTypes() { for(NFTypeSerializer<?> serializer : getOrderedSerializers()) { if(serializer instanceof ListSerializer) { ListSerializer<?> listSerializer = (ListSerializer<?>)serializer; TypedFieldDefinition elementFieldDef = (TypedFieldDefinition)listSerializer.getFastBlobSchema().getFieldDefinition(0); HollowListSchema listSchema = new HollowListSchema(serializer.getName(), elementFieldDef.getSubType()); HollowTypeWriteState writeState = new HollowListTypeWriteState(listSchema); stateEngine.addTypeState(writeState); } else if(serializer instanceof SetSerializer) { SetSerializer<?> setSerializer = (SetSerializer<?>)serializer; TypedFieldDefinition elementFieldDef = (TypedFieldDefinition)setSerializer.getFastBlobSchema().getFieldDefinition(0); HollowSetSchema setSchema = new HollowSetSchema(serializer.getName(), elementFieldDef.getSubType()); HollowTypeWriteState writeState = new HollowSetTypeWriteState(setSchema); stateEngine.addTypeState(writeState); } else if(serializer instanceof MapSerializer) { MapSerializer<?, ?> mapSerializer = (MapSerializer<?, ?>)serializer; MapFieldDefinition fieldDef = (MapFieldDefinition)mapSerializer.getFastBlobSchema().getFieldDefinition(0); HollowMapSchema mapSchema = new HollowMapSchema(serializer.getName(), fieldDef.getKeyType(), fieldDef.getValueType()); HollowTypeWriteState writeState = new HollowMapTypeWriteState(mapSchema); stateEngine.addTypeState(writeState); } else { HollowObjectSchema objectSchema = getHollowObjectSchema(serializer.getFastBlobSchema()); HollowTypeWriteState writeState = new HollowObjectTypeWriteState(objectSchema); stateEngine.addTypeState(writeState); } } } private HollowObjectSchema getHollowObjectSchema(FastBlobSchema schema) { HollowObjectSchema hollowSchema = new HollowObjectSchema(schema.getName(), schema.numFields()); for(int i=0;i<schema.numFields();i++) { FieldDefinition def = schema.getFieldDefinition(i); switch(def.getFieldType()) { case OBJECT: hollowSchema.addField(schema.getFieldName(i), FieldType.REFERENCE, ((TypedFieldDefinition)def).getSubType()); break; case LIST: String listTypeName = schema.getName() + "_" + schema.getFieldName(i); String listElementType = ((TypedFieldDefinition)def).getSubType(); hollowSchema.addField(schema.getFieldName(i), FieldType.REFERENCE, listTypeName); HollowListSchema listSchema = new HollowListSchema(listTypeName, listElementType); HollowTypeWriteState listWriteState = new HollowListTypeWriteState(listSchema); stateEngine.addTypeState(listWriteState); break; case SET: String setTypeName = schema.getName() + "_" + schema.getFieldName(i); String setElementType = ((TypedFieldDefinition)def).getSubType(); hollowSchema.addField(schema.getFieldName(i), FieldType.REFERENCE, setTypeName); HollowSetSchema setSchema = new HollowSetSchema(setTypeName, setElementType); HollowTypeWriteState setWriteState = new HollowSetTypeWriteState(setSchema); stateEngine.addTypeState(setWriteState); break; case MAP: String mapTypeName = schema.getName() + "_" + schema.getFieldName(i); String keyType = ((MapFieldDefinition)def).getKeyType(); String valueType = ((MapFieldDefinition)def).getValueType(); hollowSchema.addField(schema.getFieldName(i), FieldType.REFERENCE, mapTypeName); HollowMapSchema mapSchema = new HollowMapSchema(mapTypeName, keyType, valueType); HollowTypeWriteState mapWriteState = new HollowMapTypeWriteState(mapSchema); stateEngine.addTypeState(mapWriteState); break; case BOOLEAN: hollowSchema.addField(schema.getFieldName(i), FieldType.BOOLEAN); break; case BYTES: hollowSchema.addField(schema.getFieldName(i), FieldType.BYTES); break; case DOUBLE: hollowSchema.addField(schema.getFieldName(i), FieldType.DOUBLE); break; case FLOAT: hollowSchema.addField(schema.getFieldName(i), FieldType.FLOAT); break; case INT: hollowSchema.addField(schema.getFieldName(i), FieldType.INT); break; case LONG: hollowSchema.addField(schema.getFieldName(i), FieldType.LONG); break; case STRING: hollowSchema.addField(schema.getFieldName(i), FieldType.STRING); break; default: throw new IllegalArgumentException("Field " + schema.getName() + "." + schema.getFieldName(i) + " is declared with illegal type " + schema.getFieldType(i)); } } return hollowSchema; } private ObjectIdentityOrdinalMap getIdentityOrdinalMap(String type) { ObjectIdentityOrdinalMap objectIdentityOrdinalMap = objectIdentityOrdinalMaps.get(type); if(objectIdentityOrdinalMap == null) { objectIdentityOrdinalMap = new ObjectIdentityOrdinalMap(); ObjectIdentityOrdinalMap existing = objectIdentityOrdinalMaps.putIfAbsent(type, objectIdentityOrdinalMap); if(existing != null) objectIdentityOrdinalMap = existing; } return objectIdentityOrdinalMap; } }
8,600
0
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow/zenoadapter/HollowOrdinalMappingLoader.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.zenoadapter; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class HollowOrdinalMappingLoader { public static Map<String, int[]> load(InputStream is) throws IOException { DataInputStream dis = new DataInputStream(is); int size = dis.readShort(); Map<String, int[]> idx = new HashMap<String, int[]>(size); for (int i = 0; i < size; i++) { String type = dis.readUTF(); int typeIdx[] = new int[dis.readInt()]; for (int j = 0; j < typeIdx.length; j++) { typeIdx[j] = dis.readInt(); } idx.put(type, typeIdx); } dis.close(); return idx; } }
8,601
0
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow/zenoadapter/HollowFrameworkSerializer.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.zenoadapter; 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.HollowSchema; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import com.netflix.hollow.core.write.HollowListWriteRecord; import com.netflix.hollow.core.write.HollowMapWriteRecord; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowSetWriteRecord; import com.netflix.zeno.fastblob.record.schema.TypedFieldDefinition; import com.netflix.zeno.serializer.FrameworkSerializer; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class HollowFrameworkSerializer extends FrameworkSerializer<HollowSerializationRecord>{ final HollowObjectHashCodeFinder hasher; protected HollowFrameworkSerializer(HollowSerializationFramework framework, HollowObjectHashCodeFinder hasher) { super(framework); this.hasher = hasher; } @Override public void serializePrimitive(HollowSerializationRecord rec, String fieldName, Object value) { if (value == null) return; if (value instanceof Integer) { serializePrimitive(rec, fieldName, ((Integer) value).intValue()); } else if (value instanceof Long) { serializePrimitive(rec, fieldName, ((Long) value).longValue()); } else if (value instanceof Float) { serializePrimitive(rec, fieldName, ((Float) value).floatValue()); } else if (value instanceof Double) { serializePrimitive(rec, fieldName, ((Double) value).doubleValue()); } else if (value instanceof Boolean) { serializePrimitive(rec, fieldName, ((Boolean) value).booleanValue()); } else if (value instanceof String) { serializeString(rec, fieldName, (String) value); } else if (value instanceof byte[]){ serializeBytes(rec, fieldName, (byte[]) value); } else { throw new RuntimeException("Primitive type " + value.getClass().getSimpleName() + " not supported!"); } } @Override public void serializePrimitive(HollowSerializationRecord rec, String fieldName, int value) { HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); writeRec.setInt(fieldName, value); } @Override public void serializePrimitive(HollowSerializationRecord rec, String fieldName, long value) { HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); writeRec.setLong(fieldName, value); } @Override public void serializePrimitive(HollowSerializationRecord rec, String fieldName, float value) { HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); writeRec.setFloat(fieldName, value); } @Override public void serializePrimitive(HollowSerializationRecord rec, String fieldName, double value) { HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); writeRec.setDouble(fieldName, value); } @Override public void serializePrimitive(HollowSerializationRecord rec, String fieldName, boolean value) { HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); writeRec.setBoolean(fieldName, value); } @Override public void serializeBytes(HollowSerializationRecord rec, String fieldName, byte[] value) { if(value == null) return; HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); writeRec.setBytes(fieldName, value); } public void serializeString(HollowSerializationRecord rec, String fieldName, String value) { if(value == null) return; HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); writeRec.setString(fieldName, value); } @Override @Deprecated public void serializeObject(HollowSerializationRecord rec, String fieldName, String typeName, Object obj) { throw new UnsupportedOperationException(); } @Override public void serializeObject(HollowSerializationRecord rec, String fieldName, Object obj) { if(obj == null) return; HollowObjectWriteRecord writeRec = (HollowObjectWriteRecord)rec.getHollowWriteRecord(); int position = rec.getSchema().getPosition(fieldName); TypedFieldDefinition fieldDef = (TypedFieldDefinition)rec.getSchema().getFieldDefinition(position); int ordinal = getFramework().add(fieldDef.getSubType(), obj); writeRec.setReference(fieldName, ordinal); } @Override public <T> void serializeList(HollowSerializationRecord rec, String fieldName, String typeName, Collection<T> obj) { if(obj == null) return; String subType = getSubType(rec.getSchema().getName(), fieldName); HollowSerializationRecord subRec = getRec(subType); int ordinal = serializeList(subRec, typeName, obj); ((HollowObjectWriteRecord)rec.getHollowWriteRecord()).setReference(fieldName, ordinal); } <T> int serializeList(HollowSerializationRecord rec, String typeName, Collection<T> obj) { HollowListWriteRecord listRec = (HollowListWriteRecord)rec.getHollowWriteRecord(); listRec.reset(); for(T t : obj) { if(t != null) listRec.addElement(getFramework().add(typeName, t)); } return getFramework().getStateEngine().add(rec.getTypeName(), listRec); } @Override public <T> void serializeSet(HollowSerializationRecord rec, String fieldName, String typeName, Set<T> obj) { if(obj == null) return; String subType = getSubType(rec.getSchema().getName(), fieldName); HollowSerializationRecord subRec = getRec(subType); int ordinal = serializeSet(subRec, typeName, obj); ((HollowObjectWriteRecord)rec.getHollowWriteRecord()).setReference(fieldName, ordinal); } <T> int serializeSet(HollowSerializationRecord rec, String typeName, Set<T> obj) { HollowSetWriteRecord setRec = (HollowSetWriteRecord)rec.getHollowWriteRecord(); setRec.reset(); for(T t : obj) { if(t != null) { int ordinal = getFramework().add(typeName, t); int hashCode = hasher.hashCode(typeName, ordinal, t); setRec.addElement(ordinal, hashCode); } } return getFramework().getStateEngine().add(rec.getTypeName(), setRec); } @Override public <K, V> void serializeMap(HollowSerializationRecord rec, String fieldName, String keyTypeName, String valueTypeName, Map<K, V> obj) { if(obj == null) return; String subType = getSubType(rec.getSchema().getName(), fieldName); HollowSerializationRecord subRec = getRec(subType); int ordinal = serializeMap(subRec, keyTypeName, valueTypeName, obj); ((HollowObjectWriteRecord)rec.getHollowWriteRecord()).setReference(fieldName, ordinal); } <K, V> int serializeMap(HollowSerializationRecord rec, String keyTypeName, String valueTypeName, Map<K, V> obj) { HollowMapWriteRecord mapRec = (HollowMapWriteRecord)rec.getHollowWriteRecord(); mapRec.reset(); for(Map.Entry<K, V> entry : obj.entrySet()) { if(entry.getKey() != null && entry.getValue() != null) { int keyOrdinal = getFramework().add(keyTypeName, entry.getKey()); int valueOrdinal = getFramework().add(valueTypeName, entry.getValue()); int hashCode = hasher.hashCode(keyTypeName, keyOrdinal, entry.getKey()); mapRec.addEntry(keyOrdinal, valueOrdinal, hashCode); } } return getFramework().getStateEngine().add(rec.getTypeName(), mapRec); } private final ThreadLocal<Map<String, HollowSerializationRecord>> serializationRecordHandle = new ThreadLocal<Map<String, HollowSerializationRecord>>(); public HollowSerializationRecord getRec(String type) { Map<String, HollowSerializationRecord> map = serializationRecordHandle.get(); if(map == null) { map = new HashMap<String, HollowSerializationRecord>(); serializationRecordHandle.set(map); } HollowSerializationRecord rec = map.get(type); if(rec == null) { rec = createRec(type); map.put(type, rec); } return rec; } private HollowSerializationRecord createRec(String type) { HollowSchema schema = ((HollowSerializationFramework)framework).getHollowSchema(type); if(schema instanceof HollowListSchema) { return new HollowSerializationRecord(new HollowListWriteRecord(), type); } else if(schema instanceof HollowSetSchema) { return new HollowSerializationRecord(new HollowSetWriteRecord(), type); } else if(schema instanceof HollowMapSchema) { return new HollowSerializationRecord(new HollowMapWriteRecord(), type); } HollowSerializationRecord rec = new HollowSerializationRecord(new HollowObjectWriteRecord((HollowObjectSchema)schema), type); rec.setSchema(framework.getSerializer(type).getFastBlobSchema()); return rec; } private HollowSerializationFramework getFramework() { return (HollowSerializationFramework)framework; } Map<String, Map<String, String>> subTypeMap = new ConcurrentHashMap<String, Map<String, String>>(); private String getSubType(String typeName, String fieldName) { Map<String, String> map = subTypeMap.get(typeName); if(map == null) { map = new ConcurrentHashMap<String, String>(); subTypeMap.put(typeName, map); } String subtype = map.get(fieldName); if(subtype == null) { subtype = typeName + "_" + fieldName; map.put(fieldName, subtype); } return subtype; } }
8,602
0
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow/zenoadapter
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow/zenoadapter/util/ObjectIdentityOrdinalMap.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.zenoadapter.util; import java.util.Arrays; /** * Hash lookup map associate object references to already seen ordinals. * The fundamental assumption made here is that objects are immutable, so that * once the ordinal is assigned to an object, the ordinal stays the same * throughout the life of the object. * * @author timurua * */ public class ObjectIdentityOrdinalMap { public static final class Entry { private final Object key; // ordinal private final int ordinal; // linked list pointer private Entry next; /** * Creates new entry. */ Entry(Object key, int hash, int ordinal, Entry next) { this.key = key; this.ordinal = ordinal; this.next = next; } public Object getKey() { return key; } public int getOrdinal() { return ordinal; } @Override public String toString() { Object v = key; return v == null ? "null" : v.toString(); } public int hash() { return System.identityHashCode(key); } } /** * The map is divided into segments to increase concurrency */ private class Segment { // The same concept as in HashMap. If the entry array is becoming too // dense, it should be increased private static final int LOAD_FACTOR_PERCENT = 75; private static final int MINIMUM_CAPACITY = 256; private static final int MAXIMUM_CAPACITY = (1<<30); private int count = 0; private int maxThreshold = 0; private int minThreshold = 0; private Entry[] entries; public Segment(){ resize(MINIMUM_CAPACITY); } public synchronized void put(Object object, int hashCode, int ordinal) { int index = index(hashCode, entries.length); Entry current = entries[index]; Entry prev = null; while (current != null) { if (current.hash() == hashCode) { Object currentObject = current.getKey(); if( currentObject == null){ deleteEntry(index, current, prev); current = current.next; continue; } else if (currentObject == object) { return; } } prev = current; current = current.next; } count++; Entry first = entries[index]; Entry entry = new Entry(object, hashCode, ordinal, first); entries[index] = entry; entry.next = first; checkSize(); return; } public synchronized Entry get(Object object, int hashCode) { int index = index(hashCode, entries.length); Entry current = entries[index]; Entry prev = null; while (current != null) { if (current.hash() == hashCode) { Object currentObject = current.getKey(); if( currentObject == null){ deleteEntry(index, current, prev); current = current.next; continue; } else if (currentObject == object) { return current; } } prev = current; current = current.next; } return null; } private void checkSize() { if( count >= minThreshold && count <= maxThreshold ){ return; } int newCapacity; if( count < minThreshold ) { newCapacity = Math.max(MINIMUM_CAPACITY, entries.length >> 1); } else { newCapacity = Math.min(MAXIMUM_CAPACITY, entries.length << 1); } // nothing should be done, since capacity is not changed if (newCapacity == entries.length) { return; } resize(newCapacity); } private void resize(int newCapacity) { Entry[] newEntries = new Entry[newCapacity]; if( entries != null){ for(Entry entry : entries){ Entry current = entry; while(current != null){ Entry newEntry = current; current = current.next; int index = index(newEntry.hash(), newEntries.length); newEntry.next = newEntries[index]; newEntries[index] = newEntry; } } } minThreshold = (newEntries.length == MINIMUM_CAPACITY) ? 0 : (newEntries.length * LOAD_FACTOR_PERCENT / 200); maxThreshold = (newEntries.length == MAXIMUM_CAPACITY) ? Integer.MAX_VALUE : newEntries.length * LOAD_FACTOR_PERCENT / 100; entries = newEntries; } private void deleteEntry(int index, Entry current, Entry prev) { count--; if (prev != null) { prev.next = current.next; } else { entries[index] = current.next; } } private final int index(int hashCode, int capacity) { return (hashCode >>> ObjectIdentityOrdinalMap.this.logOfSegmentNumber) % capacity; } public synchronized void clear() { Arrays.fill(entries, null); count = 0; resize(MINIMUM_CAPACITY); } public synchronized int size() { return count; } } private final Segment[] segments; private final int mask; private final int logOfSegmentNumber; public ObjectIdentityOrdinalMap() { this(8); } public ObjectIdentityOrdinalMap(int logOfSegmentNumber) { if (logOfSegmentNumber < 1 && logOfSegmentNumber > 32) { throw new RuntimeException("Invalid power level"); } segments = new Segment[2 << logOfSegmentNumber]; for(int i=0; i<segments.length; i++){ segments[i] = new Segment(); } this.mask = (2 << logOfSegmentNumber) - 1; this.logOfSegmentNumber = logOfSegmentNumber; } /** * Associating the obj with an ordinal * * @param obj * @param ordinal */ public void put(Object obj, int ordinal) { int hashCode = System.identityHashCode(obj); int segment = segment(hashCode); segments[segment].put(obj, hashCode, ordinal); } public Entry getEntry(Object obj) { int hashCode = System.identityHashCode(obj); int segment = segment(hashCode); return segments[segment].get(obj, hashCode); } private final int segment(int hashCode) { return hashCode & mask; } public void clear(){ for (Segment segment : segments) { segment.clear(); } } public int size() { int size = 0; for (Segment segment : segments) { size += segment.size(); } return size; } }
8,603
0
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow/zenoadapter
Create_ds/hollow/hollow-zenoadapter/src/main/java/com/netflix/hollow/zenoadapter/util/HollowStateEngineCreator.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.zenoadapter.util; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import com.netflix.hollow.core.util.SimultaneousExecutor; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.zenoadapter.HollowSerializationFramework; import com.netflix.zeno.fastblob.FastBlobStateEngine; import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState; import com.netflix.zeno.serializer.NFTypeSerializer; import com.netflix.zeno.serializer.SerializerFactory; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class HollowStateEngineCreator { private final FastBlobStateEngine stateEngine; private final HollowSerializationFramework hollowFramework; private final Map<String, int[]> ordinalMappings = new ConcurrentHashMap<String, int[]>(); public HollowStateEngineCreator(FastBlobStateEngine stateEngine, SerializerFactory serializerFactory, HollowObjectHashCodeFinder hashCodeFinder) { this.stateEngine = stateEngine; this.hollowFramework = new HollowSerializationFramework(serializerFactory, hashCodeFinder); } public void copyAllObjectsToHollowStateEngine() { hollowFramework.prepareForNextCycle(); ordinalMappings.clear(); for (NFTypeSerializer<?> serializer : stateEngine.getOrderedSerializers()) { FastBlobTypeDeserializationState<?> typeState = stateEngine.getTypeDeserializationState(serializer.getName()); typeState.createIdentityOrdinalMap(); } SimultaneousExecutor executor = new SimultaneousExecutor(8, getClass(), "copy-all"); for (final NFTypeSerializer<?> serializer : stateEngine.getOrderedSerializers()) { executor.execute(new Runnable() { @Override public void run() { System.out.println("ADDING OBJECTS FOR TYPE " + serializer.getName()); FastBlobTypeDeserializationState<Object> state = stateEngine.getTypeDeserializationState(serializer.getName()); int maxOrdinal = state.maxOrdinal(); int mapping[] = new int[maxOrdinal + 1]; Arrays.fill(mapping, -1); for (int i = 0; i <= maxOrdinal; i++) { Object obj = state.get(i); if (obj != null) { int ordinal = hollowFramework.add(serializer.getName(), obj); while(ordinal >= mapping.length) { int oldLength = mapping.length; mapping = Arrays.copyOf(mapping, mapping.length * 2); Arrays.fill(mapping, oldLength, mapping.length, -1); } mapping[ordinal] = i; } } ordinalMappings.put(serializer.getName(), mapping); } }); } try { executor.awaitSuccessfulCompletion(); } catch(Exception e) { throw new RuntimeException(e); } } public void writeHollowBlobSnapshot(OutputStream os) throws IOException { HollowBlobWriter writer = new HollowBlobWriter(hollowFramework.getStateEngine()); writer.writeSnapshot(os); os.flush(); } public void writeHollowBlobDelta(OutputStream os) throws IOException { HollowBlobWriter writer = new HollowBlobWriter(hollowFramework.getStateEngine()); writer.writeDelta(os); os.flush(); } public void writeHollowBlobReverseDelta(OutputStream os) throws IOException { HollowBlobWriter writer = new HollowBlobWriter(hollowFramework.getStateEngine()); writer.writeReverseDelta(os); os.flush(); } public HollowWriteStateEngine getWriteStateEngine() { return hollowFramework.getStateEngine(); } public HollowSerializationFramework getHollowSerializationFramework() { return hollowFramework; } public void writeHollowToFastBlobIndex(OutputStream os) throws IOException { System.out.println("WRITING HOLLOWBLOB -> FASTBLOB ORDINAL INDEX"); DataOutputStream dos = new DataOutputStream(os); dos.writeShort(ordinalMappings.size()); for (Map.Entry<String, int[]> entry : ordinalMappings.entrySet()) { dos.writeUTF(entry.getKey()); dos.writeInt(entry.getValue().length); for (int i = 0; i < entry.getValue().length; i++) { dos.writeInt(entry.getValue()[i]); } } dos.flush(); dos.close(); } }
8,604
0
Create_ds/hollow/hollow-explorer-ui/src/test/java/com/netflix/hollow/explorer
Create_ds/hollow/hollow-explorer-ui/src/test/java/com/netflix/hollow/explorer/ui/HollowExplorerUIServerTest.java
package com.netflix.hollow.explorer.ui; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import org.junit.Test; public class HollowExplorerUIServerTest { @Test public void test() throws Exception { HollowExplorerUIServer server = new HollowExplorerUIServer(new HollowReadStateEngine(), 7890); server.start(); server.stop(); } @Test public void testBackwardsCompatibiltyWithJettyImplementation() throws Exception { com.netflix.hollow.explorer.ui.jetty.HollowExplorerUIServer server = new com.netflix.hollow.explorer.ui.jetty.HollowExplorerUIServer(new HollowReadStateEngine(), 7890); server.start(); server.stop(); } }
8,605
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/HollowExplorerUIServer.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.explorer.ui; import com.netflix.hollow.api.client.HollowClient; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.ui.HollowUIWebServer; import com.netflix.hollow.ui.HttpHandlerWithServletSupport; public class HollowExplorerUIServer { private final HollowUIWebServer server; private final HollowExplorerUI ui; public HollowExplorerUIServer(HollowReadStateEngine readEngine, int port) { this(new HollowExplorerUI("", readEngine), port); } public HollowExplorerUIServer(HollowConsumer consumer, int port) { this(new HollowExplorerUI("", consumer), port); } public HollowExplorerUIServer(HollowClient client, int port) { this(new HollowExplorerUI("", client), port); } public HollowExplorerUIServer(HollowExplorerUI ui, int port) { this.server = new HollowUIWebServer(new HttpHandlerWithServletSupport(ui), port); this.ui = ui; } public HollowExplorerUIServer start() throws Exception { server.start(); return this; } public HollowExplorerUIServer join() throws InterruptedException { server.join(); return this; } public void stop() throws Exception { server.stop(); } public HollowExplorerUI getUI() { return ui; } }
8,606
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/HollowExplorerUI.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.explorer.ui; import com.netflix.hollow.api.client.HollowClient; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.explorer.ui.pages.BrowseSchemaPage; import com.netflix.hollow.explorer.ui.pages.BrowseSelectedTypePage; import com.netflix.hollow.explorer.ui.pages.QueryPage; import com.netflix.hollow.explorer.ui.pages.ShowAllTypesPage; import com.netflix.hollow.ui.HollowUIRouter; import com.netflix.hollow.ui.HollowUISession; import java.io.IOException; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("deprecation") public class HollowExplorerUI extends HollowUIRouter { private final HollowConsumer consumer; private final HollowClient client; private final HollowReadStateEngine stateEngine; /** General purpose map to store header string and corresponding values used in HollowExplorer. It also stores headerDisplayString * for backwards compatibility. **/ private final HashMap<String, String> headerDisplayMap = new HashMap<>(); private final static String HEADER_DISPLAY_STRING = "headerDisplayString"; private final ShowAllTypesPage showAllTypesPage; private final BrowseSelectedTypePage browseTypePage; private final BrowseSchemaPage browseSchemaPage; private final QueryPage queryPage; public HollowExplorerUI(String baseUrlPath, HollowConsumer consumer) { this(baseUrlPath, consumer, null, null); } public HollowExplorerUI(String baseUrlPath, HollowClient client) { this(baseUrlPath, null, client, null); } public HollowExplorerUI(String baseUrlPath, HollowReadStateEngine stateEngine) { this(baseUrlPath, null, null, stateEngine); } private HollowExplorerUI(String baseUrlPath, HollowConsumer consumer, HollowClient client, HollowReadStateEngine stateEngine) { super(baseUrlPath); this.consumer = consumer; this.client = client; this.stateEngine = stateEngine; this.showAllTypesPage = new ShowAllTypesPage(this); this.browseTypePage = new BrowseSelectedTypePage(this); this.browseSchemaPage = new BrowseSchemaPage(this); this.queryPage = new QueryPage(this); } @Override public boolean handle(String target, HttpServletRequest req, HttpServletResponse resp) throws IOException { String pageName = getTargetRootPath(target); HollowUISession session = HollowUISession.getSession(req, resp); if("".equals(pageName) || "home".equals(pageName)) { showAllTypesPage.render(req, resp, session); return true; } else if("type".equals(pageName)) { browseTypePage.render(req, resp, session); return true; } else if("schema".equals(pageName)) { browseSchemaPage.render(req, resp, session); return true; } else if("query".equals(pageName)) { queryPage.render(req, resp, session); return true; } return false; } public long getCurrentStateVersion() { if(consumer != null) return consumer.getCurrentVersionId(); if(client != null) return client.getCurrentVersionId(); return Long.MIN_VALUE; } public HollowReadStateEngine getStateEngine() { if(consumer != null) return consumer.getStateEngine(); if(client != null) return client.getStateEngine(); return stateEngine; } public String getHeaderDisplayString() { return headerDisplayMap.get(HEADER_DISPLAY_STRING); } public void setHeaderDisplayString(String str) { this.headerDisplayMap.put(HEADER_DISPLAY_STRING, str); } public void addToHeaderDisplayMap(String key, String value) { headerDisplayMap.put(key, value); } public String getFromHeaderDisplayMap(String key) { return headerDisplayMap.get(key); } }
8,607
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/jetty/HollowExplorerUIServer.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.explorer.ui.jetty; import com.netflix.hollow.api.client.HollowClient; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.explorer.ui.HollowExplorerUI; /** * @deprecated use {@link com.netflix.hollow.explorer.ui.HollowExplorerUIServer}. This is deprecated because package name * contains "jetty" but jetty-server dep is no longer required. Instead, this class lives on as an adapter * over {@link com.netflix.hollow.explorer.ui.HollowExplorerUIServer}. */ @Deprecated public class HollowExplorerUIServer { private final com.netflix.hollow.explorer.ui.HollowExplorerUIServer server; public HollowExplorerUIServer(HollowReadStateEngine readEngine, int port) { server = new com.netflix.hollow.explorer.ui.HollowExplorerUIServer( readEngine, port); } public HollowExplorerUIServer(HollowConsumer consumer, int port) { server = new com.netflix.hollow.explorer.ui.HollowExplorerUIServer( consumer, port); } public HollowExplorerUIServer(HollowClient client, int port) { server = new com.netflix.hollow.explorer.ui.HollowExplorerUIServer( client, port); } public HollowExplorerUIServer(HollowExplorerUI ui, int port) { server = new com.netflix.hollow.explorer.ui.HollowExplorerUIServer(ui, port); } public HollowExplorerUIServer start() throws Exception { server.start(); return this; } public HollowExplorerUIServer join() throws InterruptedException { server.join(); return this; } public void stop() throws Exception { server.stop(); } public HollowExplorerUI getUI() { return server.getUI(); } }
8,608
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/model/SchemaDisplayField.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.explorer.ui.model; import com.netflix.hollow.core.schema.HollowCollectionSchema; 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.HollowSchema.SchemaType; public class SchemaDisplayField { private final String fieldName; private final String fieldPath; private final FieldType fieldType; private final boolean isSearchable; private final SchemaDisplay referencedType; public SchemaDisplayField(String fieldPath, HollowCollectionSchema parentSchema) { this.fieldPath = fieldPath; this.fieldName = "element"; this.fieldType = FieldType.REFERENCE; this.isSearchable = false; this.referencedType = new SchemaDisplay(parentSchema.getElementTypeState().getSchema(), fieldPath); } public SchemaDisplayField(String fieldPath, HollowMapSchema parentSchema, int fieldNumber) { this.fieldPath = fieldPath; this.fieldName = fieldNumber == 0 ? "key" : "value"; this.fieldType = FieldType.REFERENCE; this.isSearchable = false; this.referencedType = fieldNumber == 0 ? new SchemaDisplay(parentSchema.getKeyTypeState().getSchema(), fieldPath) : new SchemaDisplay(parentSchema.getValueTypeState().getSchema(), fieldPath); } public SchemaDisplayField(String fieldPath, HollowObjectSchema parentSchema, int fieldNumber) { this.fieldPath = fieldPath; this.fieldName = parentSchema.getFieldName(fieldNumber); this.fieldType = parentSchema.getFieldType(fieldNumber); this.isSearchable = isSearchable(parentSchema, fieldNumber); this.referencedType = fieldType == FieldType.REFERENCE ? new SchemaDisplay(parentSchema.getReferencedTypeState(fieldNumber).getSchema(), fieldPath) : null; } private boolean isSearchable(HollowObjectSchema schema, int fieldNumber) { if(schema.getFieldType(fieldNumber) == FieldType.REFERENCE) { if(schema.getReferencedTypeState(fieldNumber).getSchema().getSchemaType() != SchemaType.OBJECT) return false; HollowObjectSchema refObjSchema = (HollowObjectSchema)schema.getReferencedTypeState(fieldNumber).getSchema(); if(refObjSchema.numFields() != 1) return false; return isSearchable(refObjSchema, 0); } return true; } public String getFieldName() { return fieldName; } public FieldType getFieldType() { return fieldType; } public boolean isSearchable() { return isSearchable; } public String getFieldPath() { return fieldPath; } public SchemaDisplay getReferencedType() { return referencedType; } }
8,609
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/model/QueryResult.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.explorer.ui.model; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.tools.query.HollowFieldMatchQuery; import com.netflix.hollow.tools.traverse.TransitiveSetTraverser; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class QueryResult { private final List<QueryClause> queryClauses; private final Map<String, BitSet> queryMatches; private long randomizedStateTag; public QueryResult(long randomizedStateTag) { this.queryClauses = new ArrayList<QueryClause>(); this.queryMatches = new HashMap<String, BitSet>(); this.randomizedStateTag = randomizedStateTag; } public List<QueryClause> getQueryClauses() { return queryClauses; } public String getQueryDisplayString() { StringBuilder builder = new StringBuilder(); for(int i=0;i<queryClauses.size();i++) { if(i > 0) builder.append(" AND "); builder.append(queryClauses.get(i)); } return builder.toString(); } public Map<String, BitSet> getQueryMatches() { return queryMatches; } public void recalculateIfNotCurrent(HollowReadStateEngine stateEngine) { if(stateEngine.getCurrentRandomizedTag() != randomizedStateTag) { queryMatches.clear(); List<QueryClause> requeryClauses = new ArrayList<QueryClause>(this.queryClauses); this.queryClauses.clear(); for(QueryClause clause : requeryClauses) augmentQuery(clause, stateEngine); randomizedStateTag = stateEngine.getCurrentRandomizedTag(); } } public void augmentQuery(QueryClause clause, HollowReadStateEngine stateEngine) { HollowFieldMatchQuery query = new HollowFieldMatchQuery(stateEngine); Map<String, BitSet> clauseMatches = clause.getType() != null ? query.findMatchingRecords(clause.getType(), clause.getField(), clause.getValue()) : query.findMatchingRecords(clause.getField(), clause.getValue()); TransitiveSetTraverser.addReferencingOutsideClosure(stateEngine, clauseMatches); if(queryClauses.isEmpty()) queryMatches.putAll(clauseMatches); else booleanAndQueryMatches(clauseMatches); queryClauses.add(clause); } public void booleanAndQueryMatches(Map<String, BitSet> newQueryMatches) { Iterator<Map.Entry<String, BitSet>> iter = queryMatches.entrySet().iterator(); while(iter.hasNext()) { Map.Entry<String, BitSet> existingEntry = iter.next(); BitSet newTypeMatches = newQueryMatches.get(existingEntry.getKey()); if(newTypeMatches != null) { existingEntry.getValue().and(newTypeMatches); } else { iter.remove(); } } } public List<QueryTypeMatches> getTypeMatches() { List<QueryTypeMatches> list = new ArrayList<QueryTypeMatches>(); for(Map.Entry<String, BitSet> entry : queryMatches.entrySet()) { int numTypeMatches = entry.getValue().cardinality(); if(numTypeMatches > 0) list.add(new QueryTypeMatches(entry.getKey(), numTypeMatches)); } Collections.sort(list, new Comparator<QueryTypeMatches>() { public int compare(QueryTypeMatches o1, QueryTypeMatches o2) { return Integer.compare(o2.getNumMatches(), o1.getNumMatches()); } }); return list; } public static class QueryClause { private final String type; private final String field; private final String value; public QueryClause(String type, String field, String value) { this.type = type; this.field = field; this.value = value; } public String getType() { return type; } public String getField() { return field; } public String getValue() { return value; } @Override public String toString() { StringBuilder builder = new StringBuilder(); if(type != null) builder.append(type).append("."); builder.append(field).append("=\"").append(value).append("\""); return builder.toString(); } } public static class QueryTypeMatches { private final String typeName; private final int numMatches; public QueryTypeMatches(String typeName, int numMatches) { this.typeName = typeName; this.numMatches = numMatches; } public String getTypeName() { return typeName; } public int getNumMatches() { return numMatches; } } }
8,610
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/model/SchemaDisplay.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.explorer.ui.model; import com.netflix.hollow.core.schema.HollowCollectionSchema; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchema; import java.util.ArrayList; import java.util.List; public class SchemaDisplay { private final HollowSchema schema; private final List<SchemaDisplayField> displayFields; private final String fieldPath; private boolean isExpanded; public SchemaDisplay(HollowSchema schema) { this(schema, ""); } public SchemaDisplay(HollowSchema schema, String fieldPath) { this.schema = schema; this.fieldPath = fieldPath; this.displayFields = createDisplayFields(); this.isExpanded = false; } private List<SchemaDisplayField> createDisplayFields() { List<SchemaDisplayField> displayFields = new ArrayList<SchemaDisplayField>(); switch(schema.getSchemaType()) { case OBJECT: HollowObjectSchema objSchema = (HollowObjectSchema)schema; for(int i=0;i<objSchema.numFields();i++) displayFields.add(new SchemaDisplayField(fieldPath + "." + objSchema.getFieldName(i), objSchema, i)); return displayFields; case LIST: case SET: HollowCollectionSchema collSchema = (HollowCollectionSchema)schema; displayFields.add(new SchemaDisplayField(fieldPath + ".element", collSchema)); return displayFields; case MAP: HollowMapSchema mapSchema = (HollowMapSchema)schema; displayFields.add(new SchemaDisplayField(fieldPath + ".key", mapSchema, 0)); displayFields.add(new SchemaDisplayField(fieldPath + ".value", mapSchema, 1)); return displayFields; } throw new IllegalArgumentException(); } public String getTypeName() { return schema.getName(); } public HollowSchema getSchema() { return schema; } public List<SchemaDisplayField> getFields() { return displayFields; } public void setExpanded(boolean isExpanded) { this.isExpanded = isExpanded; } public boolean isExpanded() { return isExpanded; } }
8,611
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/model/TypeKey.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.explorer.ui.model; public class TypeKey { private final int idx; private final String keyStr; private final String keyDisplayStr; private final int ordinal; public TypeKey(int idx, int ordinal, String keyStr, String keyDisplayStr) { this.idx = idx; this.ordinal = ordinal; this.keyStr = keyStr; this.keyDisplayStr = keyDisplayStr; } public int getIdx() { return idx; } public int getOrdinal() { return ordinal; } public String getKey() { return keyStr; } public String getKeyDisplay() { return keyDisplayStr; } }
8,612
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/model/TypeOverview.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.explorer.ui.model; import static com.netflix.hollow.ui.HollowDiffUtil.formatBytes; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.schema.HollowSchema; import java.text.NumberFormat; public class TypeOverview { private final String typeName; private final int numRecords; private final int numHoles; private final long approxHoleFootprint; private final long approxHeapFootprint; private final PrimaryKey primaryKey; private final HollowSchema schema; private final int numShards; public TypeOverview(String typeName, int numRecords, int numHoles, long approxHoleFootprint, long approxHeapFootprint, PrimaryKey primaryKey, HollowSchema schema, int numShards) { this.typeName = typeName; this.numRecords = numRecords; this.numHoles = numHoles; this.approxHoleFootprint = approxHoleFootprint; this.approxHeapFootprint = approxHeapFootprint; this.primaryKey = primaryKey; this.schema = schema; this.numShards = numShards; } public String getTypeName() { return typeName; } public int getNumRecordsInt() { return numRecords; } public String getNumRecords() { return NumberFormat.getIntegerInstance().format(numRecords); } public int getNumHolesInt() { return numHoles; } public String getNumHoles() { return NumberFormat.getIntegerInstance().format(numHoles); } public long getApproxHoleFootprintLong() { return approxHoleFootprint; } public String getApproxHoleFootprint() { return formatBytes(approxHoleFootprint); } public long getApproxHeapFootprintLong() { return approxHeapFootprint; } public String getApproxHeapFootprint() { return formatBytes(approxHeapFootprint); } public String getPrimaryKey() { return primaryKey == null ? "" : primaryKey.toString(); } public String getSchema() { return schema.toString(); } public int getNumShardsInt() { return numShards; } public String getNumShards() { return NumberFormat.getIntegerInstance().format(numShards); } }
8,613
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/pages/QueryPage.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.explorer.ui.pages; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.explorer.ui.HollowExplorerUI; import com.netflix.hollow.explorer.ui.model.QueryResult; import com.netflix.hollow.explorer.ui.model.QueryResult.QueryClause; import com.netflix.hollow.ui.HollowUISession; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.VelocityContext; public class QueryPage extends HollowExplorerPage { public QueryPage(HollowExplorerUI ui) { super(ui); } @Override protected void setUpContext(HttpServletRequest req, HollowUISession session, VelocityContext ctx) { if("true".equals(req.getParameter("clear"))) session.clearAttribute("query-result"); String type = req.getParameter("type"); String field = req.getParameter("field"); if("ANY TYPE".equals(type)) type = null; String queryValue = req.getParameter("queryValue"); List<String> allTypes = new ArrayList<String>(); for(HollowSchema schema : ui.getStateEngine().getSchemas()) allTypes.add(schema.getName()); Collections.sort(allTypes); QueryResult result = (QueryResult) session.getAttribute("query-result"); if(result != null) result.recalculateIfNotCurrent(ui.getStateEngine()); if(field != null && queryValue != null) { HollowReadStateEngine stateEngine = ui.getStateEngine(); QueryClause queryClause = new QueryClause(type, field, queryValue); if(result == null) { result = new QueryResult(stateEngine.getCurrentRandomizedTag()); session.setAttribute("query-result", result); } result.augmentQuery(queryClause, ui.getStateEngine()); type = null; field = null; queryValue = null; } ctx.put("allTypes", allTypes); ctx.put("selectedType", type); ctx.put("selectedField", field); ctx.put("queryValue", queryValue); ctx.put("queryResult", session.getAttribute("query-result")); } @Override protected void renderPage(HttpServletRequest req, VelocityContext ctx, Writer writer) { ui.getVelocityEngine().getTemplate("query.vm").merge(ctx, writer); } }
8,614
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/pages/BrowseSelectedTypePage.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.explorer.ui.pages; import static com.netflix.hollow.core.HollowConstants.ORDINAL_NONE; import static com.netflix.hollow.tools.util.SearchUtils.ESCAPED_MULTI_FIELD_KEY_DELIMITER; import static com.netflix.hollow.tools.util.SearchUtils.MULTI_FIELD_KEY_DELIMITER; import static com.netflix.hollow.tools.util.SearchUtils.REGEX_MATCH_DELIMITER; import static com.netflix.hollow.tools.util.SearchUtils.getFieldPathIndexes; import static com.netflix.hollow.tools.util.SearchUtils.getOrdinalToDisplay; import static com.netflix.hollow.tools.util.SearchUtils.getPrimaryKey; import static com.netflix.hollow.tools.util.SearchUtils.parseKey; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.HollowReadFieldUtils; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.explorer.ui.HollowExplorerUI; import com.netflix.hollow.explorer.ui.model.QueryResult; import com.netflix.hollow.explorer.ui.model.TypeKey; import com.netflix.hollow.tools.stringifier.HollowRecordJsonStringifier; import com.netflix.hollow.tools.stringifier.HollowRecordStringifier; import com.netflix.hollow.tools.stringifier.HollowStringifier; import com.netflix.hollow.ui.HollowUISession; import com.netflix.hollow.ui.HtmlEscapingWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.VelocityContext; public class BrowseSelectedTypePage extends HollowExplorerPage { private static final String SESSION_ATTR_QUERY_RESULT = "query-result"; public BrowseSelectedTypePage(HollowExplorerUI ui) { super(ui); } @Override protected void setUpContext(HttpServletRequest req, HollowUISession session, VelocityContext ctx) { HollowTypeReadState typeState = getTypeState(req); int page = req.getParameter("page") == null ? 0 : Integer.parseInt(req.getParameter("page")); int pageSize = req.getParameter("pageSize") == null ? 20 : Integer.parseInt(req.getParameter("pageSize")); int startRec = page * pageSize; String displayFormat = "json".equals(req.getParameter("display")) ? "json" : "text"; BitSet selectedOrdinals = typeState.getPopulatedOrdinals(); if("true".equals(req.getParameter("clearQuery"))) session.clearAttribute(SESSION_ATTR_QUERY_RESULT); if(session.getAttribute(SESSION_ATTR_QUERY_RESULT) != null) { QueryResult queryResult = (QueryResult) session.getAttribute(SESSION_ATTR_QUERY_RESULT); queryResult.recalculateIfNotCurrent(ui.getStateEngine()); selectedOrdinals = queryResult.getQueryMatches().get(typeState.getSchema().getName()); if(selectedOrdinals == null) selectedOrdinals = new BitSet(); ctx.put("filteredByQuery", queryResult.getQueryDisplayString()); } int currentOrdinal = selectedOrdinals.nextSetBit(0); for(int i=0;i<startRec;i++) { currentOrdinal = selectedOrdinals.nextSetBit(currentOrdinal+1); } PrimaryKey primaryKey = getPrimaryKey(typeState.getSchema()); int fieldPathIndexes[][] = getFieldPathIndexes(ui.getStateEngine(), primaryKey); List<TypeKey> keys = new ArrayList<>(pageSize); for(int i = 0; i < pageSize && currentOrdinal != ORDINAL_NONE; i ++) { keys.add(getKey(startRec + i, typeState, currentOrdinal, fieldPathIndexes)); currentOrdinal = selectedOrdinals.nextSetBit(currentOrdinal + 1); } String key = req.getParameter("key") == null ? "" : req.getParameter("key"); Object parsedKey[] = null; try { parsedKey = parseKey(ui.getStateEngine(), primaryKey, key); } catch(Exception e) { key = ""; } HollowTypeReadState readTypeState = getTypeState(req); int ordinal = req.getParameter("ordinal") == null ? ORDINAL_NONE : Integer.parseInt(req.getParameter("ordinal")); ordinal = getOrdinalToDisplay(ui.getStateEngine(), key, parsedKey, ordinal, selectedOrdinals, fieldPathIndexes, readTypeState); if (ordinal != ORDINAL_NONE && "".equals(key) && fieldPathIndexes != null) { // set key for the case where it was unset previously key = getKey(ORDINAL_NONE, typeState, ordinal, fieldPathIndexes).getKey(); } int numRecords = selectedOrdinals.cardinality(); ctx.put("keys", keys); ctx.put("page", page); ctx.put("pageSize", pageSize); ctx.put("numPages", ((numRecords - 1) / pageSize) + 1); ctx.put("numRecords", numRecords); ctx.put("type", typeState.getSchema().getName()); ctx.put("key", key); ctx.put("ordinal", ordinal); ctx.put("display", displayFormat); } @Override protected void renderPage(HttpServletRequest req, VelocityContext ctx, Writer writer) { String key = (String) ctx.get("key"); Integer ordinal = (Integer) ctx.get("ordinal"); ui.getVelocityEngine().getTemplate("browse-selected-type-top.vm").merge(ctx, writer); try { Writer htmlEscapingWriter = new HtmlEscapingWriter(writer); if (!"".equals(key) && ordinal != null && ordinal.equals(ORDINAL_NONE)) { htmlEscapingWriter.append("ERROR: Key " + key + " was not found!"); } else if (ordinal != null && !ordinal.equals(ORDINAL_NONE)) { HollowStringifier stringifier = "json".equals(req.getParameter("display")) ? new HollowRecordJsonStringifier() : new HollowRecordStringifier(); stringifier.stringify(htmlEscapingWriter, ui.getStateEngine(), getTypeState(req).getSchema().getName(), ordinal); } } catch (IOException e) { throw new RuntimeException("Error streaming response", e); } ui.getVelocityEngine().getTemplate("browse-selected-type-bottom.vm").merge(ctx, writer); } private TypeKey getKey(int recordIdx, HollowTypeReadState typeState, int ordinal, int[][] fieldPathIndexes) { if(fieldPathIndexes != null) { StringBuilder keyBuilder = new StringBuilder(); StringBuilder delimiterEscapedKeyBuilder = new StringBuilder(); HollowObjectTypeReadState objState = (HollowObjectTypeReadState)typeState; for(int i=0;i<fieldPathIndexes.length;i++) { int curOrdinal = ordinal; HollowObjectTypeReadState curState = objState; for(int j=0;j<fieldPathIndexes[i].length - 1;j++) { curOrdinal = curState.readOrdinal(curOrdinal, fieldPathIndexes[i][j]); curState = (HollowObjectTypeReadState) curState.getSchema().getReferencedTypeState(fieldPathIndexes[i][j]); } if(i > 0) { keyBuilder.append(MULTI_FIELD_KEY_DELIMITER); delimiterEscapedKeyBuilder.append(MULTI_FIELD_KEY_DELIMITER); } Object fieldValueObject = HollowReadFieldUtils.fieldValueObject(curState, curOrdinal, fieldPathIndexes[i][fieldPathIndexes[i].length - 1]); keyBuilder.append(fieldValueObject); if (fieldValueObject instanceof String) { // escape delimiters if present in the value delimiterEscapedKeyBuilder.append(((String) fieldValueObject) .replaceAll(REGEX_MATCH_DELIMITER, ESCAPED_MULTI_FIELD_KEY_DELIMITER)); } else { delimiterEscapedKeyBuilder.append(fieldValueObject); } } return new TypeKey(recordIdx, ordinal, delimiterEscapedKeyBuilder.toString(), keyBuilder.toString()); } return new TypeKey(recordIdx, ordinal, "", "ORDINAL:" + ordinal); } private HollowTypeReadState getTypeState(HttpServletRequest req) { return ui.getStateEngine().getTypeState(req.getParameter("type")); } }
8,615
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/pages/HollowExplorerPage.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.explorer.ui.pages; import com.netflix.hollow.explorer.ui.HollowExplorerUI; import com.netflix.hollow.ui.EscapingTool; import com.netflix.hollow.ui.HollowUISession; import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; public abstract class HollowExplorerPage { protected final HollowExplorerUI ui; private final Template headerTemplate; private final Template footerTemplate; public HollowExplorerPage(HollowExplorerUI ui) { this.ui = ui; this.headerTemplate = ui.getVelocityEngine().getTemplate("explorer-header.vm"); this.footerTemplate = ui.getVelocityEngine().getTemplate("explorer-footer.vm"); } public void render(HttpServletRequest req, HttpServletResponse resp, HollowUISession session) throws IOException { VelocityContext ctx = new VelocityContext(); if (ui.getCurrentStateVersion() != Long.MIN_VALUE) ctx.put("stateVersion", ui.getCurrentStateVersion()); String headerDisplayString = ui.getHeaderDisplayString(); if (headerDisplayString != null) { ctx.put("headerDisplayString", headerDisplayString); String headerDisplayURL = (ui.getFromHeaderDisplayMap(headerDisplayString) != null) ? ui.getFromHeaderDisplayMap(headerDisplayString) : ""; ctx.put("headerStringURL", headerDisplayURL); } ctx.put("basePath", ui.getBaseURLPath()); ctx.put("esc", new EscapingTool()); setUpContext(req, session, ctx); resp.setContentType("text/html;charset=UTF-8"); Writer writer = resp.getWriter(); headerTemplate.merge(ctx, writer); renderPage(req, ctx, writer); footerTemplate.merge(ctx, writer); } /** * Renders the page to the provided Writer, using the provided VelocityContext. */ protected abstract void renderPage(HttpServletRequest req, VelocityContext ctx, Writer writer); /** * Populates the provided VelocityContext. */ protected abstract void setUpContext(HttpServletRequest req, HollowUISession session, VelocityContext ctx); }
8,616
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/pages/BrowseSchemaPage.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.explorer.ui.pages; import com.netflix.hollow.explorer.ui.HollowExplorerUI; import com.netflix.hollow.explorer.ui.model.SchemaDisplay; import com.netflix.hollow.explorer.ui.model.SchemaDisplayField; import com.netflix.hollow.ui.HollowUISession; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.VelocityContext; public class BrowseSchemaPage extends HollowExplorerPage { public BrowseSchemaPage(HollowExplorerUI ui) { super(ui); } @Override protected void setUpContext(HttpServletRequest req, HollowUISession session, VelocityContext ctx) { String type = req.getParameter("type"); String expand = req.getParameter("expand"); String collapse = req.getParameter("collapse"); SchemaDisplay schemaDisplay = (SchemaDisplay) session.getAttribute("schema-display-" + type); if(schemaDisplay == null) { schemaDisplay = new SchemaDisplay(ui.getStateEngine().getSchema(type)); schemaDisplay.setExpanded(true); } if(expand != null) expandOrCollapse(schemaDisplay, expand.split("\\."), 1, true); if(collapse != null) expandOrCollapse(schemaDisplay, collapse.split("\\."), 1, false); session.setAttribute("schema-display-" + type, schemaDisplay); ctx.put("schemaDisplay", schemaDisplay); ctx.put("type", type); } @Override protected void renderPage(HttpServletRequest req, VelocityContext ctx, Writer writer) { ui.getVelocityEngine().getTemplate("browse-schema.vm").merge(ctx, writer); } private void expandOrCollapse(SchemaDisplay display, String fieldPaths[], int cursor, boolean isExpand) { if(display == null) return; if(cursor >= fieldPaths.length) { display.setExpanded(isExpand); return; } for(SchemaDisplayField field : display.getFields()) { if(field.getFieldName().equals(fieldPaths[cursor])) expandOrCollapse(field.getReferencedType(), fieldPaths, cursor+1, isExpand); } } }
8,617
0
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui
Create_ds/hollow/hollow-explorer-ui/src/main/java/com/netflix/hollow/explorer/ui/pages/ShowAllTypesPage.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.explorer.ui.pages; import static com.netflix.hollow.ui.HollowDiffUtil.formatBytes; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSchema.SchemaType; import com.netflix.hollow.explorer.ui.HollowExplorerUI; import com.netflix.hollow.explorer.ui.model.TypeOverview; import com.netflix.hollow.ui.HollowUISession; import java.io.Writer; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.velocity.VelocityContext; public class ShowAllTypesPage extends HollowExplorerPage { public ShowAllTypesPage(HollowExplorerUI ui) { super(ui); } @Override protected void setUpContext(HttpServletRequest req, HollowUISession session, VelocityContext ctx) { String sort = req.getParameter("sort") == null ? "primaryKey" : req.getParameter("sort"); List<TypeOverview> typeOverviews = new ArrayList<TypeOverview>(); for(HollowTypeReadState typeState : ui.getStateEngine().getTypeStates()) { String typeName = typeState.getSchema().getName(); BitSet populatedOrdinals = typeState.getPopulatedOrdinals(); int numRecords = populatedOrdinals == null ? Integer.MIN_VALUE : populatedOrdinals.cardinality(); int numHoles = populatedOrdinals == null ? Integer.MIN_VALUE : populatedOrdinals.length()-populatedOrdinals.cardinality(); long approxHoleFootprint = typeState.getApproximateHoleCostInBytes(); PrimaryKey primaryKey = typeState.getSchema().getSchemaType() == SchemaType.OBJECT ? ((HollowObjectSchema)typeState.getSchema()).getPrimaryKey() : null; long approxHeapFootprint = typeState.getApproximateHeapFootprintInBytes(); HollowSchema schema = typeState.getSchema(); int numShards = typeState.numShards(); typeOverviews.add(new TypeOverview(typeName, numRecords, numHoles, approxHoleFootprint, approxHeapFootprint, primaryKey, schema, numShards)); } switch(sort) { case "typeName": Collections.sort(typeOverviews, new Comparator<TypeOverview>() { public int compare(TypeOverview o1, TypeOverview o2) { return o1.getTypeName().compareTo(o2.getTypeName()); } }); break; case "numRecords": Collections.sort(typeOverviews, new Comparator<TypeOverview>() { public int compare(TypeOverview o1, TypeOverview o2) { return Integer.compare(o2.getNumRecordsInt(), o1.getNumRecordsInt()); } }); break; case "numHoles": typeOverviews.sort((o1, o2) -> Integer.compare(o2.getNumHolesInt(), o1.getNumHolesInt())); break; case "holeSize": typeOverviews.sort((o1, o2) -> Long.compare(o2.getApproxHoleFootprintLong(), o1.getApproxHoleFootprintLong())); break; case "heapSize": Collections.sort(typeOverviews, new Comparator<TypeOverview>() { public int compare(TypeOverview o1, TypeOverview o2) { return Long.compare(o2.getApproxHeapFootprintLong(), o1.getApproxHeapFootprintLong()); } }); break; case "numShards": typeOverviews.sort((o1, o2) -> Integer.compare(o2.getNumShardsInt(), o1.getNumShardsInt())); break; default: Collections.sort(typeOverviews, new Comparator<TypeOverview>() { public int compare(TypeOverview o1, TypeOverview o2) { if(!"".equals(o1.getPrimaryKey()) && "".equals(o2.getPrimaryKey())) return -1; if("".equals(o1.getPrimaryKey()) && !"".equals(o2.getPrimaryKey())) return 1; return o1.getTypeName().compareTo(o2.getTypeName()); } }); } ctx.put("totalHoleFootprint", totalApproximateHoleFootprint(typeOverviews)); ctx.put("totalHeapFootprint", totalApproximateHeapFootprint(typeOverviews)); ctx.put("typeOverviews", typeOverviews); } @Override protected void renderPage(HttpServletRequest req, VelocityContext ctx, Writer writer) { ui.getVelocityEngine().getTemplate("show-all-types.vm").merge(ctx, writer); } private String totalApproximateHeapFootprint(List<TypeOverview> allTypes) { long totalHeapFootprint = 0; for(TypeOverview type : allTypes) totalHeapFootprint += type.getApproxHeapFootprintLong(); return formatBytes(totalHeapFootprint); } private String totalApproximateHoleFootprint(List<TypeOverview> allTypes) { long totalFootprint = 0; for(TypeOverview type : allTypes) totalFootprint += type.getApproxHoleFootprintLong(); return formatBytes(totalFootprint); } }
8,618
0
Create_ds/hollow/hollow-fakedata/src/main/java
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/FakeDataGenerator.java
package hollow; import com.github.javafaker.Faker; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.fs.HollowFilesystemBlobRetriever; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowFilesystemPublisher; import com.netflix.hollow.explorer.ui.HollowExplorerUIServer; import com.netflix.hollow.history.ui.HollowHistoryUIServer; import hollow.model.Art; import hollow.model.Artist; import hollow.model.Book; import hollow.model.BookId; import hollow.model.BookImages; import hollow.model.BookMetadata; import hollow.model.Chapter; import hollow.model.ChapterId; import hollow.model.ChapterInfo; import hollow.model.Country; import hollow.model.Genre; import hollow.model.Scene; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; /** * Produces a fake book catalog dataset with some entropy in delta chain. */ public class FakeDataGenerator { // tunable parameters of the generated fake dataset public static final String BLOB_PATH = "/tmp/fakehollowdata"; public static final int NUM_RUN_CYCLES = 100; // how many producer cycles to run, typically maps to the no. of states in the produced delta chain public static final int NUM_BOOKS_IN_CATALOG = 10000; // total no. of records at the top level public static final int MAX_ADDS_PER_CYCLE = 200; // entropy public static final int MAX_REMOVES_PER_CYCLE = 100; // entropy public static final int MAX_MODIFICATIONS_PER_CYCLE = 1000; // entropy // other variables controlling dataset size and cardinality public static final int MAX_CHARACTERS_IN_A_CHAPTER = 100; public static final int NUM_ARTISTS = 1000; private final static Faker faker = new Faker(); private static final List<String> COUNTRIES = Arrays.asList("US", "CA", "MX", "BE", "BZ", "BJ", "BM", "BT", "BR", "BG", "BI", "CV", "KH", "CM", "CL", "CN", "CW", "CY", "CZ", "DK", "DJ", "DM", "EC", "EG", "SV", "ER", "EE", "SZ", "ET", "FI", "FR", "GA", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GT", "GG", "GN", "GY", "HT", "HK", "HU", "IS", "IN", "ID", "IRQ", "IE", "Man", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "PK", "PW", "TK", "TO", "TN", "TR", "TM", "TV", "UG", "UA"); private static List<Book> books = new ArrayList<>(); private static int maxBookId; private static List<Artist> artists = new ArrayList<>(100000); public static void main(String[] args) throws Exception { System.out.println("Writing fake data blobs to local path: " + BLOB_PATH); populateArtists(); populateCatalog(1, NUM_BOOKS_IN_CATALOG); HollowProducer p = new HollowProducer.Builder<>() .withPublisher(new HollowFilesystemPublisher(Paths.get(BLOB_PATH))) .withNumStatesBetweenSnapshots(NUM_RUN_CYCLES/3) .build(); p.runCycle(state -> { for (Book book : books) { state.add(book); } }); HollowConsumer c = HollowConsumer.withBlobRetriever(new HollowFilesystemBlobRetriever(Paths.get(BLOB_PATH))).build(); c.triggerRefresh(); HollowExplorerUIServer explorerUIServer = new HollowExplorerUIServer(c, 7001).start(); System.out.println("Explorer started at http://localhost:7001"); new HollowHistoryUIServer(c, 7002).start(); System.out.println("History server started listening at http://localhost:7002"); for (int i = 0; i < NUM_RUN_CYCLES-1; i ++) { Set<Integer> bookIdsToModifyThisCycle = randomBookIds(new Random().nextInt(MAX_MODIFICATIONS_PER_CYCLE)); int booksToAddThisCycle = new Random().nextInt(MAX_ADDS_PER_CYCLE); Set<Integer> bookIdsToRemoveThisCycle = randomBookIds(new Random().nextInt(MAX_REMOVES_PER_CYCLE)); bookIdsToRemoveThisCycle.removeAll(bookIdsToModifyThisCycle); long v = p.runCycle(state -> { populateCatalog(maxBookId, booksToAddThisCycle); for (Book book : books) { if (bookIdsToRemoveThisCycle.contains(book.id.value)) { continue; // drop book } if (bookIdsToModifyThisCycle.contains(book.id.value)) { modifyBook(book); } state.add(book); // add remaining as is } }); c.triggerRefreshTo(v); } explorerUIServer.join(); } private static Genre randomGenre() { int randomGenreOrdinal = new Random().nextInt(Genre.values().length); Genre randomGenre = Genre.values()[randomGenreOrdinal]; return randomGenre; } private static String randomSceneDescription() { return faker.funnyName().name() + ", a " + faker.job().title().toString() + ", teams up with a pet " + faker.animal().name() + " to rescue the planet from " + faker.pokemon().name(); } private static Set<String> randomSetOfPeople() { int numPeople = new Random().nextInt(5); Set<String> people = new HashSet<>(5); for (int i = 0; i < numPeople; i ++) { people.add(faker.name().name()); } return people; } private static Set<String> randomSetOfCountries() { int numCountries = new Random().nextInt(COUNTRIES.size()); if (numCountries == 0) { numCountries = 1; } Set<String> countries = new HashSet<>(numCountries); for (int i = 0; i < numCountries; i ++) { countries.add(COUNTRIES.get(new Random().nextInt(COUNTRIES.size()))); } return countries; } private static byte[] randomChapterContent() { return faker.lorem().characters(10, MAX_CHARACTERS_IN_A_CHAPTER).getBytes(); } private static Artist randomArtist() { return artists.get(new Random().nextInt(artists.size())); } private static void populateArtists() { Set<Artist> setOfArtists = new HashSet<>(NUM_ARTISTS); for (int i = 0; i < NUM_ARTISTS; i ++) { Artist artist = new Artist(faker.artist().name().toString(), faker.country().capital().toString()); setOfArtists.add(artist); } artists = new ArrayList<>(setOfArtists); } private static void populateCatalog(int bookStartId, int numBooksToAdd) { for (int bookIdIter = bookStartId; bookIdIter < numBooksToAdd; bookIdIter ++) { final int bookId = bookIdIter; for (String country : randomSetOfCountries()) { int pages = new Random().nextInt(1000); Book book = new Book( new BookId(bookId), new Country(country), new BookImages(new HashMap<String, List<Art>>() {{ put("small", Arrays.asList(new Art(bookId + country, randomArtist(), System.currentTimeMillis(), new Random().nextInt(10000)))); put("medium", Arrays.asList(new Art(bookId + country, randomArtist(), System.currentTimeMillis(), new Random().nextInt(10000)))); put("large", Arrays.asList(new Art(bookId + country, randomArtist(), System.currentTimeMillis(), new Random().nextInt(10000)))); }} .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))), new BookMetadata(faker.book().title(), randomGenre(), Arrays.asList( new Chapter(new ChapterId(UUID.randomUUID().toString()), new ChapterInfo(new BookId(bookId), pages, randomChapterContent()), Arrays.asList(new Scene(randomSceneDescription(), new Random().nextInt(100000), randomSetOfPeople()))), new Chapter(new ChapterId(UUID.randomUUID().toString()), new ChapterInfo(new BookId(bookId), pages, randomChapterContent()), Arrays.asList(new Scene(randomSceneDescription(), new Random().nextInt(100000), randomSetOfPeople()))) ).stream().collect(Collectors.toList())) ); books.add(book); maxBookId ++; } } } private static void modifyBook(Book book) { boolean maybeRemoveArt = new Random().nextBoolean(); if (maybeRemoveArt) { Optional<Map.Entry<String, List<Art>>> art = book.images.art.entrySet().stream().findFirst(); if (art.isPresent()) { book.images.art.remove(art.get()); } } boolean maybeAddArt = new Random().nextBoolean(); if (maybeAddArt && book.images.art.size() < 3) { Set<String> sizes = book.images.art.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toSet()); String size; if (!sizes.contains("small")) { size = "small"; } else if (!sizes.contains("medium")) { size = "medium"; } else { size = "large"; } book.images.art.put(size, Arrays.asList(new Art(book.id.toString() + book.country, randomArtist(), System.currentTimeMillis(), new Random().nextInt(10000)))); } boolean maybeRemoveBookChapter = new Random().nextBoolean(); if (maybeRemoveBookChapter) { if (book.bookMetadata.chapters.size() > 0) { book.bookMetadata.chapters.remove(0); } } boolean maybeAddBookChapter = new Random().nextBoolean(); if (maybeAddBookChapter) { book.bookMetadata.chapters.add( new Chapter(new ChapterId(UUID.randomUUID().toString()), new ChapterInfo(new BookId(book.id.value), new Random().nextInt(1000), randomChapterContent()), Arrays.asList(new Scene(randomSceneDescription(), new Random().nextInt(100000), randomSetOfPeople())))); } } private static Set<Integer> randomBookIds(int maxHowMany) { if (maxHowMany == 0) { maxHowMany = 1; } Set<Integer> result = new HashSet<>(); for (int i = 0; i < maxHowMany; i ++) { int bookId = new Random().nextInt(maxBookId); if (bookId == 0) { bookId = 1; } result.add(bookId); } return result; } }
8,619
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/Country.java
package hollow.model; import com.netflix.hollow.core.write.objectmapper.HollowInline; public class Country { @HollowInline String id; public Country(String id) { this.id = id; } }
8,620
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/ChapterInfo.java
package hollow.model; public class ChapterInfo { BookId bookId; int pages; byte[] content; public ChapterInfo(BookId bookId, int pages, byte[] content) { this.bookId = bookId; this.pages = pages; this.content = content; } }
8,621
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/BookImages.java
package hollow.model; import java.util.List; import java.util.Map; public class BookImages { public Map<String, List<Art>> art; public BookImages(Map<String, List<Art>> art) { this.art = art; } }
8,622
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/Art.java
package hollow.model; public class Art { String id; Artist artist; long timeOfCreation; long size; public Art(String id, Artist artist, long timeOfCreation, long size) { this.id = id; this.artist = artist; this.timeOfCreation = timeOfCreation; this.size = size; } }
8,623
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/Scene.java
package hollow.model; import java.util.Set; public class Scene { String description; long popularity; Set<String> characters; public Scene(String description, long popularity, Set<String> characters) { this.description = description; this.popularity = popularity; this.characters = characters; } }
8,624
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/Book.java
package hollow.model; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; @HollowPrimaryKey(fields = {"id", "country"}) public class Book { public BookId id; public Country country; public BookImages images; public BookMetadata bookMetadata; public Book(BookId id, Country country, BookImages images, BookMetadata bookMetadata) { this.id = id; this.country = country; this.images = images; this.bookMetadata = bookMetadata; } }
8,625
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/Artist.java
package hollow.model; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; @HollowPrimaryKey(fields = "name") public class Artist { String name; String city; public Artist(String name, String city) { this.name = name; this.city = city; } }
8,626
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/BookId.java
package hollow.model; public class BookId { public int value; public BookId(int value) { this.value = value; } }
8,627
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/Genre.java
package hollow.model; public enum Genre { ACTION, CLASSIC, ART, TRAVEL, GUIDE, PSYCHOLOGY, BUSINESS, DRAMA, POETRY, ROMANCE, FICTION }
8,628
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/Chapter.java
package hollow.model; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.List; @HollowPrimaryKey(fields = "chapterId") public class Chapter { ChapterId chapterId; ChapterInfo chapterInfo; List<Scene> scenes; public Chapter(ChapterId chapterId, ChapterInfo chapterInfo, List<Scene> scenes) { this.chapterId = chapterId; this.chapterInfo = chapterInfo; this.scenes = scenes; } }
8,629
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/ChapterId.java
package hollow.model; public class ChapterId { String val; public ChapterId(String val) { this.val = val; } }
8,630
0
Create_ds/hollow/hollow-fakedata/src/main/java/hollow
Create_ds/hollow/hollow-fakedata/src/main/java/hollow/model/BookMetadata.java
package hollow.model; import java.util.List; public class BookMetadata { public String name; public Genre genre; public List<Chapter> chapters; public BookMetadata(String name, Genre genre, List<Chapter> chapters) { this.name = name; this.genre = genre; this.chapters = chapters; } }
8,631
0
Create_ds/hollow/hollow-test/src/test/java/com/netflix/hollow
Create_ds/hollow/hollow-test/src/test/java/com/netflix/hollow/test/HollowReadStateEngineBuilderTest.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.test; import static org.junit.Assert.assertEquals; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import java.util.Arrays; import java.util.HashSet; import org.junit.Test; public class HollowReadStateEngineBuilderTest { @Test public void testBuild_withoutTypeInitialization() { HollowReadStateEngine readEngine = new HollowReadStateEngineBuilder() .add("penguins3peat").add(3L).build(); assertEquals("Should have both types", new HashSet<String>(Arrays.asList( String.class.getSimpleName(), Long.class.getSimpleName())), new HashSet<String>(readEngine.getAllTypes())); } @Test public void testBuild_withTypeInitialization() { HollowReadStateEngine readEngine = new HollowReadStateEngineBuilder(Arrays.<Class<?>>asList(String.class, Long.class)) .add("foo").add(3L).build(); assertEquals("Should have both types", new HashSet<String>(Arrays.asList( String.class.getSimpleName(), Long.class.getSimpleName())), new HashSet<String>(readEngine.getAllTypes())); assertEquals("Should have one String", 1, readEngine.getTypeDataAccess( String.class.getSimpleName()).getTypeState().getPopulatedOrdinals().cardinality()); assertEquals("The one String should be foo", "foo", new GenericHollowObject(readEngine, String.class.getSimpleName(), 0).getString("value")); assertEquals("Should have one Long", 1, readEngine.getTypeDataAccess( Long.class.getSimpleName()).getTypeState().getPopulatedOrdinals().cardinality()); assertEquals("The one Long should be 3L", 3L, new GenericHollowObject(readEngine, Long.class.getSimpleName(), 0).getLong("value")); } @Test public void testBuild_canConstructMultiple() { HollowReadStateEngineBuilder builder = new HollowReadStateEngineBuilder(); builder.build(); builder.build(); } @Test(expected = IllegalArgumentException.class) public void testBuild_cannotAddAfterBuild() { HollowReadStateEngineBuilder builder = new HollowReadStateEngineBuilder(); builder.build(); builder.add("foo"); } }
8,632
0
Create_ds/hollow/hollow-test/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow-test/src/test/java/com/netflix/hollow/test/consumer/TestHollowConsumerTest.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.test.consumer; import static com.netflix.hollow.core.HollowConstants.VERSION_NONE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.netflix.hollow.api.consumer.HollowConsumer.AnnouncementWatcher; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.test.HollowWriteStateEngineBuilder; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TestHollowConsumerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testAddSnapshot_version() throws Exception { long latestVersion = 1L; TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withAnnouncementWatcher(new TestAnnouncementWatcher().setLatestVersion(latestVersion)) .withBlobRetriever(new TestBlobRetriever()) .build(); consumer.addSnapshot(latestVersion, new HollowWriteStateEngineBuilder().build()); assertEquals("Should be no version", AnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE, consumer.getCurrentVersionId()); consumer.triggerRefresh(); assertEquals("Should be at latest version", latestVersion, consumer.getCurrentVersionId()); } @Test public void testAddSnapshot_data() throws Exception { long latestVersion = 1L; TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withAnnouncementWatcher(new TestAnnouncementWatcher().setLatestVersion(1L)) .withBlobRetriever(new TestBlobRetriever()) .build(); consumer.addSnapshot(latestVersion, new HollowWriteStateEngineBuilder().add("foo").add(2).build()); consumer.triggerRefresh(); HollowDataAccess data = consumer.getAPI().getDataAccess(); assertEquals("Should have string and int", new HashSet<>(Arrays.asList("String", "Integer")), data.getAllTypes()); assertEquals("foo", new GenericHollowObject(data, "String", 0).getString("value")); assertEquals(2, new GenericHollowObject(data, "Integer", 0).getInt("value")); } @Test public void testAddSnapshot_triggerRefreshTo() throws Exception { long version = 2; TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .build(); consumer.addSnapshot(version, new HollowWriteStateEngineBuilder().build()); try { consumer.triggerRefreshTo(version - 1); fail("Should have failed to create an update plan"); } catch (RuntimeException e) { // we should make this a specific exception } consumer.triggerRefreshTo(version); // should succeed } @Test public void testAddSnapshot_afterUpdate() throws Exception { long version1 = 1L; long version2 = 2L; TestAnnouncementWatcher announcementWatcher = new TestAnnouncementWatcher().setLatestVersion(version1); TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withAnnouncementWatcher(announcementWatcher) .withBlobRetriever(new TestBlobRetriever()) .build(); consumer.addSnapshot(version1, new HollowWriteStateEngineBuilder().build()); consumer.triggerRefresh(); assertEquals(version1, consumer.getCurrentVersionId()); consumer.addSnapshot(version2, new HollowWriteStateEngineBuilder().build()); consumer.triggerRefresh(); assertEquals("We haven't told announcementWatcher about version2 yet", version1, consumer.getCurrentVersionId()); announcementWatcher.setLatestVersion(version2); consumer.triggerRefresh(); assertEquals(version2, consumer.getCurrentVersionId()); } @Test public void testDelta_versionTransition() throws Exception { long snapshotVersion = 1l; TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .build(); HollowWriteStateEngine state1 = new HollowWriteStateEngineBuilder().build(); consumer.addSnapshot(snapshotVersion, state1); assertEquals("Should be no version", VERSION_NONE, consumer.getCurrentVersionId()); consumer.triggerRefreshTo(snapshotVersion); assertEquals("Should be at snapshot version", snapshotVersion, consumer.getCurrentVersionId()); long deltaToVersion = 2l; HollowWriteStateEngine state2 = new HollowWriteStateEngineBuilder().build(); consumer.addDelta(snapshotVersion, deltaToVersion, state2); assertEquals("Should still be at snapshot version", snapshotVersion, consumer.getCurrentVersionId()); consumer.triggerRefreshTo(deltaToVersion); assertEquals("Should be at delta To version", deltaToVersion, consumer.getCurrentVersionId()); } @Test public void testSnapshotDeltaSnapshot_dataTransition() throws Exception { TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .build(); HollowWriteStateEngine state1 = new HollowWriteStateEngineBuilder(Collections.singletonList(Movie.class)) .add(new Movie(1, "first")) .build(); HollowWriteStateEngine state2 = new HollowWriteStateEngineBuilder(Collections.singletonList(Movie.class)) .add(new Movie(2, "second")) .build(); HollowWriteStateEngine state3 = new HollowWriteStateEngineBuilder(Collections.singletonList(Movie.class)) .add(new Movie(3, "third")) .build(); HollowWriteStateEngine state4 = new HollowWriteStateEngineBuilder(Collections.singletonList(Movie.class)) .add(new Movie(4, "fourth")) .build(); // SNAPSHOT consumer.applySnapshot(1l, state1); HollowDataAccess data = consumer.getAPI().getDataAccess(); assertEquals("Should have Movie and String", new HashSet<>(Arrays.asList("Movie", "String")), data.getAllTypes()); assertConsumerData(consumer, 0, new Movie(1, "first")); // DELTA consumer.applyDelta(2l, state2); assertConsumerData(consumer, 0, new Movie(1, "first")); // ghost record assertConsumerData(consumer, 1, new Movie(2, "second")); // new record // DELTA consumer.applyDelta(3l, state3); assertConsumerData(consumer, 0, new Movie(3, "third")); // ordinal for ghost record is reclaimed in next cycle assertConsumerData(consumer, 1, new Movie(2, "second")); // ghost record // SNAPSHOT consumer.applySnapshot(4l, state4); assertConsumerData(consumer, 0, new Movie(4, "fourth")); // double snapshot; ordinals from previous state not presserved } @Test public void testDeltaBeforeSnapshot_Unsupported() throws IOException { TestHollowConsumer consumer = new TestHollowConsumer.Builder().withBlobRetriever(new TestBlobRetriever()).build(); HollowWriteStateEngine state = new HollowWriteStateEngineBuilder(Collections.singletonList(Movie.class)) .add(new Movie(1, "first")).build(); thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("Delta can not be applied without first applying a snapshot"); consumer.applyDelta(1l, state); } // Assert that consumer data contains given movie object at given ordinal private void assertConsumerData(TestHollowConsumer consumer, int ordinal, Movie m) { HollowDataAccess data = consumer.getAPI().getDataAccess(); // The hydration of a movie POJO can be substituted with api.getMovie(ordinal) if generated api is available GenericHollowObject actualHollowObject = new GenericHollowObject(data, Movie.class.getSimpleName(), ordinal); Movie actualMovie = new Movie(actualHollowObject.getInt("id"), actualHollowObject.getObject("name").getString("value")); assertEquals(actualMovie, m); } @HollowPrimaryKey(fields="id") static class Movie { int id; String name; Movie(int id, String name) { this.id = id; this.name = name; } @Override public boolean equals(Object o) { Movie other = (Movie) o; return this.id == other.id && this.name.equals(other.name); } @Override public int hashCode() { int result = 1; result = 31 * result + id; result = 31 * result + ((name == null) ? 0 : name.hashCode()); return result; } } }
8,633
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/HollowReadStateEngineBuilder.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.test; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import java.util.Collection; import java.util.Collections; /** * This class allows constructing HollowReadStateEngine instances for testing purposes. * You cannot add to a HollowReadStateEngineBuilder after calling build, however you may build * multiple HollowReadStateEngine objects with the same builder. */ public class HollowReadStateEngineBuilder { private final HollowWriteStateEngineBuilder writeEngineBuilder; /** * Create a HollowReadStateEngineBuilder with an empty initial type state. Adding objects will * add their types, if not already present. */ public HollowReadStateEngineBuilder() { this(Collections.emptyList()); } /** * Create a HollowReadStateEngineBuilder, initializing it with a type state containing the * provided types. Adding objects will add their types, if not already present. */ public HollowReadStateEngineBuilder(Collection<Class<?>> types) { writeEngineBuilder = new HollowWriteStateEngineBuilder(types); } /** * Add an object that will be in our built HollowReadStateEngine. You cannot add any more * objects after calling build(). */ public HollowReadStateEngineBuilder add(Object... objects) { writeEngineBuilder.add(objects); return this; } /** * Build a HollowReadStateEngine. You cannot add() any more objects after calling this. */ public HollowReadStateEngine build() { HollowWriteStateEngine writeEngine = writeEngineBuilder.build(); HollowReadStateEngine readEngine = new HollowReadStateEngine(); try { StateEngineRoundTripper.roundTripSnapshot(writeEngine, readEngine, null); } catch (IOException e) { throw new RuntimeException("Error creating HollowReadStateEngine", e); } return readEngine; } }
8,634
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/InMemoryBlobStore.java
/* * Copyright 2016-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.test; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.HollowConsumer.Blob; import com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever; import com.netflix.hollow.api.consumer.HollowConsumer.HeaderBlob; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.HollowProducer.Publisher; import com.netflix.hollow.core.read.OptionalBlobPartInput; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Set; /// This InMemoryBlobStore is both a HollowProducer.Publisher and HollowConsumer.BlobRetriever! public class InMemoryBlobStore implements BlobRetriever, Publisher { private final Set<String> optionalPartsToRetrieve; private Map<Long, Blob> snapshots; private Map<Long, Blob> deltas; private Map<Long, Blob> reverseDeltas; private Map<Long, HeaderBlob> headers; public InMemoryBlobStore() { this(null); } public InMemoryBlobStore(Set<String> optionalPartsToRetrieve) { this.snapshots = new HashMap<>(); this.deltas = new HashMap<>(); this.reverseDeltas = new HashMap<>(); this.headers = new HashMap<>(); this.optionalPartsToRetrieve = optionalPartsToRetrieve; } private HollowConsumer.Blob getDesiredVersion(long desiredVersion, Map<Long, ? extends HollowConsumer.Blob> map) { HollowConsumer.Blob snapshot = map.get(desiredVersion); if(snapshot != null) return snapshot; long greatestPriorSnapshotVersion = Long.MIN_VALUE; for(Map.Entry<Long, ? extends HollowConsumer.Blob> entry : map.entrySet()) { if(entry.getKey() > greatestPriorSnapshotVersion && entry.getKey() < desiredVersion) greatestPriorSnapshotVersion = entry.getKey(); } return map.get(greatestPriorSnapshotVersion); } @Override public Blob retrieveSnapshotBlob(long desiredVersion) { return getDesiredVersion(desiredVersion, snapshots); } @Override public Blob retrieveDeltaBlob(long currentVersion) { return deltas.get(currentVersion); } @Override public Blob retrieveReverseDeltaBlob(long currentVersion) { return reverseDeltas.get(currentVersion); } @Override public HeaderBlob retrieveHeaderBlob(long currentVersion) { return headers.get(currentVersion); } @Override // For backwards compatability. public void publish(HollowProducer.Blob blob) { publishBlob(blob); } @Override public void publish(HollowProducer.PublishArtifact publishArtifact) { if (publishArtifact instanceof HollowProducer.HeaderBlob) { publishHeader((HollowProducer.HeaderBlob) publishArtifact); } else { publishBlob((HollowProducer.Blob) publishArtifact); } } private void publishHeader(HollowProducer.HeaderBlob headerBlob) { HeaderBlob consumerBlob = new HeaderBlob(headerBlob.getVersion()) { @Override public InputStream getInputStream() throws IOException { return headerBlob.newInputStream(); } }; headers.put(headerBlob.getVersion(), consumerBlob); } private void publishBlob(final HollowProducer.Blob blob) { Blob consumerBlob = new Blob(blob.getFromVersion(), blob.getToVersion()) { @Override public InputStream getInputStream() throws IOException { return blob.newInputStream(); } @Override public OptionalBlobPartInput getOptionalBlobPartInputs() throws IOException { if(blob.getOptionalPartConfig() == null || optionalPartsToRetrieve == null) return null; OptionalBlobPartInput parts = new OptionalBlobPartInput(); for(String part : blob.getOptionalPartConfig().getParts()) { if(optionalPartsToRetrieve.contains(part)) parts.addInput(part, blob.newOptionalPartInputStream(part)); } if(parts.getPartNames().isEmpty()) return null; return parts; } }; switch(blob.getType()) { case SNAPSHOT: snapshots.put(blob.getToVersion(), consumerBlob); break; case DELTA: deltas.put(blob.getFromVersion(), consumerBlob); break; case REVERSE_DELTA: reverseDeltas.put(blob.getFromVersion(), consumerBlob); break; } } public void removeSnapshot(long version) { snapshots.remove(version); } }
8,635
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/HollowWriteStateEngineBuilder.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.test; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.util.Arrays; import java.util.Collection; import java.util.Collections; /** * This class allows constructing HollowWriteStateEngine instances for testing purposes. * You cannot add to a HollowWriteStateEngineBuilder after calling build, however you may build * multiple HollowWriteStateEngine objects with the same builder. */ public class HollowWriteStateEngineBuilder { private final HollowWriteStateEngine writeEngine; private final HollowObjectMapper objectMapper; private boolean built; /** * Create a HollowWriteStateEngineBuilder with an empty initial type state. Adding objects will * add their types, if not already present. */ public HollowWriteStateEngineBuilder() { this(Collections.emptyList()); } /** * Create a HollowWriteStateEngineBuilder, initializing it with a type state containing the * provided types. Adding objects will add their types, if not already present. */ public HollowWriteStateEngineBuilder(Collection<Class<?>> types) { writeEngine = new HollowWriteStateEngine(); objectMapper = new HollowObjectMapper(writeEngine); for (Class<?> type : types) { objectMapper.initializeTypeState(type); } } /** * Add an object that will be in our built HollowWriteStateEngine. You cannot add any more * objects after calling build(). */ public HollowWriteStateEngineBuilder add(Object... objects) { if (built) { throw new IllegalArgumentException("Cannot add after building Hollow state engine"); } Arrays.stream(objects).forEach(objectMapper::add); return this; } /** * Build a HollowWriteStateEngine. You cannot add() any more objects after calling this. */ public HollowWriteStateEngine build() { built = true; return writeEngine; } }
8,636
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/model/TestTypeA.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.test.model; public class TestTypeA { int id; String name; public TestTypeA(int id, String name) { this.id = id; this.name = name; } }
8,637
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/consumer/TestBlobRetriever.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.test.consumer; import com.netflix.hollow.api.consumer.HollowConsumer.Blob; import com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever; import com.netflix.hollow.api.consumer.HollowConsumer.HeaderBlob; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * A simple implementation of a BlobRetriever which allows adding blobs and holds them all in * memory. */ public class TestBlobRetriever implements BlobRetriever { private final Map<Long, Blob> snapshots = new HashMap<>(); private final Map<Long, Blob> deltas = new HashMap<>(); private final Map<Long, Blob> reverseDeltas = new HashMap<>(); private final Map<Long, HeaderBlob> headers = new HashMap<>(); @Override public HeaderBlob retrieveHeaderBlob(long desiredVersion) { return headers.get(desiredVersion); } @Override public Blob retrieveSnapshotBlob(long desiredVersion) { Blob b = snapshots.get(desiredVersion); resetStream(b); return b; } @Override public Blob retrieveDeltaBlob(long currentVersion) { Blob b = deltas.get(currentVersion); resetStream(b); return b; } @Override public Blob retrieveReverseDeltaBlob(long currentVersion) { Blob b = reverseDeltas.get(currentVersion); resetStream(b); return b; } // so blob can be reused private void resetStream(Blob b) { try { if (b!= null && b.getInputStream() != null) { b.getInputStream().reset(); } } catch (IOException e) { throw new RuntimeException("Unable to get and reset stream", e); } } public void addSnapshot(long desiredVersion, Blob transition) { snapshots.put(desiredVersion, transition); } public void addDelta(long currentVersion, Blob transition) { deltas.put(currentVersion, transition); } public void addReverseDelta(long currentVersion, Blob transition) { reverseDeltas.put(currentVersion, transition); } public void addHeader(long desiredVersion, HeaderBlob headerBlob) { headers.put(desiredVersion, headerBlob); } }
8,638
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/consumer/TestBlob.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.test.consumer; import com.netflix.hollow.api.consumer.HollowConsumer.Blob; import java.io.File; import java.io.IOException; import java.io.InputStream; public class TestBlob extends Blob { private final InputStream inputStream; public TestBlob(long toVersion) { super(toVersion); this.inputStream = null; } public TestBlob(long toVersion, InputStream inputStream) { super(toVersion); this.inputStream = inputStream; } public TestBlob(long fromVersion, long toVersion) { super(fromVersion, toVersion); this.inputStream = null; } public TestBlob(long fromVersion, long toVersion, InputStream inputStream) { super(fromVersion, toVersion); this.inputStream = inputStream; } @Override public InputStream getInputStream() throws IOException { return inputStream; } @Override public File getFile() throws IOException { throw new UnsupportedOperationException(); } }
8,639
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/consumer/TestHollowConsumer.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.test.consumer; import com.netflix.hollow.Internal; import com.netflix.hollow.PublicSpi; import com.netflix.hollow.api.client.HollowAPIFactory; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.metrics.HollowConsumerMetrics; import com.netflix.hollow.api.metrics.HollowMetricsCollector; import com.netflix.hollow.core.memory.MemoryMode; 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.filter.HollowFilterConfig; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import com.netflix.hollow.core.util.HollowWriteStateCreator; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.tools.combine.HollowCombiner; import com.netflix.hollow.tools.combine.HollowCombinerCopyDirector; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import java.util.concurrent.Executor; /** * This class allows constructing HollowConsumer objects for use in unit and integration tests. * This uses an in-memory blob store, which means that all state is kept in memory, and so this is * not suited for use in normal application usage, just in tests. * * Example usage: * * // your data state will be represented by a state engine * HollowWriteStateEngine stateEngine = new HollowWriteStateEngineBuilder() * .add("somedata") * .add(new MyDataModelType("somestuff", 2)) * .build(); * // we will add the snapshot with a version, and make the announcementWatcher see this version * long latestVersion = 1L; * TestHollowConsumer consumer = new TestHollowConsumer.Builder() * .withAnnouncementWatcher(new TestAnnouncementWatcher().setLatestVersion(latestVersion)) * .withBlobRetriever(new TestBlobRetriever()) * .withGeneratedAPIClass(MyApiClass.class) * .build(); * consumer.addSnapshot(latestVersion, stateEngine); * consumer.triggerRefresh(); * * If you wish to use triggerRefreshTo instead of triggerRefresh, do not provide an * AnnouncementWatcher. */ @PublicSpi public class TestHollowConsumer extends HollowConsumer { private final BlobRetriever blobRetriever; /** * @deprecated use {@link TestHollowConsumer.Builder} */ @Internal @Deprecated protected TestHollowConsumer(BlobRetriever blobRetriever, AnnouncementWatcher announcementWatcher, List<RefreshListener> refreshListeners, HollowAPIFactory apiFactory, HollowFilterConfig dataFilter, ObjectLongevityConfig objectLongevityConfig, ObjectLongevityDetector objectLongevityDetector, DoubleSnapshotConfig doubleSnapshotConfig, HollowObjectHashCodeFinder hashCodeFinder, Executor refreshExecutor, HollowMetricsCollector<HollowConsumerMetrics> metricsCollector) { super(blobRetriever, announcementWatcher, refreshListeners, apiFactory, dataFilter, objectLongevityConfig, objectLongevityDetector, doubleSnapshotConfig, hashCodeFinder, refreshExecutor, MemoryMode.ON_HEAP, metricsCollector); this.blobRetriever = blobRetriever; } protected TestHollowConsumer(Builder builder) { super(builder); this.blobRetriever = builder.blobRetriever(); } /** * Apply a snapshot transition to {@code version} by applying {@code state}. This can be called on a {@code TestHollowConsumer} * that hasn't been initialized with a read state, or as a double-snapshot on a {@code TestHollowConsumer} with existing state. */ public void applySnapshot(long toVersion, HollowWriteStateEngine state) throws IOException { addSnapshot(toVersion, state); triggerRefreshTo(toVersion); } /** * Apply a delta transition to {@code toVersion} by applying {@code state}. */ public void applyDelta(long toVersion, HollowWriteStateEngine state) throws IOException { addDelta(getCurrentVersionId(), toVersion, state); triggerRefreshTo(toVersion); } public TestHollowConsumer addSnapshot(long version, HollowWriteStateEngine state) throws IOException { // if consumer has state then restore it if (getStateEngine() != null) { HollowWriteStateEngine snapshotState = HollowWriteStateCreator.createWithSchemas(getStateEngine().getSchemas()); snapshotState.restoreFrom(getStateEngine()); HollowCombiner combiner = new HollowCombiner(HollowCombinerCopyDirector.DEFAULT_DIRECTOR, snapshotState, // output roundTrip(state)); // input combiner.combine(); } if (blobRetriever instanceof TestBlobRetriever) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new HollowBlobWriter(state).writeSnapshot(outputStream); ((TestBlobRetriever) blobRetriever).addSnapshot(version, new TestBlob(version, new ByteArrayInputStream(outputStream.toByteArray()))); } else { throw new IllegalStateException("Cannot add snapshot if not using TestBlobRetriever"); } return this; } public TestHollowConsumer addDelta(long fromVersion, long toVersion, HollowWriteStateEngine state) throws IOException { if (getStateEngine() == null) { throw new UnsupportedOperationException("Delta can not be applied without first applying a snapshot"); } // create a new write state for delta application, restore from current state HollowWriteStateEngine deltaState = HollowWriteStateCreator.createWithSchemas(getStateEngine().getSchemas()); deltaState.restoreFrom(getStateEngine()); // add all records from passed in {@code state} to delta write state HollowCombiner combiner = new HollowCombiner(HollowCombinerCopyDirector.DEFAULT_DIRECTOR, deltaState, // output roundTrip(state)); // input combiner.combine(); // apply delta write state to consumer if (blobRetriever instanceof TestBlobRetriever) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new HollowBlobWriter(deltaState).writeDelta(outputStream); ((TestBlobRetriever) blobRetriever).addDelta(fromVersion, new TestBlob(fromVersion, toVersion, new ByteArrayInputStream(outputStream.toByteArray()))); } else { throw new IllegalStateException("Cannot add delta if not using TestBlobRetriever"); } return this; } private HollowReadStateEngine roundTrip(HollowWriteStateEngine writeEngine) throws IOException { writeEngine.prepareForWrite(); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); HollowReadStateEngine readEngine = new HollowReadStateEngine(writeEngine.getHashCodeFinder()); HollowBlobReader reader = new HollowBlobReader(readEngine); reader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); return readEngine; } @PublicSpi public static class Builder extends HollowConsumer.Builder<Builder> { protected HollowConsumer.BlobRetriever blobRetriever() { return blobRetriever; } @Override public TestHollowConsumer build() { checkArguments(); TestHollowConsumer consumer = new TestHollowConsumer(this); return consumer; } } }
8,640
0
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test
Create_ds/hollow/hollow-test/src/main/java/com/netflix/hollow/test/consumer/TestAnnouncementWatcher.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.test.consumer; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.HollowConsumer.AnnouncementWatcher; /** * A simple implementation of an AnnouncementWatcher which allows setting the latest version. */ public class TestAnnouncementWatcher implements AnnouncementWatcher { private long latestVersion = NO_ANNOUNCEMENT_AVAILABLE; @Override public long getLatestVersion() { return latestVersion; } public TestAnnouncementWatcher setLatestVersion(long latestVersion) { this.latestVersion = latestVersion; return this; } @Override public void subscribeToUpdates(HollowConsumer consumer) { // no-op } }
8,641
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/combine/HollowCombinerTest.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.tools.combine; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.generic.GenericHollowSet; import com.netflix.hollow.core.HollowDataset; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.memory.pool.RecyclingRecycler; 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.set.HollowSetTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSchema.SchemaType; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.util.DefaultHashCodeFinder; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowHashableWriteRecord.HashBehavior; 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 com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowCombinerTest { HollowObjectSchema aSchema; HollowSetSchema bSchema; HollowObjectSchema cSchema; HollowObjectHashCodeFinder hashCodeFinder; HollowWriteStateEngine shard1; HollowWriteStateEngine shard2; HollowWriteStateEngine shard3; @Before public void setUp() { aSchema = new HollowObjectSchema("A", 2, new PrimaryKey("A", "a1")); aSchema.addField("a1", FieldType.INT); aSchema.addField("a2", FieldType.REFERENCE, "B"); bSchema = new HollowSetSchema("B", "C"); cSchema = new HollowObjectSchema("C", 1); cSchema.addField("c1", FieldType.STRING); hashCodeFinder = new DefaultHashCodeFinder("C"); shard1 = createStateEngine(); shard2 = createStateEngine(); shard3 = createStateEngine(); } @Test public void testCombiner() throws IOException { addRecord(shard1, 1, "C1", "C2", "C3"); addRecord(shard1, 2, "C2", "C3", "C4"); addRecord(shard1, 3, "C1", "C2", "C3"); addRecord(shard2, 4, "C2", "C3", "C4"); addRecord(shard2, 5, "C1", "C4", "C5"); addRecord(shard2, 6, "C1", "C2", "C3"); addRecord(shard3, 7, "C4", "C5", "C6"); HollowCombiner combiner = new HollowCombiner(roundTrip(shard1), roundTrip(shard2), roundTrip(shard3)); combiner.combine(); HollowReadStateEngine combinedResult = roundTrip(combiner.getCombinedStateEngine()); Assert.assertEquals(6, combinedResult.getTypeState("A").maxOrdinal()); Assert.assertEquals(3, combinedResult.getTypeState("B").maxOrdinal()); Assert.assertEquals(5, combinedResult.getTypeState("C").maxOrdinal()); HollowSetTypeReadState bTypeState = (HollowSetTypeReadState)combinedResult.getTypeState("B"); Assert.assertTrue(setOrderingExists(bTypeState, "C1", "C2", "C3")); Assert.assertTrue(setOrderingExists(bTypeState, "C2", "C3", "C4")); Assert.assertTrue(setOrderingExists(bTypeState, "C1", "C4", "C5")); Assert.assertTrue(setOrderingExists(bTypeState, "C4", "C5", "C6")); } @Test public void testCombinerPrimaryKey() throws IOException { HollowWriteStateEngine sEngine = createStateEngine(); List<PrimaryKey> pKeys = extractPrimaryKeys(sEngine); Assert.assertEquals(1, pKeys.size()); // Make sure combinedResult has PrimaryKey transferred { HollowCombiner combiner = new HollowCombiner(roundTrip(sEngine), roundTrip(shard1)); HollowReadStateEngine combinedResult = roundTrip(combiner.getCombinedStateEngine()); Assert.assertEquals(1, extractPrimaryKeys(combinedResult).size()); Assert.assertEquals(pKeys, extractPrimaryKeys(combinedResult)); } // validate deduping { PrimaryKey oldPK = pKeys.get(0); PrimaryKey newPK = new PrimaryKey(oldPK.getType(), oldPK.getFieldPaths()); Assert.assertEquals(oldPK.getType(), newPK.getType()); Assert.assertEquals(oldPK, newPK); HollowCombiner combiner = new HollowCombiner(roundTrip(sEngine), roundTrip(shard1)); combiner.setPrimaryKeys(newPK); Assert.assertEquals(1, combiner.getPrimaryKeys().size()); Assert.assertEquals(oldPK, combiner.getPrimaryKeys().get(0)); Assert.assertEquals(newPK, combiner.getPrimaryKeys().get(0)); } // validate new PK of same type replaces old one { PrimaryKey oldPK = pKeys.get(0); PrimaryKey newPK = new PrimaryKey(oldPK.getType(), "xyz"); Assert.assertEquals(oldPK.getType(), newPK.getType()); Assert.assertNotEquals(oldPK, newPK); HollowCombiner combiner = new HollowCombiner(roundTrip(sEngine), roundTrip(shard1)); combiner.setPrimaryKeys(newPK); Assert.assertEquals(1, combiner.getPrimaryKeys().size()); Assert.assertNotEquals(oldPK, combiner.getPrimaryKeys().get(0)); Assert.assertEquals(newPK, combiner.getPrimaryKeys().get(0)); } // validate new PK gets added { PrimaryKey oldPK = pKeys.get(0); PrimaryKey newPK = new PrimaryKey("C", "c1"); Assert.assertNotEquals(oldPK.getType(), newPK.getType()); Assert.assertNotEquals(oldPK, newPK); HollowCombiner combiner = new HollowCombiner(roundTrip(sEngine), roundTrip(shard1)); combiner.setPrimaryKeys(newPK); Assert.assertEquals(2, combiner.getPrimaryKeys().size()); Assert.assertTrue(combiner.getPrimaryKeys().contains(oldPK)); Assert.assertTrue(combiner.getPrimaryKeys().contains(newPK)); } } private boolean setOrderingExists(HollowSetTypeReadState bTypeState, String... orderedCValues) { for(int i=0;i<=bTypeState.maxOrdinal();i++) { GenericHollowSet set = new GenericHollowSet(bTypeState, i); Iterator<HollowRecord> iter = set.iterator(); for(int j=0;j<orderedCValues.length;j++) { if(!iter.hasNext()) break; HollowObject obj = (HollowObject)iter.next(); String cValue = obj.getString("c1"); if(!cValue.equals(orderedCValues[j])) break; if(j == (orderedCValues.length - 1)) return true; } } return false; } private int addRecord(HollowWriteStateEngine shardEngine, int aVal, String... cVals) { int cOrdinals[] = new int[cVals.length]; HollowObjectWriteRecord cRec = new HollowObjectWriteRecord(cSchema); for(int i=0;i<cVals.length;i++) { cRec.reset(); cRec.setString("c1", cVals[i]); cOrdinals[i] = shardEngine.add("C", cRec); } HollowSetWriteRecord bRec = new HollowSetWriteRecord(HashBehavior.UNMIXED_HASHES); for(int i=0;i<cOrdinals.length;i++) { bRec.addElement(cOrdinals[i], i); /// hash code is ordering here } int bOrdinal = shardEngine.add("B", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(aSchema); aRec.setInt("a1", aVal); aRec.setReference("a2", bOrdinal); return shardEngine.add("A", aRec); } private HollowReadStateEngine roundTrip(HollowWriteStateEngine writeEngine) throws IOException { writeEngine.prepareForWrite(); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); HollowReadStateEngine readEngine = new HollowReadStateEngine(writeEngine.getHashCodeFinder(), true, new RecyclingRecycler()); HollowBlobReader reader = new HollowBlobReader(readEngine); reader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); return readEngine; } private HollowWriteStateEngine createStateEngine() { HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(hashCodeFinder); stateEngine.addTypeState(new HollowObjectTypeWriteState(aSchema)); stateEngine.addTypeState(new HollowSetTypeWriteState(bSchema)); stateEngine.addTypeState(new HollowObjectTypeWriteState(cSchema)); return stateEngine; } private List<PrimaryKey> extractPrimaryKeys(HollowDataset dataset) { List<PrimaryKey> keys = new ArrayList<PrimaryKey>(); for (HollowSchema schema : dataset.getSchemas()) { if (schema.getSchemaType() == SchemaType.OBJECT) { PrimaryKey pk = ((HollowObjectSchema) schema).getPrimaryKey(); if (pk != null) keys.add(pk); } } return keys; } }
8,642
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/combine/HollowCombinerFilteredReferencedTypeTest.java
package com.netflix.hollow.tools.combine; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.read.filter.HollowFilterConfig; 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 org.junit.Assert; import org.junit.Test; public class HollowCombinerFilteredReferencedTypeTest { @Test public void combinesEvenIfReferencedTypesAreFiltered() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new TypeA(1, 1)); mapper.add(new TypeA(2, 2)); mapper.add(new TypeA(3, 3)); HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowFilterConfig filter = new HollowFilterConfig(true); filter.addType("TypeB"); StateEngineRoundTripper.roundTripSnapshot(writeEngine, readEngine, filter); HollowCombiner combiner = new HollowCombiner(readEngine); combiner.combine(); HollowWriteStateEngine combined = combiner.getCombinedStateEngine(); HollowReadStateEngine combinedReadStateEngine = StateEngineRoundTripper.roundTripSnapshot(combined); HollowTypeReadState typeState = combinedReadStateEngine.getTypeState("TypeA"); Assert.assertEquals(3, typeState.getPopulatedOrdinals().cardinality()); Assert.assertNull(combinedReadStateEngine.getTypeState("TypeB")); } @SuppressWarnings("unused") private class TypeA { int id; TypeB typeB; TypeA(int id, int bVal) { this.id = id; this.typeB = new TypeB(); typeB.val = bVal; } } @SuppressWarnings("unused") private class TypeB { int val; } }
8,643
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/combine/HollowCombinerPrimaryKeyTests.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.tools.combine; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.index.key.PrimaryKey; 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 org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowCombinerPrimaryKeyTests { HollowReadStateEngine input1; HollowReadStateEngine input2; HollowReadStateEngine input3; @Before public void setUp() throws IOException { HollowWriteStateEngine input = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(input); addObject(mapper, 1, 1, 1, 1); addObject(mapper, 1, 2, 2, 2); addObject(mapper, 1, 3, 3, 3); input1 = StateEngineRoundTripper.roundTripSnapshot(input); input = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(input); addObject(mapper, 2, 4, 2, 3); addObject(mapper, 2, 5, 4, 4); addObject(mapper, 2, 6, 6, 6); input2 = StateEngineRoundTripper.roundTripSnapshot(input); input = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(input); addObject(mapper, 3, 7, 2, 3); addObject(mapper, 3, 8, 7, 6); addObject(mapper, 3, 9, 8, 8); addObject(mapper, 3, 10, 4, 10); mapper.add(new TypeC(100, 3)); input3 = StateEngineRoundTripper.roundTripSnapshot(input); } @Test public void testCascadingKeys() throws IOException { HollowCombiner combiner = new HollowCombiner(input1, input2, input3); combiner.setPrimaryKeys(new PrimaryKey("TypeB", "key"), new PrimaryKey("TypeC", "key")); combiner.combine(); HollowReadStateEngine output = StateEngineRoundTripper.roundTripSnapshot(combiner.getCombinedStateEngine()); assertObject(output, 1, 1, 1, 1, 1, 1); assertObject(output, 2, 1, 2, 1, 2, 1); assertObject(output, 3, 1, 3, 1, 3, 1); assertObject(output, 4, 2, 2, 1, 2, 1); assertObject(output, 5, 2, 4, 2, 4, 2); assertObject(output, 6, 2, 6, 2, 6, 2); assertObject(output, 7, 3, 2, 1, 2, 1); assertObject(output, 8, 3, 7, 3, 6, 2); assertObject(output, 9, 3, 8, 3, 8, 3); assertObject(output, 10,3, 4, 2, 4, 2); } @Test public void testCompoundKeys() throws IOException { HollowCombiner combiner = new HollowCombiner(input1, input2, input3); combiner.setPrimaryKeys(new PrimaryKey("TypeB", "key", "c.key")); combiner.combine(); HollowReadStateEngine output = StateEngineRoundTripper.roundTripSnapshot(combiner.getCombinedStateEngine()); assertObject(output, 1, 1, 1, 1, 1, 1); assertObject(output, 2, 1, 2, 1, 2, 1); assertObject(output, 3, 1, 3, 1, 3, 1); assertObject(output, 4, 2, 2, 2, 3, 2); assertObject(output, 5, 2, 4, 2, 4, 2); assertObject(output, 6, 2, 6, 2, 6, 2); assertObject(output, 7, 3, 2, 2, 3, 2); assertObject(output, 8, 3, 7, 3, 6, 3); assertObject(output, 9, 3, 8, 3, 8, 3); assertObject(output, 10,3, 4, 3, 10,3); } @Test public void testCompoundCascadingKeys() throws IOException { HollowCombiner combiner = new HollowCombiner(input1, input2, input3); combiner.setPrimaryKeys(new PrimaryKey("TypeB", "key", "c.key"), new PrimaryKey("TypeC", "key")); combiner.combine(); HollowReadStateEngine output = StateEngineRoundTripper.roundTripSnapshot(combiner.getCombinedStateEngine()); assertObject(output, 1, 1, 1, 1, 1, 1); assertObject(output, 2, 1, 2, 1, 2, 1); assertObject(output, 3, 1, 3, 1, 3, 1); assertObject(output, 4, 2, 2, 2, 3, 1); assertObject(output, 5, 2, 4, 2, 4, 2); assertObject(output, 6, 2, 6, 2, 6, 2); assertObject(output, 7, 3, 2, 2, 3, 1); assertObject(output, 8, 3, 7, 3, 6, 2); assertObject(output, 9, 3, 8, 3, 8, 3); assertObject(output, 10,3, 4, 3, 10,3); } @Test public void testExplicitlyExcludedAndRemappedKeys() throws IOException { HollowPrimaryKeyIndex cIdx1 = new HollowPrimaryKeyIndex(input1, "TypeC", "key"); HollowCombinerExcludePrimaryKeysCopyDirector director = new HollowCombinerExcludePrimaryKeysCopyDirector(); director.excludeKey(cIdx1, 3); HollowCombiner combiner = new HollowCombiner(director, input1, input2, input3); combiner.setPrimaryKeys(new PrimaryKey("TypeB", "key", "c.key"), new PrimaryKey("TypeC", "key")); combiner.combine(); HollowReadStateEngine output = StateEngineRoundTripper.roundTripSnapshot(combiner.getCombinedStateEngine()); assertObject(output, 1, 1, 1, 1, 1, 1); assertObject(output, 2, 1, 2, 1, 2, 1); assertObject(output, 3, 1, 3, 1, 3, 2); assertObject(output, 4, 2, 2, 2, 3, 2); assertObject(output, 5, 2, 4, 2, 4, 2); assertObject(output, 6, 2, 6, 2, 6, 2); assertObject(output, 7, 3, 2, 2, 3, 2); assertObject(output, 8, 3, 7, 3, 6, 2); assertObject(output, 9, 3, 8, 3, 8, 3); assertObject(output, 10,3, 4, 3, 10,3); } @Test public void testExplicitlyExcludedButOtherwiseReferencedKeys() throws IOException { HollowPrimaryKeyIndex cIdx3 = new HollowPrimaryKeyIndex(input3, "TypeC", "key"); HollowCombinerExcludePrimaryKeysCopyDirector director = new HollowCombinerExcludePrimaryKeysCopyDirector(); director.excludeKey(cIdx3, 8); HollowCombiner combiner = new HollowCombiner(director, input1, input2, input3); combiner.setPrimaryKeys(new PrimaryKey("TypeB", "key", "c.key"), new PrimaryKey("TypeC", "key")); combiner.combine(); HollowReadStateEngine output = StateEngineRoundTripper.roundTripSnapshot(combiner.getCombinedStateEngine()); assertObject(output, 9, 3, 8, 3, 8, 3); } @Test public void testExcludeReferencedObjectsFromPrimaryKeyCopyDirector() throws IOException { HollowPrimaryKeyIndex aIdx3 = new HollowPrimaryKeyIndex(input3, "TypeA", "key"); HollowCombinerExcludePrimaryKeysCopyDirector director = new HollowCombinerExcludePrimaryKeysCopyDirector(); director.excludeKey(aIdx3, 9); HollowCombiner combiner = new HollowCombiner(director, input1, input2, input3); combiner.setPrimaryKeys(new PrimaryKey("TypeB", "key", "c.key"), new PrimaryKey("TypeC", "key")); combiner.combine(); HollowReadStateEngine output = StateEngineRoundTripper.roundTripSnapshot(combiner.getCombinedStateEngine()); Assert.assertEquals(-1, new HollowPrimaryKeyIndex(output, "TypeA", "key").getMatchingOrdinal(9)); Assert.assertNotEquals(-1, new HollowPrimaryKeyIndex(output, "TypeB", "key").getMatchingOrdinal(8)); Assert.assertNotEquals(-1, new HollowPrimaryKeyIndex(output, "TypeC", "key").getMatchingOrdinal(8)); director.excludeReferencedObjects(); combiner = new HollowCombiner(director, input1, input2, input3); combiner.setPrimaryKeys(new PrimaryKey("TypeB", "key", "c.key"), new PrimaryKey("TypeC", "key")); combiner.combine(); output = StateEngineRoundTripper.roundTripSnapshot(combiner.getCombinedStateEngine()); Assert.assertEquals(-1, new HollowPrimaryKeyIndex(output, "TypeA", "key").getMatchingOrdinal(9)); Assert.assertEquals(-1, new HollowPrimaryKeyIndex(output, "TypeB", "key").getMatchingOrdinal(8)); Assert.assertEquals(-1, new HollowPrimaryKeyIndex(output, "TypeC", "key").getMatchingOrdinal(8)); } private void assertObject(HollowReadStateEngine output, int aKey, int expectAOrigin, int expectBKey, int expectBOrigin, int expectCKey, int expectCOrigin) { HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(output, new PrimaryKey("TypeA", "key")); GenericHollowObject typeA = (GenericHollowObject)GenericHollowRecordHelper.instantiate(output, "TypeA", idx.getMatchingOrdinal(aKey)); Assert.assertEquals(aKey, typeA.getInt("key")); Assert.assertEquals(expectAOrigin, typeA.getInt("origin")); GenericHollowObject typeB = (GenericHollowObject)typeA.getReferencedGenericRecord("b"); Assert.assertEquals(expectBKey, typeB.getInt("key")); Assert.assertEquals(expectBOrigin, typeB.getInt("origin")); GenericHollowObject typeC = (GenericHollowObject)typeB.getReferencedGenericRecord("c"); Assert.assertEquals(expectCKey, typeC.getInt("key")); Assert.assertEquals(expectCOrigin, typeC.getInt("origin")); } private void addObject(HollowObjectMapper mapper, int origin, int aKey, int bKey, int cKey) { mapper.add(new TypeA(aKey, origin, new TypeB(bKey, origin, new TypeC(cKey, origin)))); } @SuppressWarnings("unused") private static class TypeA { private final int key; private final int origin; private final TypeB b; public TypeA(int key, int origin, TypeB b) { this.key = key; this.origin = origin; this.b = b; } } @SuppressWarnings("unused") private static class TypeB { private final int key; private final int origin; private final TypeC c; public TypeB(int key, int origin, TypeC c) { this.key = key; this.origin = origin; this.c = c; } } @SuppressWarnings("unused") private static class TypeC { private final int key; private final int origin; public TypeC(int key, int origin) { this.key = key; this.origin = origin; } } }
8,644
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/combine/HollowCombinerIgnoreTest.java
package com.netflix.hollow.tools.combine; import static org.junit.Assert.assertEquals; 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 com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.io.IOException; import org.junit.Test; public class HollowCombinerIgnoreTest { @Test public void testIgnoreWithSingleInput() throws IOException { HollowWriteStateEngine combineInto = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(combineInto); mapper.initializeTypeState(TypeA.class); mapper.initializeTypeState(TypeB.class); HollowWriteStateEngine combineFromWriteEngine = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(combineFromWriteEngine); mapper.add(new TypeA(1)); mapper.add(new TypeB(1)); mapper.add(new TypeC(1)); HollowReadStateEngine combineFrom = StateEngineRoundTripper.roundTripSnapshot(combineFromWriteEngine); HollowCombiner combiner = new HollowCombiner(combineInto, combineFrom); combiner.addIgnoredTypes("TypeB", "TypeC"); combiner.combine(); HollowReadStateEngine combined = StateEngineRoundTripper.roundTripSnapshot(combineInto); assertEquals(1, combined.getTypeState("TypeA").getPopulatedOrdinals().cardinality()); assertEquals(0, combined.getTypeState("TypeB").getPopulatedOrdinals().cardinality()); assertEquals(0, combined.getTypeState("TypeC").getPopulatedOrdinals().cardinality()); } @Test public void testIgnoreWithMultipleInput() throws IOException { HollowWriteStateEngine combineInto = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(combineInto); mapper.initializeTypeState(TypeA.class); mapper.initializeTypeState(TypeB.class); HollowWriteStateEngine combineFromWriteEngine1 = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(combineFromWriteEngine1); mapper.add(new TypeA(1)); mapper.add(new TypeB(1)); mapper.add(new TypeC(1)); HollowReadStateEngine combineFrom1 = StateEngineRoundTripper.roundTripSnapshot(combineFromWriteEngine1); HollowWriteStateEngine combineFromWriteEngine2 = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(combineFromWriteEngine2); mapper.add(new TypeA(2)); mapper.add(new TypeB(2)); mapper.add(new TypeC(2)); HollowReadStateEngine combineFrom2 = StateEngineRoundTripper.roundTripSnapshot(combineFromWriteEngine2); HollowCombiner combiner = new HollowCombiner(combineInto, combineFrom1, combineFrom2); combiner.addIgnoredTypes("TypeB", "TypeC"); combiner.combine(); HollowReadStateEngine combined = StateEngineRoundTripper.roundTripSnapshot(combineInto); assertEquals(2, combined.getTypeState("TypeA").getPopulatedOrdinals().cardinality()); assertEquals(0, combined.getTypeState("TypeB").getPopulatedOrdinals().cardinality()); assertEquals(0, combined.getTypeState("TypeC").getPopulatedOrdinals().cardinality()); } @HollowPrimaryKey(fields={"id", "b.id"}) private static class TypeA { final int id; final TypeB b; final TypeC c; private TypeA(int id) { this.id = id; this.b = new TypeB(id); this.c = new TypeC(id); } } @HollowPrimaryKey(fields="id") private static class TypeB { final int id; private TypeB(int id) { this.id = id; } } private static class TypeC { final int id; private TypeC(int id) { this.id = id; } } }
8,645
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/combine/HollowCombinerMissingTypeWithPrimaryKeyTest.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.tools.combine; import static org.junit.Assert.assertEquals; 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 com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.io.IOException; import org.junit.Test; public class HollowCombinerMissingTypeWithPrimaryKeyTest { @Test public void multipleTypes() throws IOException { HollowWriteStateEngine combineInto = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(combineInto); mapper.initializeTypeState(TypeA.class); mapper.initializeTypeState(TypeB.class); HollowWriteStateEngine combineFromWriteEngine1 = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(combineFromWriteEngine1); mapper.add(new TypeB(1)); HollowReadStateEngine combineFrom1 = StateEngineRoundTripper.roundTripSnapshot(combineFromWriteEngine1); HollowWriteStateEngine combineFromWriteEngine2 = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(combineFromWriteEngine2); mapper.add(new TypeB(2)); mapper.add(new TypeA(2)); HollowReadStateEngine combineFrom2 = StateEngineRoundTripper.roundTripSnapshot(combineFromWriteEngine2); HollowCombiner combiner = new HollowCombiner(combineInto, combineFrom1, combineFrom2); combiner.combine(); HollowReadStateEngine combined = StateEngineRoundTripper.roundTripSnapshot(combineInto); assertEquals(2, combined.getTypeState("TypeB").getPopulatedOrdinals().cardinality()); assertEquals(1, combined.getTypeState("TypeA").getPopulatedOrdinals().cardinality()); } @HollowPrimaryKey(fields="id") private static class TypeA { @SuppressWarnings("unused") int id; private TypeA(int id) { this.id = id; } } @HollowPrimaryKey(fields="id") private static class TypeB { @SuppressWarnings("unused") int id; private TypeB(int id) { this.id = id; } } }
8,646
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/util/SearchUtilsTest.java
package com.netflix.hollow.tools.util; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowObjectSchema; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class SearchUtilsTest { @Mock HollowReadStateEngine stateEngine; @Mock PrimaryKey primaryKey; @Before public void setup() { MockitoAnnotations.initMocks(this); when(primaryKey.numFields()).thenReturn(2); when(primaryKey.getFieldType(eq(stateEngine), anyInt())).thenReturn(HollowObjectSchema.FieldType.STRING); } @Test public void testParseKey() { String keyString = "a:b"; Object[] key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a", key[0]); assertEquals("b", key[1]); // two fields, where the second field contains a ':' char // NOTE that this split based on delimiter works even without escaping the delimiter because // string split is performed based on no. of fields in the key. So if delimiter exists in the // last field then the parsing logic doesn't break keyString = "a:b1:b2"; key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a", key[0]); assertEquals("b1:b2", key[1]); // again two fields, where the second field contains a ':' char keyString = "a:b1\\:b2"; key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a", key[0]); assertEquals("b1:b2", key[1]); // two fields, where the first field contains a ':' char keyString = "a1\\:a2:b"; key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a1:a2", key[0]); assertEquals("b", key[1]); } }
8,647
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/util/ObjectInternPoolTest.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.tools.util; import static org.junit.Assert.assertEquals; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import org.junit.Before; import org.junit.Test; public class ObjectInternPoolTest { ObjectInternPool internPool = new ObjectInternPool(); @Before public void setup() { internPool = new ObjectInternPool(); } @Test public void testInt() { Integer intObj1 = 130; Integer intObj2 = 130; int int1Ordinal = internPool.writeAndGetOrdinal(intObj1); int int2Ordinal = internPool.writeAndGetOrdinal(intObj2); internPool.prepareForRead(); int retrievedInt1 = (int) internPool.getObject(int1Ordinal, FieldType.INT); assertEquals(int1Ordinal, int2Ordinal); assertEquals(retrievedInt1, 130); Integer intObj3 = 1900; Integer intObj4 = 1900; int int3Ordinal = internPool.writeAndGetOrdinal(intObj3); int int4Ordinal = internPool.writeAndGetOrdinal(intObj4); internPool.prepareForRead(); int retrievedInt3 = (int) internPool.getObject(int3Ordinal, FieldType.INT); assertEquals(int3Ordinal, int4Ordinal); assertEquals(retrievedInt3, 1900); } @Test public void testFloat() { Float floatObj1 = 130.0f; Float floatObj2 = 130.0f; Float floatObj3 = 1900.0f; Float floatObj4 = 1900.0f; int float1Ordinal = internPool.writeAndGetOrdinal(floatObj1); int float2Ordinal = internPool.writeAndGetOrdinal(floatObj2); internPool.prepareForRead(); float retrievedFloat1 = (float) internPool.getObject(float1Ordinal, FieldType.FLOAT); assertEquals(float1Ordinal, float2Ordinal); assertEquals(retrievedFloat1, 130.0f, 0.0f); int float3Ordinal = internPool.writeAndGetOrdinal(floatObj3); int float4Ordinal = internPool.writeAndGetOrdinal(floatObj4); internPool.prepareForRead(); float retrievedFloat2 = (float) internPool.getObject(float3Ordinal, FieldType.FLOAT); assertEquals(float3Ordinal, float4Ordinal); assertEquals(retrievedFloat2, 1900.0f, 0.0f); } @Test public void testLong() { Long longObj1 = 130L; Long longObj2 = 130L; Long longObj3 = 1900L; Long longObj4 = 1900L; int long1Ordinal = internPool.writeAndGetOrdinal(longObj1); int long2Ordinal = internPool.writeAndGetOrdinal(longObj2); internPool.prepareForRead(); long retrievedLong1 = (Long) internPool.getObject(long1Ordinal, FieldType.LONG); assertEquals(long1Ordinal, long2Ordinal); assertEquals(retrievedLong1, 130L); int long3Ordinal = internPool.writeAndGetOrdinal(longObj3); int long4Ordinal = internPool.writeAndGetOrdinal(longObj4); internPool.prepareForRead(); long retrievedLong2 = (Long) internPool.getObject(long3Ordinal, FieldType.LONG); assertEquals(long3Ordinal, long4Ordinal); assertEquals(retrievedLong2, 1900L); } @Test public void testDouble() { Double doubleObj1 = 130.0; Double doubleObj2 = 130.0; Double doubleObj3 = 1900.0; Double doubleObj4 = 1900.0; int double1Ordinal = internPool.writeAndGetOrdinal(doubleObj1); int double2Ordinal = internPool.writeAndGetOrdinal(doubleObj2); internPool.prepareForRead(); double retrievedDouble1 = (double) internPool.getObject(double1Ordinal, FieldType.DOUBLE); assertEquals(double1Ordinal, double2Ordinal); assertEquals(retrievedDouble1, 130.0, 0.0); int double3Ordinal = internPool.writeAndGetOrdinal(doubleObj3); int double4Ordinal = internPool.writeAndGetOrdinal(doubleObj4); internPool.prepareForRead(); double retrievedDouble2 = (double) internPool.getObject(double3Ordinal, FieldType.DOUBLE); assertEquals(double3Ordinal, double4Ordinal); assertEquals(retrievedDouble2, 1900.0, 0.0); } @Test public void testString() { String stringObj1 = "I am Groot"; String stringObj2 = "I am Groot"; String stringObj3 = "I can do this all day"; String stringObj4 = "I can do this all day"; int string1Ordinal = internPool.writeAndGetOrdinal(stringObj1); int string2Ordinal = internPool.writeAndGetOrdinal(stringObj2); internPool.prepareForRead(); String retrievedString1 = (String) internPool.getObject(string1Ordinal, FieldType.STRING); assertEquals(string1Ordinal, string2Ordinal); assertEquals(retrievedString1, "I am Groot"); int string3Ordinal = internPool.writeAndGetOrdinal(stringObj3); int string4Ordinal = internPool.writeAndGetOrdinal(stringObj4); internPool.prepareForRead(); String retrievedString2 = (String) internPool.getObject(string3Ordinal, FieldType.STRING); assertEquals(string3Ordinal, string4Ordinal); assertEquals(retrievedString2, "I can do this all day"); } @Test public void testBool() { Boolean boolObj1 = true; Boolean boolObj2 = true; Boolean boolObj3 = false; Boolean boolObj4 = false; int bool1Ordinal = internPool.writeAndGetOrdinal(boolObj1); int bool2Ordinal = internPool.writeAndGetOrdinal(boolObj2); internPool.prepareForRead(); boolean retrievedBool1 = (boolean) internPool.getObject(bool1Ordinal, FieldType.BOOLEAN); assertEquals(bool1Ordinal, bool2Ordinal); assertEquals(retrievedBool1, true); int bool3Ordinal = internPool.writeAndGetOrdinal(boolObj3); int bool4Ordinal = internPool.writeAndGetOrdinal(boolObj4); internPool.prepareForRead(); boolean retrievedBool2 = (boolean) internPool.getObject(bool3Ordinal, FieldType.BOOLEAN); assertEquals(bool3Ordinal, bool4Ordinal); assertEquals(retrievedBool2, false); } }
8,648
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff/HollowDiffChangedSchemaTest.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.tools.diff; 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.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.HollowBlobWriter; 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 com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.tools.diff.count.HollowFieldDiff; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Before; import org.junit.Test; public class HollowDiffChangedSchemaTest { HollowObjectSchema typeASchema1; HollowObjectSchema typeASchema2; HollowObjectSchema typeBSchema; HollowListSchema listOfTypeCSchema; HollowSetSchema setOfTypeCSchema; HollowMapSchema mapOfTypeCSchema; HollowObjectSchema typeCSchema; HollowWriteStateEngine stateEngine1; HollowWriteStateEngine stateEngine2; @Before public void setUp() { typeASchema1 = new HollowObjectSchema("TypeA", 3); typeASchema1.addField("key", FieldType.BYTES); typeASchema1.addField("b", FieldType.REFERENCE, "TypeB"); typeASchema1.addField("doubleVal", FieldType.DOUBLE); typeASchema2 = new HollowObjectSchema("TypeA", 6); typeASchema2.addField("key", FieldType.BYTES); typeASchema2.addField("b", FieldType.REFERENCE, "TypeB"); typeASchema2.addField("c", FieldType.REFERENCE, "TypeC"); typeASchema2.addField("cList", FieldType.REFERENCE, "ListOfTypeC"); typeASchema2.addField("cSet", FieldType.REFERENCE, "SetOfTypeC"); typeASchema2.addField("cMap", FieldType.REFERENCE, "MapOfTypeC"); typeBSchema = new HollowObjectSchema("TypeB", 1); typeBSchema.addField("longVal", FieldType.LONG); listOfTypeCSchema = new HollowListSchema("ListOfTypeC", "TypeC"); setOfTypeCSchema = new HollowSetSchema("SetOfTypeC", "TypeC"); mapOfTypeCSchema = new HollowMapSchema("MapOfTypeC", "TypeC", "TypeC"); typeCSchema = new HollowObjectSchema("TypeC", 1); typeCSchema.addField("stringVal", FieldType.STRING); stateEngine1 = new HollowWriteStateEngine(); stateEngine1.addTypeState(new HollowObjectTypeWriteState(typeASchema1)); stateEngine1.addTypeState(new HollowObjectTypeWriteState(typeBSchema)); stateEngine2 = new HollowWriteStateEngine(); stateEngine2.addTypeState(new HollowObjectTypeWriteState(typeASchema2)); stateEngine2.addTypeState(new HollowObjectTypeWriteState(typeBSchema)); stateEngine2.addTypeState(new HollowListTypeWriteState(listOfTypeCSchema)); stateEngine2.addTypeState(new HollowSetTypeWriteState(setOfTypeCSchema)); stateEngine2.addTypeState(new HollowMapTypeWriteState(mapOfTypeCSchema)); stateEngine2.addTypeState(new HollowObjectTypeWriteState(typeCSchema)); } @Test @SuppressWarnings("unused") public void testDiffWithChangedSchemas() throws IOException { int a1_0 = a1(new byte[] {1, 2, 3}, 1024L, 1020.3523d); int a2_0 = a2(new byte[] {1, 2, 3}, 1024L, list(c("list1"), c("list2")), set(c("list1"), c("set1"), c("set2")), map(c("key1"), c("val1"), c("key2"), c("val2"), c("key3"), c("val3")), c("singleton1")); int a1_1 = a1(new byte[] {2, 4, 6}, 12345678L, 1020.3523d); int a2_1 = a2(new byte[] {2, 4, 6}, 123456L, list(c("list3")), set(c("set4"), c("set5"), c("set6"), c("set7")), map(c("key10"), c("val10"), c("key20"), c("val20")), c("singleton2")); HollowDiff diff = diff(); HollowTypeDiff typeDiff = diff.getTypeDiffs().get(0); for(HollowFieldDiff fieldDiff : typeDiff.getFieldDiffs()) { System.out.println(fieldDiff.getFieldIdentifier() + ": " + fieldDiff.getTotalDiffScore()); for(int i=0;i<fieldDiff.getNumDiffs();i++) { System.out.println(" " + fieldDiff.getFromOrdinal(i) + "," + fieldDiff.getToOrdinal(i) + ": " + fieldDiff.getPairScore(i)); } } } private int a1(byte[] key, long bVal, double d) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema); bRec.setLong("longVal", bVal); int bOrdinal = stateEngine1.add("TypeB", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema1); aRec.setBytes("key", key); aRec.setReference("b", bOrdinal); aRec.setDouble("doubleVal", d); return stateEngine1.add("TypeA", aRec); } private int a2(byte[] key, long bVal, int listOrdinal, int setOrdinal, int mapOrdinal, int cOrdinal) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema); bRec.setLong("longVal", bVal); int bOrdinal = stateEngine2.add("TypeB", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema2); aRec.setBytes("key", key); aRec.setReference("b", bOrdinal); aRec.setReference("c", cOrdinal); aRec.setReference("cList", listOrdinal); aRec.setReference("cSet", setOrdinal); aRec.setReference("cMap", mapOrdinal); return stateEngine2.add("TypeA", aRec); } private int list(int... cOrdinals) { HollowListWriteRecord listRec = new HollowListWriteRecord(); for(int ordinal : cOrdinals) { listRec.addElement(ordinal); } return stateEngine2.add("ListOfTypeC", listRec); } private int set(int... cOrdinals) { HollowSetWriteRecord setRec = new HollowSetWriteRecord(); for(int ordinal : cOrdinals) { setRec.addElement(ordinal); } return stateEngine2.add("SetOfTypeC", setRec); } private int map(int... cOrdinals) { HollowMapWriteRecord mapRec = new HollowMapWriteRecord(); for(int i=0;i<cOrdinals.length;i+=2) { mapRec.addEntry(cOrdinals[i], cOrdinals[i+1]); } return stateEngine2.add("MapOfTypeC", mapRec); } private int c(String val) { HollowObjectWriteRecord cRec = new HollowObjectWriteRecord(typeCSchema); cRec.setString("stringVal", val); return stateEngine2.add("TypeC", cRec); } private HollowDiff diff() throws IOException { HollowDiff diff = new HollowDiff(roundTrip(stateEngine1), roundTrip(stateEngine2)); HollowTypeDiff typeDiff = diff.addTypeDiff("TypeA"); typeDiff.addMatchPath("key"); diff.calculateDiffs(); return diff; } private final HollowReadStateEngine roundTrip(HollowWriteStateEngine stateEngine) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); HollowBlobWriter writer = new HollowBlobWriter(stateEngine); writer.writeSnapshot(baos); HollowReadStateEngine readStateEngine = new HollowReadStateEngine(true); HollowBlobReader reader = new HollowBlobReader(readStateEngine); reader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); return readStateEngine; } }
8,649
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff/HollowDiffShortcutTest.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.tools.diff; 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 com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import com.netflix.hollow.tools.diff.count.HollowFieldDiff; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowDiffShortcutTest { @Test public void testShortcutType() throws Exception { HollowReadStateEngine from = createStateEngine(false, new TypeA(1, 1, 1), new TypeA(2, 2, 2), new TypeA(3, 3, 3), new TypeA(4, 4, 4), new TypeA(5, 5, 5), new TypeA(6) ); HollowReadStateEngine to = createStateEngine(false, new TypeA(1, 1, 1), new TypeA(2, 2, 3), new TypeA(3, 4, 4), new TypeA(4, 4, 4), new TypeA(5), new TypeA(6, 7, 8) ); HollowDiff diff = new HollowDiff(from, to); HollowTypeDiff typeADiff = diff.getTypeDiff("TypeA"); typeADiff.addShortcutType("TypeB"); diff.calculateDiffs(); Assert.assertEquals(1, typeADiff.getFieldDiffs().size()); HollowFieldDiff aFieldDiff = typeADiff.getFieldDiffs().get(0); Assert.assertEquals("TypeA.b (TypeB)", aFieldDiff.getFieldIdentifier().toString()); Assert.assertEquals(4, aFieldDiff.getNumDiffs()); } @Test public void testShortcutTypeMissingField() throws Exception { HollowReadStateEngine from = createStateEngine(false, new TypeA(1, 1, 1), new TypeA(2, 2, 2), new TypeA(3, 3, 3), new TypeA(4, 4, 4), new TypeA(5, 5, 5), new TypeA(6) ); HollowReadStateEngine to = createStateEngine( new TypeAKeyOnly(1), new TypeAKeyOnly(2), new TypeAKeyOnly(3), new TypeAKeyOnly(4), new TypeAKeyOnly(5), new TypeAKeyOnly(6) ); HollowDiff diff = new HollowDiff(from, to); HollowTypeDiff typeADiff = diff.getTypeDiff("TypeA"); typeADiff.addShortcutType("TypeB"); diff.calculateDiffs(); Assert.assertEquals(1, typeADiff.getFieldDiffs().size()); HollowFieldDiff aFieldDiff = typeADiff.getFieldDiffs().get(0); Assert.assertEquals("TypeA.b (TypeB)", aFieldDiff.getFieldIdentifier().toString()); Assert.assertEquals(5, aFieldDiff.getNumDiffs()); } @Test public void testShortcutTypeMissingHierarchicalField() throws Exception { HollowReadStateEngine from = createStateEngine( new Type0KeyOnly(1), new Type0KeyOnly(2), new Type0KeyOnly(3), new Type0KeyOnly(4), new Type0KeyOnly(5), new Type0KeyOnly(6) ); HollowReadStateEngine to = createStateEngine(true, new TypeA(1, 1, 1), new TypeA(2, 2, 2), new TypeA(3, 3, 3), new TypeA(4, 4, 4), new TypeA(5, 5, 5), new TypeA(6) ); HollowDiff diff = new HollowDiff(from, to, false); diff.addTypeDiff("Type0", "key").addShortcutType("TypeB"); diff.addTypeDiff("TypeB", "key"); diff.calculateDiffs(); HollowTypeDiff typeADiff = diff.getTypeDiff("Type0"); Assert.assertEquals(2, typeADiff.getFieldDiffs().size()); HollowFieldDiff keyFieldDiff = typeADiff.getFieldDiffs().get(0); HollowFieldDiff bFieldDiff = typeADiff.getFieldDiffs().get(1); Assert.assertEquals("Type0.a.key (INT)", keyFieldDiff.getFieldIdentifier().toString()); Assert.assertEquals(6, keyFieldDiff.getNumDiffs()); Assert.assertEquals("Type0.a.b (TypeB)", bFieldDiff.getFieldIdentifier().toString()); Assert.assertEquals(5, bFieldDiff.getNumDiffs()); } private HollowReadStateEngine createStateEngine(boolean addType0, TypeA... typeAs) throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); for(TypeA a : typeAs) { mapper.add(addType0 ? new Type0(a) : a); } return StateEngineRoundTripper.roundTripSnapshot(writeEngine); } private HollowReadStateEngine createStateEngine(TypeAKeyOnly... typeAs) throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeB.class); for(TypeAKeyOnly a : typeAs) { mapper.add(a); } return StateEngineRoundTripper.roundTripSnapshot(writeEngine); } private HollowReadStateEngine createStateEngine(Type0KeyOnly... type0s) throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeB.class); for(Type0KeyOnly a : type0s) { mapper.add(a); } return StateEngineRoundTripper.roundTripSnapshot(writeEngine); } @HollowPrimaryKey(fields="key") private static class TypeA { int key; TypeB b; public TypeA(int key) { this.key = key; this.b = null; } public TypeA(int key, int bKey, int data) { this.key = key; this.b = new TypeB(); b.key = bKey; b.data = data; } } @SuppressWarnings("unused") private static class TypeB { int key; int data; } @SuppressWarnings("unused") @HollowTypeName(name="TypeA") @HollowPrimaryKey(fields="key") private static class TypeAKeyOnly { int key; public TypeAKeyOnly(int key) { this.key = key; } } @SuppressWarnings("unused") private static class Type0 { int key; TypeA a; public Type0(TypeA a) { this.key = a.key; this.a = a; } } @SuppressWarnings("unused") @HollowTypeName(name="Type0") private static class Type0KeyOnly { int key; public Type0KeyOnly(int key) { this.key = key; } } }
8,650
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff/HollowDiffTest.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.tools.diff; 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.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.HollowBlobWriter; 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 com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.tools.diff.count.HollowFieldDiff; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowDiffTest { HollowObjectSchema typeASchema; HollowObjectSchema typeBSchema; HollowObjectSchema typeCSchema; HollowObjectSchema typeDSchema; HollowObjectSchema typeESchema; HollowObjectSchema typeFSchema; HollowListSchema listOfTypeCSchema; HollowSetSchema setOfTypeDSchema; HollowMapSchema mapOfTypeCToTypeDSchema; @Before public void setUp() { typeASchema = new HollowObjectSchema("TypeA", 3); typeASchema.addField("a1", FieldType.STRING); typeASchema.addField("a2", FieldType.REFERENCE, "TypeB"); typeASchema.addField("a3", FieldType.REFERENCE, "MapOfTypeCToTypeD"); typeBSchema = new HollowObjectSchema("TypeB", 3); typeBSchema.addField("b1", FieldType.INT); typeBSchema.addField("b2", FieldType.REFERENCE, "ListOfTypeC"); typeBSchema.addField("b3", FieldType.REFERENCE, "SetOfTypeD"); typeCSchema = new HollowObjectSchema("TypeC", 2); typeCSchema.addField("c1", FieldType.LONG); typeCSchema.addField("c2", FieldType.BOOLEAN); typeDSchema = new HollowObjectSchema("TypeD", 3, "d1", "d2"); typeDSchema.addField("d1", FieldType.FLOAT); typeDSchema.addField("d2", FieldType.DOUBLE); typeDSchema.addField("d3", FieldType.BYTES); typeESchema = new HollowObjectSchema("TypeE", 1, "e1"); typeESchema.addField("e1", FieldType.FLOAT); typeFSchema = new HollowObjectSchema("TypeF", 1); typeFSchema.addField("f1", FieldType.FLOAT); listOfTypeCSchema = new HollowListSchema("ListOfTypeC", "TypeC"); setOfTypeDSchema = new HollowSetSchema("SetOfTypeD", "TypeD"); mapOfTypeCToTypeDSchema = new HollowMapSchema("MapOfTypeCToTypeD", "TypeC", "TypeD"); } @Test public void test() throws IOException { HollowWriteStateEngine fromStateEngine = newWriteStateEngine(); HollowWriteStateEngine toStateEngine = newWriteStateEngine(); //// FIRST OBJECT PAIR //// addRec(fromStateEngine, "recordOne", 1, cList( c(1001, true), c(1002, true), c(1003, true) ), dSet( d(1.001f, 1.00001d, new byte[]{ 1, 1 }), d(1.002f, 1.00002d, new byte[]{ 1, 2 }) ), map( entry( c(1001, true), d(1.001f, 1.00001d, new byte[]{ 1, 1 }) ), entry( c(1002, true), d(1.002f, 1.00002d, new byte[]{ 1, 2 }) ) )); addRec(toStateEngine, "recordOne", 1, cList( c(1001, false), // now false instead of true c(1002, true), c(1003, false) // now false instead of true ), dSet( d(1.001f, 1.00001d, new byte[]{ 1, 9 }), /// 9 instead of 1 d(1.002f, 1.00002d, new byte[]{ 1, 2 }) ), map( entry( c(1001, true), d(1.001f, 1.00001d, new byte[]{ 1, 9 }) /// 9 instead of 1 ), entry( c(1002, true), d(1.002f, 1.00002d, new byte[]{ 1, 2 }) ) )); //// SECOND OBJECT PAIR //// addRec(fromStateEngine, "recordTwo", 2, cList( c(2001, true), c(2002, true), c(2003, true) ), dSet( d(2.001f, 2.00001d, new byte[]{ 2, 1 }), d(2.002f, 2.00002d, new byte[]{ 2, 2 }) ), map( entry( c(2001, true), d(2.001f, 2.00001d, new byte[]{ 2, 1 }) ), entry( c(2002, true), d(2.002f, 2.00002d, new byte[]{ 2, 2 }) ) )); addRec(toStateEngine, "recordTwo", 2, cList( c(2001, true), c(2002, false), // now false instead of true c(2003, true) ), dSet( d(2.001f, 2.00001d, new byte[]{ 2, 7 }), /// 7 instead of 1 d(2.002f, 2.00002d, new byte[]{ 2, 2 }) ), map( entry( c(2001, true), d(2.001f, 2.00001d, new byte[]{ 2, 7 }) /// 7 instead of 1 ), entry( c(2002, true), d(2.002f, 2.00002d, new byte[]{ 2, 2 }) ) )); //// UNPAIRED OBJECTS //// addRec(toStateEngine, "recordThree", 3, cList(), dSet(), map()); addRec(fromStateEngine, "recordThree", 4, cList(), dSet(), map()); HollowDiff diff = new HollowDiff(readEngine(fromStateEngine), readEngine(toStateEngine), false); HollowTypeDiff typeDiff = diff.addTypeDiff("TypeA"); typeDiff.addMatchPath("a1"); typeDiff.addMatchPath("a2.b1"); diff.calculateDiffs(); List<HollowFieldDiff> fieldDiffs = typeDiff.getFieldDiffs(); Assert.assertEquals(3, fieldDiffs.size()); assertContainsFieldDiff(fieldDiffs, "TypeA.a2.b2.element.c2 (BOOLEAN)", 2, 6); assertContainsFieldDiff(fieldDiffs, "TypeA.a2.b3.element.d3 (BYTES)", 2, 4); assertContainsFieldDiff(fieldDiffs, "TypeA.a3.value.d3 (BYTES)", 2, 4); Assert.assertEquals(1, typeDiff.getUnmatchedOrdinalsInTo().size()); Assert.assertEquals(1, typeDiff.getUnmatchedOrdinalsInTo().size()); } @Test public void testAutoDiscoverTypeDiffs() throws Exception { HollowWriteStateEngine fromStateEngine = newWriteStateEngine(); HollowWriteStateEngine toStateEngine = newWriteStateEngine(); HollowDiff diff = new HollowDiff(readEngine(fromStateEngine), readEngine(toStateEngine)); Assert.assertEquals(1, diff.getTypeDiffs().size()); HollowTypeDiff typeDDiff = diff.getTypeDiff("TypeD"); Assert.assertNotNull(typeDDiff); HollowDiffMatcher matcher = typeDDiff.getMatcher(); Assert.assertNotNull(matcher); List<String> matchPaths = matcher.getMatchPaths(); Assert.assertEquals(2, matchPaths.size()); Assert.assertEquals("d1", matchPaths.get(0)); Assert.assertEquals("d2", matchPaths.get(1)); } @Test public void testUnmatchedSchema() throws Exception { HollowWriteStateEngine fromStateEngine = newWriteStateEngine(); HollowWriteStateEngine toStateEngine = newWriteStateEngine(); toStateEngine.addTypeState(new HollowObjectTypeWriteState(typeESchema)); addERec(toStateEngine, e(1)); HollowDiff diff = new HollowDiff(readEngine(fromStateEngine), readEngine(toStateEngine)); diff.calculateDiffs(); Assert.assertEquals(2, diff.getTypeDiffs().size()); { HollowTypeDiff typeEDiff = diff.getTypeDiff("TypeE"); Assert.assertNotNull(typeEDiff); HollowDiffMatcher matcherE = typeEDiff.getMatcher(); Assert.assertNotNull(matcherE); List<String> matchPathsE = matcherE.getMatchPaths(); Assert.assertEquals(1, matchPathsE.size()); Assert.assertEquals("e1", matchPathsE.get(0)); Assert.assertEquals( typeEDiff.getUnmatchedOrdinalsInFrom().size(), 0 ); Assert.assertEquals( typeEDiff.getUnmatchedOrdinalsInTo().size(), 1 ); } } @Test public void testDiffTypeWithoutPrimaryKey() throws Exception { HollowWriteStateEngine fromStateEngine = newWriteStateEngine(); HollowWriteStateEngine toStateEngine = newWriteStateEngine(); addCRec(toStateEngine, c(2, true)); fromStateEngine.addTypeState(new HollowObjectTypeWriteState(typeFSchema)); toStateEngine.addTypeState(new HollowObjectTypeWriteState(typeFSchema)); addFRec(fromStateEngine, f(1)); addFRec(fromStateEngine, f(2)); addFRec(toStateEngine, f(2)); addFRec(toStateEngine, f(3)); addFRec(toStateEngine, f(4)); HollowDiff diff = new HollowDiff(readEngine(fromStateEngine), readEngine(toStateEngine), true, true); diff.calculateDiffs(); Assert.assertEquals(5, diff.getTypeDiffs().size()); { // Multi Field without Primary Key HollowTypeDiff typeDiff = diff.getTypeDiff("TypeC"); Assert.assertNotNull(typeDiff); HollowDiffMatcher matcher = typeDiff.getMatcher(); Assert.assertNotNull(matcher); // No Primary Key so not match Paths List<String> matchPaths = matcher.getMatchPaths(); Assert.assertEquals(0, matchPaths.size()); Assert.assertEquals( typeDiff.getUnmatchedOrdinalsInFrom().size(), 0 ); Assert.assertEquals( typeDiff.getUnmatchedOrdinalsInTo().size(), 1 ); } { // Single Field without Primary Key HollowTypeDiff typeDiff = diff.getTypeDiff("TypeF"); Assert.assertNotNull(typeDiff); HollowDiffMatcher matcher = typeDiff.getMatcher(); Assert.assertNotNull(matcher); // Automatic add single field List<String> matchPaths = matcher.getMatchPaths(); Assert.assertEquals(1, matchPaths.size()); Assert.assertEquals("f1", matchPaths.get(0)); Assert.assertEquals( typeDiff.getUnmatchedOrdinalsInFrom().size(), 1 ); Assert.assertEquals( typeDiff.getUnmatchedOrdinalsInTo().size(), 2 ); } } private void assertContainsFieldDiff(List<HollowFieldDiff> diffs, String fieldId, int numDiffPairs, int totalDiffScores) { for(HollowFieldDiff diff : diffs) { if(fieldId.equals(diff.getFieldIdentifier().toString())) { Assert.assertEquals(numDiffPairs, diff.getNumDiffs()); Assert.assertEquals(totalDiffScores, diff.getTotalDiffScore()); return; } } Assert.fail(); } private HollowReadStateEngine readEngine(HollowWriteStateEngine writeEngine) throws IOException { HollowBlobWriter writer = new HollowBlobWriter(writeEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); HollowReadStateEngine readEngine = new HollowReadStateEngine(true); HollowBlobReader reader = new HollowBlobReader(readEngine); reader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); return readEngine; } private HollowWriteStateEngine newWriteStateEngine() { HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); stateEngine.addTypeState(new HollowObjectTypeWriteState(typeASchema)); stateEngine.addTypeState(new HollowObjectTypeWriteState(typeBSchema)); stateEngine.addTypeState(new HollowObjectTypeWriteState(typeCSchema)); stateEngine.addTypeState(new HollowObjectTypeWriteState(typeDSchema)); stateEngine.addTypeState(new HollowListTypeWriteState(listOfTypeCSchema)); stateEngine.addTypeState(new HollowSetTypeWriteState(setOfTypeDSchema)); stateEngine.addTypeState(new HollowMapTypeWriteState(mapOfTypeCToTypeDSchema)); return stateEngine; } private int addRec(HollowWriteStateEngine stateEngine, String a1, int b1, TypeCRec[] typeCs, TypeDRec[] typeDs, MapEntry[] mapEntries) { int listOrdinal = addListRec(stateEngine, typeCs); int setOrdinal = addSetRec(stateEngine, typeDs); int bOrdinal = addBRec(stateEngine, b1, listOrdinal, setOrdinal); int mapOrdinal = addMapRec(stateEngine, mapEntries); return addARec(stateEngine, a1, bOrdinal, mapOrdinal); } private int addARec(HollowWriteStateEngine stateEngine, String a1, int bOrdinal, int mapOrdinal) { HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema); aRec.setString("a1", a1); aRec.setReference("a2", bOrdinal); aRec.setReference("a3", mapOrdinal); return stateEngine.add("TypeA", aRec); } private int addMapRec(HollowWriteStateEngine stateEngine, MapEntry[] mapEntries) { HollowMapWriteRecord mapRec = new HollowMapWriteRecord(); for(MapEntry entry : mapEntries) { int cOrdinal = addCRec(stateEngine, entry.key); int dOrdinal = addDRec(stateEngine, entry.value); mapRec.addEntry(cOrdinal, dOrdinal); } int mapOrdinal = stateEngine.add(mapOfTypeCToTypeDSchema.getName(), mapRec); return mapOrdinal; } private int addBRec(HollowWriteStateEngine stateEngine, int b1, int listOrdinal, int setOrdinal) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema); bRec.setInt("b1", b1); bRec.setReference("b2", listOrdinal); bRec.setReference("b3", setOrdinal); int bOrdinal = stateEngine.add("TypeB", bRec); return bOrdinal; } private int addListRec(HollowWriteStateEngine stateEngine, TypeCRec[] typeCs) { HollowListWriteRecord listRec = new HollowListWriteRecord(); for(TypeCRec typeC : typeCs) { listRec.addElement(addCRec(stateEngine, typeC)); } int listOrdinal = stateEngine.add(listOfTypeCSchema.getName(), listRec); return listOrdinal; } private int addSetRec(HollowWriteStateEngine stateEngine, TypeDRec[] typeDs) { HollowSetWriteRecord setRec = new HollowSetWriteRecord(); for(TypeDRec typeD : typeDs) { setRec.addElement(addDRec(stateEngine, typeD)); } int setOrdinal = stateEngine.add(setOfTypeDSchema.getName(), setRec); return setOrdinal; } private int addCRec(HollowWriteStateEngine stateEngine, TypeCRec typeC) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(typeCSchema); rec.setLong("c1", typeC.c1); rec.setBoolean("c2", typeC.c2); return stateEngine.add("TypeC", rec); } private int addDRec(HollowWriteStateEngine stateEngine, TypeDRec typeD) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(typeDSchema); rec.setFloat("d1", typeD.d1); rec.setDouble("d2", typeD.d2); rec.setBytes("d3", typeD.d3); return stateEngine.add("TypeD", rec); } private int addERec(HollowWriteStateEngine stateEngine, TypeERec typeE) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(typeESchema); rec.setFloat("e1", typeE.e1); return stateEngine.add("TypeE", rec); } private int addFRec(HollowWriteStateEngine stateEngine, TypeFRec typeF) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(typeFSchema); rec.setFloat("f1", typeF.f1); return stateEngine.add("TypeF", rec); } private TypeCRec[] cList(TypeCRec... cs) { return cs; } private TypeDRec[] dSet(TypeDRec... ds) { return ds; } private MapEntry[] map(MapEntry... entries) { return entries; } private MapEntry entry(TypeCRec c, TypeDRec d) { MapEntry entry = new MapEntry(); entry.key = c; entry.value = d; return entry; } private TypeCRec c(long c1, boolean c2) { TypeCRec rec = new TypeCRec(); rec.c1 = c1; rec.c2 = c2; return rec; } private TypeDRec d(float d1, double d2, byte[] d3) { TypeDRec rec = new TypeDRec(); rec.d1 = d1; rec.d2 = d2; rec.d3 = d3; return rec; } private TypeERec e(float e1) { TypeERec rec = new TypeERec(); rec.e1 = e1; return rec; } private TypeFRec f(float f1) { TypeFRec rec = new TypeFRec(); rec.f1 = f1; return rec; } private static class MapEntry { TypeCRec key; TypeDRec value; } private static class TypeCRec { private long c1; private boolean c2; } private static class TypeDRec { private float d1; private double d2; private byte[] d3; } private static class TypeERec { private float e1; } private static class TypeFRec { private float f1; } }
8,651
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff/HollowDiffMatcherTest.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.tools.diff; 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.util.IntList; import com.netflix.hollow.core.util.LongList; 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 HollowDiffMatcherTest { private HollowObjectSchema fromSchema; private HollowObjectSchema toSchema; private HollowObjectSchema subObjectSchema; private HollowWriteStateEngine fromStateEngine; private HollowWriteStateEngine toStateEngine; @Before public void setUp() { fromSchema = new HollowObjectSchema("TestObject", 3); fromSchema.addField("int", FieldType.INT); fromSchema.addField("ref", FieldType.REFERENCE, "TestSubObject"); fromSchema.addField("str", FieldType.STRING); toSchema = new HollowObjectSchema("TestObject", 2); toSchema.addField("ref", FieldType.REFERENCE, "TestSubObject"); toSchema.addField("str", FieldType.STRING); subObjectSchema = new HollowObjectSchema("TestSubObject", 2); subObjectSchema.addField("int", FieldType.INT); subObjectSchema.addField("double", FieldType.DOUBLE); fromStateEngine = new HollowWriteStateEngine(); fromStateEngine.addTypeState(new HollowObjectTypeWriteState(fromSchema)); fromStateEngine.addTypeState(new HollowObjectTypeWriteState(subObjectSchema)); toStateEngine = new HollowWriteStateEngine(); toStateEngine.addTypeState(new HollowObjectTypeWriteState(toSchema)); toStateEngine.addTypeState(new HollowObjectTypeWriteState(subObjectSchema)); } @Test public void findsObjectMatches() throws IOException { int from1 = addFromRecord(1, "one", 1, 1.1d); int from2 = addFromRecord(2, "two", 2, 2.2d); int from3 = addFromRecord(3, "three", 3, 3.3d); int from4 = addFromRecord(4, "four", 1, 1.1d); int to4 = addToRecord("four", 4, 4.4d); int to3 = addToRecord("three", 3, 3.3d); int to2 = addToRecord("two", 2, 2.2d); int to1 = addToRecord("one", 1, 1.1d); HollowObjectTypeReadState fromState = roundTripAndGetTypeState(fromStateEngine); HollowObjectTypeReadState toState = roundTripAndGetTypeState(toStateEngine); HollowDiffMatcher matcher = new HollowDiffMatcher(fromState, toState); matcher.addMatchPath("ref.double"); matcher.addMatchPath("str"); matcher.calculateMatches(); LongList matches = matcher.getMatchedOrdinals(); IntList fromExtra = matcher.getExtraInFrom(); IntList toExtra = matcher.getExtraInTo(); Assert.assertEquals((long)from3 << 32 | to3, matches.get(0)); Assert.assertEquals((long)from2 << 32 | to2, matches.get(1)); Assert.assertEquals((long)from1 << 32 | to1, matches.get(2)); Assert.assertEquals(3, matches.size()); Assert.assertEquals(from4, fromExtra.get(0)); Assert.assertEquals(1, fromExtra.size()); Assert.assertEquals(to4, toExtra.get(0)); Assert.assertEquals(1, toExtra.size()); } @Test public void retrievesDisplayStringsForRecords() throws IOException { int from1 = addFromRecord(1, "one", 1, 1.1d); int from2 = addFromRecord(2, "two", 2, 2.2d); int from3 = addFromRecord(3, "three", 3, 3.3d); int from4 = addFromRecord(4, "four", 1, 1.1d); int to4 = addToRecord("four", 4, 4.4d); int to3 = addToRecord("three", 3, 3.3d); int to2 = addToRecord("two", 2, 2.2d); int to1 = addToRecord("one", 1, 1.1d); HollowObjectTypeReadState fromState = roundTripAndGetTypeState(fromStateEngine); HollowObjectTypeReadState toState = roundTripAndGetTypeState(toStateEngine); HollowDiffMatcher matcher = new HollowDiffMatcher(fromState, toState); matcher.addMatchPath("ref.double"); matcher.addMatchPath("str"); matcher.calculateMatches(); Assert.assertEquals("1.1 one", matcher.getKeyDisplayString(fromState, from1)); Assert.assertEquals("2.2 two", matcher.getKeyDisplayString(fromState, from2)); Assert.assertEquals("3.3 three", matcher.getKeyDisplayString(fromState, from3)); Assert.assertEquals("1.1 four", matcher.getKeyDisplayString(fromState, from4)); Assert.assertEquals("1.1 one", matcher.getKeyDisplayString(toState, to1)); Assert.assertEquals("2.2 two", matcher.getKeyDisplayString(toState, to2)); Assert.assertEquals("3.3 three", matcher.getKeyDisplayString(toState, to3)); Assert.assertEquals("4.4 four", matcher.getKeyDisplayString(toState, to4)); } private HollowObjectTypeReadState roundTripAndGetTypeState(HollowWriteStateEngine stateEngine) throws IOException { HollowBlobWriter writer = new HollowBlobWriter(stateEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); HollowReadStateEngine readStateEngine = new HollowReadStateEngine(); readStateEngine.addTypeListener("TestObject", new PopulatedOrdinalListener()); HollowBlobReader reader = new HollowBlobReader(readStateEngine); reader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); return (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); } private int addFromRecord(int i, String str, int subi, double subd) { int subOrdinal = addSubRecord(fromStateEngine, subi, subd); HollowObjectWriteRecord rec = new HollowObjectWriteRecord(fromSchema); rec.setString("str", str); rec.setInt("int", i); rec.setReference("ref", subOrdinal); return fromStateEngine.add("TestObject", rec); } private int addToRecord(String str, int subi, double subd) { int subOrdinal = addSubRecord(toStateEngine, subi, subd); HollowObjectWriteRecord rec = new HollowObjectWriteRecord(toSchema); rec.setString("str", str); rec.setReference("ref", subOrdinal); return toStateEngine.add("TestObject", rec); } private int addSubRecord(HollowWriteStateEngine stateEngine, int subi, double subd) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(subObjectSchema); rec.setInt("int", subi); rec.setDouble("double", subd); return stateEngine.add("TestSubObject", rec); } }
8,652
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff/exact/DiffEqualOrdinalFilterTest.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.tools.diff.exact; import com.netflix.hollow.core.util.IntList; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DiffEqualOrdinalFilterTest { DiffEqualOrdinalFilter filter; @Before public void setUp() { DiffEqualOrdinalMap map = new DiffEqualOrdinalMap(10); map.putEqualOrdinals(1, list(100)); map.putEqualOrdinals(2, list(200)); map.putEqualOrdinals(3, list(300)); map.putEqualOrdinals(4, list(400)); map.putEqualOrdinals(5, list(500)); map.putEqualOrdinals(6, list(600)); map.putEqualOrdinals(7, list(700)); map.putEqualOrdinals(8, list(800)); map.putEqualOrdinals(9, list(900)); map.putEqualOrdinals(10, list(1000)); map.buildToOrdinalIdentityMapping(); filter = new DiffEqualOrdinalFilter(map); } @Test public void separatesListsIntoMatchedAndUnmatchedLists() { IntList fromOrdinals = list(3, 2, 4, 1); IntList toOrdinals = list(200, 100, 300, 500); filter.filter(fromOrdinals, toOrdinals); assertList(filter.getMatchedFromOrdinals(), 3, 2, 1); assertList(filter.getMatchedToOrdinals(), 200, 100, 300); assertList(filter.getUnmatchedFromOrdinals(), 4); assertList(filter.getUnmatchedToOrdinals(), 500); } @Test public void handlesOrdinalsMissingFromMap() { IntList fromOrdinals = list(3, 2, 4, 1, 9999); IntList toOrdinals = list(200, 100, 300, 500, 9999); filter.filter(fromOrdinals, toOrdinals); assertList(filter.getMatchedFromOrdinals(), 3, 2, 1); assertList(filter.getMatchedToOrdinals(), 200, 100, 300); assertList(filter.getUnmatchedFromOrdinals(), 4, 9999); assertList(filter.getUnmatchedToOrdinals(), 500, 9999); } private IntList list(int... ordinals) { IntList list = new IntList(ordinals.length); for(int i=0;i<ordinals.length;i++) { list.add(ordinals[i]); } return list; } private void assertList(IntList list, int... expectedEntries) { Assert.assertEquals(expectedEntries.length, list.size()); for(int i=0;i<list.size();i++) { Assert.assertEquals(expectedEntries[i], list.get(i)); } } }
8,653
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/diff/exact/DiffEqualOrdinalMapTest.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.tools.diff.exact; import com.netflix.hollow.core.util.IntList; import com.netflix.hollow.tools.diff.exact.DiffEqualOrdinalMap.MatchIterator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DiffEqualOrdinalMapTest { private DiffEqualOrdinalMap map; @Before public void setUp() { map = new DiffEqualOrdinalMap(10); map.putEqualOrdinals(1, list(1, 2, 3)); map.putEqualOrdinals(2, list(4, 5, 6)); map.putEqualOrdinals(3, list(7, 8, 9)); map.putEqualOrdinals(100, list(5025)); } @Test public void testFromOrdinals() { assertMatchIterator(map.getEqualOrdinals(1), 1, 2, 3); assertMatchIterator(map.getEqualOrdinals(2), 4, 5, 6); assertMatchIterator(map.getEqualOrdinals(3), 7, 8, 9); assertMatchIterator(map.getEqualOrdinals(100), 5025); assertMatchIterator(map.getEqualOrdinals(200)); } @Test public void testFromIdentityOrdinals() { Assert.assertEquals(1, map.getIdentityFromOrdinal(1)); Assert.assertEquals(4, map.getIdentityFromOrdinal(2)); Assert.assertEquals(7, map.getIdentityFromOrdinal(3)); Assert.assertEquals(5025, map.getIdentityFromOrdinal(100)); Assert.assertEquals(-1, map.getIdentityFromOrdinal(200)); } @Test public void testToIdentityOrdinals() { map.buildToOrdinalIdentityMapping(); Assert.assertEquals(1, map.getIdentityToOrdinal(1)); Assert.assertEquals(1, map.getIdentityToOrdinal(2)); Assert.assertEquals(1, map.getIdentityToOrdinal(3)); Assert.assertEquals(4, map.getIdentityToOrdinal(4)); Assert.assertEquals(4, map.getIdentityToOrdinal(5)); Assert.assertEquals(4, map.getIdentityToOrdinal(6)); Assert.assertEquals(7, map.getIdentityToOrdinal(7)); Assert.assertEquals(7, map.getIdentityToOrdinal(8)); Assert.assertEquals(7, map.getIdentityToOrdinal(9)); Assert.assertEquals(5025, map.getIdentityToOrdinal(5025)); Assert.assertEquals(-1, map.getIdentityToOrdinal(200)); } private void assertMatchIterator(MatchIterator iter, int... values) { for(int i=0;i<values.length;i++) { Assert.assertTrue(iter.hasNext()); Assert.assertEquals(values[i], iter.next()); } Assert.assertFalse(iter.hasNext()); } private IntList list(int... values) { IntList list = new IntList(values.length); for(int i=0;i<values.length;i++) { list.add(values[i]); } return list; } }
8,654
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/stringifier/HollowRecordJsonStringifierTest.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.tools.stringifier; import static com.netflix.hollow.tools.stringifier.HollowStringifier.INDENT; import static com.netflix.hollow.tools.stringifier.HollowStringifier.NEWLINE; import com.netflix.hollow.api.objects.HollowRecord; 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 com.netflix.hollow.test.model.TestTypeA; import java.io.IOException; import java.io.StringWriter; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class HollowRecordJsonStringifierTest extends AbstractHollowRecordStringifierTest { @Test public void testStringifyTypeWithString() throws IOException { String msg = "String types should be printed correctly"; Assert.assertEquals(msg, "\"foo\"", stringifyType(TypeWithString.class, true, false, new TypeWithString("foo"))); Assert.assertEquals(msg, "{" + NEWLINE + INDENT + "\"value\": {" + NEWLINE + INDENT + INDENT + "\"value\": \"foo\"" + NEWLINE + INDENT + "}" + NEWLINE + "}", stringifyType(TypeWithString.class, true, true, new TypeWithString("foo"))); } @Test public void testStringifyTypeWithPrimitive() throws IOException { String msg = "Primitive types should be printed correctly"; Assert.assertEquals(msg, "1337", stringifyType(TypeWithPrimitive.class, true, false, new TypeWithPrimitive(1337))); Assert.assertEquals(msg, "{" + NEWLINE + INDENT + "\"value\": 1337" + NEWLINE + "}", stringifyType(TypeWithPrimitive.class, true, true, new TypeWithPrimitive(1337))); } @Test public void testStringifyTypeWithNonPrimitive() throws IOException { String msg = "Non-primitive types should be printed correctly"; Assert.assertEquals(msg, "31337", stringifyType(TypeWithNonPrimitive.class, true, false, new TypeWithNonPrimitive(31337))); Assert.assertEquals(msg, "{" + NEWLINE + INDENT + "\"value\": {" + NEWLINE + INDENT + INDENT + "\"value\": 31337" + NEWLINE + INDENT + "}" + NEWLINE + "}", stringifyType(TypeWithNonPrimitive.class, true, true, new TypeWithNonPrimitive(31337))); } @Test public void testStringifyTypeWithNestedPrimitiveType() throws IOException { String msg = "Types with nested primitives should be printed correctly"; Assert.assertEquals(msg, "{" + NEWLINE + INDENT + "\"value\": 42.0," + NEWLINE + INDENT + "\"nestedType\": 42" + NEWLINE + "}", stringifyType(TypeWithNestedPrimitive.class, true, false, new TypeWithNestedPrimitive(42.0, new TypeWithPrimitive(42)))); Assert.assertEquals(msg, "{" + NEWLINE + INDENT + "\"value\": {" + NEWLINE + INDENT + INDENT + "\"value\": 42.0" + NEWLINE + INDENT + "}," + NEWLINE + INDENT + "\"nestedType\": {" + NEWLINE + INDENT + INDENT + "\"value\": 42" + NEWLINE + INDENT + "}" + NEWLINE + "}", stringifyType(TypeWithNestedPrimitive.class, true, true, new TypeWithNestedPrimitive(42.0, new TypeWithPrimitive(42)))); } @Test public void testStringifyTypeWithNestedNonPrimitiveType() throws IOException { // with prettyPrint String msg = "Types with nested non-primitives should be printed correctly"; Assert.assertEquals(msg, "{" + NEWLINE + INDENT + "\"value\": 42.0," + NEWLINE + INDENT + "\"nestedType\": 42" + NEWLINE + "}", stringifyType(TypeWithNestedNonPrimitive.class, true, false, new TypeWithNestedNonPrimitive(42.0, new TypeWithNonPrimitive(42)))); Assert.assertEquals(msg, "{" + NEWLINE + INDENT + "\"value\": {" + NEWLINE + INDENT + INDENT + "\"value\": 42.0" + NEWLINE + INDENT + "}," + NEWLINE + INDENT + "\"nestedType\": {" + NEWLINE + INDENT + INDENT + "\"value\": {" + NEWLINE + INDENT + INDENT + INDENT + "\"value\": 42" + NEWLINE + INDENT + INDENT + "}" + NEWLINE + INDENT + "}" + NEWLINE + "}", stringifyType(TypeWithNestedNonPrimitive.class, true, true, new TypeWithNestedNonPrimitive(42.0, new TypeWithNonPrimitive(42)))); } @Test public void testStringifyWithoutPrettyPrint() throws IOException { String msg = "Types should be printed correctly without prettyPrint"; // without prettyPrint Assert.assertEquals(msg, "{" + "\"value\": 42.0," + "\"nestedType\": 42" + "}", stringifyType(TypeWithNestedNonPrimitive.class, false, false, new TypeWithNestedNonPrimitive(42.0, new TypeWithNonPrimitive(42)))); Assert.assertEquals(msg, "{" + "\"value\": {" + "\"value\": 42.0" + "}," + "\"nestedType\": {" + "\"value\": {" + "\"value\": 42" + "}" + "}" + "}", stringifyType(TypeWithNestedNonPrimitive.class, false, true, new TypeWithNestedNonPrimitive(42.0, new TypeWithNonPrimitive(42)))); } @Test public void testStringifyMultipleRecords() throws IOException { Assert.assertEquals("Multiple records should be printed correctly", "\"foo\"" + NEWLINE + "\"bar\"", stringifyType(TypeWithString.class, true, false, new TypeWithString("foo"), new TypeWithString("bar"))); } @Test public void testStringifyIterator() throws IOException { HollowRecordJsonStringifier recordJsonStringifier = new HollowRecordJsonStringifier(false, false); HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.useDefaultHashKeys(); mapper.add(new TestTypeA(1, "one")); mapper.add(new TestTypeA(2, "two")); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); Iterable<HollowRecord> genericHollowObjects = (Iterable) Arrays.asList(new GenericHollowObject(readEngine, "TestTypeA", 0), new GenericHollowObject(readEngine, "TestTypeA", 1)); StringWriter writer = new StringWriter(); recordJsonStringifier.stringify(writer, genericHollowObjects); Assert.assertEquals("Multiple records should be printed correctly", "[{\"id\": 1,\"name\": {\"value\": \"one\"}},{\"id\": 2,\"name\": {\"value\": \"two\"}}]", writer.toString()); } private static <T> String stringifyType(Class<T> clazz, boolean prettyPrint, boolean expanded, T... instances) throws IOException { HollowRecordJsonStringifier stringifier = new HollowRecordJsonStringifier(prettyPrint, !expanded); // HollowRecordJsonStringifier stringifier = expanded // ? new HollowRecordJsonStringifier(prettyPrint, false) : new HollowRecordJsonStringifier(); return stringifyType(clazz, stringifier, instances); } }
8,655
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/stringifier/HollowRecordStringifierTest.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.tools.stringifier; import static com.netflix.hollow.tools.stringifier.HollowStringifier.INDENT; import static com.netflix.hollow.tools.stringifier.HollowStringifier.NEWLINE; import com.netflix.hollow.api.objects.HollowRecord; 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 com.netflix.hollow.test.model.TestTypeA; import java.io.IOException; import java.io.StringWriter; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; /** * Unit tests for the HollowRecordStringifier. */ public class HollowRecordStringifierTest extends AbstractHollowRecordStringifierTest { @Test public void testStringifyTypeWithString() throws IOException { String msg = "String types should be printed correctly"; Assert.assertEquals(msg, "foo", stringifyType(TypeWithString.class, false, new TypeWithString("foo"))); Assert.assertEquals(msg, "(TypeWithString) (ordinal 0)" + NEWLINE + INDENT + "value: (String) (ordinal 0)" + NEWLINE + INDENT + INDENT + "value: foo", stringifyType(TypeWithString.class, true, new TypeWithString("foo"))); } @Test public void testStringifyTypeWithPrimitive() throws IOException { String msg = "Primitive types should be printed correctly"; Assert.assertEquals(msg, "1337", stringifyType(TypeWithPrimitive.class, false, new TypeWithPrimitive(1337))); Assert.assertEquals(msg, "(TypeWithPrimitive) (ordinal 0)" + NEWLINE + INDENT + "value: 1337", stringifyType(TypeWithPrimitive.class, true, new TypeWithPrimitive(1337))); } @Test public void testStringifyTypeWithNonPrimitive() throws IOException { String msg = "Non-primitive types should be printed correctly"; Assert.assertEquals(msg, "31337", stringifyType(TypeWithNonPrimitive.class, false, new TypeWithNonPrimitive(31337))); Assert.assertEquals(msg, "(TypeWithNonPrimitive) (ordinal 0)" + NEWLINE + INDENT + "value: (Integer) (ordinal 0)" + NEWLINE + INDENT + INDENT + "value: 31337", stringifyType(TypeWithNonPrimitive.class, true, new TypeWithNonPrimitive(31337))); } @Test public void testStringifyTypeWithNestedPrimitiveType() throws IOException { String msg = "Types with nested primitives should be printed correctly"; Assert.assertEquals(msg, NEWLINE + INDENT + "value: 42.0" + NEWLINE + INDENT + "nestedType: 42", stringifyType(TypeWithNestedPrimitive.class, false, new TypeWithNestedPrimitive(42.0, new TypeWithPrimitive(42)))); Assert.assertEquals(msg, "(TypeWithNestedPrimitive) (ordinal 0)" + NEWLINE + INDENT + "value: (Double) (ordinal 0)" + NEWLINE + INDENT + INDENT + "value: 42.0" + NEWLINE + INDENT + "nestedType: (TypeWithPrimitive) (ordinal 0)" + NEWLINE + INDENT + INDENT + "value: 42", stringifyType(TypeWithNestedPrimitive.class, true, new TypeWithNestedPrimitive(42.0, new TypeWithPrimitive(42)))); } @Test public void testStringifyTypeWithNestedNonPrimitiveType() throws IOException { String msg = "Types with nested non-primitives should be printed correctly"; Assert.assertEquals(msg, NEWLINE + INDENT + "value: 42.0" + NEWLINE + INDENT + "nestedType: 42", stringifyType(TypeWithNestedNonPrimitive.class, false, new TypeWithNestedNonPrimitive(42.0, new TypeWithNonPrimitive(42)))); Assert.assertEquals(msg, "(TypeWithNestedNonPrimitive) (ordinal 0)" + NEWLINE + INDENT + "value: (Double) (ordinal 0)" + NEWLINE + INDENT + INDENT + "value: 42.0" + NEWLINE + INDENT + "nestedType: (TypeWithNonPrimitive) (ordinal 0)" + NEWLINE + INDENT + INDENT + "value: (Integer) (ordinal 0)" + NEWLINE + INDENT + INDENT + INDENT + "value: 42", stringifyType(TypeWithNestedNonPrimitive.class, true, new TypeWithNestedNonPrimitive(42.0, new TypeWithNonPrimitive(42)))); } @Test public void testStringifyMultipleRecords() throws IOException { Assert.assertEquals("Multiple records should be printed correctly", "foo" + NEWLINE + "bar", stringifyType(TypeWithString.class, false, new TypeWithString("foo"), new TypeWithString("bar"))); } @Test public void testStringifyIterator() throws IOException { HollowRecordStringifier recordStringifier = new HollowRecordStringifier(); HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.useDefaultHashKeys(); mapper.add(new TestTypeA(1, "one")); mapper.add(new TestTypeA(2, "two")); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); Iterable<HollowRecord> genericHollowObjects = (Iterable) Arrays.asList(new GenericHollowObject(readEngine, "TestTypeA", 0), new GenericHollowObject(readEngine, "TestTypeA", 1)); StringWriter writer = new StringWriter(); recordStringifier.stringify(writer, genericHollowObjects); Assert.assertEquals("Multiple records should be printed correctly", "[\n" + " id: 1\n" + " name: one,\n" + " id: 2\n" + " name: two" + "\n]", writer.toString()); } private static <T> String stringifyType(Class<T> clazz, boolean expanded, T... instances) throws IOException { HollowRecordStringifier stringifier = expanded ? new HollowRecordStringifier(true, true, false) : new HollowRecordStringifier(); return stringifyType(clazz, stringifier, instances); } }
8,656
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/stringifier/AbstractHollowRecordStringifierTest.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.tools.stringifier; import static com.netflix.hollow.tools.stringifier.HollowStringifier.NEWLINE; 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.io.StringWriter; /** * Code shared between HollowRecordStringifierTest and HollowRecordJsonStringifierTest. */ public class AbstractHollowRecordStringifierTest { static class TypeWithString { private final String value; public TypeWithString(String value) { this.value = value; } } static class TypeWithPrimitive { private final int value; public TypeWithPrimitive(int value) { this.value = value; } } static class TypeWithNonPrimitive { private final Integer value; public TypeWithNonPrimitive(Integer value) { this.value = value; } } static class TypeWithNestedPrimitive { private final Double value; private final TypeWithPrimitive nestedType; public TypeWithNestedPrimitive(Double value, TypeWithPrimitive nestedType) { this.value = value; this.nestedType = nestedType; } } static class TypeWithNestedNonPrimitive { private final Double value; private final TypeWithNonPrimitive nestedType; public TypeWithNestedNonPrimitive(Double value, TypeWithNonPrimitive nestedType) { this.value = value; this.nestedType = nestedType; } } /** * Sends instances of a type through the HollowRecordStringifier. This concatenates records * for all the instances, separated by newlines. */ protected static <T, S extends HollowStringifier> String stringifyType( Class<T> clazz, HollowStringifier<S> stringifier, T... instances) throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper objectMapper = new HollowObjectMapper(writeStateEngine); // add our types and records to the writeStateEngine objectMapper.initializeTypeState(clazz); for (T instance : instances) { objectMapper.add(instance); } HollowReadStateEngine readStateEngine = new HollowReadStateEngine(); // simulate a roundtrip to copy our types and records into the readStateEngine StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine, null); StringWriter writer = new StringWriter(); // use the version of stringify that takes a Writer, since the non-Writer version calls this stringifier.stringify(writer, readStateEngine, clazz.getSimpleName(), 0); // join all records with newlines for (int i = 1; i < instances.length; i++) { writer.append(NEWLINE); stringifier.stringify(writer, readStateEngine, clazz.getSimpleName(), i); } return writer.toString(); } }
8,657
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/patch
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/patch/delta/HollowStateDeltaPatcherTest.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.tools.patch.delta; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; 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.util.StateEngineRoundTripper; 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.HollowTypeName; import com.netflix.hollow.tools.checksum.HollowChecksum; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; public class HollowStateDeltaPatcherTest { @Test public void test() throws IOException { HollowReadStateEngine state1 = constructState1(); HollowReadStateEngine state2 = constructState2(); HollowStateDeltaPatcher patcher = new HollowStateDeltaPatcher(state1, state2); patcher.prepareInitialTransition(); ByteArrayOutputStream delta1 = new ByteArrayOutputStream(); HollowBlobWriter writer = new HollowBlobWriter(patcher.getStateEngine()); writer.writeDelta(delta1); ByteArrayOutputStream reverseDelta1 = new ByteArrayOutputStream(); writer.writeReverseDelta(reverseDelta1); patcher.prepareFinalTransition(); ByteArrayOutputStream delta2 = new ByteArrayOutputStream(); writer = new HollowBlobWriter(patcher.getStateEngine()); writer.writeDelta(delta2); ByteArrayOutputStream reverseDelta2 = new ByteArrayOutputStream(); writer.writeReverseDelta(reverseDelta2); patcher.getStateEngine().prepareForNextCycle(); HollowBlobReader reader = new HollowBlobReader(state1); reader.applyDelta(HollowBlobInput.serial(delta1.toByteArray())); reader.applyDelta(HollowBlobInput.serial(delta2.toByteArray())); // state1 corresponds to final state assertEquals("true", state1.getHeaderTags().get("final_state")); assertNull(state1.getHeaderTag("origin_state")); HollowChecksum checksum1 = HollowChecksum.forStateEngineWithCommonSchemas(state1, state2); HollowChecksum checksum2 = HollowChecksum.forStateEngineWithCommonSchemas(state2, state1); assertEquals(checksum1, checksum2); // reverse deltas to back to original state reader.applyDelta(HollowBlobInput.serial(reverseDelta2.toByteArray())); reader.applyDelta(HollowBlobInput.serial(reverseDelta1.toByteArray())); // state1 corresponds to origin state so the origin state header tag is present assertEquals("true", state1.getHeaderTag("origin_state")); assertNull(state1.getHeaderTag("final_state")); } private HollowReadStateEngine constructState1() throws IOException { HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); stateEngine.getHeaderTags().put("origin_state", "true"); HollowObjectMapper mapper = new HollowObjectMapper(stateEngine); mapper.add(new TypeB1(1, 0)); mapper.add(new TypeA1(1, new TypeB1(2, 1))); mapper.add(new TypeA1(2, new TypeB1(3, 2))); mapper.add(new TypeA1(999, new TypeB1(999, 3))); HollowReadStateEngine state1 = StateEngineRoundTripper.roundTripSnapshot(stateEngine); stateEngine.prepareForNextCycle(); mapper.add(new TypeB1(1, 0)); mapper.add(new TypeA1(1, new TypeB1(2, 1))); mapper.add(new TypeA1(2, new TypeB1(3, 2))); mapper.add(new TypeA1(4, new TypeB1(5, 4))); mapper.add(new TypeB1(6, 7)); StateEngineRoundTripper.roundTripDelta(stateEngine, state1); return state1; } private HollowReadStateEngine constructState2() throws IOException { HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); stateEngine.getHeaderTags().put("final_state", "true"); HollowObjectMapper mapper = new HollowObjectMapper(stateEngine); mapper.add(new TypeB2(1, 100)); mapper.add(new TypeA2(1, new TypeB2(2, 101))); mapper.add(new TypeA2(2, new TypeB2(7, 102))); mapper.add(new TypeA2(5, new TypeB2(8, 103))); mapper.add(new TypeA2(4, new TypeB2(5, 104))); mapper.add(new TypeA2(999, new TypeB2(999, 105))); mapper.add(new TypeA2(6, new TypeB2(9, 106))); HollowReadStateEngine state2 = StateEngineRoundTripper.roundTripSnapshot(stateEngine); stateEngine.prepareForNextCycle(); mapper.add(new TypeB2(1, 100)); mapper.add(new TypeA2(1, new TypeB2(2, 101))); mapper.add(new TypeA2(2, new TypeB2(7, 102))); mapper.add(new TypeA2(5, new TypeB2(8, 103))); mapper.add(new TypeA2(4, new TypeB2(5, 104))); mapper.add(new TypeA2(6, new TypeB2(9, 106))); StateEngineRoundTripper.roundTripDelta(stateEngine, state2); return state2; } @SuppressWarnings("unused") @HollowTypeName(name="TypeA") private static class TypeA1 { int a1; TypeB1 b; public TypeA1(int a1, TypeB1 b) { this.a1 = a1; this.b = b; } } @SuppressWarnings("unused") @HollowTypeName(name="TypeB") private static class TypeB1 { int b1; int b2; public TypeB1(int b1, int b2) { this.b1 = b1; this.b2 = b2; } } @SuppressWarnings("unused") @HollowTypeName(name="TypeA") private static class TypeA2 { int a1; TypeB2 b; public TypeA2(int a1, TypeB2 b) { this.a1 = a1; this.b = b; } } @SuppressWarnings("unused") @HollowTypeName(name="TypeB") private static class TypeB2 { int b1; float b3; public TypeB2(int b1, float b3) { this.b1 = b1; this.b3 = b3; } } }
8,658
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/history/HollowHistoryKeyIndexTest.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.tools.history; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; 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.util.IntList; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.tools.history.keyindex.HollowHistoryKeyIndex; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowHistoryKeyIndexTest extends AbstractStateEngineTest { private HollowObjectSchema aSchema; private HollowObjectSchema bSchema; @Before public void setUp() { aSchema = new HollowObjectSchema("A", 3); aSchema.addField("id", FieldType.FLOAT); aSchema.addField("anotherField", FieldType.LONG); aSchema.addField("bRef", FieldType.REFERENCE, "B"); bSchema = new HollowObjectSchema("B", 2, new PrimaryKey("B", "id")); bSchema.addField("id", FieldType.STRING); bSchema.addField("anotherField", FieldType.DOUBLE); super.setUp(); } @Test public void extractsAndIndexesKeyRecords() throws IOException { HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeStateEngine); HollowHistory history = new HollowHistory(readEngine, 1L, 1); HollowHistoryKeyIndex keyIdx = new HollowHistoryKeyIndex(history); keyIdx.addTypeIndex("A", "id", "bRef.id"); keyIdx.addTypeIndex("B", "id"); keyIdx.indexTypeField("A", "bRef"); keyIdx.indexTypeField("A", "id"); keyIdx.indexTypeField("B", "id"); addRecord(1.1F, "one", 1L, 1.1D); addRecord(2.2F, "two", 2L, 2.2D); addRecord(3.3F, "one", 3L, 1.1D); roundTripSnapshot(); assertResults(keyIdx, "A", "two"); keyIdx.update(readStateEngine, false); addRecord(1.1F, "one", 1L, 1.1D); //addRecord(2.2F, "2.2", 2L, 2.2D); addRecord(3.3F, "one", 3L, 1.1D); addRecord(4.4F, "four", 4L, 4.4D); roundTripDelta(); keyIdx.update(readStateEngine, true); addRecord(1.1F, "one", 1L, 1.1D); addRecord(5.5F, "five!", 5L, 5.5D); addRecord(3.3F, "one", 3L, 1.1D); addRecord(4.4F, "four", 4L, 4.4D); roundTripDelta(); keyIdx.update(readStateEngine, true); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("A"); Assert.assertEquals(0, keyIdx.getRecordKeyOrdinal(typeState, 0)); Assert.assertEquals("1.1:one", keyIdx.getKeyDisplayString("A", 0)); Assert.assertEquals(4, keyIdx.getRecordKeyOrdinal(typeState, 1)); Assert.assertEquals("5.5:five!", keyIdx.getKeyDisplayString("A", 4)); Assert.assertEquals(2, keyIdx.getRecordKeyOrdinal(typeState, 2)); Assert.assertEquals("3.3:one", keyIdx.getKeyDisplayString("A", 2)); Assert.assertEquals(3, keyIdx.getRecordKeyOrdinal(typeState, 3)); Assert.assertEquals("4.4:four", keyIdx.getKeyDisplayString("A", 3)); Assert.assertEquals("2.2:two", keyIdx.getKeyDisplayString("A", 1)); /// query returns all matching keys assertResults(keyIdx, "A", "one", 0, 2); assertResults(keyIdx, "A", "two", 1); assertResults(keyIdx, "A", "four", 3); assertResults(keyIdx, "A", "five!", 4); assertResults(keyIdx, "A", "1.1", 0); assertResults(keyIdx, "A", "2.2", 1); assertResults(keyIdx, "A", "3.3", 2); assertResults(keyIdx, "A", "4.4", 3); assertResults(keyIdx, "A", "5.5", 4); assertResults(keyIdx, "A", "notfound"); assertResults(keyIdx, "B", "one", 0); assertResults(keyIdx, "B", "two", 1); assertResults(keyIdx, "B", "four", 2); assertResults(keyIdx, "B", "five!", 3); } private void assertResults(HollowHistoryKeyIndex keyIdx, String type, String query, int... expectedResults) { IntList actualResults = keyIdx.getTypeKeyIndexes().get(type).queryIndexedFields(query); Assert.assertEquals(expectedResults.length, actualResults.size()); actualResults.sort(); for(int i=0;i<expectedResults.length;i++) { Assert.assertEquals(expectedResults[i], actualResults.get(i)); } } private void addRecord(float aId, String bId, long anotherAField, double anotherBField) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(bSchema); bRec.setString("id", bId); bRec.setDouble("anotherField", anotherBField); int bOrdinal = writeStateEngine.add("B", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(aSchema); aRec.setFloat("id", aId); aRec.setReference("bRef", bOrdinal); aRec.setLong("anotherField", anotherAField); writeStateEngine.add("A", aRec); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState aWriteState = new HollowObjectTypeWriteState(aSchema); HollowObjectTypeWriteState bWriteState = new HollowObjectTypeWriteState(bSchema); writeStateEngine.addTypeState(aWriteState); writeStateEngine.addTypeState(bWriteState); } }
8,659
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/history/HollowHistoryTest.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.tools.history; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.util.IntList; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.tools.history.keyindex.HollowHistoryKeyIndex; import com.netflix.hollow.tools.history.keyindex.HollowHistoryTypeKeyIndex; import java.io.IOException; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowHistoryTest extends AbstractStateEngineTest { ///TODO: Use key index to test double snapshot behavior. private HollowObjectSchema aSchema; private HollowObjectSchema bSchema; private HollowObjectSchema emptyTypeSchema; private static final String B_TYPE = "B"; private static final String B_FN_PREFIX = "b"; @Override @Before public void setUp() { emptyTypeSchema = new HollowObjectSchema("Empty", 1); emptyTypeSchema.addField("value", FieldType.STRING); aSchema = new HollowObjectSchema("A", 3, "a1"); aSchema.addField("a1", FieldType.INT); aSchema.addField("a2", FieldType.INT); aSchema.addField("a3", FieldType.INT); bSchema = new HollowObjectSchema(B_TYPE, 2, B_FN_PREFIX + "1"); bSchema.addField(B_FN_PREFIX + "1", FieldType.INT); bSchema.addField(B_FN_PREFIX + "2", FieldType.INT); super.setUp(); } @Test public void test() throws IOException { addRecord(1, 2, 3); addRecord(2, 3, 4); addRecord(3, 4, 5); addRecord(4, 5, 6); roundTripSnapshot(); HollowHistory history = new HollowHistory(readStateEngine, 1L, 5); // No needed since it can auto discover from schema's primary key // history.getKeyIndex().addTypeIndex("A", "a1"); history.getKeyIndex().indexTypeField("A", "a1"); addRecord(1, 2, 3); /// addRecord(2, 3, 4); removed record addRecord(3, 4, 5); addRecord(4, 5, 6); addRecord(2, 3, 7); roundTripDelta(); history.deltaOccurred(2L); addRecord(1, 2, 3); addRecord(3, 4, 7); /// addRecord(3, 4, 5); removed record addRecord(4, 5, 6); addRecord(2, 3, 7); roundTripSnapshot(); history.doubleSnapshotOccurred(readStateEngine, 3L); super.setUp(); //addRecord(3, 4, 7); addRecord(4, 5, 7); addRecord(1, 2, 3); // addRecord(4, 5, 6); /// removed record addRecord(2, 3, 7); //addRecord(5, 6, 7); roundTripSnapshot(); history.doubleSnapshotOccurred(readStateEngine, 4L); addRecord(1, 2, 3); addRecord(3, 4, 7); //addRecord(4, 5, 7); addRecord(5, 6, 7); //addRecord(2, 3, 7); roundTripDelta(); history.deltaOccurred(5L); assertRecord(retrieveRemovedRecord(history, 2L, 2), 2, 3, 4); assertRecord(retrieveAddedRecord (history, 2L, 2), 2, 3, 7); assertRecord(retrieveRemovedRecord(history, 3L, 3), 3, 4, 5); assertRecord(retrieveAddedRecord (history, 3L, 3), 3, 4, 7); assertRecord(retrieveRemovedRecord(history, 4L, 4), 4, 5, 6); assertRecord(retrieveAddedRecord (history, 4L, 4), 4, 5, 7); assertRecord(retrieveRemovedRecord(history, 4L, 3), 3, 4, 7); assertRecord(retrieveRemovedRecord(history, 5L, 4), 4, 5, 7); assertRecord(retrieveRemovedRecord(history, 5L, 2), 2, 3, 7); assertRecord(retrieveAddedRecord (history, 5L, 5), 5, 6, 7); assertRecord(retrieveAddedRecord (history, 5L, 3), 3, 4, 7); } @Test public void testNewType() throws IOException { addRecord(1, 2, 3); addRecord(2, 3, 4); roundTripSnapshot(); HollowHistory history = new HollowHistory(readStateEngine, 1L, 5); setupKeyIndex(readStateEngine, history); // Double Snapshot - With New Type { initWriteStateEngine(); addRecord(1, 2, 3); // addRecord(2, 3, 4); removed record addRecord(3, 4, 5); addRecord(bSchema, B_FN_PREFIX, 1, 2); roundTripSnapshot(); setupKeyIndex(readStateEngine, history); history.doubleSnapshotOccurred(readStateEngine, 2L); assertRecord(retrieveRemovedRecord(history, 2L, 2), 2, 3, 4); assertRecord(retrieveAddedRecord(history, 2L, 3), 3, 4, 5); // First cycle with new type, it does not know assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 1), B_FN_PREFIX, 1, 2); } { addRecord(1, 2, 3); addRecord(2, 3, 4); addRecord(3, 4, 5); // addRecord(bSchema, B_FN_PREFIX, 1, 2); remove record addRecord(bSchema, B_FN_PREFIX, 2, 3); roundTripDelta(); history.deltaOccurred(3L); assertRecord(retrieveAddedRecord(history, 3L, 2), 2, 3, 4); assertRecord(retrieveRemovedRecord(history, 3L, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveAddedRecord(history, 3L, B_TYPE, 2), B_FN_PREFIX, 2, 3); } } @Test public void testRemoveType() throws IOException { addRecord(1, 2, 3); addRecord(2, 3, 4); addRecord(bSchema, B_FN_PREFIX, 1, 2); addRecord(bSchema, B_FN_PREFIX, 2, 3); roundTripSnapshot(); HollowHistory history = new HollowHistory(readStateEngine, 1L, 5); setupKeyIndex(readStateEngine, history); // Double Snapshot - With New Type { initWriteStateEngine(); Assert.assertNull(writeStateEngine.getTypeState(B_TYPE)); addRecord(1, 2, 3); // addRecord(2, 3, 4); addRecord(3, 4, 5); // addRecord(bSchema, B_FN_PREFIX, 1, 2); // addRecord(bSchema, B_FN_PREFIX, 2, 3); roundTripSnapshot(); setupKeyIndex(readStateEngine, history); history.doubleSnapshotOccurred(readStateEngine, 2L); assertRecord(retrieveRemovedRecord(history, 2L, 2), 2, 3, 4); assertRecord(retrieveAddedRecord(history, 2L, 3), 3, 4, 5); assertRecord(retrieveRemovedRecord(history, 2L, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveRemovedRecord(history, 2L, B_TYPE, 2), B_FN_PREFIX, 2, 3); } { addRecord(1, 2, 3); addRecord(2, 3, 4); // Added it back addRecord(3, 4, 5); roundTripDelta(); history.deltaOccurred(3L); assertRecord(retrieveAddedRecord(history, 3L, 2), 2, 3, 4); } } @Test public void testAddRemoveTypeThenDelta() throws IOException { addRecord(1, 2, 3); addRecord(2, 3, 4); roundTripSnapshot(); long version = 1; HollowHistory history = new HollowHistory(readStateEngine, 1, 10); setupKeyIndex(readStateEngine, history); { initWriteStateEngine(); addRecord(1, 2, 3); addRecord(2, 3, 4); // Add new type addRecord(bSchema, B_FN_PREFIX, 1, 2); addRecord(bSchema, B_FN_PREFIX, 2, 3); roundTripSnapshot(); // Populate the B om the history primiary key indexes setupKeyIndex(readStateEngine, history); history.doubleSnapshotOccurred(readStateEngine, 2); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 2), B_FN_PREFIX, 2, 3); version++; } { initWriteStateEngine(); addRecord(1, 2, 3); addRecord(2, 3, 4); // Remove instances of B roundTripSnapshot(); setupKeyIndex(readStateEngine, history); history.doubleSnapshotOccurred(readStateEngine, 3); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 2), B_FN_PREFIX, 2, 3); assertRecord(retrieveRemovedRecord(history, 3, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveRemovedRecord(history, 3, B_TYPE, 2), B_FN_PREFIX, 2, 3); } { addRecord(1, 2, 3); addRecord(2, 3, 4); roundTripDelta(); history.deltaOccurred(4); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 2), B_FN_PREFIX, 2, 3); assertRecord(retrieveRemovedRecord(history, 3, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveRemovedRecord(history, 3, B_TYPE, 2), B_FN_PREFIX, 2, 3); } { initWriteStateEngine(); addRecord(1, 2, 3); addRecord(2, 3, 4); roundTripSnapshot(); setupKeyIndex(readStateEngine, history); history.doubleSnapshotOccurred(readStateEngine, 5); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveAddedRecord(history, 2L, B_TYPE, 2), B_FN_PREFIX, 2, 3); assertRecord(retrieveRemovedRecord(history, 3, B_TYPE, 1), B_FN_PREFIX, 1, 2); assertRecord(retrieveRemovedRecord(history, 3, B_TYPE, 2), B_FN_PREFIX, 2, 3); } } @Test public void testHistoricalStates() throws IOException { addRecord(1, 2, 3); roundTripSnapshot(); HollowHistory history = new HollowHistory(readStateEngine, 1L, 2); Assert.assertEquals(0, history.getNumberOfHistoricalStates()); { addRecord(1, 2, 3); addRecord(4, 5, 6); roundTripDelta(); history.deltaOccurred(2L); Assert.assertEquals(1, history.getNumberOfHistoricalStates()); } HollowHistoricalState[] historicalStates; { addRecord(1, 2, 3); roundTripDelta(); history.deltaOccurred(3L); Assert.assertEquals(2, history.getNumberOfHistoricalStates()); historicalStates = history.getHistoricalStates(); } { addRecord(1, 2, 3); addRecord(4, 5, 6); roundTripDelta(); history.deltaOccurred(4L); Assert.assertEquals(2, history.getNumberOfHistoricalStates()); Assert.assertEquals(historicalStates[0], history.getHistoricalStates()[1]); } { history.removeHistoricalStates(1); Assert.assertEquals(1, history.getNumberOfHistoricalStates()); historicalStates = history.getHistoricalStates(); } { addRecord(1, 2, 3); roundTripDelta(); history.deltaOccurred(5L); Assert.assertEquals(2, history.getNumberOfHistoricalStates()); Assert.assertEquals(historicalStates[0], history.getHistoricalStates()[1]); } { history.removeHistoricalStates(history.getNumberOfHistoricalStates()); Assert.assertEquals(0, history.getNumberOfHistoricalStates()); } { addRecord(1, 2, 3); addRecord(4, 5, 6); roundTripDelta(); history.deltaOccurred(6L); Assert.assertEquals(1, history.getNumberOfHistoricalStates()); } } private void setupKeyIndex(HollowReadStateEngine stateEngine, HollowHistory history) { HollowHistoryKeyIndex keyIndex = history.getKeyIndex(); for (String type : stateEngine.getAllTypes()) { HollowTypeReadState typeState = stateEngine.getTypeState(type); HollowSchema schema = typeState.getSchema(); if (schema instanceof HollowObjectSchema) { HollowObjectSchema oSchema = (HollowObjectSchema) schema; PrimaryKey pKey = oSchema.getPrimaryKey(); if (pKey == null) continue; keyIndex.indexTypeField(pKey, stateEngine); System.out.println("Setup KeyIndex: type=" + type + "\t" + pKey); } } } private HollowObject retrieveRemovedRecord(HollowHistory history, long version, int key) { return retrieveRemovedRecord(history, version, "A", key); } private HollowObject retrieveAddedRecord(HollowHistory history, long version, int key) { return retrieveAddedRecord(history, version, "A", key); } private HollowObject retrieveRemovedRecord(HollowHistory history, long version, String type, int key) { HollowHistoricalState historicalState = history.getHistoricalState(version); IntList queryResult = history.getKeyIndex().getTypeKeyIndexes().get(type).queryIndexedFields(String.valueOf(key)); int keyOrdinal = queryResult.get(0); int removedOrdinal = historicalState.getKeyOrdinalMapping().getTypeMapping(type).findRemovedOrdinal(keyOrdinal); return (HollowObject) GenericHollowRecordHelper.instantiate(historicalState.getDataAccess(), type, removedOrdinal); } private HollowObject retrieveAddedRecord(HollowHistory history, long version, String type, int key) { HollowHistoricalState historicalState = history.getHistoricalState(version); Map<String, HollowHistoryTypeKeyIndex> typeKeyIndexes = history.getKeyIndex().getTypeKeyIndexes(); IntList queryResult = typeKeyIndexes.get(type).queryIndexedFields(String.valueOf(key)); int keyOrdinal = queryResult.get(0); int addedOrdinal = historicalState.getKeyOrdinalMapping().getTypeMapping(type).findAddedOrdinal(keyOrdinal); return (HollowObject) GenericHollowRecordHelper.instantiate(historicalState.getDataAccess(), type, addedOrdinal); } private void assertRecord(HollowObject obj, int a1, int a2, int a3) { Assert.assertEquals(a1, obj.getInt("a1")); Assert.assertEquals(a2, obj.getInt("a2")); Assert.assertEquals(a3, obj.getInt("a3")); } @SuppressWarnings("unused") private void printRecord(HollowObject obj) { System.out.println(obj.getInt("a1") + "," + obj.getInt("a2") + "," + obj.getInt("a3")); } private void addRecord(int a1, int a2, int a3) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(aSchema); rec.setInt("a1", a1); rec.setInt("a2", a2); rec.setInt("a3", a3); writeStateEngine.add("A", rec); } private void assertRecord(HollowObject obj, String fnPrefix, int... vals) { for (int i = 0; i < vals.length; i++) { String fn = fnPrefix + (i + 1); Assert.assertEquals(vals[i], obj.getInt(fn)); } } private void addRecord(HollowObjectSchema schema, String fnPrefix, int ... vals) { String bType = schema.getName(); if (writeStateEngine.getTypeState(bType) == null) { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(schema)); } HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); for (int i = 0; i < vals.length; i++) { String fn = fnPrefix + (i + 1); rec.setInt(fn, vals[i]); } writeStateEngine.add(bType, rec); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(aSchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(emptyTypeSchema)); } }
8,660
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/history/HollowHistorySetTest.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.tools.history; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess; 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.Before; import org.junit.Test; public class HollowHistorySetTest extends AbstractStateEngineTest { private HollowSetSchema schema; @Before public void setUp() { schema = new HollowSetSchema("TestSet", "TestObject"); super.setUp(); } @Test public void testHistoricalSet() throws IOException { addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(30, 40, 50); addRecord(40, 50, 60); addRecord(50, 60, 70); roundTripSnapshot(); addRecord(10, 20, 30); addRecord(20, 30, 40); //addRecord(30, 40, 50); addRecord(40, 50, 60); //addRecord(50, 60, 70); addRecord(60, 70, 80); addRecord(70, 80, 90); addRecord(80, 90, 100); roundTripDelta(); HollowHistoricalStateDataAccess history1 = new HollowHistoricalStateCreator().createBasedOnNewDelta(2, readStateEngine); addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(100, 200, 300); //addRecord(30, 40, 50); addRecord(40, 50, 60); // addRecord(50, 60, 70); addRecord(60, 70, 80); // addRecord(70, 80, 90); // addRecord(80, 90, 100); roundTripDelta(); HollowHistoricalStateDataAccess history2 = new HollowHistoricalStateCreator().createBasedOnNewDelta(3, readStateEngine); addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(100, 200, 300); //addRecord(30, 40, 50); addRecord(40, 50, 60); addRecord(200, 300, 400); // addRecord(50, 60, 70); addRecord(60, 70, 80); addRecord(300, 400, 500); // addRecord(70, 80, 90); addRecord(400, 500, 600); // addRecord(80, 90, 100); roundTripDelta(); assertRecord(history1, 0, 10, 20, 30); assertRecord(history1, 1, 20, 30, 40); assertRecord(history1, 2, 30, 40, 50); assertRecord(history1, 3, 40, 50, 60); assertRecord(history1, 4, 50, 60, 70); assertRecord(history2, 0, 10, 20, 30); assertRecord(history2, 1, 20, 30, 40); assertRecord(history2, 3, 40, 50, 60); assertRecord(history2, 5, 60, 70, 80); assertRecord(history2, 6, 70, 80, 90); assertRecord(history2, 7, 80, 90, 100); assertRecord(readStateEngine, 0, 10, 20, 30); assertRecord(readStateEngine, 1, 20, 30, 40); assertRecord(readStateEngine, 2, 100, 200, 300); assertRecord(readStateEngine, 3, 40, 50, 60); assertRecord(readStateEngine, 4, 200, 300, 400); assertRecord(readStateEngine, 5, 60, 70, 80); assertRecord(readStateEngine, 6, 300, 400, 500); assertRecord(readStateEngine, 7, 400, 500, 600); } private void assertRecord(HollowDataAccess dataAccess, int ordinal, int... expectedElements) { HollowSetTypeDataAccess typeDataAccess = (HollowSetTypeDataAccess)dataAccess.getTypeDataAccess("TestSet"); test: for(int expected : expectedElements) { HollowOrdinalIterator iter = typeDataAccess.potentialMatchOrdinalIterator(ordinal, expected); int actual = iter.next(); while(actual != HollowOrdinalIterator.NO_MORE_ORDINALS) { if(actual == expected) continue test; actual = iter.next(); } Assert.fail("Did not find expected element " + expected + " for ordinal " + ordinal); } } private void addRecord(int... elements) { HollowSetWriteRecord rec = new HollowSetWriteRecord(); for(int element : elements) { rec.addElement(element); } writeStateEngine.add("TestSet", rec); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowSetTypeWriteState(schema)); } }
8,661
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/history/HollowHistoryListTest.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.tools.history; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; 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 org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowHistoryListTest extends AbstractStateEngineTest { private HollowListSchema schema; @Before public void setUp() { schema = new HollowListSchema("TestList", "TestObject"); super.setUp(); } @Test public void testHistoricalList() throws IOException { addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(30, 40, 50); addRecord(40, 50, 60); addRecord(50, 60, 70); roundTripSnapshot(); addRecord(10, 20, 30); addRecord(20, 30, 40); //addRecord(30, 40, 50); addRecord(40, 50, 60); //addRecord(50, 60, 70); addRecord(60, 70, 80); addRecord(70, 80, 90); addRecord(80, 90, 100); roundTripDelta(); HollowHistoricalStateDataAccess history1 = new HollowHistoricalStateCreator().createBasedOnNewDelta(2, readStateEngine); addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(100, 200, 300); //addRecord(30, 40, 50); addRecord(40, 50, 60); // addRecord(50, 60, 70); addRecord(60, 70, 80); // addRecord(70, 80, 90); // addRecord(80, 90, 100); roundTripDelta(); HollowHistoricalStateDataAccess history2 = new HollowHistoricalStateCreator().createBasedOnNewDelta(3, readStateEngine); addRecord(10, 20, 30); addRecord(20, 30, 40); addRecord(100, 200, 300); //addRecord(30, 40, 50); addRecord(40, 50, 60); addRecord(200, 300, 400); // addRecord(50, 60, 70); addRecord(60, 70, 80); addRecord(300, 400, 500); // addRecord(70, 80, 90); addRecord(400, 500, 600); // addRecord(80, 90, 100); roundTripDelta(); assertRecord(history1, 0, 10, 20, 30); assertRecord(history1, 1, 20, 30, 40); assertRecord(history1, 2, 30, 40, 50); assertRecord(history1, 3, 40, 50, 60); assertRecord(history1, 4, 50, 60, 70); assertRecord(history2, 0, 10, 20, 30); assertRecord(history2, 1, 20, 30, 40); assertRecord(history2, 3, 40, 50, 60); assertRecord(history2, 5, 60, 70, 80); assertRecord(history2, 6, 70, 80, 90); assertRecord(history2, 7, 80, 90, 100); assertRecord(readStateEngine, 0, 10, 20, 30); assertRecord(readStateEngine, 1, 20, 30, 40); assertRecord(readStateEngine, 2, 100, 200, 300); assertRecord(readStateEngine, 3, 40, 50, 60); assertRecord(readStateEngine, 4, 200, 300, 400); assertRecord(readStateEngine, 5, 60, 70, 80); assertRecord(readStateEngine, 6, 300, 400, 500); assertRecord(readStateEngine, 7, 400, 500, 600); } private void assertRecord(HollowDataAccess dataAccess, int ordinal, int... expectedElements) { HollowListTypeDataAccess typeDataAccess = (HollowListTypeDataAccess)dataAccess.getTypeDataAccess("TestList"); for(int i=0;i<expectedElements.length;i++) { Assert.assertEquals(expectedElements[i], typeDataAccess.getElementOrdinal(ordinal, i)); } } private void addRecord(int... elements) { HollowListWriteRecord rec = new HollowListWriteRecord(); for(int element : elements) { rec.addElement(element); } writeStateEngine.add("TestList", rec); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowListTypeWriteState(schema)); } }
8,662
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/history/HollowHistoryHashKeyTest.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.tools.history; import com.netflix.hollow.api.objects.HollowRecord; 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.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class HollowHistoryHashKeyTest { @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); HollowHistoricalStateDataAccess history0 = new HollowHistoricalStateCreator().createBasedOnNewDelta(0, readEngine); mapper.add(new TestTopLevelObject(1, new Obj(1, "US", 101), new Obj(2, "CA", 200), new Obj(3, "IT", 300), new Obj(4, "GB", 401), new Obj(5, "IT", 500))); StateEngineRoundTripper.roundTripDelta(writeEngine, readEngine); HollowHistoricalStateDataAccess history1 = new HollowHistoricalStateCreator().createBasedOnNewDelta(1, readEngine); history0.setNextState(history1); mapper.add(new TestTopLevelObject(1, new Obj(1, "US", 101), new Obj(2, "CA", 200), new Obj(3, "IT", 302), new Obj(4, "GB", 401), new Obj(5, "IT", 500))); StateEngineRoundTripper.roundTripDelta(writeEngine, readEngine); HollowHistoricalStateDataAccess history2 = new HollowHistoricalStateCreator().createBasedOnNewDelta(2, readEngine); history1.setNextState(history2); history2.setNextState(readEngine); GenericHollowObject obj = new GenericHollowObject(history0, "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")); 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")); 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")); 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")); 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="SetById") @HollowHashKey(fields="id") Set<Obj> setById; @HollowTypeName(name="SetByIdCountry") @HollowHashKey(fields={"id", "country.value"}) Set<Obj> setByIdCountry; Set<Integer> intSet; @HollowTypeName(name="MapById") @HollowHashKey(fields="id") Map<Obj, Integer> mapById; @HollowTypeName(name="MapByIdCountry") @HollowHashKey(fields={"id", "country.value"}) Map<Obj, Integer> mapByIdCountry; Map<Integer, Integer> intMap; public TestTopLevelObject(int id, Obj... elements) { this.id = id; this.setById = new HashSet<Obj>(); this.setByIdCountry = new HashSet<Obj>(); this.intSet = new HashSet<Integer>(); this.mapById = new HashMap<Obj, Integer>(); this.mapByIdCountry = new HashMap<Obj, Integer>(); this.intMap = new HashMap<Integer, Integer>(); for(int i=0;i<elements.length;i++) { setById.add(elements[i]); setByIdCountry.add(elements[i]); intSet.add((int)elements[i].extraValue); mapById.put(elements[i], (int)elements[i].extraValue); mapByIdCountry.put(elements[i], (int)elements[i].extraValue); intMap.put(elements[i].id, (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,663
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/history/HollowHistoryRehashTest.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.tools.history; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; 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.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.tools.history.keyindex.HollowHistoryKeyIndex; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; public class HollowHistoryRehashTest extends AbstractStateEngineTest { private HollowObjectSchema aSchema; private HollowObjectSchema bSchema; @Before public void setUp() { aSchema = new HollowObjectSchema("A", 3); aSchema.addField("id", FieldType.FLOAT); aSchema.addField("anotherField", FieldType.LONG); aSchema.addField("bRef", FieldType.REFERENCE, "B"); bSchema = new HollowObjectSchema("B", 2, new PrimaryKey("B", "id")); bSchema.addField("id", FieldType.STRING); bSchema.addField("anotherField", FieldType.DOUBLE); super.setUp(); } @Test public void correctlyRehashesKeys_beforeAndAfterSnapshot() throws IOException { HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeStateEngine); HollowHistory history = new HollowHistory(readEngine, 1L, 1); HollowHistoryKeyIndex keyIdx = new HollowHistoryKeyIndex(history); keyIdx.addTypeIndex("A", "id", "bRef.id"); keyIdx.addTypeIndex("B", "id"); keyIdx.indexTypeField("A", "bRef"); keyIdx.indexTypeField("A", "id"); keyIdx.indexTypeField("B", "id"); roundTripSnapshot(); keyIdx.update(readStateEngine, false); // Will rehash before 2069, otherwise couldn't store all values for(int i=0;i<5000;i++) { addRecord((float) i, Integer.toString(i), 1L, 1.1D); } roundTripSnapshot(); keyIdx.update(readStateEngine, false); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("A"); // Test objects before and after rehash for(int ordinal=0;ordinal<5000;ordinal++) { Assert.assertEquals(keyIdx.getRecordKeyOrdinal(typeState, ordinal), ordinal); String expectedString = (float)ordinal+":"+ordinal; Assert.assertEquals(keyIdx.getKeyDisplayString("A", ordinal), expectedString); } } @Test public void correctlyRehashesKeys_beforeAndAfterDelta() throws IOException { HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeStateEngine); HollowHistory history = new HollowHistory(readEngine, 1L, 1); HollowHistoryKeyIndex keyIdx = new HollowHistoryKeyIndex(history); keyIdx.addTypeIndex("A", "id", "bRef.id"); keyIdx.addTypeIndex("B", "id"); keyIdx.indexTypeField("A", "bRef"); keyIdx.indexTypeField("A", "id"); keyIdx.indexTypeField("B", "id"); roundTripSnapshot(); keyIdx.update(readStateEngine, false); // Will rehash before 2069, otherwise couldn't store all values for(int i=0;i<1000;i++) { addRecord((float) i, Integer.toString(i), 1L, 1.1D); } roundTripSnapshot(); keyIdx.update(readStateEngine, false); for(int i=1000;i<5000;i++) { addRecord((float) i, Integer.toString(i), 1L, 1.1D); } roundTripDelta(); keyIdx.update(readStateEngine, true); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("A"); // Test objects before and after rehash for(int ordinal=0;ordinal<5000;ordinal++) { Assert.assertEquals(keyIdx.getRecordKeyOrdinal(typeState, ordinal), ordinal); String expectedString = (float)ordinal+":"+ordinal; Assert.assertEquals(keyIdx.getKeyDisplayString("A", ordinal), expectedString); } } private void addRecord(float aId, String bId, long anotherAField, double anotherBField) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(bSchema); bRec.setString("id", bId); bRec.setDouble("anotherField", anotherBField); int bOrdinal = writeStateEngine.add("B", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(aSchema); aRec.setFloat("id", aId); aRec.setReference("bRef", bOrdinal); aRec.setLong("anotherField", anotherAField); writeStateEngine.add("A", aRec); } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState aWriteState = new HollowObjectTypeWriteState(aSchema); HollowObjectTypeWriteState bWriteState = new HollowObjectTypeWriteState(bSchema); writeStateEngine.addTypeState(aWriteState); writeStateEngine.addTypeState(bWriteState); } }
8,664
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/history/HollowHistoryMapTest.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.tools.history; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess; 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.Before; import org.junit.Test; public class HollowHistoryMapTest extends AbstractStateEngineTest { private HollowMapSchema schema; @Before public void setUp() { schema = new HollowMapSchema("TestMap", "TestKey", "TestValue"); super.setUp(); } @Test public void testHistoricalSet() throws IOException { addRecord(10, 11, 20, 21, 30, 31); addRecord(20, 21, 30, 31, 40, 41); addRecord(30, 31, 40, 41, 50, 51); addRecord(40, 41, 50, 51, 60, 61); addRecord(50, 51, 60, 61, 70, 71); roundTripSnapshot(); addRecord(10, 11, 20, 21, 30, 31); addRecord(20, 21, 30, 31, 40, 41); //addRecord(30, 31, 40, 41, 50, 51); addRecord(40, 41, 50, 51, 60, 61); //addRecord(50, 51, 60, 61, 70, 71); addRecord(60, 61, 70, 71, 80, 81); addRecord(70, 71, 80, 81, 90, 91); addRecord(80, 81, 90, 91, 100, 101); roundTripDelta(); HollowHistoricalStateDataAccess history1 = new HollowHistoricalStateCreator().createBasedOnNewDelta(2, readStateEngine); addRecord(10, 11, 20, 21, 30, 31); addRecord(20, 21, 30, 31, 40, 41); addRecord(100, 101, 200, 201, 300, 301, 400, 401); //addRecord(30, 31, 40, 41, 50, 51); addRecord(40, 41, 50, 51, 60, 61); // addRecord(50, 51, 60, 61, 70, 71); addRecord(60, 61, 70, 71, 80, 81); // addRecord(70, 71, 80, 81, 90, 91); // addRecord(80, 81, 90, 91, 100, 101); roundTripDelta(); HollowHistoricalStateDataAccess history2 = new HollowHistoricalStateCreator().createBasedOnNewDelta(3, readStateEngine); addRecord(10, 11, 20, 21, 30, 31); addRecord(20, 21, 30, 31, 40, 41); addRecord(100, 101, 200, 201, 300, 301, 400, 401); //addRecord(30, 31, 40, 41, 50, 51); addRecord(40, 41, 50, 51, 60, 61); addRecord(200, 201); // addRecord(50, 51, 60, 61, 70, 71); addRecord(60, 61, 70, 71, 80, 81); addRecord(300, 301, 400, 401, 500, 501); // addRecord(70, 71, 80, 81, 90, 91); addRecord(400, 401, 500, 501, 600, 601); // addRecord(80, 81, 90, 91, 100, 101); roundTripDelta(); assertRecord(history1, 0, 10, 11, 20, 21, 30, 31); assertRecord(history1, 1, 20, 21, 30, 31, 40, 41); assertRecord(history1, 2, 30, 31, 40, 41, 50, 51); assertRecord(history1, 3, 40, 41, 50, 51, 60, 61); assertRecord(history1, 4, 50, 51, 60, 61, 70, 71); assertRecord(history2, 0, 10, 11, 20, 21, 30, 31); assertRecord(history2, 1, 20, 21, 30, 31, 40, 41); assertRecord(history2, 3, 40, 41, 50, 51, 60, 61); assertRecord(history2, 5, 60, 61, 70, 71, 80, 81); assertRecord(history2, 6, 70, 71, 80, 81, 90, 91); assertRecord(history2, 7, 80, 81, 90, 91, 100, 101); assertRecord(readStateEngine, 0, 10, 11, 20, 21, 30, 31); assertRecord(readStateEngine, 1, 20, 21, 30, 31, 40, 41); assertRecord(readStateEngine, 2, 100, 101, 200, 201, 300, 301, 400, 401); assertRecord(readStateEngine, 3, 40, 41, 50, 51, 60, 61); assertRecord(readStateEngine, 4, 200, 201); assertRecord(readStateEngine, 5, 60, 61, 70, 71, 80, 81); assertRecord(readStateEngine, 6, 300, 301, 400, 401, 500, 501); assertRecord(readStateEngine, 7, 400, 401, 500, 501, 600, 601); } private void assertRecord(HollowDataAccess dataAccess, int ordinal, int... expectedEntries) { HollowMapTypeDataAccess typeDataAccess = (HollowMapTypeDataAccess)dataAccess.getTypeDataAccess("TestMap"); test: for(int i=0;i<expectedEntries.length;i+=2) { HollowMapEntryOrdinalIterator iter = typeDataAccess.potentialMatchOrdinalIterator(ordinal, expectedEntries[i]); while(iter.next()) { if(iter.getKey() == expectedEntries[i] && iter.getValue() == expectedEntries[i+1]) continue test; } Assert.fail("Did not find expected entry (" + expectedEntries[i] + "," + expectedEntries[i+1] + ") for ordinal " + ordinal); } } private void addRecord(int... entries) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<entries.length;i+=2) { rec.addEntry(entries[i], entries[i+1]); } writeStateEngine.add("TestMap", rec); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowMapTypeWriteState(schema)); } }
8,665
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/filter/FilteredHollowBlobWriterTest.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.tools.filter; import com.netflix.hollow.api.objects.generic.GenericHollowObject; 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.filter.HollowFilterConfig; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class FilteredHollowBlobWriterTest { private byte[] snapshotData; private byte[] deltaData; private byte[] removeOnlyDeltaData; @Before public void setUp() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new TypeA(1, "one")); mapper.add(new TypeA(2, "two")); mapper.add(new TypeA(3, "three")); mapper.add(new TypeB(1, 1.1f)); mapper.add(new TypeB(2, 2.2f)); mapper.add(new TypeB(3, 3.3f)); HollowBlobWriter writer = new HollowBlobWriter(writeEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); snapshotData = baos.toByteArray(); writeEngine.prepareForNextCycle(); mapper.add(new TypeA(1, "one")); mapper.add(new TypeA(2, "two")); mapper.add(new TypeA(3, "four")); mapper.add(new TypeB(1, 1.1f)); mapper.add(new TypeB(2, 2.2f)); mapper.add(new TypeB(3, 4.4f)); baos.reset(); writer.writeDelta(baos); deltaData = baos.toByteArray(); writeEngine.prepareForNextCycle(); mapper.add(new TypeA(2, "two")); mapper.add(new TypeA(3, "four")); mapper.add(new TypeB(2, 2.2f)); mapper.add(new TypeB(3, 4.4f)); baos.reset(); writer.writeDelta(baos); removeOnlyDeltaData = baos.toByteArray(); } @Test public void filtersDataFromBlob() throws IOException { HollowFilterConfig filterConfig = new HollowFilterConfig(true); filterConfig.addType("String"); filterConfig.addField("TypeA", "value"); filterConfig.addField("TypeA", "nonexistentField"); filterConfig.addType("NonexistentType"); FilteredHollowBlobWriter blobWriter = new FilteredHollowBlobWriter(filterConfig); ByteArrayOutputStream filteredBlobStream = new ByteArrayOutputStream(); blobWriter.filterSnapshot(new ByteArrayInputStream(snapshotData), filteredBlobStream); HollowReadStateEngine readEngine = new HollowReadStateEngine(); HollowBlobReader reader = new HollowBlobReader(readEngine); reader.readSnapshot(HollowBlobInput.serial(filteredBlobStream.toByteArray())); filteredBlobStream.reset(); blobWriter.filterDelta(new ByteArrayInputStream(deltaData), filteredBlobStream); reader.applyDelta(HollowBlobInput.serial(filteredBlobStream.toByteArray())); Assert.assertEquals(2, readEngine.getSchemas().size()); Assert.assertEquals(1, ((HollowObjectSchema)readEngine.getSchema("TypeA")).numFields()); Assert.assertEquals(2, ((HollowObjectSchema)readEngine.getSchema("TypeB")).numFields()); Assert.assertEquals(3, readEngine.getTypeState("TypeA").getPopulatedOrdinals().cardinality()); Assert.assertEquals(1, new GenericHollowObject(readEngine, "TypeA", 0).getInt("id")); Assert.assertEquals(2, new GenericHollowObject(readEngine, "TypeA", 1).getInt("id")); Assert.assertEquals(3, new GenericHollowObject(readEngine, "TypeA", 3).getInt("id")); Assert.assertEquals(3, readEngine.getTypeState("TypeB").getPopulatedOrdinals().cardinality()); Assert.assertEquals(1, new GenericHollowObject(readEngine, "TypeB", 0).getInt("id")); Assert.assertEquals(1.1f, new GenericHollowObject(readEngine, "TypeB", 0).getFloat("value"), 0); Assert.assertEquals(2, new GenericHollowObject(readEngine, "TypeB", 1).getInt("id")); Assert.assertEquals(2.2f, new GenericHollowObject(readEngine, "TypeB", 1).getFloat("value"), 0); Assert.assertEquals(3, new GenericHollowObject(readEngine, "TypeB", 3).getInt("id")); Assert.assertEquals(4.4f, new GenericHollowObject(readEngine, "TypeB", 3).getFloat("value"), 0); filteredBlobStream.reset(); blobWriter.filterDelta(new ByteArrayInputStream(removeOnlyDeltaData), filteredBlobStream); reader.applyDelta(HollowBlobInput.serial(filteredBlobStream.toByteArray())); Assert.assertEquals(2, readEngine.getTypeState("TypeA").getPopulatedOrdinals().cardinality()); Assert.assertEquals(2, readEngine.getTypeState("TypeB").getPopulatedOrdinals().cardinality()); } @SuppressWarnings("unused") private static class TypeA { int id; String value; public TypeA(int id, String value) { this.id = id; this.value = value; } } @SuppressWarnings("unused") private static class TypeB { int id; float value; public TypeB(int id, float value) { this.id = id; this.value = value; } } }
8,666
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/checksum/HollowChecksumTest.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.tools.checksum; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.util.StateEngineRoundTripper; 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 HollowChecksumTest { HollowReadStateEngine readEngine1; HollowReadStateEngine readEngine2; @Before public void setUp() throws IOException { HollowObjectSchema schema1 = new HollowObjectSchema("TypeA", 3); HollowObjectSchema schema2 = new HollowObjectSchema("TypeA", 3); schema1.addField("a1", FieldType.INT); schema2.addField("a1", FieldType.INT); schema1.addField("a4", FieldType.FLOAT); schema2.addField("a4", FieldType.FLOAT); schema1.addField("a2", FieldType.STRING); schema2.addField("a3", FieldType.LONG); readEngine1 = createStateEngine(schema1); readEngine2 = createStateEngine(schema2); } @Test public void checksumsCanBeEvaluatedAcrossObjectTypesWithDifferentSchemas() { HollowChecksum cksum1 = HollowChecksum.forStateEngineWithCommonSchemas(readEngine1, readEngine2); HollowChecksum cksum2 = HollowChecksum.forStateEngineWithCommonSchemas(readEngine2, readEngine1); Assert.assertEquals(cksum1, cksum2); } private HollowReadStateEngine createStateEngine(HollowObjectSchema schema) throws IOException { HollowWriteStateEngine writeState = new HollowWriteStateEngine(); writeState.addTypeState(new HollowObjectTypeWriteState(schema)); HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); for(int i=0;i<100;i++) { rec.reset(); rec.setInt("a1", i); rec.setFloat("a4", (float)i); if(schema.getPosition("a2") != -1) rec.setString("a2", String.valueOf(i)); if(schema.getPosition("a3") != -1) rec.setLong("a3", i); writeState.add(schema.getName(), rec); } return StateEngineRoundTripper.roundTripSnapshot(writeState); } }
8,667
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/tools/query/HollowFieldMatchQueryTest.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.tools.query; 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.BitSet; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowFieldMatchQueryTest { private HollowReadStateEngine stateEngine; @Before public void setUp() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.add(new TypeA(1, 100)); mapper.add(new TypeA(2, 200)); mapper.add(new TypeA(3, 100)); mapper.add(new TypeA(4, 200)); mapper.add(new TypeB("1", 1.1f)); mapper.add(new TypeB("2", 2.2f)); mapper.add(new TypeB("3", 3.3f)); mapper.add(new TypeB("4", 4.4f)); stateEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); } @Test public void matchesRecordsOfAnyType() { HollowFieldMatchQuery query = new HollowFieldMatchQuery(stateEngine); Map<String, BitSet> matches = query.findMatchingRecords("id", "2"); Assert.assertEquals(2, matches.size()); Assert.assertEquals(1, matches.get("TypeA").cardinality()); Assert.assertTrue(matches.get("TypeA").get(1)); Assert.assertEquals(1, matches.get("TypeB").cardinality()); Assert.assertTrue(matches.get("TypeB").get(1)); } @Test public void matchesOnlyRecordsOfSpecifiedType() { HollowFieldMatchQuery query = new HollowFieldMatchQuery(stateEngine); Map<String, BitSet> matches = query.findMatchingRecords("TypeA", "id", "2"); Assert.assertEquals(1, matches.size()); Assert.assertEquals(1, matches.get("TypeA").cardinality()); Assert.assertTrue(matches.get("TypeA").get(1)); } @Test public void matchesOnlyRecordsWithSpecifiedField() { HollowFieldMatchQuery query = new HollowFieldMatchQuery(stateEngine); Map<String, BitSet> matches = query.findMatchingRecords("bValue", "4.4"); Assert.assertEquals(1, matches.size()); Assert.assertEquals(1, matches.get("TypeB").cardinality()); Assert.assertTrue(matches.get("TypeB").get(3)); } @SuppressWarnings("unused") private static class TypeA { int id; int aValue; public TypeA(int id, int aValue) { this.id = id; this.aValue = aValue; } } @SuppressWarnings("unused") private static class TypeB { String id; float bValue; public TypeB(String id, float bValue) { this.id = id; this.bValue = bValue; } } }
8,668
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/HollowDatasetTest.java
package com.netflix.hollow.core; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSchemaParser; import com.netflix.hollow.core.schema.SimpleHollowDataset; import java.io.IOException; import java.util.List; import org.junit.Test; public class HollowDatasetTest { @Test public void identifiesIdenticalSchemas() throws IOException { List<HollowSchema> schemas1 = HollowSchemaParser.parseCollectionOfSchemas("TypeA { int a1; string a2; TypeB a3; MapOfTypeB a4; } MapOfTypeB Map<TypeB, TypeB>; TypeB { float b1; bytes b2; }"); List<HollowSchema> schemas2 = HollowSchemaParser.parseCollectionOfSchemas("TypeB { float b1; bytes b2; } TypeA { int a1; string a2; TypeB a3; MapOfTypeB a4; } MapOfTypeB Map<TypeB, TypeB>;"); HollowDataset dataset1 = new SimpleHollowDataset(schemas1); HollowDataset dataset2 = new SimpleHollowDataset(schemas2); assertTrue(dataset1.hasIdenticalSchemas(dataset2)); assertTrue(dataset2.hasIdenticalSchemas(dataset1)); } @Test public void identifiesDifferentSchemasWithSameName() throws IOException { List<HollowSchema> schemas1 = HollowSchemaParser.parseCollectionOfSchemas("TypeA { int a1; string a2; TypeB a3; MapOfTypeB a4; boolean newField; } MapOfTypeB Map<TypeB, TypeB>; TypeB { float b1; bytes b2; }"); List<HollowSchema> schemas2 = HollowSchemaParser.parseCollectionOfSchemas("TypeB { float b1; bytes b2; } TypeA { int a1; string a2; TypeB a3; MapOfTypeB a4; } MapOfTypeB Map<TypeB, TypeB>;"); HollowDataset dataset1 = new SimpleHollowDataset(schemas1); HollowDataset dataset2 = new SimpleHollowDataset(schemas2); assertFalse(dataset1.hasIdenticalSchemas(dataset2)); assertFalse(dataset2.hasIdenticalSchemas(dataset1)); } @Test public void identifiesDifferentSchemasWithDifferentName() throws IOException { List<HollowSchema> schemas1 = HollowSchemaParser.parseCollectionOfSchemas("DifferentTypeName { int a1; string a2; TypeB a3; MapOfTypeB a4; } MapOfTypeB Map<TypeB, TypeB>; TypeB { float b1; bytes b2; }"); List<HollowSchema> schemas2 = HollowSchemaParser.parseCollectionOfSchemas("TypeB { float b1; bytes b2; } TypeA { int a1; string a2; TypeB a3; MapOfTypeB a4; } MapOfTypeB Map<TypeB, TypeB>;"); HollowDataset dataset1 = new SimpleHollowDataset(schemas1); HollowDataset dataset2 = new SimpleHollowDataset(schemas2); assertFalse(dataset1.hasIdenticalSchemas(dataset2)); assertFalse(dataset2.hasIdenticalSchemas(dataset1)); } @Test public void identifiesMissingSchema() throws IOException { List<HollowSchema> schemas1 = HollowSchemaParser.parseCollectionOfSchemas("TypeA { int a1; string a2; TypeB a3; MapOfTypeB a4; } MapOfTypeB Map<TypeB, TypeB>; TypeB { float b1; bytes b2; }"); List<HollowSchema> schemas2 = HollowSchemaParser.parseCollectionOfSchemas("TypeB { float b1; bytes b2; } MapOfTypeB Map<TypeB, TypeB>;"); HollowDataset dataset1 = new SimpleHollowDataset(schemas1); HollowDataset dataset2 = new SimpleHollowDataset(schemas2); assertFalse(dataset1.hasIdenticalSchemas(dataset2)); assertFalse(dataset2.hasIdenticalSchemas(dataset1)); } }
8,669
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/AbstractStateEngineTest.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; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.filter.HollowFilterConfig; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import org.junit.Before; public abstract class AbstractStateEngineTest { protected HollowWriteStateEngine writeStateEngine; protected HollowReadStateEngine readStateEngine; protected HollowFilterConfig readFilter; @Before public void setUp() { initWriteStateEngine(); } protected void initWriteStateEngine() { writeStateEngine = new HollowWriteStateEngine(); initializeTypeStates(); } protected void roundTripSnapshot() throws IOException { readStateEngine = new HollowReadStateEngine(); StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine, readFilter); } protected void roundTripDelta() throws IOException { StateEngineRoundTripper.roundTripDelta(writeStateEngine, readStateEngine); } protected void restoreWriteStateEngineFromReadStateEngine() { writeStateEngine = new HollowWriteStateEngine(); initializeTypeStates(); writeStateEngine.restoreFrom(readStateEngine); writeStateEngine.prepareForNextCycle(); } protected abstract void initializeTypeStates(); }
8,670
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/NegativeFloatTest.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; 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.objectmapper.HollowObjectMapper; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class NegativeFloatTest { @Test public void test() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); for(int i=0;i<10;i++) { mapper.add(new TypeWithFloat(-200f, i)); } HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); for(int i=0;i<10;i++) { GenericHollowObject obj = new GenericHollowObject(readEngine, "TypeWithFloat", i); Assert.assertEquals(i, obj.getInt("i")); } } @SuppressWarnings("unused") private static class TypeWithFloat { float f; int i; public TypeWithFloat(float f, int i) { this.f = f; this.i = i; } } }
8,671
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/EmptyTypeSnapshotTest.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; 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.HollowSetSchema; import java.io.IOException; import org.junit.Test; public class EmptyTypeSnapshotTest extends AbstractStateEngineTest { @Test public void test() throws IOException { roundTripSnapshot(); } @Override protected void initializeTypeStates() { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(new HollowObjectSchema("TestObject", 0))); writeStateEngine.addTypeState(new HollowListTypeWriteState(new HollowListSchema("TestList", "TestObject"))); writeStateEngine.addTypeState(new HollowSetTypeWriteState(new HollowSetSchema("TestSet", "TestObject"))); writeStateEngine.addTypeState(new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestObject", "TestObject"))); } }
8,672
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/DefinedHashHeadersTest.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; 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.util.DefaultHashCodeFinder; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class DefinedHashHeadersTest { @Test public void definedHashTypesAreSentInHollowHeader() throws IOException { DefaultHashCodeFinder hasher = new DefaultHashCodeFinder("DefinedHash1", "DefinedHash2", "DefinedHash3"); HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(hasher); stateEngine.prepareForWrite(); HollowBlobWriter writer = new HollowBlobWriter(stateEngine); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.writeSnapshot(baos); HollowReadStateEngine readEngine = new HollowReadStateEngine(true); HollowBlobReader reader = new HollowBlobReader(readEngine); reader.readSnapshot(HollowBlobInput.serial(baos.toByteArray())); String headerTag = readEngine.getHeaderTag(HollowObjectHashCodeFinder.DEFINED_HASH_CODES_HEADER_NAME); String types[] = headerTag.split(","); Set<String> definedHashTypes = new HashSet<String>(); for(String type : types) { definedHashTypes.add(type); } Assert.assertEquals(3, definedHashTypes.size()); Assert.assertTrue(definedHashTypes.contains("DefinedHash1")); Assert.assertTrue(definedHashTypes.contains("DefinedHash2")); Assert.assertTrue(definedHashTypes.contains("DefinedHash3")); } }
8,673
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/HollowWriteStateEngineTest.java
package com.netflix.hollow.core.write; import static com.netflix.hollow.core.HollowStateEngine.HEADER_TAG_PRODUCER_TO_VERSION; import static org.junit.Assert.assertEquals; 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.test.InMemoryBlobStore; import org.junit.Test; public class HollowWriteStateEngineTest { private static final String TEST_TAG = "test"; @Test public void testHeaderTagsOnDeltaAndReverseDelta() { InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowInMemoryBlobStager blobStager = new HollowInMemoryBlobStager(); HollowProducer p = HollowProducer .withPublisher(blobStore) .withBlobStager(blobStager) .build(); p.initializeDataModel(String.class); long version1 = p.runCycle(ws -> { // override cycle start time with a strictly incrementing count to work around clock skew ws.getStateEngine().addHeaderTag(TEST_TAG, "1"); ws.add("A"); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .build(); consumer.triggerRefreshTo(version1); // snapshot load long version2 = p.runCycle(ws -> { ws.getStateEngine().addHeaderTag(TEST_TAG, "2"); ws.add("B"); }); consumer.triggerRefreshTo(version2); // delta transition assertEquals("2", consumer.getStateEngine().getHeaderTag(TEST_TAG)); consumer.triggerRefreshTo(version1); // reverse delta transition assertEquals("1", consumer.getStateEngine().getHeaderTag(TEST_TAG)); // now test the RESTORE case HollowProducer p2 = HollowProducer .withPublisher(blobStore) .withBlobStager(blobStager) .build(); p2.initializeDataModel(String.class); p2.restore(version2, blobStore); long version3 = p2.runCycle(ws -> { ws.getStateEngine().addHeaderTag(TEST_TAG, "3"); ws.add("C"); }); consumer.triggerRefreshTo(version3); // delta transition assertEquals("3", consumer.getStateEngine().getHeaderTag(TEST_TAG)); assertEquals(String.valueOf(version3), consumer.getStateEngine().getHeaderTag(HEADER_TAG_PRODUCER_TO_VERSION)); consumer.triggerRefreshTo(version2); // reverse delta transition assertEquals("2", consumer.getStateEngine().getHeaderTag(TEST_TAG)); assertEquals(String.valueOf(version2), consumer.getStateEngine().getHeaderTag(HEADER_TAG_PRODUCER_TO_VERSION)); } }
8,674
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/HollowObjectWriteRecordTest.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; import com.netflix.hollow.core.memory.ByteDataArray; import com.netflix.hollow.core.memory.encoding.VarInt; import com.netflix.hollow.core.memory.encoding.ZigZag; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectWriteRecordTest { HollowObjectSchema schema; @Before public void setUp() { schema = new HollowObjectSchema("Test", 3); schema.addField("FieldA", FieldType.INT); schema.addField("FieldB", FieldType.LONG); schema.addField("FieldC", FieldType.BOOLEAN); } @Test public void translatesSchemas() { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("FieldA", 1023); rec.setLong("FieldB", 123556); rec.setBoolean("FieldC", true); HollowObjectSchema translatedSchema = new HollowObjectSchema("Test", 3); translatedSchema.addField("FieldB", FieldType.LONG); translatedSchema.addField("FieldD", FieldType.STRING); translatedSchema.addField("FieldA", FieldType.INT); ByteDataArray buf = new ByteDataArray(WastefulRecycler.DEFAULT_INSTANCE); rec.writeDataTo(buf, translatedSchema); long field0 = VarInt.readVLong(buf.getUnderlyingArray(), 0); int field0Length = VarInt.sizeOfVLong(field0); int field2 = VarInt.readVInt(buf.getUnderlyingArray(), field0Length + 1); Assert.assertEquals(123556, ZigZag.decodeLong(field0)); Assert.assertTrue(VarInt.readVNull(buf.getUnderlyingArray(), field0Length)); Assert.assertEquals(1023, ZigZag.decodeInt(field2)); } }
8,675
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/ResetToLastPreparedForNextCycleTest.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; 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 java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ResetToLastPreparedForNextCycleTest 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 resetWillReturnToPreviousStateEvenAfterWriting() 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"); writeDelta(); 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"); } @Test public void resetWillReturnToInitialState() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); writeStateEngine.resetToLastPrepareForNextCycle(); addRecord(1, "one"); addRecord(3, "three"); addRecord(1000, "ten thousand"); addRecord(0, "zero"); roundTripSnapshot(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); Assert.assertEquals(3, typeState.maxOrdinal()); assertObject(typeState, 0, 1, "one"); assertObject(typeState, 1, 3, "three"); assertObject(typeState, 2, 1000, "ten thousand"); assertObject(typeState, 3, 0, "zero"); } @Test public void resetWillReturnToInitialStateEvenAfterWriting() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); writeSnapshot(); writeStateEngine.resetToLastPrepareForNextCycle(); addRecord(1, "one"); addRecord(3, "three"); addRecord(1000, "ten thousand"); addRecord(0, "zero"); roundTripSnapshot(); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TestObject"); Assert.assertEquals(3, typeState.maxOrdinal()); assertObject(typeState, 0, 1, "one"); assertObject(typeState, 1, 3, "three"); assertObject(typeState, 2, 1000, "ten thousand"); assertObject(typeState, 3, 0, "zero"); } public void writeSnapshot() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); HollowBlobWriter writer = new HollowBlobWriter(writeStateEngine); writer.writeSnapshot(baos); } public void writeDelta() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); HollowBlobWriter writer = new HollowBlobWriter(writeStateEngine); writer.writeDelta(baos); writer.writeSnapshot(baos); } 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,676
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/objectmapper/TypeC.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.objectmapper; import java.util.List; import java.util.Map; public class TypeC { private final char c1; private final Map<String, List<Integer>> map; public TypeC(char c1, Map<String, List<Integer>> map) { this.c1 = c1; this.map = map; } public char getC1() { return c1; } public Map<String, List<Integer>> getMap() { return map; } }
8,677
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/objectmapper/HollowObjectMapperPrimaryKeyExtractionTests.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.objectmapper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import org.junit.Assert; import org.junit.Test; public class HollowObjectMapperPrimaryKeyExtractionTests { @Test public void extractsPrimaryKey() { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); Object[] key1 = mapper.extractPrimaryKey(new TypeA(1, "one")).getKey(); Object[] key2 = mapper.extractPrimaryKey(new TypeA(2, "two")).getKey(); Object[] key3 = mapper.extractPrimaryKey(new TypeA(3, "three")).getKey(); Assert.assertArrayEquals(new Object[] { 1, "one" }, key1); Assert.assertArrayEquals(new Object[] { 2, "two" }, key2); Assert.assertArrayEquals(new Object[] { 3, "three" }, key3); } @Test public void willReturnNullFields() { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); Object[] key1 = mapper.extractPrimaryKey(new TypeA(1)).getKey(); Object[] key2 = mapper.extractPrimaryKey(new TypeA(null)).getKey(); Object[] key3 = mapper.extractPrimaryKey(new TypeA(2, null)).getKey(); Object[] key4 = mapper.extractPrimaryKey(new TypeA(null, null)).getKey(); Assert.assertArrayEquals(new Object[] { 1, null }, key1); Assert.assertArrayEquals(new Object[] { null, null }, key2); Assert.assertArrayEquals(new Object[] { 2, null }, key3); Assert.assertArrayEquals(new Object[] { null, null }, key4); } @Test public void failsIfPrimaryKeyIncludesReferenceField() { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); try { mapper.extractPrimaryKey(new TypeAWithReferenceTypeForPrimaryKeyField(1, "asdf")); Assert.fail(); } catch(IllegalArgumentException expected) { Assert.assertEquals("Cannot extract POJO primary key from a REFERENCE mapped field type", expected.getMessage()); } } @SuppressWarnings("unused") @HollowPrimaryKey(fields={"id", "name"}) private static class TypeA { Str name; @HollowInline Integer id; public TypeA(Integer id) { this.id = id; this.name = null; } public TypeA(Integer id, String name) { this.id = id; this.name = new Str(name); } } @SuppressWarnings("unused") private static class Str { String value; public Str(String value) { this.value = value; } } @SuppressWarnings("unused") @HollowPrimaryKey(fields={"id", "name!"}) private static class TypeAWithReferenceTypeForPrimaryKeyField { int id; String name; public TypeAWithReferenceTypeForPrimaryKeyField(int id, String name) { this.id = id; this.name = name; } } }
8,678
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/objectmapper/DirectSetCircularReference.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.objectmapper; import java.util.Set; /** * Sample type that represents a direct circular reference between 2 classes, with a Set containing the child. */ @SuppressWarnings("unused") public class DirectSetCircularReference { private final String name; private final Set<DirectSetCircularReference> children; public DirectSetCircularReference(String name, Set<DirectSetCircularReference> children) { this.name = name; this.children = children; } }
8,679
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/objectmapper/HollowObjectMapperTest.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.objectmapper; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.HollowConstants; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.tools.stringifier.HollowRecordJsonStringifier; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; 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.Test; public class HollowObjectMapperTest extends AbstractStateEngineTest { @Test public void testBasic() 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)))))); roundTripSnapshot(); Assert.assertEquals("{\"a1\": \"two\",\"a2\": 2,\"b\": {\"b1\": 20,\"b2\": 20000000,\"b3\": 2.2,\"b4\": \"two\",\"b5\": [2, 2, 2]},\"cList\": []}", new HollowRecordJsonStringifier(false, true).stringify(readStateEngine, "TypeA", 0)); //System.out.println("---------------------------------"); //System.out.println(new HollowRecordJsonStringifier(false, true).stringify(readStateEngine, "TypeA", 1)); } @Test public void testNullElements() { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); // Lists cannot contain null elements try { mapper.add(new TypeWithList("a", null, "c")); Assert.fail("NullPointerException not thrown from List containing null elements"); } catch (NullPointerException e) { String m = e.getMessage(); Assert.assertNotNull(m); Assert.assertTrue(m.contains("Lists")); } // Sets cannot contain null elements try { mapper.add(new TypeWithSet("a", null, "c")); Assert.fail("NullPointerException not thrown from Set containing null elements"); } catch (NullPointerException e) { String m = e.getMessage(); Assert.assertNotNull(m); Assert.assertTrue(m.contains("Sets")); } // Maps cannot contain null keys try { mapper.add(new TypeWithMap("a", "a", null, "b", "c", "c")); Assert.fail("NullPointerException not thrown from Map containing null keys"); } catch (NullPointerException e) { String m = e.getMessage(); Assert.assertNotNull(m); Assert.assertTrue(m.contains("Maps")); Assert.assertTrue(m.contains("key")); } // Maps cannot contain null values try { mapper.add(new TypeWithMap("a", "a", "b", null, "c", "c")); Assert.fail("NullPointerException not thrown from Map containing null values"); } catch (NullPointerException e) { String m = e.getMessage(); Assert.assertNotNull(m); Assert.assertTrue(m.contains("Maps")); Assert.assertTrue(m.contains("value")); } } @Test public void testAllFieldTypes() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeWithAllFieldTypes(1)); mapper.add(new TypeWithAllFieldTypes(2)); TypeWithAllFieldTypes t = new TypeWithAllFieldTypes(3); t.nullFirstHalf(); mapper.add(t); t = new TypeWithAllFieldTypes(4); t.nullSecondHalf(); mapper.add(t); roundTripSnapshot(); TypeWithAllFieldTypes expected = new TypeWithAllFieldTypes(1); TypeWithAllFieldTypes actual = new TypeWithAllFieldTypes(new GenericHollowObject(readStateEngine, "TypeWithAllFieldTypes", 0)); Assert.assertEquals(expected, actual); expected = new TypeWithAllFieldTypes(2); actual = new TypeWithAllFieldTypes(new GenericHollowObject(readStateEngine, "TypeWithAllFieldTypes", 1)); Assert.assertEquals(expected, actual); expected = new TypeWithAllFieldTypes(3); expected.nullFirstHalf(); actual = new TypeWithAllFieldTypes(new GenericHollowObject(readStateEngine, "TypeWithAllFieldTypes", 2)); Assert.assertEquals(expected, actual); expected = new TypeWithAllFieldTypes(4); expected.nullSecondHalf(); actual = new TypeWithAllFieldTypes(new GenericHollowObject(readStateEngine, "TypeWithAllFieldTypes", 3)); Assert.assertEquals(expected, actual); } @Test public void testEnumAndInlineClass() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(TestEnum.ONE); mapper.add(TestEnum.TWO); mapper.add(TestEnum.THREE); roundTripSnapshot(); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(readStateEngine, new PrimaryKey("TestEnum", "_name")); int twoOrdinal = idx.getMatchingOrdinal("TWO"); GenericHollowObject obj = new GenericHollowObject(readStateEngine, "TestEnum", twoOrdinal); Assert.assertEquals("TWO", obj.getString("_name")); GenericHollowObject subObj = obj.getObject("testClass"); Assert.assertEquals(2, subObj.getInt("val1")); Assert.assertEquals(3, subObj.getInt("val2")); } @Test public void testDate() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); long time = System.currentTimeMillis(); mapper.add(new Date(time)); roundTripSnapshot(); int theOrdinal = readStateEngine.getTypeState("Date").maxOrdinal(); GenericHollowObject obj = new GenericHollowObject(readStateEngine, "Date", theOrdinal); Assert.assertEquals(time, obj.getLong("value")); } @Test public void testTransient() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(TestTransientClass.class); mapper.add(new TestTransientClass(1, 2, 3)); roundTripSnapshot(); HollowSchema schema = readStateEngine.getSchema("TestTransientClass"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); schema.writeTo(baos); String schemeText = baos.toString(); Assert.assertTrue(schemeText.contains("notTransient")); Assert.assertFalse(schemeText.contains("transientKeyword")); Assert.assertFalse(schemeText.contains("annotatedTransient")); } @Test public void testMappingInterface() throws IOException { assertExpectedFailureMappingInterfaceType(TestInterface.class, TestInterface.class); } @Test public void testMappingClassWithInterface() throws IOException { assertExpectedFailureMappingInterfaceType(TestClassContainingInterface.class, TestInterface.class); } @Test public void testMappingClassWithArray() throws IOException { assertExpectedFailureMappingArraysType(TestClassContainingArray.class, int[].class); } @Test public void testMappingClassWithTransientArray() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(TestClassContainingTransientArray.class); mapper.add(new TestClassContainingTransientArray(new int[]{1, 2})); roundTripSnapshot(); HollowSchema schema = readStateEngine.getSchema("TestClassContainingTransientArray"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); schema.writeTo(baos); String schemeText = baos.toString(); Assert.assertTrue(schemeText.contains("TestClassContainingTransientArray")); Assert.assertFalse(schemeText.contains("int[]")); Assert.assertFalse(schemeText.contains("intArray")); } @Test public void testMappingClassWithHollowTransientArray() throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(TestClassContainingHollowTransientArray.class); mapper.add(new TestClassContainingTransientArray(new int[]{1, 2})); roundTripSnapshot(); HollowSchema schema = readStateEngine.getSchema("TestClassContainingHollowTransientArray"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); schema.writeTo(baos); String schemeText = baos.toString(); Assert.assertTrue(schemeText.contains("TestClassContainingHollowTransientArray")); Assert.assertFalse(schemeText.contains("int[]")); Assert.assertFalse(schemeText.contains("intArray")); } @Test public void testMappingCircularReference() throws IOException { assertExpectedFailureMappingType(DirectCircularReference.class, "child"); } @Test public void testMappingCircularReferenceList() throws IOException { assertExpectedFailureMappingType(DirectListCircularReference.class, "children"); } @Test public void testMappingCircularReferenceSet() throws IOException { assertExpectedFailureMappingType(DirectSetCircularReference.class, "children"); } @Test public void testMappingCircularReferenceMap() throws IOException { assertExpectedFailureMappingType(DirectMapCircularReference.class, "children"); } @Test public void testMappingIndirectircularReference() throws IOException { assertExpectedFailureMappingType(IndirectCircularReference.TypeE.class, "f"); } @Test public void testAssignedOrdinal() { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); TypeWithAssignedOrdinal o = new TypeWithAssignedOrdinal(); mapper.add(o); Assert.assertNotEquals(HollowConstants.ORDINAL_NONE, o.__assigned_ordinal); } @Test public void testFinalAssignedOrdinal() { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); TypeWithFinalAssignedOrdinal o = new TypeWithFinalAssignedOrdinal(); mapper.add(o); Assert.assertNotEquals(HollowConstants.ORDINAL_NONE, o.__assigned_ordinal); } @Test public void testPreassignedOrdinal() { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); TypeWithAssignedOrdinal o = new TypeWithAssignedOrdinal(); o.__assigned_ordinal = 1; mapper.add(o); Assert.assertNotEquals(1, o.__assigned_ordinal); } @Test public void testIntAssignedOrdinal() { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); TypeWithIntAssignedOrdinal o = new TypeWithIntAssignedOrdinal(); mapper.add(o); Assert.assertEquals(HollowConstants.ORDINAL_NONE, o.__assigned_ordinal); } @Test public void testIntPreassignedOrdinal() { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); TypeWithIntAssignedOrdinal o = new TypeWithIntAssignedOrdinal(); o.__assigned_ordinal = 1; mapper.add(o); // int fields are ignored Assert.assertEquals(1, o.__assigned_ordinal); } /** * Convenience method for experimenting with {@link HollowObjectMapper#initializeTypeState(Class)} * on classes we know should fail due to circular references, confirming the exception message is correct. * * @param clazz class to initialize * @param fieldName the name of the field that should trip the circular reference detection */ protected void assertExpectedFailureMappingType(Class<?> clazz, String fieldName) { final String expected = clazz.getSimpleName() + "." + fieldName; try { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(clazz); Assert.fail("Expected Exception not thrown"); } catch (IllegalStateException e) { Assert.assertTrue(String.format("missing expected fieldname %s in the message, was %s", expected, e.getMessage()), e.getMessage().contains(expected)); } } /** * Convenience method for experimenting with {@link HollowObjectMapper#initializeTypeState(Class)} * on classes we know should fail due to fields that are interfaces, confirming the exception message is correct. * * @param clazz class to initialize * @param interfaceClazz interface class that breaks the initialization */ protected void assertExpectedFailureMappingInterfaceType(Class<?> clazz, Class<?> interfaceClazz) { final String expected = "Unexpected interface " + interfaceClazz.getSimpleName() + " passed as field."; try { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(clazz); Assert.fail("Expected Exception not thrown"); } catch (IllegalArgumentException e) { Assert.assertTrue(String.format("trying to generate schema based on interface %s, was %s", interfaceClazz.getSimpleName(), e.getMessage()), e.getMessage().contains(expected)); } } /** * Convenience method for experimenting with {@link HollowObjectMapper#initializeTypeState(Class)} * on classes we know should fail due to fields that are arrays, confirming the exception message is correct. * * @param clazz class to initialize * @param arrayClass interface class that breaks the initialization */ protected void assertExpectedFailureMappingArraysType(Class<?> clazz, Class<?> arrayClass) { final String expected = "Unexpected array " + arrayClass.getSimpleName() + " passed as field. Consider using collections or marking as transient."; try { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(clazz); Assert.fail("Expected Exception not thrown"); } catch (IllegalArgumentException e) { Assert.assertTrue(String.format("trying to generate schema based on array %s, was %s", arrayClass.getSimpleName(), e.getMessage()), e.getMessage().contains(expected)); } } 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() { } @SuppressWarnings("unused") private enum TestEnum { ONE(1), TWO(2), THREE(3); int value; TestClass<TypeA> testClass; private TestEnum(int value) { this.value = value; this.testClass = new TestClass<TypeA>(value, value + 1) { }; } } public interface TestInterface { int test(); } @SuppressWarnings("unused") private static abstract class TestClass<T> { int val1; int val2; public TestClass(int val1, int val2) { this.val1 = val1; this.val2 = val2; } } @SuppressWarnings("unused") private static class TestTransientClass { int notTransient; transient int transientKeyword; @HollowTransient int annotatedTransient; public TestTransientClass(int notTransient, int transientKeyword, int annotatedTransient) { this.notTransient = notTransient; this.transientKeyword = transientKeyword; this.annotatedTransient = annotatedTransient; } } @SuppressWarnings("unused") private static class TestClassContainingInterface { int val1; TestInterface val2; public TestClassContainingInterface(int val1, TestInterface val2) { this.val1 = val1; this.val2 = val2; } } @SuppressWarnings("unused") private static class TestClassContainingArray { int[] intArray; public TestClassContainingArray(int[] intArray) { this.intArray = intArray; } } @SuppressWarnings("unused") private static class TestClassContainingTransientArray { transient int[] intArray; public TestClassContainingTransientArray(int[] intArray) { this.intArray = intArray; } } @SuppressWarnings("unused") private static class TestClassContainingHollowTransientArray { @HollowTransient int[] intArray; public TestClassContainingHollowTransientArray(int[] intArray) { this.intArray = intArray; } } @SuppressWarnings("unused") private static class TestClassImplementingInterface implements TestInterface { int val1; public TestClassImplementingInterface(int val1) { this.val1 = val1; } @Override public int test() { return 0; } } static class TypeWithSet { Set<String> c; TypeWithSet(String... c) { this.c = new HashSet<>(Arrays.asList(c)); } } static class TypeWithList { List<String> c; TypeWithList(String... c) { this.c = new ArrayList<>(Arrays.asList(c)); } } static class TypeWithMap { Map<String, String> m; TypeWithMap(String... kv) { m = new HashMap<>(); for (int i = 0; i < kv.length; i += 2) { m.put(kv[i], kv[i + 1]); } } } static class TypeWithAssignedOrdinal { long __assigned_ordinal = HollowConstants.ORDINAL_NONE; } static class TypeWithFinalAssignedOrdinal { // Cannot assign directly to this field otherwise javac may // assume the value is a constant when accessed. final long __assigned_ordinal; TypeWithFinalAssignedOrdinal() { this.__assigned_ordinal = HollowConstants.ORDINAL_NONE; }; } static class TypeWithIntAssignedOrdinal { int __assigned_ordinal = HollowConstants.ORDINAL_NONE; } }
8,680
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/objectmapper/TypeB.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.objectmapper; public class TypeB { private final short b1; private final long b2; private final float b3; private final char[] b4; private final byte[] b5; public TypeB(short b1, long b2, float b3, char[] b4, byte[] b5) { this.b1 = b1; this.b2 = b2; this.b3 = b3; this.b4 = b4; this.b5 = b5; } public short getB1() { return b1; } public long getB2() { return b2; } public float getB3() { return b3; } public char[] getB4() { return b4; } public byte[] getB5() { return b5; } }
8,681
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/objectmapper/TypeWithAllFieldTypes.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.objectmapper; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import java.util.Arrays; @SuppressWarnings("deprecation") public class TypeWithAllFieldTypes { boolean bool; int i; byte b; short s; char c; long l; float f; double d; @HollowInline Boolean inlinedBoolean; @HollowInline Integer inlinedInt; @HollowInline Byte inlinedByte; @HollowInline Short inlinedShort; @HollowInline Character inlinedChar; @HollowInline Long inlinedLong; @HollowInline Float inlinedFloat; @HollowInline Double inlinedDouble; @HollowInline String inlinedString; char[] charArray; byte[] byteArray; NullablePrimitiveBoolean nullablePrimitiveBoolean; Integer referencedInteger; public TypeWithAllFieldTypes(int value) { this.bool = (value & 1) == 1; this.i = value; this.b = (byte)value; this.s = (short)value; this.c = (char)value; this.l = value; this.f = (float)value; this.d = (double)value; this.inlinedBoolean = Boolean.valueOf(bool); this.inlinedInt = Integer.valueOf(i); this.inlinedByte = Byte.valueOf(b); this.inlinedShort = Short.valueOf(s); this.inlinedChar = Character.valueOf(c); this.inlinedLong = Long.valueOf(l); this.inlinedFloat = Float.valueOf(f); this.inlinedDouble = Double.valueOf(d); this.inlinedString = String.valueOf(value); this.charArray = inlinedString.toCharArray(); this.byteArray = inlinedString.getBytes(); this.nullablePrimitiveBoolean = bool ? NullablePrimitiveBoolean.FALSE : NullablePrimitiveBoolean.TRUE; this.referencedInteger = inlinedInt; } public TypeWithAllFieldTypes(GenericHollowObject obj) { this.bool = obj.getBoolean("bool"); this.i = obj.getInt("i"); this.b = (byte)obj.getInt("b"); this.s = (short)obj.getInt("s"); this.c = (char)obj.getInt("c"); this.l = obj.getLong("l"); this.f = obj.getFloat("f"); this.d = obj.getDouble("d"); this.inlinedBoolean = obj.isNull("inlinedBoolean") ? null : obj.getBoolean("inlinedBoolean"); this.inlinedInt = obj.isNull("inlinedInt") ? null : obj.getInt("inlinedInt"); this.inlinedByte = obj.isNull("inlinedByte") ? null : (byte)obj.getInt("inlinedByte"); this.inlinedShort = obj.isNull("inlinedShort") ? null : (short)obj.getInt("inlinedShort"); this.inlinedChar = obj.isNull("inlinedChar") ? null : (char)obj.getInt("inlinedChar"); this.inlinedLong = obj.isNull("inlinedLong") ? null : obj.getLong("inlinedLong"); this.inlinedFloat = obj.isNull("inlinedFloat") ? null : obj.getFloat("inlinedFloat"); this.inlinedDouble = obj.isNull("inlinedDouble") ? null : obj.getDouble("inlinedDouble"); this.inlinedString = obj.isNull("inlinedString") ? null : obj.getString("inlinedString"); this.charArray = obj.isNull("charArray") ? null : obj.getString("charArray").toCharArray(); this.byteArray = obj.isNull("byteArray") ? null : obj.getBytes("byteArray"); this.nullablePrimitiveBoolean = obj.isNull("nullablePrimitiveBoolean") ? null : obj.getBoolean("nullablePrimitiveBoolean") ? NullablePrimitiveBoolean.TRUE : NullablePrimitiveBoolean.FALSE; this.referencedInteger = obj.isNull("referencedInteger") ? null : obj.getObject("referencedInteger").getInt("value"); } void nullFirstHalf() { inlinedBoolean = null; inlinedByte = null; inlinedChar = null; inlinedFloat = null; inlinedString = null; byteArray = null; referencedInteger = null; } void nullSecondHalf() { inlinedInt = null; inlinedShort = null; inlinedLong = null; inlinedDouble = null; charArray = null; nullablePrimitiveBoolean = null; } @Override @SuppressWarnings("EqualsHashCode") public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TypeWithAllFieldTypes other = (TypeWithAllFieldTypes) obj; if (b != other.b) return false; if (bool != other.bool) return false; if (!Arrays.equals(byteArray, other.byteArray)) return false; if (c != other.c) return false; if (!Arrays.equals(charArray, other.charArray)) return false; if (Double.doubleToLongBits(d) != Double.doubleToLongBits(other.d)) return false; if (Float.floatToIntBits(f) != Float.floatToIntBits(other.f)) return false; if (i != other.i) return false; if (inlinedBoolean == null) { if (other.inlinedBoolean != null) return false; } else if (!inlinedBoolean.equals(other.inlinedBoolean)) return false; if (inlinedByte == null) { if (other.inlinedByte != null) return false; } else if (!inlinedByte.equals(other.inlinedByte)) return false; if (inlinedChar == null) { if (other.inlinedChar != null) return false; } else if (!inlinedChar.equals(other.inlinedChar)) return false; if (inlinedDouble == null) { if (other.inlinedDouble != null) return false; } else if (!inlinedDouble.equals(other.inlinedDouble)) return false; if (inlinedFloat == null) { if (other.inlinedFloat != null) return false; } else if (!inlinedFloat.equals(other.inlinedFloat)) return false; if (inlinedInt == null) { if (other.inlinedInt != null) return false; } else if (!inlinedInt.equals(other.inlinedInt)) return false; if (inlinedLong == null) { if (other.inlinedLong != null) return false; } else if (!inlinedLong.equals(other.inlinedLong)) return false; if (inlinedShort == null) { if (other.inlinedShort != null) return false; } else if (!inlinedShort.equals(other.inlinedShort)) return false; if (inlinedString == null) { if (other.inlinedString != null) return false; } else if (!inlinedString.equals(other.inlinedString)) return false; if (l != other.l) return false; if (nullablePrimitiveBoolean != other.nullablePrimitiveBoolean) return false; if (referencedInteger == null) { if (other.referencedInteger != null) return false; } else if (!referencedInteger.equals(other.referencedInteger)) return false; if (s != other.s) return false; return true; } }
8,682
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/objectmapper/IndirectCircularReference.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.objectmapper; /** * Object model representing an indirect or nested circular reference: * * E depends on F, F depends on G, and G depends back on E */ @SuppressWarnings("unused") public class IndirectCircularReference { class TypeE { private final TypeF f; public TypeE(TypeF f) { this.f = f; } } class TypeF { private final TypeG g; public TypeF(TypeG g) { this.g = g; } } class TypeG { private final TypeE e; public TypeG(TypeE e) { this.e = e; } } }
8,683
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/objectmapper/HollowObjectMapperFlatRecordParserTest.java
package com.netflix.hollow.core.write.objectmapper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.flatrecords.FakeHollowSchemaIdentifierMapper; import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecord; import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecordWriter; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowObjectMapperFlatRecordParserTest { private HollowObjectMapper mapper; private FlatRecordWriter flatRecordWriter; @Before public void setUp() { mapper = new HollowObjectMapper(new HollowWriteStateEngine()); mapper.initializeTypeState(TypeWithAllSimpleTypes.class); mapper.initializeTypeState(InternalTypeA.class); mapper.initializeTypeState(TypeWithCollections.class); mapper.initializeTypeState(VersionedType2.class); mapper.initializeTypeState(SpecialWrapperTypesTest.class); flatRecordWriter = new FlatRecordWriter( mapper.getStateEngine(), new FakeHollowSchemaIdentifierMapper(mapper.getStateEngine())); } @Test public void testSpecialWrapperTypes() { SpecialWrapperTypesTest wrapperTypesTest = new SpecialWrapperTypesTest(); wrapperTypesTest.id = 8797182L; wrapperTypesTest.type = AnEnum.SOME_VALUE_C; wrapperTypesTest.complexEnum = ComplexEnum.SOME_VALUE_A; wrapperTypesTest.dateCreated = new Date(); flatRecordWriter.reset(); mapper.writeFlat(wrapperTypesTest, flatRecordWriter); FlatRecord fr = flatRecordWriter.generateFlatRecord(); SpecialWrapperTypesTest result = mapper.readFlat(fr); Assert.assertEquals(wrapperTypesTest, result); Assert.assertEquals(wrapperTypesTest.complexEnum.value, result.complexEnum.value); Assert.assertEquals(wrapperTypesTest.complexEnum.anotherValue, result.complexEnum.anotherValue); } @Test public void testSimpleTypes() { TypeWithAllSimpleTypes typeWithAllSimpleTypes = new TypeWithAllSimpleTypes(); typeWithAllSimpleTypes.boxedIntegerField = 1; typeWithAllSimpleTypes.boxedBooleanField = true; typeWithAllSimpleTypes.boxedDoubleField = 1.0; typeWithAllSimpleTypes.boxedFloatField = 1.0f; typeWithAllSimpleTypes.boxedLongField = 1L; typeWithAllSimpleTypes.boxedShortField = (short) 1; typeWithAllSimpleTypes.boxedByteField = (byte) 1; typeWithAllSimpleTypes.boxedCharField = 'a'; typeWithAllSimpleTypes.primitiveIntegerField = 1; typeWithAllSimpleTypes.primitiveBooleanField = true; typeWithAllSimpleTypes.primitiveDoubleField = 1.0; typeWithAllSimpleTypes.primitiveFloatField = 1.0f; typeWithAllSimpleTypes.primitiveLongField = 1L; typeWithAllSimpleTypes.primitiveShortField = (short) 1; typeWithAllSimpleTypes.primitiveByteField = (byte) 1; typeWithAllSimpleTypes.primitiveCharField = 'a'; typeWithAllSimpleTypes.stringField = "string"; typeWithAllSimpleTypes.inlinedIntegerField = 1; typeWithAllSimpleTypes.inlinedBooleanField = true; typeWithAllSimpleTypes.inlinedDoubleField = 1.0; typeWithAllSimpleTypes.inlinedFloatField = 1.0f; typeWithAllSimpleTypes.inlinedLongField = 1L; typeWithAllSimpleTypes.inlinedShortField = (short) 1; typeWithAllSimpleTypes.inlinedByteField = (byte) 1; typeWithAllSimpleTypes.inlinedCharField = 'a'; typeWithAllSimpleTypes.inlinedStringField = "inlinedstring"; typeWithAllSimpleTypes.internalTypeAField = new InternalTypeA(1, "name"); typeWithAllSimpleTypes.internalTypeCField = new InternalTypeC("data"); flatRecordWriter.reset(); mapper.writeFlat(typeWithAllSimpleTypes, flatRecordWriter); FlatRecord fr = flatRecordWriter.generateFlatRecord(); TypeWithAllSimpleTypes result = mapper.readFlat(fr); Assert.assertEquals(typeWithAllSimpleTypes, result); } @Test public void testCollections() { TypeWithCollections type = new TypeWithCollections(); type.id = 1; type.stringList = Arrays.asList("a", "b", "c"); type.stringSet = new HashSet<>(type.stringList); type.integerStringMap = type.stringList.stream().collect( Collectors.toMap( s -> type.stringList.indexOf(s), s -> s ) ); type.internalTypeAList = Arrays.asList(new InternalTypeA(1), new InternalTypeA(2)); type.internalTypeASet = new HashSet<>(type.internalTypeAList); type.integerInternalTypeAMap = type.internalTypeAList.stream().collect( Collectors.toMap( b -> b.id, b -> b ) ); type.internalTypeAStringMap = type.internalTypeAList.stream().collect( Collectors.toMap( b -> b, b -> b.name ) ); flatRecordWriter.reset(); mapper.writeFlat(type, flatRecordWriter); FlatRecord fr = flatRecordWriter.generateFlatRecord(); TypeWithCollections result = mapper.readFlat(fr); Assert.assertEquals(type, result); } @Test public void testMapFromVersionedTypes() { HollowObjectMapper readerMapper = new HollowObjectMapper(new HollowWriteStateEngine()); readerMapper.initializeTypeState(TypeWithAllSimpleTypes.class); readerMapper.initializeTypeState(InternalTypeA.class); readerMapper.initializeTypeState(TypeWithCollections.class); readerMapper.initializeTypeState(VersionedType1.class); VersionedType2 versionedType2 = new VersionedType2(); versionedType2.boxedIntegerField = 1; versionedType2.internalTypeBField = new InternalTypeB(1); versionedType2.charField = 'a'; versionedType2.primitiveDoubleField = 1.0; versionedType2.stringSet = new HashSet<>(Arrays.asList("a", "b", "c")); mapper.writeFlat(versionedType2, flatRecordWriter); FlatRecord fr = flatRecordWriter.generateFlatRecord(); VersionedType1 result = readerMapper.readFlat(fr); Assert.assertEquals(null, result.stringField); // stringField is not present in VersionedType1 Assert.assertEquals(versionedType2.boxedIntegerField, result.boxedIntegerField); Assert.assertEquals(versionedType2.primitiveDoubleField, result.primitiveDoubleField, 0); Assert.assertEquals(null, result.internalTypeAField); // internalTypeAField is not present in VersionedType1 Assert.assertEquals(versionedType2.stringSet, result.stringSet); } @Test public void shouldMapNonPrimitiveWrapperToPrimitiveWrapperIfCommonFieldIsTheSame() { HollowObjectMapper writerMapper = new HollowObjectMapper(new HollowWriteStateEngine()); writerMapper.initializeTypeState(TypeStateA1.class); FlatRecordWriter flatRecordWriter = new FlatRecordWriter( writerMapper.getStateEngine(), new FakeHollowSchemaIdentifierMapper(writerMapper.getStateEngine())); TypeStateA1 typeStateA1 = new TypeStateA1(); typeStateA1.id = 1; typeStateA1.subValue = new SubValue(); typeStateA1.subValue.value = "value"; writerMapper.writeFlat(typeStateA1, flatRecordWriter); FlatRecord fr = flatRecordWriter.generateFlatRecord(); HollowObjectMapper readerMapper = new HollowObjectMapper(new HollowWriteStateEngine()); readerMapper.initializeTypeState(TypeStateA2.class); TypeStateA2 result = readerMapper.readFlat(fr); Assert.assertEquals("value", result.subValue); } @Test public void shouldMapPrimitiveWrapperToNonPrimitiveWrapperIfCommonFieldIsTheSame() { HollowObjectMapper writerMapper = new HollowObjectMapper(new HollowWriteStateEngine()); writerMapper.initializeTypeState(TypeStateA2.class); FlatRecordWriter flatRecordWriter = new FlatRecordWriter( writerMapper.getStateEngine(), new FakeHollowSchemaIdentifierMapper(writerMapper.getStateEngine())); TypeStateA2 typeStateA2 = new TypeStateA2(); typeStateA2.id = 1; typeStateA2.subValue = "value"; writerMapper.writeFlat(typeStateA2, flatRecordWriter); FlatRecord fr = flatRecordWriter.generateFlatRecord(); HollowObjectMapper readerMapper = new HollowObjectMapper(new HollowWriteStateEngine()); readerMapper.initializeTypeState(TypeStateA1.class); TypeStateA1 result = readerMapper.readFlat(fr); Assert.assertEquals("value", result.subValue.value); } @HollowPrimaryKey(fields={"boxedIntegerField", "stringField"}) private static class TypeWithAllSimpleTypes { Integer boxedIntegerField; Boolean boxedBooleanField; Double boxedDoubleField; Float boxedFloatField; Long boxedLongField; Short boxedShortField; Byte boxedByteField; Character boxedCharField; int primitiveIntegerField; boolean primitiveBooleanField; double primitiveDoubleField; float primitiveFloatField; long primitiveLongField; short primitiveShortField; byte primitiveByteField; char primitiveCharField; String stringField; @HollowInline Integer inlinedIntegerField; @HollowInline Boolean inlinedBooleanField; @HollowInline Double inlinedDoubleField; @HollowInline Float inlinedFloatField; @HollowInline Long inlinedLongField; @HollowInline Short inlinedShortField; @HollowInline Byte inlinedByteField; @HollowInline Character inlinedCharField; @HollowInline String inlinedStringField; InternalTypeA internalTypeAField; InternalTypeC internalTypeCField; public TypeWithAllSimpleTypes() {} @Override public boolean equals(Object o) { if(o instanceof TypeWithAllSimpleTypes) { TypeWithAllSimpleTypes other = (TypeWithAllSimpleTypes)o; return Objects.equals(boxedIntegerField, other.boxedIntegerField) && Objects.equals(boxedBooleanField, other.boxedBooleanField) && Objects.equals(boxedDoubleField, other.boxedDoubleField) && Objects.equals(boxedFloatField, other.boxedFloatField) && Objects.equals(boxedLongField, other.boxedLongField) && Objects.equals(boxedShortField, other.boxedShortField) && Objects.equals(boxedByteField, other.boxedByteField) && Objects.equals(boxedCharField, other.boxedCharField) && primitiveIntegerField == other.primitiveIntegerField && primitiveBooleanField == other.primitiveBooleanField && primitiveDoubleField == other.primitiveDoubleField && primitiveFloatField == other.primitiveFloatField && primitiveLongField == other.primitiveLongField && primitiveShortField == other.primitiveShortField && primitiveByteField == other.primitiveByteField && primitiveCharField == other.primitiveCharField && Objects.equals(stringField, other.stringField) && Objects.equals(inlinedIntegerField, other.inlinedIntegerField) && Objects.equals(inlinedBooleanField, other.inlinedBooleanField) && Objects.equals(inlinedDoubleField, other.inlinedDoubleField) && Objects.equals(inlinedFloatField, other.inlinedFloatField) && Objects.equals(inlinedLongField, other.inlinedLongField) && Objects.equals(inlinedShortField, other.inlinedShortField) && Objects.equals(inlinedByteField, other.inlinedByteField) && Objects.equals(inlinedCharField, other.inlinedCharField) && Objects.equals(inlinedStringField, other.inlinedStringField) && Objects.equals(internalTypeAField, other.internalTypeAField) && Objects.equals(internalTypeCField, other.internalTypeCField); } return false; } @Override public String toString() { return "TypeA{" + "boxedIntegerField=" + boxedIntegerField + ", boxedBooleanField=" + boxedBooleanField + ", boxedDoubleField=" + boxedDoubleField + ", boxedFloatField=" + boxedFloatField + ", boxedLongField=" + boxedLongField + ", boxedShortField=" + boxedShortField + ", boxedByteField=" + boxedByteField + ", boxedCharField=" + boxedCharField + ", primitiveIntegerField=" + primitiveIntegerField + ", primitiveBooleanField=" + primitiveBooleanField + ", primitiveDoubleField=" + primitiveDoubleField + ", primitiveFloatField=" + primitiveFloatField + ", primitiveLongField=" + primitiveLongField + ", primitiveShortField=" + primitiveShortField + ", primitiveByteField=" + primitiveByteField + ", primitiveCharField=" + primitiveCharField + ", stringField='" + stringField + '\'' + ", inlinedIntegerField=" + inlinedIntegerField + ", inlinedBooleanField=" + inlinedBooleanField + ", inlinedDoubleField=" + inlinedDoubleField + ", inlinedFloatField=" + inlinedFloatField + ", inlinedLongField=" + inlinedLongField + ", inlinedShortField=" + inlinedShortField + ", inlinedByteField=" + inlinedByteField + ", inlinedCharField=" + inlinedCharField + ", internalTypeAField=" + internalTypeAField + '}'; } } @HollowPrimaryKey(fields={"id"}) private static class TypeWithCollections { int id; List<String> stringList; Set<String> stringSet; Map<Integer, String> integerStringMap; List<InternalTypeA> internalTypeAList; Set<InternalTypeA> internalTypeASet; Map<Integer, InternalTypeA> integerInternalTypeAMap; Map<InternalTypeA, String> internalTypeAStringMap; public TypeWithCollections() {} @Override public boolean equals(Object o) { if(o instanceof TypeWithCollections) { TypeWithCollections other = (TypeWithCollections)o; return id == other.id && Objects.equals(stringList, other.stringList) && Objects.equals(stringSet, other.stringSet) && Objects.equals(integerStringMap, other.integerStringMap) && Objects.equals(internalTypeAList, other.internalTypeAList) && Objects.equals(internalTypeASet, other.internalTypeASet) && Objects.equals(integerInternalTypeAMap, other.integerInternalTypeAMap) && Objects.equals(internalTypeAStringMap, other.internalTypeAStringMap); } return false; } @Override public String toString() { return "TypeWithCollections{" + "id=" + id + ", stringList=" + stringList + ", stringSet=" + stringSet + ", integerStringMap=" + integerStringMap + ", internalTypeAList=" + internalTypeAList + ", internalTypeASet=" + internalTypeASet + ", integerInternalTypeAMap=" + integerInternalTypeAMap + ", internalTypeAStringMap=" + internalTypeAStringMap + '}'; } } @HollowTypeName(name = "VersionedType") private static class VersionedType1 { String stringField; Integer boxedIntegerField; double primitiveDoubleField; InternalTypeA internalTypeAField; Set<String> stringSet; public VersionedType1() {} @Override public boolean equals(Object o) { if(o instanceof VersionedType1) { VersionedType1 other = (VersionedType1)o; return Objects.equals(stringField, other.stringField) && Objects.equals(boxedIntegerField, other.boxedIntegerField) && primitiveDoubleField == other.primitiveDoubleField && Objects.equals(internalTypeAField, other.internalTypeAField) && Objects.equals(stringSet, other.stringSet); } return false; } @Override public String toString() { return "VersionedType1{" + "stringField='" + stringField + '\'' + ", boxedIntegerField=" + boxedIntegerField + ", primitiveDoubleField=" + primitiveDoubleField + ", internalTypeAField=" + internalTypeAField + ", stringSet=" + stringSet + '}'; } } @HollowTypeName(name = "VersionedType") private static class VersionedType2 { // No longer has the stringField Integer boxedIntegerField; double primitiveDoubleField; // No longer has the typeBField Set<String> stringSet; char charField; // Added a char field InternalTypeB internalTypeBField; // Added a new type field public VersionedType2() {} @Override public boolean equals(Object o) { if(o instanceof VersionedType2) { VersionedType2 other = (VersionedType2)o; return Objects.equals(boxedIntegerField, other.boxedIntegerField) && primitiveDoubleField == other.primitiveDoubleField && Objects.equals(stringSet, other.stringSet) && charField == other.charField && Objects.equals(internalTypeBField, other.internalTypeBField); } return false; } @Override public String toString() { return "VersionedType2{" + "boxedIntegerField=" + boxedIntegerField + ", primitiveDoubleField=" + primitiveDoubleField + ", stringSet=" + stringSet + ", charField=" + charField + ", internalTypeBField=" + internalTypeBField + '}'; } } private static class InternalTypeA { Integer id; String name; public InternalTypeA() {} public InternalTypeA(Integer id) { this(id, String.valueOf(id)); } public InternalTypeA(Integer id, String name) { this.id = id; this.name = name; } @Override public int hashCode() { return Objects.hash(id, name); } @Override public boolean equals(Object o) { if(o instanceof InternalTypeA) { InternalTypeA other = (InternalTypeA)o; return id.equals(other.id) && name.equals(other.name); } return false; } @Override public String toString() { return "InternalTypeA{" + "id=" + id + ", name='" + name + '\'' + '}'; } } private static class InternalTypeB { Integer id; String name; public InternalTypeB() {} public InternalTypeB(Integer id) { this(id, String.valueOf(id)); } public InternalTypeB(Integer id, String name) { this.id = id; this.name = name; } @Override public int hashCode() { return Objects.hash(id, name); } @Override public boolean equals(Object o) { if(o instanceof InternalTypeB) { InternalTypeB other = (InternalTypeB)o; return id.equals(other.id) && name.equals(other.name); } return false; } @Override public String toString() { return "InternalTypeB{" + "id=" + id + ", name='" + name + '\'' + '}'; } } public static class InternalTypeC { @HollowInline String data; public InternalTypeC() { } public InternalTypeC(String data) { this.data = data; } @Override public boolean equals(Object o) { if(o instanceof InternalTypeC) { InternalTypeC other = (InternalTypeC)o; return data.equals(other.data); } return false; } @Override public String toString() { return "InternalTypeC{" + "data=" + data + '}'; } } @HollowTypeName(name="TypeStateA") @HollowPrimaryKey(fields="id") public static class TypeStateA1 { public int id; public SubValue subValue; } @HollowTypeName(name="TypeStateA") @HollowPrimaryKey(fields="id") public static class TypeStateA2 { public int id; @HollowTypeName(name="SubValue") public String subValue; } public static class SubValue { @HollowInline public String value; @HollowInline public String anotherValue; } enum AnEnum { SOME_VALUE_A, SOME_VALUE_B, SOME_VALUE_C, } enum ComplexEnum { SOME_VALUE_A("A", 1), SOME_VALUE_B("B", 2), SOME_VALUE_C("C", 3); final String value; final int anotherValue; ComplexEnum(String value, int anotherValue) { this.value = value; this.anotherValue = anotherValue; } } @HollowTypeName(name = "SpecialWrapperTypesTest") @HollowPrimaryKey(fields = {"id"}) static class SpecialWrapperTypesTest { long id; @HollowTypeName(name = "AnEnum") AnEnum type; @HollowTypeName(name = "ComplexEnum") ComplexEnum complexEnum; Date dateCreated; @Override public boolean equals(Object o) { if(o instanceof SpecialWrapperTypesTest) { SpecialWrapperTypesTest other = (SpecialWrapperTypesTest)o; return id == other.id && complexEnum == other.complexEnum && type == other.type && dateCreated.equals(other.dateCreated); } return false; } @Override public String toString() { return "SpecialWrapperTypesTest{" + "id=" + id + ", type='" + type + '\'' + ", complexEnum='" + complexEnum + '\'' + ", dateCreated=" + dateCreated + '}'; } } }
8,684
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/objectmapper/DirectMapCircularReference.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.objectmapper; import java.util.Map; /** * Sample type that represents a direct circular reference between 2 classes, with a Map containing the child. */ @SuppressWarnings("unused") public class DirectMapCircularReference { private final String name; private final Map<String, DirectMapCircularReference> children; public DirectMapCircularReference(String name, Map<String, DirectMapCircularReference> children) { this.name = name; this.children = children; } }
8,685
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/objectmapper/TypeD.java
package com.netflix.hollow.core.write.objectmapper; public class TypeD { @HollowInline private final String inlinedString; public TypeD(String inlinedString) { this.inlinedString = inlinedString; } public String getInlinedString() { return inlinedString; } }
8,686
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/objectmapper/HollowObjectTypeMapperCompressedStringTest.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.objectmapper; import static org.junit.Assert.assertEquals; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import java.io.IOException; import org.junit.Test; /** * Checks String encoding handling in presence of JDK9 compressed String feature */ public class HollowObjectTypeMapperCompressedStringTest extends AbstractStateEngineTest { @Test public void referencedStringUtfHandling() throws IOException { final String stringValue = "龍爭虎鬥";// "Enter The Dragon" String readValue = roundTripReferenceStringValue(stringValue); assertEquals(stringValue, readValue); } @Test public void referenceStringLatin1Handling() throws IOException { final String stringValue = "abc"; String readValue = roundTripReferenceStringValue(stringValue); assertEquals(stringValue, readValue); } @Test public void inlinedStringUtfHandling() throws IOException { final String stringValue = "龍爭虎鬥";// "Enter The Dragon" String readValue = roundTripInlinedStringValue(stringValue); assertEquals(stringValue, readValue); } @Test public void inlinedStringLatin1Handling() throws IOException { final String stringValue = "abc"; String readValue = roundTripInlinedStringValue(stringValue); assertEquals(stringValue, readValue); } private String roundTripReferenceStringValue(String value) throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeA(value, 1, null, null)); roundTripSnapshot(); HollowObjectTypeDataAccess typeDataAccess = (HollowObjectTypeDataAccess) readStateEngine.getTypeDataAccess("TypeA"); int stringFieldIndex = typeDataAccess.getSchema().getPosition("a1"); int stringValueOrdinal = typeDataAccess.readOrdinal(0, stringFieldIndex); HollowObjectTypeDataAccess stringDataAccess = (HollowObjectTypeDataAccess) readStateEngine.getTypeDataAccess("String"); int stringValueField = stringDataAccess.getSchema().getPosition("value"); return stringDataAccess.readString(stringValueOrdinal, stringValueField); } private String roundTripInlinedStringValue(String value) throws IOException { HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); mapper.add(new TypeD(value)); roundTripSnapshot(); HollowObjectTypeDataAccess typeDataAccess = (HollowObjectTypeDataAccess) readStateEngine.getTypeDataAccess("TypeD"); int stringFieldIndex = typeDataAccess.getSchema().getPosition("inlinedString"); return typeDataAccess.readString(0, stringFieldIndex); } @Override protected void initializeTypeStates() { } }
8,687
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/objectmapper/DirectCircularReference.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.objectmapper; /** * Sample type that represents a direct circular reference between 2 classes. */ @SuppressWarnings("unused") public class DirectCircularReference { private final String name; private final DirectCircularReference child; public DirectCircularReference(String name, DirectCircularReference child) { this.name = name; this.child = child; } }
8,688
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/objectmapper/DirectListCircularReference.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.objectmapper; import java.util.List; /** * Sample type that represents a direct circular reference between 2 classes, with a List containing the child. */ @SuppressWarnings("unused") public class DirectListCircularReference { private final String name; private final List<DirectListCircularReference> children; public DirectListCircularReference(String name, List<DirectListCircularReference> children) { this.name = name; this.children = children; } }
8,689
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/objectmapper/TypeA.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.objectmapper; import java.util.Set; public class TypeA { private final String a1; private final int a2; private final TypeB b; private final Set<TypeC> cList; public TypeA(String a1, int a2, TypeB b, Set<TypeC> cList) { this.a1 = a1; this.a2 = a2; this.b = b; this.cList = cList; } public String getA1() { return a1; } public int getA2() { return a2; } public TypeB getB() { return b; } public Set<TypeC> getCList() { return cList; } }
8,690
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/objectmapper/ReuseMemoizedObjectsAcrossCyclesTest.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.objectmapper; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.util.StateEngineRoundTripper; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; public class ReuseMemoizedObjectsAcrossCyclesTest { @Test public void reuseObjectsAcrossCycles() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); TypeA a1 = new TypeA(1); TypeA a2 = new TypeA(2); Assert.assertEquals(0, mapper.add(a1)); Assert.assertEquals(1, mapper.add(a2)); Assert.assertEquals(0, mapper.add(a1)); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); writeEngine.prepareForNextCycle(); Assert.assertEquals(0, mapper.add(a1)); Assert.assertEquals(2, mapper.add(new TypeA(3))); Assert.assertEquals(1, mapper.add(a2)); Assert.assertEquals(1, mapper.add(a2)); StateEngineRoundTripper.roundTripDelta(writeEngine, readEngine); Assert.assertEquals(3, readEngine.getTypeState("TypeA").getPopulatedOrdinals().cardinality()); } @Test public void reuseMemoizedListsAcrossCycles() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); List<TypeA> a1 = new MemoizedList<TypeA>(Arrays.asList(new TypeA(1))); List<TypeA> a2 = new MemoizedList<TypeA>(Arrays.asList(new TypeA(2))); Assert.assertEquals(0, mapper.add(new ListType(a1))); Assert.assertEquals(1, mapper.add(new ListType(a2))); Assert.assertEquals(0, mapper.add(new ListType(a1))); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); writeEngine.prepareForNextCycle(); List<TypeA> a3 = new MemoizedList<TypeA>(Arrays.asList(new TypeA(3))); Assert.assertEquals(0, mapper.add(new ListType(a1))); Assert.assertEquals(2, mapper.add(new ListType(a3))); Assert.assertEquals(1, mapper.add(new ListType(a2))); StateEngineRoundTripper.roundTripDelta(writeEngine, readEngine); Assert.assertEquals(3, readEngine.getTypeState("ListOfTypeA").getPopulatedOrdinals().cardinality()); } @SuppressWarnings("unused") public class ListType { private final List<TypeA> list; public ListType(List<TypeA> list) { this.list = list; } } @Test public void reuseMemoizedSetsAcrossCycles() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); Set<TypeA> a1 = new MemoizedSet<TypeA>(Arrays.asList(new TypeA(1))); Set<TypeA> a2 = new MemoizedSet<TypeA>(Arrays.asList(new TypeA(2))); Assert.assertEquals(0, mapper.add(new SetType(a1))); Assert.assertEquals(1, mapper.add(new SetType(a2))); Assert.assertEquals(0, mapper.add(new SetType(a1))); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); writeEngine.prepareForNextCycle(); Set<TypeA> a3 = new MemoizedSet<TypeA>(Arrays.asList(new TypeA(3))); Assert.assertEquals(0, mapper.add(new SetType(a1))); Assert.assertEquals(2, mapper.add(new SetType(a3))); Assert.assertEquals(1, mapper.add(new SetType(a2))); StateEngineRoundTripper.roundTripDelta(writeEngine, readEngine); Assert.assertEquals(3, readEngine.getTypeState("SetOfTypeA").getPopulatedOrdinals().cardinality()); } @SuppressWarnings("unused") public class SetType { private final Set<TypeA> set; public SetType(Set<TypeA> set) { this.set = set; } } @Test public void reuseMemoizedMapsAcrossCycles() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); Map<Integer, TypeA> a1 = new MemoizedMap<Integer, TypeA>(); a1.put(1, new TypeA(1)); Map<Integer, TypeA> a2 = new MemoizedMap<Integer, TypeA>(); a2.put(2, new TypeA(2)); Assert.assertEquals(0, mapper.add(new MapType(a1))); Assert.assertEquals(1, mapper.add(new MapType(a2))); Assert.assertEquals(0, mapper.add(new MapType(a1))); HollowReadStateEngine readEngine = StateEngineRoundTripper.roundTripSnapshot(writeEngine); writeEngine.prepareForNextCycle(); Map<Integer, TypeA> a3 = new MemoizedMap<Integer, TypeA>(); a3.put(3, new TypeA(3)); Assert.assertEquals(0, mapper.add(new MapType(a1))); Assert.assertEquals(2, mapper.add(new MapType(a3))); Assert.assertEquals(1, mapper.add(new MapType(a2))); StateEngineRoundTripper.roundTripDelta(writeEngine, readEngine); Assert.assertEquals(3, readEngine.getTypeState("MapOfIntegerToTypeA").getPopulatedOrdinals().cardinality()); } @SuppressWarnings("unused") public class MapType { private final Map<Integer, TypeA> map; public MapType(Map<Integer, TypeA> map) { this.map = map; } } @SuppressWarnings("unused") private static class TypeA { int value; public TypeA(int value) { this.value = value; } private final long __assigned_ordinal = -1; } }
8,691
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/objectmapper
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/objectmapper/flatrecords/FlatRecordWriterTests.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.objectmapper.flatrecords; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; 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.HollowHashKey; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class FlatRecordWriterTests { private HollowObjectMapper mapper; private HollowSchemaIdentifierMapper schemaIdMapper; private FlatRecordWriter flatRecordWriter; private HollowProducer producer; private InMemoryBlobStore blobStore; @Before public void setUp() { mapper = new HollowObjectMapper(new HollowWriteStateEngine()); mapper.initializeTypeState(TypeA.class); mapper.initializeTypeState(TypeC.class); schemaIdMapper = new FakeHollowSchemaIdentifierMapper(mapper.getStateEngine()); blobStore = new InMemoryBlobStore(); flatRecordWriter = new FlatRecordWriter(mapper.getStateEngine(), schemaIdMapper); producer = HollowProducer.withPublisher(blobStore).withBlobStager(new HollowInMemoryBlobStager()).build(); } @Test public void flatRecordsDedupRedundantDataWithinRecords() { int recSize1 = flatRecordSize(new TypeA(1, "two", "three", "four")); int recSize2 = flatRecordSize(new TypeA(1, "two", "three", "four", "three")); Assert.assertTrue(recSize2 - recSize1 == 1); } @Test public void flatRecordsCanBeDumpedToStateEngineWithIdenticalSchemas() throws IOException { producer.initializeDataModel(TypeA.class, TypeC.class); producer.runCycle(state -> { FlatRecordDumper dumper = new FlatRecordDumper(state.getStateEngine()); dumper.dump(flatten(new TypeA(1, "two", "three", "four", "five"))); dumper.dump(flatten(new TypeA(2, "two", "four", "six", "eight", "é with acute accent", "ten"))); dumper.dump(flatten(new TypeC("one", "four"))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefresh(); GenericHollowObject typeA0 = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 0); GenericHollowObject typeA1 = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 1); Assert.assertEquals(1, typeA0.getInt("a1")); Assert.assertEquals("two", typeA0.getString("a2")); Assert.assertEquals("three", typeA0.getObject("a3").getString("b1")); Assert.assertEquals(2, typeA0.getSet("a4").size()); Assert.assertTrue(typeA0.getSet("a4").findElement("four") != null); Assert.assertTrue(typeA0.getSet("a4").findElement("five") != null); Assert.assertEquals(2, typeA1.getInt("a1")); Assert.assertEquals("two", typeA1.getString("a2")); Assert.assertEquals("four", typeA1.getObject("a3").getString("b1")); Assert.assertEquals(4, typeA1.getSet("a4").size()); Assert.assertTrue(typeA1.getSet("a4").findElement("six") != null); Assert.assertTrue(typeA1.getSet("a4").findElement("eight") != null); Assert.assertTrue(typeA1.getSet("a4").findElement("é with acute accent") != null); Assert.assertTrue(typeA1.getSet("a4").findElement("ten") != null); GenericHollowObject typeC0 = new GenericHollowObject(consumer.getStateEngine(), "TypeC", 0); Assert.assertEquals("one", typeC0.getString("c1")); Assert.assertEquals("four", typeC0.getObject("c2").getString("b1")); Assert.assertEquals(typeC0.getObject("c2").getOrdinal(), typeA0.getSet("a4").findElement("four").getOrdinal()); } @Test public void flatRecordsCanBeDumpedToStateEnginesWithDifferentButCompatibleSchemas() { HollowObjectSchema typeASchema = new HollowObjectSchema("TypeA", 4, new PrimaryKey("TypeA", "a1", "a3.b1")); typeASchema.addField("a1", FieldType.INT); typeASchema.addField("a2", FieldType.STRING); typeASchema.addField("a3", FieldType.REFERENCE, "TypeB"); typeASchema.addField("a5", FieldType.BYTES); HollowObjectSchema typeBSchema = new HollowObjectSchema("TypeB", 2); typeBSchema.addField("b1", FieldType.STRING); typeBSchema.addField("b2", FieldType.INT); HollowObjectSchema typeCSchema = new HollowObjectSchema("TypeC", 2); typeCSchema.addField("c2", FieldType.REFERENCE, "TypeB"); typeCSchema.addField("c3", FieldType.FLOAT); producer.initializeDataModel(typeASchema, typeBSchema, typeCSchema); producer.runCycle(state -> { FlatRecordDumper dumper = new FlatRecordDumper(state.getStateEngine()); dumper.dump(flatten(new TypeA(1, "two", "three", "four", "five"))); dumper.dump(flatten(new TypeA(2, "two", "four", "six", "eight", "ten"))); dumper.dump(flatten(new TypeC("one", "three"))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefresh(); GenericHollowObject typeA0 = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 0); GenericHollowObject typeA1 = new GenericHollowObject(consumer.getStateEngine(), "TypeA", 1); Assert.assertEquals(1, typeA0.getInt("a1")); Assert.assertEquals("two", typeA0.getString("a2")); Assert.assertEquals("three", typeA0.getObject("a3").getString("b1")); Assert.assertNull(typeA0.getSet("a4")); Assert.assertNull(typeA0.getBytes("a5")); Assert.assertEquals(2, typeA1.getInt("a1")); Assert.assertEquals("two", typeA1.getString("a2")); Assert.assertEquals("four", typeA1.getObject("a3").getString("b1")); Assert.assertNull(typeA1.getSet("a4")); Assert.assertNull(typeA1.getBytes("a4")); GenericHollowObject typeC0 = new GenericHollowObject(consumer.getStateEngine(), "TypeC", 0); Assert.assertTrue(typeC0.isNull("c1")); Assert.assertEquals("three", typeC0.getObject("c2").getString("b1")); Assert.assertTrue(typeC0.isNull("c3")); Assert.assertEquals(typeC0.getObject("c2").getOrdinal(), typeA0.getObject("a3").getOrdinal()); } private FlatRecord flatten(Object obj) { flatRecordWriter.reset(); mapper.writeFlat(obj, flatRecordWriter); return flatRecordWriter.generateFlatRecord(); } private int flatRecordSize(Object obj) { flatRecordWriter.reset(); mapper.writeFlat(obj, flatRecordWriter); try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) { flatRecordWriter.writeTo(baos); return baos.size(); } catch(IOException e) { throw new RuntimeException(e); } } @HollowPrimaryKey(fields = { "a1", "a3" }) public static class TypeA { int a1; @HollowInline String a2; TypeB a3; @HollowHashKey(fields="b1") Set<TypeB> a4; @HollowInline Integer nullablePrimitiveInt; public TypeA(int a1, String a2, String a3, String... b1s) { this.a1 = a1; this.a2 = a2; this.a3 = new TypeB(a3); this.a4 = new HashSet<>(b1s.length); for (int i = 0; i < b1s.length; i++) { this.a4.add(new TypeB(b1s[i])); } this.nullablePrimitiveInt = null; } } public static class TypeB { @HollowInline String b1; public TypeB(String b1) { this.b1 = b1; } } public static class TypeC { @HollowInline String c1; TypeB c2; public TypeC(String c1, String b1) { this.c1 = c1; this.c2 = new TypeB(b1); } } }
8,692
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/objectmapper
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/core/write/objectmapper/flatrecords/FakeHollowSchemaIdentifierMapper.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.objectmapper.flatrecords; import com.netflix.hollow.core.HollowDataset; 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.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSchema.SchemaType; import java.util.List; public class FakeHollowSchemaIdentifierMapper implements HollowSchemaIdentifierMapper { private final HollowDataset dataset; private final List<HollowSchema> schemas; public FakeHollowSchemaIdentifierMapper(HollowDataset dataset) { this.schemas = dataset.getSchemas(); this.dataset = dataset; } @Override public HollowSchema getSchema(int identifier) { return schemas.get(identifier); } @Override public FieldType[] getPrimaryKeyFieldTypes(int identifier) { HollowSchema schema = getSchema(identifier); if (schema.getSchemaType() == SchemaType.OBJECT) { PrimaryKey primaryKey = ((HollowObjectSchema) schema).getPrimaryKey(); if (primaryKey != null) { FieldType fieldTypes[] = new FieldType[primaryKey.numFields()]; for (int i = 0; i < fieldTypes.length; i++) { fieldTypes[i] = primaryKey.getFieldType(dataset, i); } return fieldTypes; } } return null; } @Override public int getSchemaId(HollowSchema forSchema) { for (int i = 0; i < schemas.size(); i++) { HollowSchema datasetSchema = schemas.get(i); if (forSchema.equals(datasetSchema)) { return i; } } throw new IllegalArgumentException("Schema is unidentified: \n" + forSchema.toString()); } }
8,693
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/RestoreWriteStateEngineFieldRemovalCollapsesOrdinals.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.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.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 RestoreWriteStateEngineFieldRemovalCollapsesOrdinals extends AbstractStateEngineTest { HollowObjectSchema typeASchema; HollowObjectSchema typeBSchema_state1; HollowObjectSchema typeBSchema_state2; private boolean afterRestoreWithNewSchemas; @Before public void setUp() { typeASchema = new HollowObjectSchema("TypeA", 2); typeASchema.addField("a1", FieldType.INT); typeASchema.addField("a2", FieldType.REFERENCE, "TypeB"); typeBSchema_state1 = new HollowObjectSchema("TypeB", 2); typeBSchema_state1.addField("b1", FieldType.INT); typeBSchema_state1.addField("b2", FieldType.BOOLEAN); typeBSchema_state2 = new HollowObjectSchema("TypeB", 1); typeBSchema_state2.addField("b1", FieldType.INT); super.setUp(); } @Test public void test() throws IOException { addState1Record(0, 0, true); addState1Record(1, 1, true); addState1Record(2, 1, false); addState1Record(1, 1, false); roundTripSnapshot(); afterRestoreWithNewSchemas = true; restoreWriteStateEngineFromReadStateEngine(); addState2Record(1, 1); addState2Record(2, 1); addState2Record(0, 0); addState2Record(1, 1); addState2Record(1, 3); roundTripDelta(); assertTypeA(0, 0, 0); assertTypeA(1, 1, 1); assertTypeA(4, 2, 1); assertTypeA(5, 1, 3); assertTypeB(0, 0); assertTypeB(1, 1); assertTypeB(3, 3); /// the following are removed objects Assert.assertFalse((readStateEngine.getTypeState("TypeA").getListener(PopulatedOrdinalListener.class)).getPopulatedOrdinals().get(2)); Assert.assertFalse((readStateEngine.getTypeState("TypeB").getListener(PopulatedOrdinalListener.class)).getPopulatedOrdinals().get(2)); assertTypeB(2, 1); /// this object was removed, because it was a duplicate with a lower ordinal. assertTypeA(2, 2, 2); /// these objects were removed and re-added, because they were referencing the removed duplicate record. assertTypeA(3, 1, 2); } private void addState1Record(int a1, int b1, boolean b2) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema_state1); bRec.setInt("b1", b1); bRec.setBoolean("b2", b2); int bOrdinal = writeStateEngine.add("TypeB", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema); aRec.setInt("a1", a1); aRec.setReference("a2", bOrdinal); writeStateEngine.add("TypeA", aRec); } private void addState2Record(int a1, int b1) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema_state2); bRec.setInt("b1", b1); int bOrdinal = writeStateEngine.add("TypeB", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema); aRec.setInt("a1", a1); aRec.setReference("a2", bOrdinal); writeStateEngine.add("TypeA", aRec); } private void assertTypeA(int ordinal, int a1, int bOrdinal) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TypeA"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(a1, obj.getInt("a1")); Assert.assertEquals(bOrdinal, obj.getOrdinal("a2")); } private void assertTypeB(int ordinal, int b1) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TypeB"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(b1, obj.getInt("b1")); } @Override protected void initializeTypeStates() { if(!afterRestoreWithNewSchemas) { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeASchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeBSchema_state1)); } else { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeASchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeBSchema_state2)); } } }
8,694
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/RestoreWriteStateEngineMapReverseDeltaTest.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.map.HollowMapTypeReadState; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class RestoreWriteStateEngineMapReverseDeltaTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(1, 1, 3, 2, 2, 2); roundTripSnapshot(); assertMapContains(0, 1, 1, 3); assertMapContains(0, 2, 2, 2); restoreWriteStateEngineFromReadStateEngine(); addRecord(3, 3, 3, 4, 4, 2); 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())); assertMapContains(0, 1, 1, 3); assertMapContains(0, 2, 2, 2); } private void assertMapContains(int mapOrdinal, int keyOrdinal, int valueOrdinal, int hashCode) { HollowMapTypeReadState typeState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); int actualValueOrdinal = typeState.get(mapOrdinal, keyOrdinal, hashCode); Assert.assertEquals(valueOrdinal, actualValueOrdinal); } private void addRecord(int... ordinalsAndHashCodes) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<ordinalsAndHashCodes.length;i+=3) { rec.addEntry(ordinalsAndHashCodes[i], ordinalsAndHashCodes[i+1], ordinalsAndHashCodes[i+2]); } writeStateEngine.add("TestMap", rec); } @Override protected void initializeTypeStates() { HollowMapTypeWriteState writeState = new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestKey", "TestValue")); writeStateEngine.addTypeState(writeState); } }
8,695
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/RestoreWriteStateEngineFieldAdditionSplitsOrdinals.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 java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class RestoreWriteStateEngineFieldAdditionSplitsOrdinals extends AbstractStateEngineTest { HollowObjectSchema typeASchema; HollowObjectSchema typeBSchema_state1; HollowObjectSchema typeBSchema_state2; private boolean afterRestoreWithNewSchemas; @Before public void setUp() { typeASchema = new HollowObjectSchema("TypeA", 2); typeASchema.addField("a1", FieldType.INT); typeASchema.addField("a2", FieldType.REFERENCE, "TypeB"); typeBSchema_state1 = new HollowObjectSchema("TypeB", 1); typeBSchema_state1.addField("b1", FieldType.INT); typeBSchema_state2 = new HollowObjectSchema("TypeB", 2); typeBSchema_state2.addField("b1", FieldType.INT); typeBSchema_state2.addField("b2", FieldType.BOOLEAN); super.setUp(); } @Test public void test() throws IOException { addState1Record(0, 0); addState1Record(1, 1); addState1Record(2, 1); roundTripSnapshot(); afterRestoreWithNewSchemas = true; restoreWriteStateEngineFromReadStateEngine(); addState2Record(0, 0, true); addState2Record(1, 1, true); addState2Record(2, 1, false); roundTripDelta(); assertTypeA(0, 0, 0); assertTypeA(1, 1, 1); assertTypeA(3, 2, 2); assertTypeB(0, 0); assertTypeB(1, 1); assertTypeB(2, 1); addState2Record(0, 0, true); addState2Record(1, 1, true); addState2Record(2, 1, false); roundTripSnapshot(); assertTypeA(0, 0, 0); assertTypeA(1, 1, 1); assertTypeA(3, 2, 2); assertTypeB(0, 0, true); assertTypeB(1, 1, true); assertTypeB(2, 1, false); } private void addState1Record(int a1, int b1) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema_state1); bRec.setInt("b1", b1); int bOrdinal = writeStateEngine.add("TypeB", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema); aRec.setInt("a1", a1); aRec.setReference("a2", bOrdinal); writeStateEngine.add("TypeA", aRec); } private void addState2Record(int a1, int b1, boolean b2) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema_state2); bRec.setInt("b1", b1); bRec.setBoolean("b2", b2); int bOrdinal = writeStateEngine.add("TypeB", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema); aRec.setInt("a1", a1); aRec.setReference("a2", bOrdinal); writeStateEngine.add("TypeA", aRec); } private void assertTypeA(int ordinal, int a1, int bOrdinal) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TypeA"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(a1, obj.getInt("a1")); Assert.assertEquals(bOrdinal, obj.getOrdinal("a2")); } private void assertTypeB(int ordinal, int b1) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TypeB"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(b1, obj.getInt("b1")); } private void assertTypeB(int ordinal, int b1, boolean b2) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("TypeB"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(b1, obj.getInt("b1")); Assert.assertEquals(b2, obj.getBoolean("b2")); } @Override protected void initializeTypeStates() { if(!afterRestoreWithNewSchemas) { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeASchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeBSchema_state1)); } else { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeASchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeBSchema_state2)); } } }
8,696
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/RestoreWriteStateEngineHierarchyScenario.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.generic.GenericHollowList; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.objects.generic.GenericHollowRecordHelper; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; 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.util.StateEngineRoundTripper; 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.HollowTypeName; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collections; import java.util.List; import org.junit.Assert; import org.junit.Test; @SuppressWarnings("unused") public class RestoreWriteStateEngineHierarchyScenario { @HollowTypeName(name="TypeA") private static class TypeA1 { int id; List<TypeB1> b = Collections.singletonList(new TypeB1()); } @HollowTypeName(name="TypeB") private static class TypeB1 { String val; float removedData; } @HollowTypeName(name="TypeA") private static class TypeA2 { int id; int idEcho; List<TypeB2> b = Collections.singletonList(new TypeB2()); } @HollowTypeName(name="TypeB") private static class TypeB2 { String val; int idEcho; } @Test public void testAddition() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); TypeA1 a11 = new TypeA1(); a11.id = 1; a11.b.get(0).val = "A"; a11.b.get(0).removedData = 1.0f; mapper.add(a11); TypeA1 a12 = new TypeA1(); a12.id = 2; a12.b.get(0).val = "B"; a12.b.get(0).removedData = 2.0f; mapper.add(a12); TypeA1 a13 = new TypeA1(); a13.id = 3; a13.b.get(0).val = "A"; a13.b.get(0).removedData = 1.0f; mapper.add(a13); HollowReadStateEngine readStateEngine = StateEngineRoundTripper.roundTripSnapshot(writeStateEngine); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); writeStateEngine = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(TypeA2.class); mapper.initializeTypeState(TypeB2.class); writeStateEngine.restoreFrom(readStateEngine); TypeA2 a22 = new TypeA2(); a22.id = 2; a22.idEcho = 2; a22.b.get(0).val = "B"; a22.b.get(0).idEcho = 2; mapper.add(a22); TypeA2 a23 = new TypeA2(); a23.id = 3; a23.idEcho = 3; a23.b.get(0).val = "B"; a23.b.get(0).idEcho = 3; mapper.add(a23); TypeA2 a21 = new TypeA2(); a21.id = 1; a21.idEcho = 1; a21.b.get(0).val = "A"; a21.b.get(0).idEcho = 1; mapper.add(a21); ///reset after restore writeStateEngine.resetToLastPrepareForNextCycle(); a22 = new TypeA2(); a22.id = 2; a22.idEcho = 2; a22.b.get(0).val = "B"; a22.b.get(0).idEcho = 2; mapper.add(a22); a23 = new TypeA2(); a23.id = 3; a23.idEcho = 3; a23.b.get(0).val = "A"; a23.b.get(0).idEcho = 3; mapper.add(a23); a21 = new TypeA2(); a21.id = 1; a21.idEcho = 1; a21.b.get(0).val = "A"; a21.b.get(0).idEcho = 1; mapper.add(a21); writeStateEngine.prepareForWrite(); HollowBlobWriter writer = new HollowBlobWriter(writeStateEngine); ByteArrayOutputStream delta = new ByteArrayOutputStream(); ByteArrayOutputStream reverseDelta = new ByteArrayOutputStream(); ByteArrayOutputStream snapshot = new ByteArrayOutputStream(); writer.writeDelta(delta); writer.writeReverseDelta(reverseDelta); writer.writeSnapshot(snapshot); HollowBlobReader reader = new HollowBlobReader(readStateEngine); reader.applyDelta(HollowBlobInput.serial(delta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); reader.applyDelta(HollowBlobInput.serial(reverseDelta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); readStateEngine = new HollowReadStateEngine(); reader = new HollowBlobReader(readStateEngine); reader.readSnapshot(HollowBlobInput.serial(snapshot.toByteArray())); assertA(readStateEngine, 1, "A", true); assertA(readStateEngine, 2, "B", true); assertA(readStateEngine, 3, "A", true); reader.applyDelta(HollowBlobInput.serial(reverseDelta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); reader.applyDelta(HollowBlobInput.serial(delta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); } @Test public void testRemoval() throws IOException { HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine); TypeA2 a22 = new TypeA2(); a22.id = 2; a22.idEcho = 2; a22.b.get(0).val = "B"; a22.b.get(0).idEcho = 2; mapper.add(a22); TypeA2 a23 = new TypeA2(); a23.id = 3; a23.idEcho = 3; a23.b.get(0).val = "A"; a23.b.get(0).idEcho = 3; mapper.add(a23); TypeA2 a21 = new TypeA2(); a21.id = 1; a21.idEcho = 1; a21.b.get(0).val = "A"; a21.b.get(0).idEcho = 1; mapper.add(a21); HollowReadStateEngine readStateEngine = StateEngineRoundTripper.roundTripSnapshot(writeStateEngine); assertA(readStateEngine, 1, "A", true); assertA(readStateEngine, 2, "B", true); assertA(readStateEngine, 3, "A", true); writeStateEngine = new HollowWriteStateEngine(); mapper = new HollowObjectMapper(writeStateEngine); mapper.initializeTypeState(TypeA1.class); mapper.initializeTypeState(TypeB1.class); writeStateEngine.restoreFrom(readStateEngine); TypeA1 a11 = new TypeA1(); a11.id = 1; a11.b.get(0).val = "A"; a11.b.get(0).removedData = 1.0f; mapper.add(a11); TypeA1 a12 = new TypeA1(); a12.id = 2; a12.b.get(0).val = "B"; a12.b.get(0).removedData = 2.0f; mapper.add(a12); TypeA1 a13 = new TypeA1(); a13.id = 3; a13.b.get(0).val = "A"; a13.b.get(0).removedData = 3.0f; mapper.add(a13); writeStateEngine.prepareForWrite(); writeStateEngine.resetToLastPrepareForNextCycle(); a11 = new TypeA1(); a11.id = 1; a11.b.get(0).val = "A"; a11.b.get(0).removedData = 1.0f; mapper.add(a11); a12 = new TypeA1(); a12.id = 2; a12.b.get(0).val = "B"; a12.b.get(0).removedData = 2.0f; mapper.add(a12); a13 = new TypeA1(); a13.id = 3; a13.b.get(0).val = "A"; a13.b.get(0).removedData = 1.0f; mapper.add(a13); //writeStateEngine.prepareForWrite(); HollowBlobWriter writer = new HollowBlobWriter(writeStateEngine); ByteArrayOutputStream delta = new ByteArrayOutputStream(); ByteArrayOutputStream reverseDelta = new ByteArrayOutputStream(); ByteArrayOutputStream snapshot = new ByteArrayOutputStream(); writer.writeDelta(delta); writer.writeReverseDelta(reverseDelta); writer.writeSnapshot(snapshot); HollowBlobReader reader = new HollowBlobReader(readStateEngine); reader.applyDelta(HollowBlobInput.serial(delta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); reader.applyDelta(HollowBlobInput.serial(reverseDelta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); readStateEngine = new HollowReadStateEngine(); reader = new HollowBlobReader(readStateEngine); reader.readSnapshot(HollowBlobInput.serial(snapshot.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); reader.applyDelta(HollowBlobInput.serial(reverseDelta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); reader.applyDelta(HollowBlobInput.serial(delta.toByteArray())); assertA(readStateEngine, 1, "A", false); assertA(readStateEngine, 2, "B", false); assertA(readStateEngine, 3, "A", false); } private void assertA(HollowReadStateEngine stateEngine, int id, String val, boolean verifyEchoes) { HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(stateEngine, "TypeA", "id"); int ordinal = idx.getMatchingOrdinal(id); GenericHollowObject a = (GenericHollowObject) GenericHollowRecordHelper.instantiate(stateEngine, "TypeA", ordinal); GenericHollowList bList = (GenericHollowList)a.getReferencedGenericRecord("b"); GenericHollowObject b = (GenericHollowObject)bList.get(0); GenericHollowObject str = (GenericHollowObject)b.getReferencedGenericRecord("val"); Assert.assertEquals(val, str.getString("value")); if(verifyEchoes) { Assert.assertEquals(id, a.getInt("idEcho")); Assert.assertEquals(id, b.getInt("idEcho")); } } }
8,697
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/RestoreWriteStateEngineMapTest.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.map.HollowMapTypeReadState; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class RestoreWriteStateEngineMapTest extends AbstractStateEngineTest { @Test public void test() throws IOException { addRecord(10, 20, 30, 40); addRecord(40, 50, 60, 70); addRecord(70, 80, 90, 100); roundTripSnapshot(); restoreWriteStateEngineFromReadStateEngine(); 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(); restoreWriteStateEngineFromReadStateEngine(); assertMap(0, 10, 20, 30, 40); assertMap(1, 40, 50, 60, 70); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertMap(2, 70, 80, 90, 100); assertMap(3, 100, 200, 300, 400, 500, 600, 700, 800); assertMap(4, 1, 2, 3, 4); Assert.assertEquals(4, maxOrdinal()); roundTripDelta(); assertMap(0, 10, 20, 30, 40); /// all maps were "removed", but again hang around until the following cycle. assertMap(1); /// this map should now be disappeared. assertMap(2, 70, 80, 90, 100); /// "ghost" assertMap(3, 100, 200, 300, 400, 500, 600, 700, 800); /// "ghost" assertMap(4, 1, 2, 3, 4); /// "ghost" Assert.assertEquals(4, maxOrdinal()); addRecord(634, 54732); addRecord(1, 2, 3, 4); roundTripSnapshot(); Assert.assertEquals(1, maxOrdinal()); assertMap(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(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 restoreFailsIfShardConfigurationChanges() throws IOException { roundTripSnapshot(); HollowWriteStateEngine writeStateEngine = new HollowWriteStateEngine(); HollowMapTypeWriteState misconfiguredTypeState = new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestKey", "TestValue"), 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) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<ordinals.length;i+=2) { rec.addEntry(ordinals[i], ordinals[i+1], ordinals[i] + 100); } writeStateEngine.add("TestMap", rec); } private void assertMap(int ordinal, int... elements) { HollowMapTypeReadState readState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); 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], elements[i] + 100)); } } private int maxOrdinal() { HollowMapTypeReadState readState = (HollowMapTypeReadState) readStateEngine.getTypeState("TestMap"); return readState.maxOrdinal(); } @Override protected void initializeTypeStates() { HollowMapTypeWriteState writeState = new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestKey", "TestValue")); writeStateEngine.addTypeState(writeState); } }
8,698
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/RestoreWriteStateEngineChangingSchemaTest.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 RestoreWriteStateEngineChangingSchemaTest extends AbstractStateEngineTest { HollowObjectSchema typeASchema_state1; HollowObjectSchema typeASchema_state2; HollowObjectSchema typeBSchema; HollowObjectSchema typeCSchema; private boolean afterRestoreWithNewSchemas; @Before public void setUp() { typeASchema_state1 = new HollowObjectSchema("TypeA", 3); typeASchema_state1.addField("a1", FieldType.BOOLEAN); typeASchema_state1.addField("a2", FieldType.STRING); typeASchema_state1.addField("a3", FieldType.REFERENCE, "TypeB"); typeBSchema = new HollowObjectSchema("TypeB", 2); typeBSchema.addField("b1", FieldType.LONG); typeBSchema.addField("b2", FieldType.FLOAT); typeASchema_state2 = new HollowObjectSchema("TypeA", 3); typeASchema_state2.addField("a2", FieldType.STRING); typeASchema_state2.addField("a1", FieldType.BOOLEAN); typeASchema_state2.addField("a4", FieldType.REFERENCE, "TypeC"); typeCSchema = new HollowObjectSchema("TypeC", 1); typeCSchema.addField("c1", FieldType.STRING); super.setUp(); } @Test public void test() throws IOException { addState1Record(true, "zero", 0, 0.1f); // ordinals 0, 0 addState1Record(false, "one", 1, 1.1f); // ordinals 1, 1 addState1Record(true, "two", 1, 1.1f); // ordinals 2, 1 roundTripSnapshot(); addState1Record(true, "zero", 0, 0.1f); // 0, 0 addState1Record(false, "one", 1, 1.1f); // 1, 1 addState1Record(false, "two", 2, 2.2f); // 3, 2 roundTripDelta(); afterRestoreWithNewSchemas = true; restoreWriteStateEngineFromReadStateEngine(); addState2Record(false, "one", "c1"); // 1, 0 addState2Record(false, "two", "c2"); // 3, 1 addState2Record(true, "zero", "c0"); // 0, 2 addState2Record(true, "wxyz", "c3"); // 2, 3 roundTripDelta(); assertTypeA(0, true, "zero"); assertTypeA(1, false, "one"); assertTypeA(3, false, "two"); assertTypeA(2, true, "wxyz"); addState2Record(false, "one", "c1"); // 1, 0 addState2Record(false, "two", "c2"); // 3, 1 addState2Record(true, "zero", "c0"); // 0, 2 addState2Record(true, "wxyz", "c3"); // 2, 3 roundTripSnapshot(); assertTypeAWithTypeC(0, true, "zero", "c0"); assertTypeAWithTypeC(1, false, "one", "c1"); assertTypeAWithTypeC(3, false, "two", "c2"); assertTypeAWithTypeC(2, true, "wxyz", "c3"); } @Test public void doesNotAllowImproperlyInitializedRestoredStateToProduceDelta() throws IOException { addState1Record(true, "zero", 0, 0.1f); // ordinals 0, 0 addState1Record(false, "one", 1, 1.1f); // ordinals 1, 1 addState1Record(true, "two", 1, 1.1f); // ordinals 2, 1 roundTripSnapshot(); addState1Record(true, "zero", 0, 0.1f); // 0, 0 addState1Record(false, "one", 1, 1.1f); // 1, 1 addState1Record(false, "two", 2, 2.2f); // 3, 2 roundTripDelta(); afterRestoreWithNewSchemas = true; ////restore, but initialize type states *after* restore writeStateEngine = new HollowWriteStateEngine(); writeStateEngine.restoreFrom(readStateEngine); initializeTypeStates(); writeStateEngine.prepareForNextCycle(); addState2Record(false, "one", "c1"); // 1, 0 addState2Record(false, "two", "c2"); // 3, 1 addState2Record(true, "zero", "c0"); // 0, 2 addState2Record(true, "wxyz", "c3"); // 2, 3 try { roundTripDelta(); Assert.fail("Should have thrown Exception when attempting to produce a delta!"); } catch(IllegalStateException expected) { Assert.assertTrue(expected.getMessage().contains("TypeA")); } } private void assertTypeA(int ordinal, boolean a1, String a2) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState)readStateEngine.getTypeState("TypeA"); GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); Assert.assertEquals(a1, obj.getBoolean("a1")); Assert.assertEquals(a2, obj.getString("a2")); } private void assertTypeAWithTypeC(int ordinal, boolean a1, String a2, String c1) { HollowObjectTypeReadState typeAState = (HollowObjectTypeReadState)readStateEngine.getTypeState("TypeA"); GenericHollowObject typeAObj = new GenericHollowObject(new HollowObjectGenericDelegate(typeAState), ordinal); Assert.assertEquals(a1, typeAObj.getBoolean("a1")); Assert.assertEquals(a2, typeAObj.getString("a2")); GenericHollowObject typeCObj = (GenericHollowObject) typeAObj.getReferencedGenericRecord("a4"); Assert.assertEquals(c1, typeCObj.getString("c1")); } private void addState1Record(boolean a1, String a2, long b1, float b2) { HollowObjectWriteRecord bRec = new HollowObjectWriteRecord(typeBSchema); bRec.setLong("b1", b1); bRec.setFloat("b2", b2); int bOrdinal = writeStateEngine.add("TypeB", bRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema_state1); aRec.setBoolean("a1", a1); aRec.setString("a2", a2); aRec.setReference("a3", bOrdinal); writeStateEngine.add("TypeA", aRec); } private void addState2Record(boolean a1, String a2, String c1) { HollowObjectWriteRecord cRec = new HollowObjectWriteRecord(typeCSchema); cRec.setString("c1", c1); int cOrdinal = writeStateEngine.add("TypeC", cRec); HollowObjectWriteRecord aRec = new HollowObjectWriteRecord(typeASchema_state2); aRec.setBoolean("a1", a1); aRec.setString("a2", a2); aRec.setReference("a4", cOrdinal); writeStateEngine.add("TypeA", aRec); } @Override protected void initializeTypeStates() { if(!afterRestoreWithNewSchemas) { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeBSchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeASchema_state1)); } else { writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeCSchema)); writeStateEngine.addTypeState(new HollowObjectTypeWriteState(typeASchema_state2)); } } }
8,699