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/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/TypeAState2.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
public class TypeAState2 {
private final int a1;
private final TypeC c;
public TypeAState2(int a1, TypeC c) {
this.a1 = a1;
this.c = c;
}
public int getA1() {
return a1;
}
public TypeC getC() {
return c;
}
}
| 8,200 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/TypeC.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
public class TypeC {
private final int c1;
public TypeC(int c1) {
this.c1 = c1;
}
public int getC1() {
return c1;
}
}
| 8,201 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/TypeB.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
public class TypeB {
private final int b1;
public TypeB(int b1) {
this.b1 = b1;
}
public int getB1() {
return b1;
}
}
| 8,202 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/RestoreServerAfterSchemaChangeTest.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.io.FastBlobReader;
import com.netflix.zeno.fastblob.io.FastBlobWriter;
import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
public class RestoreServerAfterSchemaChangeTest {
@Test
public void addingANewSerializerAndChangingTheFieldsInExistingSerializer() throws IOException {
// create a server's state engine with an initial set of serializers
FastBlobStateEngine stateEngine1 = new FastBlobStateEngine(state1Factory());
/// add some data to that server
stateEngine1.add("TypeA", new TypeAState1(1));
stateEngine1.add("TypeA", new TypeAState1(2));
stateEngine1.add("TypeA", new TypeAState1(3));
stateEngine1.add("TypeB", new TypeB(1));
stateEngine1.add("TypeB", new TypeB(2));
stateEngine1.add("TypeB", new TypeB(3));
/// set the latest version
stateEngine1.setLatestVersion("test1");
/// serialize that data
stateEngine1.prepareForWrite();
ByteArrayOutputStream serializedSnapshotState1 = new ByteArrayOutputStream();
new FastBlobWriter(stateEngine1, 0).writeSnapshot(new DataOutputStream(serializedSnapshotState1));
/// serialize the state engine
ByteArrayOutputStream serializedStateEngine1 = new ByteArrayOutputStream();
stateEngine1.serializeTo(serializedStateEngine1);
/// server is restarted with updated serializers
FastBlobStateEngine stateEngine2 = new FastBlobStateEngine(state2Factory());
/// deserialize the state engine from the previous server (with the old serializers)
stateEngine2.deserializeFrom(new ByteArrayInputStream(serializedStateEngine1.toByteArray()));
stateEngine2.prepareForNextCycle();
/// add new data to the state engine, with some overlap
TypeC c1 = new TypeC(1);
TypeC c2 = new TypeC(2);
TypeC c3 = new TypeC(3);
stateEngine2.add("TypeA", new TypeAState2(1, c1));
stateEngine2.add("TypeA", new TypeAState2(2, c2));
stateEngine2.add("TypeA", new TypeAState2(4, c3));
stateEngine2.add("TypeB", new TypeB(1));
stateEngine2.add("TypeB", new TypeB(9));
stateEngine2.add("TypeB", new TypeB(3));
stateEngine2.setLatestVersion("test");
/// serialize a delta between the previous state and this state
stateEngine2.prepareForWrite();
ByteArrayOutputStream serializedDeltaState2 = new ByteArrayOutputStream();
new FastBlobWriter(stateEngine2, 0).writeDelta(new DataOutputStream(serializedDeltaState2));
/// now we need to deserialize. Deserialize first the snapshot produced by server 1, then the delta produced by server 2 (with different serializers)
new FastBlobReader(stateEngine1).readSnapshot(new ByteArrayInputStream(serializedSnapshotState1.toByteArray()));
new FastBlobReader(stateEngine1).readDelta(new ByteArrayInputStream(serializedDeltaState2.toByteArray()));
/// get the type As
FastBlobTypeDeserializationState<TypeAState1> typeAs = stateEngine1.getTypeDeserializationState("TypeA");
/// here we use some implicit knowledge about how the state engine works to verify the functionality...
/// A's serializer changed, so the ordinals for the new objects should not overlap with any of the original
/// ordinals (0, 1, 2).
Assert.assertEquals(1, typeAs.get(3).getA1());
Assert.assertEquals(2, typeAs.get(4).getA1());
Assert.assertEquals(4, typeAs.get(5).getA1());
FastBlobTypeDeserializationState<TypeB> typeBs = stateEngine1.getTypeDeserializationState("TypeB");
/// B's serializer did not change. The ordinals for objects which exist across states will be reused (0, 2)
/// one new ordinal will be added for the changed object (3)
Assert.assertEquals(1, typeBs.get(0).getB1());
Assert.assertEquals(3, typeBs.get(2).getB1());
Assert.assertEquals(9, typeBs.get(3).getB1());
FastBlobStateEngine removedTypeBStateEngine = new FastBlobStateEngine(removedTypeBFactory());
new FastBlobReader(removedTypeBStateEngine).readSnapshot(new ByteArrayInputStream(serializedSnapshotState1.toByteArray()));
new FastBlobReader(removedTypeBStateEngine).readDelta(new ByteArrayInputStream(serializedDeltaState2.toByteArray()));
/// get the type As
FastBlobTypeDeserializationState<TypeAState2> typeA2s = removedTypeBStateEngine.getTypeDeserializationState("TypeA");
/// here we use some implicit knowledge about how the state engine works to verify the functionality...
/// A's serializer changed, so the ordinals for the new objects should not overlap with any of the original
/// ordinals (0, 1, 2).
Assert.assertEquals(1, typeA2s.get(3).getC().getC1());
Assert.assertEquals(2, typeA2s.get(4).getC().getC1());
Assert.assertEquals(3, typeA2s.get(5).getC().getC1());
}
private SerializerFactory removedTypeBFactory() {
return new SerializerFactory() {
@Override
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] {
new AState2Serializer()
};
}
};
}
private SerializerFactory state2Factory() {
return new SerializerFactory() {
@Override
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] {
new AState2Serializer(),
new BSerializer()
};
}
};
}
private SerializerFactory state1Factory() {
return new SerializerFactory() {
@Override
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] {
new AState1Serializer(),
new BSerializer()
};
}
};
}
}
| 8,203 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/AState2Serializer.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
import java.util.Collection;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
public class AState2Serializer extends NFTypeSerializer<TypeAState2>{
private final FastBlobSchemaField[] fields = new FastBlobSchemaField[] {
field("a1", FieldType.INT),
field("c", new TypeCSerializer())
};
public AState2Serializer() {
super("TypeA");
}
@Override
public void doSerialize(TypeAState2 value, NFSerializationRecord rec) {
serializePrimitive(rec, "a1", value.getA1());
serializeObject(rec, "c", value.getC());
}
@Override
protected TypeAState2 doDeserialize(NFDeserializationRecord rec) {
int a1 = deserializeInteger(rec, "a1");
TypeC c = deserializeObject(rec, "c");
return new TypeAState2(a1, c);
}
@Override
protected FastBlobSchema createSchema() {
return schema(fields);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return requiredSubSerializers(fields);
}
}
| 8,204 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/TypeCSerializer.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
public class TypeCSerializer extends NFTypeSerializer<TypeC>{
public TypeCSerializer() {
super("TypeC");
}
@Override
public void doSerialize(TypeC value, NFSerializationRecord rec) {
serializePrimitive(rec, "c1", value.getC1());
}
@Override
protected TypeC doDeserialize(NFDeserializationRecord rec) {
int c1 = deserializeInteger(rec, "c1");
return new TypeC(c1);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("c1", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers();
}
}
| 8,205 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/TypeAState1.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
public class TypeAState1 {
private final int a1;
public TypeAState1(int a1) {
this.a1 = a1;
}
public int getA1() {
return a1;
}
}
| 8,206 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/AState1Serializer.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
public class AState1Serializer extends NFTypeSerializer<TypeAState1>{
public AState1Serializer() {
super("TypeA");
}
@Override
public void doSerialize(TypeAState1 value, NFSerializationRecord rec) {
serializePrimitive(rec, "a1", value.getA1());
}
@Override
protected TypeAState1 doDeserialize(NFDeserializationRecord rec) {
int a1 = deserializeInteger(rec, "a1");
return new TypeAState1(a1);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("a1", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers();
}
}
| 8,207 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob | Create_ds/zeno/src/test/java/com/netflix/zeno/fastblob/restorescenarios/BSerializer.java | /*
*
* Copyright 2013 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.zeno.fastblob.restorescenarios;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
public class BSerializer extends NFTypeSerializer<TypeB> {
public BSerializer() {
super("TypeB");
}
@Override
public void doSerialize(TypeB value, NFSerializationRecord rec) {
serializePrimitive(rec, "b1", value.getB1());
}
@Override
protected TypeB doDeserialize(NFDeserializationRecord rec) {
int b1 = deserializeInteger(rec, "b1");
return new TypeB(b1);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("b1", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers();
}
}
| 8,208 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/JaccardMatrixPairwiseMatcherTest.java | /*
*
* Copyright 2013 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.zeno.diff;
import com.netflix.zeno.genericobject.GenericObject.Field;
import com.netflix.zeno.genericobject.JaccardMatrixPairwiseMatcher;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class JaccardMatrixPairwiseMatcherTest {
private DiffSerializationFramework diffFramework = null;
private JaccardMatrixPairwiseMatcher matcher = null;
@Before
public void setUp() {
List<Field> objects1 = new ArrayList<Field>();
List<Field> objects2 = new ArrayList<Field>();
List<DiffRecord> recs1 = new ArrayList<DiffRecord>();
List<DiffRecord> recs2 = new ArrayList<DiffRecord>();
diffFramework = new DiffSerializationFramework(new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new ASerializer() };
}
});
addObject(new TypeB(1, 1, 1), "TypeB", objects1, recs1);
addObject(new TypeB(2, 2, 2), "TypeB", objects1, recs1);
addObject(new TypeB(3, 3, 3), "TypeB", objects1, recs1);
addObject(new TypeB(3, 3, 3), "TypeB", objects2, recs2);
addObject(new TypeB(4, 5, 6), "TypeB", objects2, recs2);
addObject(new TypeB(2, 4, 4), "TypeB", objects2, recs2);
addObject(new TypeB(1, 1, 2), "TypeB", objects2, recs2);
matcher = new JaccardMatrixPairwiseMatcher(objects1, recs1, objects2, recs2);
}
private void addObject(Object obj, String serializerName, List<Field> objs, List<DiffRecord> recs) {
NFTypeSerializer<Object> serializer = (NFTypeSerializer<Object>) diffFramework.getSerializer(serializerName);
DiffRecord rec = new DiffRecord();
rec.setSchema(serializer.getFastBlobSchema());
rec.setTopLevelSerializerName(serializerName);
serializer.serialize(obj, rec);
objs.add(new Field("obj", obj));
recs.add(rec);
}
@Test
public void matchesPairs() {
Assert.assertTrue(matcher.nextPair());
Assert.assertEquals(new TypeB(3, 3, 3), matcher.getX().getValue());
Assert.assertEquals(new TypeB(3, 3, 3), matcher.getY().getValue());
Assert.assertTrue(matcher.nextPair());
Assert.assertEquals(new TypeB(1, 1, 1), matcher.getX().getValue());
Assert.assertEquals(new TypeB(1, 1, 2), matcher.getY().getValue());
Assert.assertTrue(matcher.nextPair());
Assert.assertEquals(new TypeB(2, 2, 2), matcher.getX().getValue());
Assert.assertEquals(new TypeB(2, 4, 4), matcher.getY().getValue());
Assert.assertTrue(matcher.nextPair());
Assert.assertNull(matcher.getX());
Assert.assertEquals(new TypeB(4, 5, 6), matcher.getY().getValue());
Assert.assertFalse(matcher.nextPair());
}
}
| 8,209 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/DiffHtmlGeneratorTest.java | /*
*
* Copyright 2013 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.zeno.diff;
import com.netflix.zeno.genericobject.DiffHtmlGenerator;
import com.netflix.zeno.genericobject.GenericObject;
import com.netflix.zeno.genericobject.GenericObjectSerializationFramework;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class DiffHtmlGeneratorTest {
TypeA a1;
TypeA a2;
@Before
public void setUp() {
a1 = new TypeA(new TypeB(999, 888, 777), new TypeB(1, 2, 3), new TypeB(4, 5, 6));
a2 = new TypeA(new TypeB(4, 5, 6), new TypeB(1, 92, 3), new TypeB(40, 41, 42));
}
@Test
public void test() {
SerializerFactory factory = new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new ASerializer() };
}
};
DiffHtmlGenerator htmlGenerator = new DiffHtmlGenerator(factory);
GenericObjectSerializationFramework framework = new GenericObjectSerializationFramework(factory);
GenericObject obj1 = framework.serialize(a1, "TypeA");
GenericObject obj2 = framework.serialize(a2, "TypeA");
String diffHtml = htmlGenerator.generateDiff(obj1, obj2);
/// 4, 5, 6 pair should be matched most closely and come first:
int indexOf456Pair = diffHtml.indexOf("val1: 4");
/// 1, 2, 3 and 1, 92, 3 should be matched second closest and come after
int indexOf123Pair = diffHtml.indexOf("val1: 1");
///999, 888, 777 has no matches and will be shown in the right column only
int indexOf999Element = diffHtml.indexOf("val1: 999");
/// 40, 41, 42 has no matches
int indexOf40Element = diffHtml.indexOf("val1: 40");
Assert.assertTrue(indexOf456Pair < indexOf123Pair);
Assert.assertTrue(indexOf123Pair < indexOf999Element);
Assert.assertTrue(indexOf123Pair < indexOf40Element);
}
}
| 8,210 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/TypeB.java | /*
*
* Copyright 2013 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.zeno.diff;
public class TypeB {
private final int val1;
private final int val2;
private final int val3;
public TypeB(int val1, int val2, int val3) {
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
}
public int getVal1() {
return val1;
}
public int getVal2() {
return val2;
}
public int getVal3() {
return val3;
}
public int hashCode() {
return val1 + 31 * val2 + 91 * val3;
}
public boolean equals(Object another) {
if(another instanceof TypeB) {
TypeB otherB = (TypeB) another;
return otherB.val1 == val1 && otherB.val2 == val2 && otherB.val3 == val3;
}
return false;
}
public String toString() {
return "TypeB { " + val1 + "," + val2 + "," + val3 + " }";
}
}
| 8,211 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/DiffPropertyPathTest.java | /*
*
* Copyright 2013 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.zeno.diff;
import org.junit.Assert;
import org.junit.Test;
public class DiffPropertyPathTest {
@Test
public void hashCodeIsConsistent() {
DiffPropertyPath prop = new DiffPropertyPath();
prop.setTopNodeSerializer("topNodeSerializer");
prop.addBreadcrumb("test");
prop.addBreadcrumb("hash");
int firstHashCode = prop.hashCode();
prop.addBreadcrumb("code");
int secondHashCode = prop.hashCode();
prop.addBreadcrumb("is");
prop.addBreadcrumb("consistent");
int thirdHashCode = prop.hashCode();
Assert.assertEquals(thirdHashCode, prop.hashCode());
prop.removeBreadcrumb();
prop.removeBreadcrumb();
Assert.assertEquals(secondHashCode, prop.hashCode());
prop.removeBreadcrumb();
Assert.assertEquals(firstHashCode, prop.hashCode());
prop.addBreadcrumb("code");
Assert.assertEquals(secondHashCode, prop.hashCode());
prop.addBreadcrumb("is");
Assert.assertFalse(thirdHashCode == prop.hashCode());
prop.addBreadcrumb("consistent");
Assert.assertEquals(thirdHashCode, prop.hashCode());
}
}
| 8,212 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/DiffFrameworkTest.java | /*
*
* Copyright 2013 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.zeno.diff;
import com.netflix.zeno.diff.TypeDiff.ObjectDiffScore;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
import com.netflix.zeno.testpojos.TypeA;
import com.netflix.zeno.testpojos.TypeASerializer;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class DiffFrameworkTest {
DiffSerializationFramework framework;
@Before
public void setUp() {
framework = new DiffSerializationFramework(new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new TypeASerializer() };
}
});
}
@Test
public void test() {
List<TypeA> list1 = new ArrayList<TypeA>();
List<TypeA> list2 = new ArrayList<TypeA>();
list1.add(new TypeA(1, 2));
list2.add(new TypeA(1, 2));
list1.add(new TypeA(2, 3));
list2.add(new TypeA(2, 4));
list1.add(new TypeA(3, 4));
list2.add(new TypeA(4, 6));
list1.add(new TypeA(5, 7));
list2.add(new TypeA(5, 8));
list1.add(new TypeA(6, 9));
list2.add(new TypeA(6, 10));
list1.add(new TypeA(7, 11));
list2.add(new TypeA(8, 12));
TypeDiffInstruction<TypeA> diffInstruction = new TypeDiffInstruction<TypeA>() {
public String getSerializerName() {
return "TypeA";
}
@Override
public Object getKey(TypeA object) {
return Integer.valueOf(object.getVal1());
}
};
TypeDiffOperation<TypeA> diffOperation = new TypeDiffOperation<TypeA>(diffInstruction);
TypeDiff<TypeA> typeDiff = diffOperation.performDiff(framework, list1, list2, 2);
Assert.assertEquals(2, typeDiff.getExtraInFrom().size());
Assert.assertTrue(typeDiff.getExtraInFrom().contains(new TypeA(3, 4)));
Assert.assertTrue(typeDiff.getExtraInFrom().contains(new TypeA(7, 11)));
Assert.assertEquals(2, typeDiff.getExtraInTo().size());
Assert.assertTrue(typeDiff.getExtraInTo().contains(new TypeA(4, 6)));
Assert.assertTrue(typeDiff.getExtraInTo().contains(new TypeA(8, 12)));
Assert.assertEquals(3, typeDiff.getDiffObjects().size());
Assert.assertEquals(2, typeDiff.getDiffObjects().get(0).getScore());
Assert.assertEquals(2, typeDiff.getDiffObjects().get(1).getScore());
Assert.assertEquals(2, typeDiff.getDiffObjects().get(2).getScore());
long fromHashTotal = 0;
long toHashTotal = 0;
for (ObjectDiffScore<TypeA> diffScore : typeDiff.getDiffObjects()) {
TypeA type = diffScore.getFrom();
Assert.assertTrue(type.equals(new TypeA(2, 3)) || type.equals(new TypeA(5, 7)) || type.equals(new TypeA(6, 9)));
TypeA toType = diffScore.getTo();
Assert.assertTrue(toType.equals(new TypeA(2, 4)) || toType.equals(new TypeA(5, 8)) || toType.equals(new TypeA(6, 10)));
fromHashTotal += type.hashCode();
toHashTotal += toType.hashCode();
}
Assert.assertEquals(650, fromHashTotal);
Assert.assertEquals(689, toHashTotal);
Assert.assertEquals(2, typeDiff.getSortedFieldDifferencesDescending().size());
Assert.assertEquals(0.75, typeDiff.getSortedFieldDifferencesDescending().get(0).getDiffScore().getDiffPercent(), 0.001);
Assert.assertEquals(0, typeDiff.getSortedFieldDifferencesDescending().get(1).getDiffScore().getDiffPercent(), 0.0);
}
}
| 8,213 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/ASerializer.java | /*
*
* Copyright 2013 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.zeno.diff;
import java.util.Collection;
import java.util.Set;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.SetSerializer;
public class ASerializer extends NFTypeSerializer<TypeA>{
private final FastBlobSchemaField[] fields = new FastBlobSchemaField[] {
field("typeBs", new SetSerializer<TypeB>(new BSerializer()))
};
public ASerializer() {
super("TypeA");
}
@Override
public void doSerialize(TypeA value, NFSerializationRecord rec) {
serializeObject(rec, "typeBs", value.getTypeBs());
}
@Override
protected TypeA doDeserialize(NFDeserializationRecord rec) {
Set<TypeB> setOfTypeBs = deserializeObject(rec, "typeBs");
return new TypeA(setOfTypeBs);
}
@Override
protected FastBlobSchema createSchema() {
return schema(fields);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return requiredSubSerializers(fields);
}
}
| 8,214 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/TypeA.java | /*
*
* Copyright 2013 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.zeno.diff;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class TypeA {
private final Set<TypeB> typeBs;
public TypeA(TypeB... typeBs) {
this.typeBs = new BSet(Arrays.asList(typeBs));
}
public TypeA(Set<TypeB> typeBs) {
this.typeBs = typeBs;
}
public Set<TypeB> getTypeBs() {
return typeBs;
}
public int hashCode() {
return typeBs.hashCode();
}
public boolean equals(Object another) {
if(another instanceof TypeA) {
TypeA otherA = (TypeA) another;
return otherA.typeBs.equals(typeBs);
}
return false;
}
private static class BSet extends AbstractSet<TypeB> {
List<TypeB> bList = new ArrayList<TypeB>();
public BSet(List<TypeB> bList) {
this.bList = bList;
}
@Override
public Iterator<TypeB> iterator() {
return bList.iterator();
}
@Override
public int size() {
return bList.size();
}
}
}
| 8,215 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/BSerializer.java | /*
*
* Copyright 2013 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.zeno.diff;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
public class BSerializer extends NFTypeSerializer<TypeB> {
public BSerializer() {
super("TypeB");
}
@Override
public void doSerialize(TypeB value, NFSerializationRecord rec) {
serializePrimitive(rec, "val1", value.getVal1());
serializePrimitive(rec, "val2", value.getVal2());
serializePrimitive(rec, "val3", value.getVal3());
}
@Override
protected TypeB doDeserialize(NFDeserializationRecord rec) {
int val1 = deserializeInteger(rec, "val1");
int val2 = deserializeInteger(rec, "val2");
int val3 = deserializeInteger(rec, "val3");
return new TypeB(val1, val2, val3);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val1", FieldType.INT),
field("val2", FieldType.INT),
field("val3", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,216 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/diff | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/history/DiffHistoryTrackerGroupedKeyTest.java | package com.netflix.zeno.diff.history;
import java.io.IOException;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.netflix.zeno.diff.DiffInstruction;
import com.netflix.zeno.diff.TypeDiffInstruction;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.testpojos.TypeA;
public class DiffHistoryTrackerGroupedKeyTest extends DiffHistoryAbstractTest {
private FastBlobStateEngine stateEngine;
private DiffHistoryTracker diffHistory;
private int versionCounter;
@Before
public void setUp() {
stateEngine = new FastBlobStateEngine(serializerFactory());
}
@Test
public void testHistory() throws IOException {
diffHistory = diffHistoryTracker();
addHistoricalState(2, 1, 1, 1);
addHistoricalState(2, 1, 1, 3);
addHistoricalState(2, 2, 1, 3);
addHistoricalState(1, 1, 1, 3);
List<DiffObjectHistoricalTransition<List<TypeA>>> object1History = diffHistory.getObjectHistory("TypeA", Integer.valueOf(1));
List<DiffObjectHistoricalTransition<List<TypeA>>> object2History = diffHistory.getObjectHistory("TypeA", Integer.valueOf(2));
List<DiffObjectHistoricalTransition<List<TypeA>>> object3History = diffHistory.getObjectHistory("TypeA", Integer.valueOf(3));
assertDiffObjectHistoricalState(object1History, arr(1, 2, 3), arr(3), arr(2, 3), arr(2, 3, 4));
assertDiffObjectHistoricalState(object2History, null, arr(1, 2), arr(1), arr(1));
assertDiffObjectHistoricalState(object3History, arr(4), arr(4), arr(4), null);
}
private void assertDiffObjectHistoricalState(List<DiffObjectHistoricalTransition<List<TypeA>>> list, int[]... expectedHistory) {
for(int i=0;i<list.size();i++) {
int[] expectedFrom = expectedHistory[i+1];
int[] expectedTo = expectedHistory[i];
List<TypeA> beforeA = list.get(i).getBefore();
List<TypeA> afterA = list.get(i).getAfter();
int[] actualFrom = toArray(beforeA);
int[] actualTo = toArray(afterA);
assertArraysContainSameElements(expectedFrom, actualFrom);
assertArraysContainSameElements(expectedTo, actualTo);
}
}
private void addHistoricalState(Integer one, Integer two, Integer three, Integer four) throws IOException {
if(one != null) stateEngine.add("TypeA", new TypeA(1, one.intValue()));
if(two != null) stateEngine.add("TypeA", new TypeA(2, two.intValue()));
if(three != null) stateEngine.add("TypeA", new TypeA(3, three.intValue()));
if(four != null) stateEngine.add("TypeA", new TypeA(4, four.intValue()));
stateEngine.setLatestVersion(String.valueOf(++versionCounter));
roundTripObjects(stateEngine);
diffHistory.addState();
}
private DiffHistoryTracker diffHistoryTracker() {
return new DiffHistoryTracker(10,
stateEngine,
new DiffInstruction(
new TypeDiffInstruction<TypeA>() {
public String getSerializerName() {
return "TypeA";
}
public Object getKey(TypeA object) {
return Integer.valueOf(object.getVal2());
}
@Override
public boolean isUniqueKey() {
return false;
}
}
)
);
}
private void assertArraysContainSameElements(int expected[], int actual[]) {
if(expected != null && actual != null) {
for(int ex : expected) {
assertArrayContains(actual, ex);
}
} else if(expected != null || actual != null) {
Assert.fail();
}
}
private void assertArrayContains(int arr[], int val) {
for(int x : arr) {
if(x == val)
return;
}
Assert.fail();
}
private int[] arr(int... arr) {
return arr;
}
private int[] toArray(List<TypeA> list) {
if(list == null)
return null;
int arr[] = new int[list.size()];
for(int i=0;i<arr.length;i++) {
arr[i] = list.get(i).getVal1();
}
return arr;
}
}
| 8,217 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/diff | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/history/DiffHistoryDataStateTest.java | package com.netflix.zeno.diff.history;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.netflix.zeno.diff.TypeDiffInstruction;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.testpojos.TypeA;
public class DiffHistoryDataStateTest extends DiffHistoryAbstractTest {
FastBlobStateEngine stateEngine;
@Before
public void setUp() throws IOException {
stateEngine = new FastBlobStateEngine(serializerFactory());
stateEngine.add("TypeA", new TypeA(1, 1));
stateEngine.add("TypeA", new TypeA(2, 2));
stateEngine.add("TypeA", new TypeA(3, 1));
stateEngine.add("TypeA", new TypeA(4, 1));
stateEngine.add("TypeA", new TypeA(5, 3));
roundTripObjects(stateEngine);
}
@Test
public void itemsAreOrgainzedByUniqueKey() {
DiffHistoryDataState dataState = new DiffHistoryDataState(stateEngine, uniqueKeyDiffInstruction);
Map<Integer, TypeA> typeState = dataState.getTypeState("TypeA");
Assert.assertEquals(1, typeState.get(1).getVal2());
Assert.assertEquals(2, typeState.get(2).getVal2());
Assert.assertEquals(1, typeState.get(3).getVal2());
Assert.assertEquals(1, typeState.get(4).getVal2());
Assert.assertEquals(3, typeState.get(5).getVal2());
}
@Test
public void itemsAreGroupedByNonUniqueKey() {
DiffHistoryDataState dataState = new DiffHistoryDataState(stateEngine, groupedDiffInstruction);
Map<Integer, List<TypeA>> typeState = dataState.getTypeState("TypeAGrouped");
Assert.assertEquals(3, typeState.size());
List<TypeA> list = typeState.get(1);
Assert.assertEquals(3, list.size());
Assert.assertEquals(1, list.get(0).getVal1());
Assert.assertEquals(3, list.get(1).getVal1());
Assert.assertEquals(4, list.get(2).getVal1());
list = typeState.get(2);
Assert.assertEquals(1, list.size());
Assert.assertEquals(2, list.get(0).getVal1());
list = typeState.get(3);
Assert.assertEquals(1, list.size());
Assert.assertEquals(5, list.get(0).getVal1());
}
private TypeDiffInstruction<TypeA> uniqueKeyDiffInstruction = new TypeDiffInstruction<TypeA>() {
public String getSerializerName() {
return "TypeA";
}
@Override
public Object getKey(TypeA object) {
return object.getVal1();
}
};
private TypeDiffInstruction<TypeA> groupedDiffInstruction = new TypeDiffInstruction<TypeA>() {
@Override
public String getSerializerName() {
return "TypeA";
}
@Override
public Object getKey(TypeA object) {
return object.getVal2();
}
@Override
public boolean isUniqueKey() {
return false;
}
@Override
public String getTypeIdentifier() {
return "TypeAGrouped";
}
};
}
| 8,218 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/diff | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/history/DiffHistoryAbstractTest.java | package com.netflix.zeno.diff.history;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.commons.io.output.ByteArrayOutputStream;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.io.FastBlobReader;
import com.netflix.zeno.fastblob.io.FastBlobWriter;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
import com.netflix.zeno.testpojos.TypeASerializer;
public class DiffHistoryAbstractTest {
protected SerializerFactory serializerFactory() {
return new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new TypeASerializer() };
}
};
}
protected void roundTripObjects(FastBlobStateEngine stateEngine) throws IOException {
stateEngine.prepareForWrite();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FastBlobWriter writer = new FastBlobWriter(stateEngine);
writer.writeSnapshot(new DataOutputStream(baos));
FastBlobReader reader = new FastBlobReader(stateEngine);
reader.readSnapshot(new ByteArrayInputStream(baos.toByteArray()));
stateEngine.prepareForNextCycle();
}
}
| 8,219 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno/diff | Create_ds/zeno/src/test/java/com/netflix/zeno/diff/history/DiffHistoryTrackerUniqueKeyTest.java | /*
*
* Copyright 2013 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.zeno.diff.history;
import java.io.IOException;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.netflix.zeno.diff.DiffInstruction;
import com.netflix.zeno.diff.TypeDiffInstruction;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.testpojos.TypeA;
public class DiffHistoryTrackerUniqueKeyTest extends DiffHistoryAbstractTest {
private FastBlobStateEngine stateEngine;
private DiffHistoryTracker diffHistory;
private int versionCounter;
@Before
public void setUp() {
stateEngine = new FastBlobStateEngine(serializerFactory());
}
@Test
public void testHistory() throws IOException {
diffHistory = diffHistoryTracker();
addHistoricalState(1, null, null, 1);
addHistoricalState(2, null, 1, 1);
addHistoricalState(null, 1, 1, 1);
addHistoricalState(null, 1, 2, 1);
addHistoricalState(3, 1, 2, 1);
addHistoricalState(3, null, 2, 1);
addHistoricalState(null, null, 2, 1);
List<DiffObjectHistoricalTransition<TypeA>> object1History = diffHistory.getObjectHistory("TypeA", Integer.valueOf(1));
List<DiffObjectHistoricalTransition<TypeA>> object2History = diffHistory.getObjectHistory("TypeA", Integer.valueOf(2));
List<DiffObjectHistoricalTransition<TypeA>> object3History = diffHistory.getObjectHistory("TypeA", Integer.valueOf(3));
List<DiffObjectHistoricalTransition<TypeA>> object4History = diffHistory.getObjectHistory("TypeA", Integer.valueOf(4));
assertDiffObjectHistoricalState(object1History, null, 3, 3, null, null, 2, 1); //1, 2, null, null, 3, 3, null);
assertDiffObjectHistoricalState(object2History, null, null, 1, 1, 1, null, null);
assertDiffObjectHistoricalState(object3History, 2, 2, 2, 2, 1, 1, null);
assertDiffObjectHistoricalState(object4History, 1, 1, 1, 1, 1, 1, 1);
}
private void assertDiffObjectHistoricalState(List<DiffObjectHistoricalTransition<TypeA>> list, Integer... expectedHistory) {
for(int i=0;i<list.size();i++) {
Integer expectedFrom = expectedHistory[i+1];
Integer expectedTo = expectedHistory[i];
TypeA beforeA = list.get(i).getBefore();
TypeA afterA = list.get(i).getAfter();
Integer actualFrom = beforeA == null ? null : beforeA.getVal2();
Integer actualTo = afterA == null ? null : afterA.getVal2();
Assert.assertEquals(expectedFrom, actualFrom);
Assert.assertEquals(expectedTo, actualTo);
}
}
private void addHistoricalState(Integer one, Integer two, Integer three, Integer four) throws IOException {
if(one != null) stateEngine.add("TypeA", new TypeA(1, one.intValue()));
if(two != null) stateEngine.add("TypeA", new TypeA(2, two.intValue()));
if(three != null) stateEngine.add("TypeA", new TypeA(3, three.intValue()));
if(four != null) stateEngine.add("TypeA", new TypeA(4, four.intValue()));
stateEngine.setLatestVersion(String.valueOf(++versionCounter));
roundTripObjects(stateEngine);
diffHistory.addState();
}
private DiffHistoryTracker diffHistoryTracker() {
return new DiffHistoryTracker(10,
stateEngine,
new DiffInstruction(
new TypeDiffInstruction<TypeA>() {
public String getSerializerName() {
return "TypeA";
}
public Object getKey(TypeA object) {
return Integer.valueOf(object.getVal1());
}
}
)
);
}
}
| 8,220 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeC.java | /*
*
* Copyright 2013 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.zeno.testpojos;
import java.util.List;
import java.util.Map;
public class TypeC {
private final Map<String, TypeA> typeAMap;
private final List<TypeB> typeBs;
public TypeC(Map<String, TypeA> typeAMap, List<TypeB> typeBs) {
this.typeAMap = typeAMap;
this.typeBs = typeBs;
}
public Map<String, TypeA> getTypeAMap() {
return typeAMap;
}
public List<TypeB> getTypeBs() {
return typeBs;
}
@Override
public int hashCode() {
return typeAMap.hashCode() ^ typeBs.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TypeC other = (TypeC) obj;
if (typeAMap == null) {
if (other.typeAMap != null)
return false;
} else if (!typeAMap.equals(other.typeAMap))
return false;
if (typeBs == null) {
if (other.typeBs != null)
return false;
} else if (!typeBs.equals(other.typeBs))
return false;
return true;
}
}
| 8,221 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeB.java | /*
*
* Copyright 2013 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.zeno.testpojos;
public class TypeB {
int val1;
String val2;
public TypeB(int val1, String val2) {
this.val1 = val1;
this.val2 = val2;
}
public int getVal1() {
return val1;
}
public String getVal2() {
return val2;
}
@Override
public int hashCode() {
return val2.hashCode() + (31 * val1);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TypeB other = (TypeB) obj;
if (val1 != other.val1)
return false;
if (val2 == null) {
if (other.val2 != null)
return false;
} else if (!val2.equals(other.val2))
return false;
return true;
}
}
| 8,222 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeE.java | /*
*
* Copyright 2013 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.zeno.testpojos;
public class TypeE {
private final TypeF typeF;
public TypeE(TypeF typeF) {
this.typeF = typeF;
}
public TypeF getTypeF() {
return typeF;
}
@Override
public int hashCode() {
return 31 * typeF.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TypeE other = (TypeE) obj;
if (typeF == null) {
if (other.typeF != null)
return false;
} else if (!typeF.equals(other.typeF))
return false;
return true;
}
}
| 8,223 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeD.java | /*
*
* Copyright 2013 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.zeno.testpojos;
public class TypeD {
Integer val;
TypeA a;
public TypeD(Integer val, TypeA a) {
this.val = val;
this.a = a;
}
public TypeA getTypeA() {
return a;
}
public Integer getVal() {
return val;
}
@Override
public int hashCode() {
return a.hashCode() ^ val.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TypeD other = (TypeD) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (val == null) {
if (other.val != null)
return false;
} else if (!val.equals(other.val))
return false;
return true;
}
}
| 8,224 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeESerializer.java | /*
*
* Copyright 2013 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.zeno.testpojos;
import java.util.Collection;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
public class TypeESerializer extends NFTypeSerializer<TypeE> {
private final FastBlobSchemaField[] fields = new FastBlobSchemaField[] {
field("typeF", new TypeFSerializer())
};
public TypeESerializer() {
super("TypeE");
}
@Override
public void doSerialize(TypeE value, NFSerializationRecord rec) {
serializeObject(rec, "typeF", value.getTypeF());
}
@Override
protected TypeE doDeserialize(NFDeserializationRecord rec) {
return new TypeE((TypeF) deserializeObject(rec, "typeF"));
}
@Override
protected FastBlobSchema createSchema() {
return schema(fields);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return requiredSubSerializers(fields);
}
}
| 8,225 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeG.java | package com.netflix.zeno.testpojos;
public class TypeG {
private final TypeD typeD;
public TypeG(TypeD typeD) {
this.typeD = typeD;
}
public TypeD getTypeD() {
return typeD;
}
}
| 8,226 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeBSerializer.java | /*
*
* Copyright 2013 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.zeno.testpojos;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.StringSerializer;
import java.util.Collection;
public class TypeBSerializer extends NFTypeSerializer<TypeB>{
public TypeBSerializer() {
super("TypeB");
}
@Override
public void doSerialize(TypeB obj, NFSerializationRecord rec) {
serializePrimitive(rec, "val1", obj.getVal1());
serializePrimitive(rec, "val2", obj.getVal2());
}
@Override
protected TypeB doDeserialize(NFDeserializationRecord rec) {
final int val1 = deserializeInteger(rec, "val1");
final String val2 = deserializePrimitiveString(rec, "val2");
return new TypeB(val1, val2);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val1", FieldType.INT),
field("val2", FieldType.STRING)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(new StringSerializer());
}
}
| 8,227 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeCSerializer.java | /*
*
* Copyright 2013 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.zeno.testpojos;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.ListSerializer;
import com.netflix.zeno.serializer.common.MapSerializer;
import com.netflix.zeno.serializer.common.StringSerializer;
public class TypeCSerializer extends NFTypeSerializer<TypeC> {
public static final ListSerializer<TypeB> LIST_SERIALIZER = new ListSerializer<TypeB>(new TypeBSerializer());
public static final MapSerializer<String, TypeA> MAP_SERIALIZER = new MapSerializer<String, TypeA>(new StringSerializer(), new TypeASerializer());
private final FastBlobSchemaField[] fields = new FastBlobSchemaField[] {
field("typeA", new MapSerializer<String, TypeA>(new StringSerializer(), new TypeASerializer())),
field("typeB", new ListSerializer<TypeB>(new TypeBSerializer()))
};
public TypeCSerializer() {
super("TypeC");
}
@Override
public void doSerialize(TypeC value, NFSerializationRecord rec) {
serializeObject(rec, "typeA", value.getTypeAMap());
serializeObject(rec, "typeB", value.getTypeBs());
}
@SuppressWarnings("unchecked")
@Override
protected TypeC doDeserialize(NFDeserializationRecord rec) {
return new TypeC(
(Map<String, TypeA>) deserializeObject(rec, "typeA"),
(List<TypeB>) deserializeObject(rec, "typeB")
);
}
@Override
protected FastBlobSchema createSchema() {
return schema(fields);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return requiredSubSerializers(fields);
}
}
| 8,228 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeF.java | /*
*
* Copyright 2013 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.zeno.testpojos;
public class TypeF {
private final int value;
public TypeF(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TypeF other = (TypeF) obj;
if (value != other.value)
return false;
return true;
}
}
| 8,229 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeDSerializer.java | /*
*
* Copyright 2013 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.zeno.testpojos;
import java.util.Collection;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
public class TypeDSerializer extends NFTypeSerializer<TypeD> {
private final FastBlobSchemaField[] fields = new FastBlobSchemaField[] {
field("val", FieldType.INT),
field("a", new TypeASerializer())
};
public TypeDSerializer() {
super("TypeD");
}
@Override
public void doSerialize(TypeD value, NFSerializationRecord rec) {
serializePrimitive(rec, "val", value.getVal());
serializeObject(rec, "a", value.getTypeA());
}
@Override
protected TypeD doDeserialize(NFDeserializationRecord rec) {
return new TypeD(
deserializeInteger(rec, "val"),
(TypeA) deserializeObject( rec, "a")
);
}
@Override
protected FastBlobSchema createSchema() {
return schema(fields);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return requiredSubSerializers(fields);
}
}
| 8,230 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeFSerializer.java | /*
*
* Copyright 2013 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.zeno.testpojos;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
public class TypeFSerializer extends NFTypeSerializer<TypeF>{
public TypeFSerializer() {
super("TypeF");
}
@Override
public void doSerialize(TypeF value, NFSerializationRecord rec) {
serializePrimitive(rec, "value", value.getValue());
}
@Override
protected TypeF doDeserialize(NFDeserializationRecord rec) {
return new TypeF(deserializeInteger(rec, "value"));
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("value", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,231 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeASerializer.java | /*
*
* Copyright 2013 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.zeno.testpojos;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
public class TypeASerializer extends NFTypeSerializer<TypeA>{
public TypeASerializer() {
super("TypeA");
}
@Override
public void doSerialize(TypeA obj, NFSerializationRecord rec) {
serializePrimitive(rec, "val1", obj.getVal1());
serializePrimitive(rec, "val2", obj.getVal2());
}
@Override
protected TypeA doDeserialize(NFDeserializationRecord rec) {
int val1 = deserializeInteger(rec, "val1");
int val2 = deserializeInteger(rec, "val2");
return new TypeA(val1, val2);
}
@Override
public FastBlobSchema createSchema() {
return schema(
field("val1", FieldType.INT),
field("val2", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,232 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeA.java | /*
*
* Copyright 2013 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.zeno.testpojos;
public class TypeA {
private final int val1;
private final int val2;
public TypeA(int val1, int val2) {
this.val1 = val1;
this.val2 = val2;
}
public int getVal1() {
return val1;
}
public int getVal2() {
return val2;
}
@Override
public int hashCode() {
return 31 * val1 + 13 * val2;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TypeA other = (TypeA) obj;
if (val1 != other.val1)
return false;
if (val2 != other.val2)
return false;
return true;
}
public String toString() {
return "<" + val1 + "," + val2 + ">";
}
}
| 8,233 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/testpojos/TypeGSerializer.java | package com.netflix.zeno.testpojos;
import java.util.Collection;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
public class TypeGSerializer extends NFTypeSerializer<TypeG>{
private final FastBlobSchemaField[] fields = new FastBlobSchemaField[] {
field("typeD", new TypeDSerializer())
};
public TypeGSerializer() {
super("TypeG");
}
@Override
protected void doSerialize(TypeG value, NFSerializationRecord rec) {
serializeObject(rec, "typeD", value.getTypeD());
}
@Override
protected TypeG doDeserialize(NFDeserializationRecord rec) {
TypeD typeD = deserializeObject(rec, "typeD");
return new TypeG(typeD);
}
@Override
protected FastBlobSchema createSchema() {
return schema(fields);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return requiredSubSerializers(fields);
}
}
| 8,234 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/flatblob/FlatBlobTest.java | package com.netflix.zeno.flatblob;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.io.FastBlobReader;
import com.netflix.zeno.fastblob.io.FastBlobWriter;
import com.netflix.zeno.fastblob.record.ByteDataBuffer;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
import com.netflix.zeno.testpojos.TypeA;
import com.netflix.zeno.testpojos.TypeD;
import com.netflix.zeno.testpojos.TypeDSerializer;
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 FlatBlobTest {
private SerializerFactory typeDSerializerFactory;
private FastBlobStateEngine stateEngine;
private FlatBlobSerializationFramework flatBlobFramework;
private TypeD d1;
private TypeD d2;
private TypeD d3;
@Before
public void setUp() throws Exception {
typeDSerializerFactory = new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new TypeDSerializer() };
}
};
stateEngine = new FastBlobStateEngine(typeDSerializerFactory);
stateEngine.add("TypeD", typeD(1, 2));
stateEngine.add("TypeD", typeD(2, 2));
stateEngine.add("TypeD", typeD(3, 2));
roundTripStateEngine(stateEngine);
d1 = (TypeD) stateEngine.getTypeDeserializationState("TypeD").get(0);
d2 = (TypeD) stateEngine.getTypeDeserializationState("TypeD").get(1);
d3 = (TypeD) stateEngine.getTypeDeserializationState("TypeD").get(2);
flatBlobFramework = new FlatBlobSerializationFramework(typeDSerializerFactory, stateEngine);
}
@Test
public void cachingElementsResultsInDeduplication() {
ByteDataBuffer d1Buf = new ByteDataBuffer();
ByteDataBuffer d2Buf = new ByteDataBuffer();
flatBlobFramework.serialize("TypeD", d1, d1Buf);
flatBlobFramework.serialize("TypeD", d2, d2Buf);
TypeD deserializedD1 = flatBlobFramework.deserialize("TypeD", d1Buf.getUnderlyingArray(), true);
TypeD deserializedD2 = flatBlobFramework.deserialize("TypeD", d2Buf.getUnderlyingArray(), true);
Assert.assertSame(deserializedD1.getTypeA(), deserializedD2.getTypeA());
}
@Test
public void uncachedElementsAreNotDeduplicated() {
ByteDataBuffer d1Buf = new ByteDataBuffer();
ByteDataBuffer d2Buf = new ByteDataBuffer();
flatBlobFramework.serialize("TypeD", d1, d1Buf);
flatBlobFramework.serialize("TypeD", d2, d2Buf);
TypeD deserializedD1 = flatBlobFramework.deserialize("TypeD", d1Buf.getUnderlyingArray(), false);
TypeD deserializedD2 = flatBlobFramework.deserialize("TypeD", d2Buf.getUnderlyingArray(), false);
Assert.assertNotSame(deserializedD1.getTypeA(), deserializedD2.getTypeA());
}
@Test
public void evictionOfCachedElementsWillResultInNewObjects() {
FlatBlobEvictor evictor = new FlatBlobEvictor(typeDSerializerFactory, flatBlobFramework);
ByteDataBuffer d1Buf = new ByteDataBuffer();
ByteDataBuffer d2Buf = new ByteDataBuffer();
flatBlobFramework.serialize("TypeD", d1, d1Buf);
flatBlobFramework.serialize("TypeD", d2, d2Buf);
TypeD deserializedD1 = flatBlobFramework.deserialize("TypeD", d1Buf.getUnderlyingArray(), true);
evictor.evict("TypeD", deserializedD1);
TypeD deserializedD2 = flatBlobFramework.deserialize("TypeD", d2Buf.getUnderlyingArray(), true);
Assert.assertNotSame(deserializedD1.getTypeA(), deserializedD2.getTypeA());
}
@Test
public void evictorCountsReferencesAndDoesNotEvictObjectsTooEarly() {
FlatBlobEvictor evictor = new FlatBlobEvictor(typeDSerializerFactory, flatBlobFramework);
ByteDataBuffer d1Buf = new ByteDataBuffer();
ByteDataBuffer d2Buf = new ByteDataBuffer();
ByteDataBuffer d3Buf = new ByteDataBuffer();
flatBlobFramework.serialize("TypeD", d1, d1Buf);
flatBlobFramework.serialize("TypeD", d2, d2Buf);
flatBlobFramework.serialize("TypeD", d3, d3Buf);
TypeD deserializedD1 = flatBlobFramework.deserialize("TypeD", d1Buf.getUnderlyingArray(), true);
TypeD deserializedD2 = flatBlobFramework.deserialize("TypeD", d1Buf.getUnderlyingArray(), true);
evictor.evict("TypeD", deserializedD1);
TypeD deserializedD3 = flatBlobFramework.deserialize("TypeD", d2Buf.getUnderlyingArray(), true);
Assert.assertSame(deserializedD2.getTypeA(), deserializedD3.getTypeA());
}
private TypeD typeD(int dVal, int aVal) {
return new TypeD(dVal, new TypeA(aVal, aVal));
}
private void roundTripStateEngine(FastBlobStateEngine stateEngine) throws Exception, IOException {
stateEngine.prepareForWrite();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new FastBlobWriter(stateEngine).writeSnapshot(baos);
new FastBlobReader(stateEngine).readSnapshot(new ByteArrayInputStream(baos.toByteArray()));
}
}
| 8,235 |
0 | Create_ds/zeno/src/test/java/com/netflix/zeno | Create_ds/zeno/src/test/java/com/netflix/zeno/json/JsonSerializationTest.java | /*
*
* Copyright 2013 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.zeno.json;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
import com.netflix.zeno.serializer.common.IntegerSerializer;
import com.netflix.zeno.testpojos.TypeA;
import com.netflix.zeno.testpojos.TypeASerializer;
import com.netflix.zeno.testpojos.TypeB;
import com.netflix.zeno.testpojos.TypeC;
import com.netflix.zeno.testpojos.TypeCSerializer;
import com.netflix.zeno.testpojos.TypeD;
import com.netflix.zeno.testpojos.TypeG;
import com.netflix.zeno.testpojos.TypeGSerializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class JsonSerializationTest {
private SerializerFactory typeCSerializerFactory;
private SerializerFactory typeASerializerFactory;
private SerializerFactory typeGSerializerFactory;
@Before
public void setUp() {
typeCSerializerFactory = new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new TypeCSerializer() };
}
};
typeASerializerFactory = new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new TypeASerializer() };
}
};
typeGSerializerFactory = new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new TypeGSerializer() };
}
};
}
private static final String expectedTypeAJson =
"{\n" +
" \"val1\" : 1,\n" +
" \"val2\" : 2\n" +
"}";
@Test
public void producesJson() {
JsonSerializationFramework jsonFramework = new JsonSerializationFramework(typeASerializerFactory);
String json = jsonFramework.serializeAsJson("TypeA", new TypeA(1, 2));
Assert.assertEquals(expectedTypeAJson, json);
}
@Test
public void consumesJson() throws IOException {
JsonSerializationFramework jsonFramework = new JsonSerializationFramework(typeASerializerFactory);
TypeA deserializedTypeA = jsonFramework.deserializeJson("TypeA", expectedTypeAJson);
Assert.assertEquals(1, deserializedTypeA.getVal1());
Assert.assertEquals(2, deserializedTypeA.getVal2());
}
@Test
public void roundTripJson() throws IOException {
TypeC originalTypeC = createTestTypeC();
JsonSerializationFramework jsonFramework = new JsonSerializationFramework(typeCSerializerFactory);
String json = jsonFramework.serializeAsJson("TypeC", createTestTypeC());
TypeC deserializedTypeC = jsonFramework.deserializeJson("TypeC", json);
Assert.assertEquals(originalTypeC, deserializedTypeC);
}
@Test
public void roundTripJsonMap() throws IOException {
Map<Integer, TypeA> map = new HashMap<Integer, TypeA>();
map.put(1, new TypeA(0, 1));
map.put(2, new TypeA(2, 3));
JsonSerializationFramework jsonFramework = new JsonSerializationFramework(new SerializerFactory() {
public NFTypeSerializer<?>[] createSerializers() {
return new NFTypeSerializer<?>[] { new TypeASerializer(), new IntegerSerializer() };
}
});
String json = jsonFramework.serializeJsonMap(IntegerSerializer.NAME, "TypeA", map, true);
Map<Integer, TypeA> deserializedMap = jsonFramework.deserializeJsonMap(IntegerSerializer.NAME, "TypeA", json);
Assert.assertEquals(2, deserializedMap.size());
Assert.assertEquals(new TypeA(0, 1), deserializedMap.get(1));
Assert.assertEquals(new TypeA(2, 3), deserializedMap.get(2));
}
@Test
public void roundTripJsonWithTwoHierarchicalLevels() throws IOException {
JsonSerializationFramework jsonFramework = new JsonSerializationFramework(typeGSerializerFactory);
String json = jsonFramework.serializeAsJson("TypeG", new TypeG(new TypeD(1, new TypeA(2, 3))));
try {
jsonFramework.deserializeJson("TypeG", json);
} catch(Exception e) {
Assert.fail("Exception was thrown");
}
}
private TypeC createTestTypeC() {
Map<String, TypeA> typeAMap = new HashMap<String, TypeA>();
List<TypeB> typeBs = new ArrayList<TypeB>();
typeAMap.put("a12", new TypeA(1, 2));
typeAMap.put("a34", new TypeA(3, 4));
typeBs.add(new TypeB(5, "five"));
typeBs.add(new TypeB(6, "six"));
return new TypeC(typeAMap, typeBs);
}
}
| 8,236 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/JSONSerializationExample.java | /*
*
* Copyright 2013 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.zeno.examples;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.examples.serializers.ExampleSerializerFactory;
import com.netflix.zeno.json.JsonSerializationFramework;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
/**
* This is an example usage of the JsonSerializationframework.<p/>
*
* Usage is detailed in the <a href="https://github.com/Netflix/zeno/wiki">documentation</a>
* on the page <a href="https://github.com/Netflix/zeno/wiki/Creating-json-data">creating json data</a>.
*
* @author dkoszewnik
*
*/
public class JSONSerializationExample {
@Test
@SuppressWarnings("unused")
public void serializeJson() throws IOException {
JsonSerializationFramework jsonFramework = new JsonSerializationFramework(new ExampleSerializerFactory());
String json = jsonFramework.serializeAsJson("A", getExampleA());
System.out.println("JSON FOR A:");
System.out.println(json);
A deserializedA = jsonFramework.deserializeJson("A", json);
String bJson = jsonFramework.serializeAsJson("B", new B(50, "fifty"));
System.out.println("JSON FOR B:");
System.out.println(bJson);
}
public A getExampleA() {
B b1 = new B(100, "one hundred");
B b2 = new B(2000, "two thousand");
List<B> bList = new ArrayList<B>();
bList.add(b1);
bList.add(b2);
C c = new C(Long.MAX_VALUE, new byte[] { 1, 2, 3, 4, 5 });
A a = new A(bList, c, 1);
return a;
}
}
| 8,237 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/DiffExample.java | /*
*
* Copyright 2013 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.zeno.examples;
import com.netflix.zeno.diff.DiffInstruction;
import com.netflix.zeno.diff.DiffOperation;
import com.netflix.zeno.diff.DiffReport;
import com.netflix.zeno.diff.TypeDiff;
import com.netflix.zeno.diff.TypeDiff.FieldDiff;
import com.netflix.zeno.diff.TypeDiff.ObjectDiffScore;
import com.netflix.zeno.diff.TypeDiffInstruction;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.examples.serializers.ExampleSerializerFactory;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.io.FastBlobReader;
import com.netflix.zeno.fastblob.io.FastBlobWriter;
import com.netflix.zeno.genericobject.DiffHtmlGenerator;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;
/**
* Example usage of the Zeno diff operation. This operation details the differences between two data states.<p/>
*
* Follow along in the documentation on the page <a href="https://github.com/Netflix/zeno/wiki/Diffing-arbitrary-data-states">diffing arbitrary data states</a>
*
* @author dkoszewnik
*
*/
public class DiffExample {
@Test
public void performDiff() throws IOException {
/// load two state engines with data states
FastBlobStateEngine fromStateEngine = getStateEngine();
FastBlobStateEngine toStateEngine = getAnotherStateEngine();
/// get a diff "instruction". This describes how to match up objects
/// between two FastBlobStateEngines.
DiffInstruction instruction = getDiffInstruction();
DiffOperation diffOperation = new DiffOperation(new ExampleSerializerFactory(), instruction);
/// perform the diff report
DiffReport diffReport = diffOperation.performDiff(fromStateEngine, toStateEngine);
/// this score can be used as a quick overview to see the magnitude of the differences between the data states
System.out.println("Total Differences Between Matched Objects: " + diffReport.getTotalDiffs());
/// this score can be used as a quick overview to see the number of unmatched objects between the data states
System.out.println("Total Unmatched Objects: " + diffReport.getTotalExtra());
/// get the differences for a single type
TypeDiff<A> typeDiff = diffReport.getTypeDiff("A");
/// iterate through all fields for that type
for(FieldDiff<A> fieldDiff : typeDiff.getSortedFieldDifferencesDescending()) {
String propertyName = fieldDiff.getPropertyPath().toString();
int totalExamples = fieldDiff.getDiffScore().getTotalCount();
int unmatchedExamples = fieldDiff.getDiffScore().getDiffCount();
System.out.println(propertyName + ": " + unmatchedExamples + " / " + totalExamples + " were unmatched");
}
/// iterate over each of the different instances
for(ObjectDiffScore<A> objectDiff : typeDiff.getDiffObjects()) {
A differentA = objectDiff.getFrom();
System.out.println("A with id " + differentA.getIntValue() + " was different");
/// show the differences
displayObjectDifferences(objectDiff.getFrom(), objectDiff.getTo());
}
}
private void displayObjectDifferences(A from, A to) {
DiffHtmlGenerator generator = new DiffHtmlGenerator(new ExampleSerializerFactory());
String html = generator.generateDiff("A", from, to);
displayTheHtml(html);
}
private void displayTheHtml(String html) {
/// for lack of a better thing to do with this.
/// System.out.println(html);
}
public DiffInstruction getDiffInstruction() {
return new DiffInstruction(
new TypeDiffInstruction<A>() {
public String getSerializerName() {
return "A";
}
public Object getKey(A object) {
return Integer.valueOf(object.getIntValue());
}
}
);
}
private FastBlobStateEngine getStateEngine() throws IOException {
return getDeserializedStateEngineWithObjects(
getExampleA1(),
getExampleA2()
);
}
private FastBlobStateEngine getAnotherStateEngine() throws IOException {
return getDeserializedStateEngineWithObjects(
getExampleA1(),
getExampleA2Prime()
);
}
/*
* Round trip the objects in a FastBlobStateEngine, so they appear in the type deserialization state.
*/
private FastBlobStateEngine getDeserializedStateEngineWithObjects(A... objects) throws IOException {
FastBlobStateEngine stateEngine = new FastBlobStateEngine(new ExampleSerializerFactory());
for(A object : objects) {
stateEngine.add("A", object);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(baos);
stateEngine.prepareForWrite();
FastBlobWriter writer = new FastBlobWriter(stateEngine);
writer.writeSnapshot(dataOutputStream);
FastBlobReader reader = new FastBlobReader(stateEngine);
reader.readSnapshot(new ByteArrayInputStream(baos.toByteArray()));
return stateEngine;
}
public A getExampleA1() {
B b1 = new B(1, "one");
B b2 = new B(2, "two");
List<B> bList = new ArrayList<B>();
bList.add(b1);
bList.add(b2);
C c = new C(Long.MAX_VALUE, new byte[] { 1, 2, 3, 4, 5 });
A a = new A(bList, c, 1);
return a;
}
public A getExampleA2() {
B b3 = new B(3, "three");
B b4 = new B(4, "four");
B b5 = new B(5, "five");
List<B> bList = new ArrayList<B>();
bList.add(b3);
bList.add(b4);
bList.add(b5);
C c = new C(Long.MAX_VALUE, new byte[] { 10, 9, 8, 7, 6 });
A a = new A(bList, c, 2);
return a;
}
public A getExampleA2Prime() {
B c3 = new B(3, "three");
B c4 = new B(4, "four");
B c6 = new B(6, "six");
List<B> cList = new ArrayList<B>();
cList.add(c3);
cList.add(c4);
cList.add(c6);
C d = new C(Long.MAX_VALUE, new byte[] { 10, 9, 8, 7, 6 });
A a = new A(cList, d, 2);
return a;
}
}
| 8,238 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/PhasedHeapFriendlyHashMapExample.java | /*
*
* Copyright 2013 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.zeno.examples;
import com.netflix.zeno.util.collections.heapfriendly.PhasedHeapFriendlyHashMap;
import java.util.Map;
import org.junit.Test;
/**
* Example usage of {@link PhasedHeapFriendlyHashMap}
*
* @author drbathgate
*
*/
public class PhasedHeapFriendlyHashMapExample {
@Test
public void runExample() {
PhasedHeapFriendlyHashMap<Integer, String> map = new PhasedHeapFriendlyHashMap<Integer, String>();
fillMap(map, 1, 2, 3, 4, 5, 6, 7, 8);
printMapEntries(map);
fillMap(map, 1, 2, 3, 4, 5, 6, 7, 9);
printMapEntries(map);
fillMap(map, 1, 2, 3, 4, 5, 6, 7, 10);
printMapEntries(map);
fillMap(map, 1, 2, 3, 4, 5, 6, 7, 11);
printMapEntries(map);
}
private void fillMap(PhasedHeapFriendlyHashMap<Integer, String> map, int... entries) {
// allow access to put data by starting data swap phase
map.beginDataSwapPhase(entries.length);
for(int entry: entries) {
// entries will not be available until the end of the data swap phase
map.put(entry, String.valueOf(entry));
}
// make data available by ending data swap phase
map.endDataSwapPhase();
}
private void printMapEntries(PhasedHeapFriendlyHashMap<Integer, String> map) {
for(Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":\"" + entry.getValue() + "\"");
}
}
}
| 8,239 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/HeapFriendlyHashMapExample.java | /*
*
* Copyright 2013 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.zeno.examples;
import com.netflix.zeno.util.collections.heapfriendly.HeapFriendlyHashMap;
import com.netflix.zeno.util.collections.heapfriendly.HeapFriendlyMapArrayRecycler;
import java.util.Map;
import org.junit.Test;
/**
* Example usage of a "heap-friendly" hash map. For details, follow
* along in the Zeno documentation on the page <a href="https://github.com/Netflix/zeno/wiki/Making-data-available">making data available</a>
*
* @author dkoszewnik
*
*/
public class HeapFriendlyHashMapExample {
public HeapFriendlyHashMap<Integer, String> accessMap;
@Test
public void runCycle() {
runCycle(1, 2, 3, 4, 5, 6, 7, 8);
runCycle(1, 2, 3, 4, 5, 6, 7, 9);
runCycle(1, 2, 3, 4, 5, 6, 7, 10);
runCycle(1, 2, 3, 4, 5, 6, 7, 11);
runCycle(1, 2, 3, 4, 5, 6, 7, 12);
for(Map.Entry<Integer, String> entry : accessMap.entrySet()) {
System.out.println(entry.getKey() + ":\"" + entry.getValue() + "\"");
}
}
/**
* For each cycle, we need to perform some administrative tasks.
*/
public void runCycle(int... valuesForMap) {
/// prepare the map Object array recycler for a new cycle.
HeapFriendlyMapArrayRecycler.get().swapCycleObjectArrays();
try {
makeDataAvailableToApplication(valuesForMap);
} finally {
// fill all of the Object arrays which were returned to the pool on this cycle with nulls,
// so that the garbage collector can clean up any data which is no longer used.
HeapFriendlyMapArrayRecycler.get().clearNextCycleObjectArrays();
}
}
public void makeDataAvailableToApplication(int... valuesForMap) {
HeapFriendlyHashMap<Integer, String> newAccessMap = new HeapFriendlyHashMap<Integer, String>(valuesForMap.length);
for(int val : valuesForMap) {
Integer key = Integer.valueOf(val);
String value = String.valueOf(val);
newAccessMap.put(key, value);
}
/// release the object arrays for the current access map
if(accessMap != null)
accessMap.releaseObjectArrays();
/// make the new access map available
accessMap = newAccessMap;
}
}
| 8,240 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/BasicSerializationExample.java | /*
*
* Copyright 2013 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.zeno.examples;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.examples.serializers.ExampleSerializerFactory;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.io.FastBlobReader;
import com.netflix.zeno.fastblob.io.FastBlobWriter;
import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;
/**
* An example detailing the basic serialization flow. Follow along in the Zeno documentation
* in the section <a href="https://github.com/Netflix/zeno/wiki/Transporting-data">transporting data</a>.
*
* @author dkoszewnik
*
*/
public class BasicSerializationExample {
private FastBlobStateEngine stateEngine;
@Test
public void basicSerializationCycle() {
/// First we create a state engine, we need to tell it about our data model by
/// passing it a serializer factory which creates our top-level serializers.
stateEngine = new FastBlobStateEngine(new ExampleSerializerFactory());
/// For this example, we're just storing the serialized data in memory.
byte snapshot[] = createSnapshot();
byte delta[] = createDelta();
/// Now we can pretend to be the client, and deserialize the data into a separate state engine.
FastBlobStateEngine clientStateEngine = deserializeLatestData(snapshot, delta);
/// We can grab the data for any class. Here, we grab the values for class A.
FastBlobTypeDeserializationState<A> aState = clientStateEngine.getTypeDeserializationState("A");
/// the following will loop through all values after loading the snapshot
/// and subsequently applying the delta. It will print out "1" followed by "3".
System.out.println("All As: ");
for(A deserializedA : aState){
System.out.println(deserializedA.getIntValue());
}
/// As another example, we can grab the values for class B.
FastBlobTypeDeserializationState<B> bState = clientStateEngine.getTypeDeserializationState("B");
/// Even though we didn't directly add the Bs, they were added because we added objects which
/// referenced them. Here, we iterate over all of the Bs after applying the delta.
/// This will print out "1", "2", "3", "4", "6"
System.out.println("All Bs: ");
for(B deserializedB : bState) {
System.out.println(deserializedB.getBInt());
}
}
public FastBlobStateEngine deserializeLatestData(byte snapshot[], byte delta[]) {
/// now we are on the client. We need to create a state engine, and again
/// tell it about our data model.
FastBlobStateEngine stateEngine = new FastBlobStateEngine(new ExampleSerializerFactory());
/// we need to create a FastBlobReader, which is responsible for reading
/// serialized blobs.
FastBlobReader reader = new FastBlobReader(stateEngine);
/// get a stream from the snapshot file location
ByteArrayInputStream snapshotStream = new ByteArrayInputStream(snapshot);
/// get a stream from the delta file location
ByteArrayInputStream deltaStream = new ByteArrayInputStream(delta);
try {
/// first read the snapshot
reader.readSnapshot(snapshotStream);
/// then apply the delta
reader.readDelta(deltaStream);
} catch (IOException e) {
/// either of these methods throws an exception if the FastBlobReader
/// is unable to read from the provided stream.
} finally {
/// it is your responsibility to close the streams. The FastBlobReader will not do this.
try {
snapshotStream.close();
deltaStream.close();
} catch (IOException ignore) { }
}
return stateEngine;
}
public byte[] createSnapshot() {
/// We add each of our object instances to the state engine.
/// This operation is thread safe and can be called from multiple processing threads.
stateEngine.add("A", getExampleA1());
stateEngine.add("A", getExampleA2());
/// The following lets the state engine know that we have finished adding all of our
/// objects to the state.
stateEngine.prepareForWrite();
/// Create a writer, which will be responsible for creating snapshot and/or delta blobs.
FastBlobWriter writer = new FastBlobWriter(stateEngine);
/// Create an output stream to somewhere. This can be to a local file on disk
/// or directly to the blob destination. The VMS team writes this data directly
/// to disk, and then spawns a new thread to upload the data to S3.
/// We need to pass a DataOutputStream. Remember that DataOutputStream is not buffered,
/// so if you write to a FileOutputStream or other non-buffered source, you likely want to
/// make the DataOutputStream wrap a BufferedOutputStream
/// (e.g. new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile))))
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
/// write the snapshot to the output stream.
writer.writeSnapshot(outputStream);
} catch(IOException e) {
/// the FastBlobWriter throws an IOException if it is
/// unable to write to the provided OutputStream
} finally {
/// it is your responsibility to close the stream. The FastBlobWriter will not do this.
try {
outputStream.close();
} catch(IOException ignore) { }
}
byte snapshot[] = baos.toByteArray();
return snapshot;
}
public byte[] createDelta() {
/// The following call informs the state engine that we have finished writing
/// all of our snapshot / delta files, and we are ready to begin adding fresh
/// object instances for the next cycle.
stateEngine.prepareForNextCycle();
// Again, we add each of our object instances to the state engine.
// This operation is still thread safe and can be called from multiple processing threads.
stateEngine.add("A", getExampleA1());
stateEngine.add("A", getExampleA2Prime());
/// We must again let the state engine know that we have finished adding all of our
/// objects to the state.
stateEngine.prepareForWrite();
/// Create a writer, which will be responsible for creating snapshot and/or delta blobs.
FastBlobWriter writer = new FastBlobWriter(stateEngine);
/// Again create an output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
/// This time write the delta file.
writer.writeDelta(outputStream);
} catch(IOException e) {
/// thrown if the FastBlobWriter was unable to write to the provided stream.
} finally {
try {
outputStream.close();
} catch(IOException ignore){ }
}
byte delta[] = baos.toByteArray();
return delta;
}
public A getExampleA1() {
B b1 = new B(1, "one");
B b2 = new B(2, "two");
List<B> bList = new ArrayList<B>();
bList.add(b1);
bList.add(b2);
C c = new C(Long.MAX_VALUE, new byte[] { 1, 2, 3, 4, 5 });
A a = new A(bList, c, 1);
return a;
}
public A getExampleA2() {
B b3 = new B(3, "three");
B b4 = new B(4, "four");
B b5 = new B(5, "five");
List<B> bList = new ArrayList<B>();
bList.add(b3);
bList.add(b4);
bList.add(b5);
C c = new C(Long.MAX_VALUE, new byte[] { 10, 9, 8, 7, 6 });
A a = new A(bList, c, 2);
return a;
}
public A getExampleA2Prime() {
B c3 = new B(3, "three");
B c4 = new B(4, "four");
B c6 = new B(6, "six");
List<B> cList = new ArrayList<B>();
cList.add(c3);
cList.add(c4);
cList.add(c6);
C d = new C(Long.MAX_VALUE, new byte[] { 10, 9, 8, 7, 6 });
A a = new A(cList, d, 2);
return a;
}
}
| 8,241 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/MultipleImageSerializationExample.java | /*
*
* Copyright 2013 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.zeno.examples;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.examples.serializers.ExampleSerializerFactory;
import com.netflix.zeno.fastblob.FastBlobStateEngine;
import com.netflix.zeno.fastblob.io.FastBlobReader;
import com.netflix.zeno.fastblob.io.FastBlobWriter;
import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;
/**
* This is similar to the example shown in the {@link BasicSerializationExample}, except
* that multiple images are now produced. Follow along in the Zeno documentation on
* the page <a href="https://github.com/Netflix/zeno/wiki/Producing-multiple-images>producing multiple images</a>
*
* @author dkoszewnik
*
*/
public class MultipleImageSerializationExample {
private FastBlobStateEngine stateEngine;
private byte[] image1Snapshot;
private byte[] image2Snapshot;
private byte[] image1Delta;
private byte[] image2Delta;
@Test
public void basicSerializationCycle() {
/// First we create a state engine, we need to tell it about our data model by
/// passing it a serializer factory which creates our top-level serializers.
/// Here, we're also telling it that we will be creating two separate images.
stateEngine = new FastBlobStateEngine(new ExampleSerializerFactory(), 2);
/// For this example, we're just storing the serialized data in memory.
createSnapshot();
createDelta();
/// Now we can pretend to be the client, and deserialize the data into a separate state engine.
/// TODO: Try changing these to be image1Snapshot and image1Delta to observe the results.
FastBlobStateEngine clientStateEngine = deserializeLatestData(image1Snapshot, image1Delta);
System.out.println("StateEngine 1:");
showValuesForStateEngine(clientStateEngine);
clientStateEngine = deserializeLatestData(image2Snapshot, image2Delta);
System.out.println("StateEngine 2:");
showValuesForStateEngine(clientStateEngine);
}
private void showValuesForStateEngine(FastBlobStateEngine clientStateEngine) {
/// We can grab the data for any class. Here, we grab the values for class A.
FastBlobTypeDeserializationState<A> aState = clientStateEngine.getTypeDeserializationState("A");
/// the following will loop through all values after loading the snapshot
/// and subsequently applying the delta.
System.out.println("All As: ");
for(A deserializedA : aState){
System.out.println(deserializedA.getIntValue());
}
/// As another example, we can grab the values for class B.
FastBlobTypeDeserializationState<B> bState = clientStateEngine.getTypeDeserializationState("B");
/// Even though we didn't directly add the Bs, they were added because we added objects which
/// referenced them. Here, we iterate over all of the Bs after applying the delta.
System.out.println("All Bs: ");
for(B deserializedB : bState) {
System.out.println(deserializedB.getBInt());
}
}
public FastBlobStateEngine deserializeLatestData(byte snapshot[], byte delta[]) {
/// now we are on the client. We need to create a state engine, and again
/// tell it about our data model.
FastBlobStateEngine stateEngine = new FastBlobStateEngine(new ExampleSerializerFactory());
/// we need to create a FastBlobReader, which is responsible for reading
/// serialized blobs.
FastBlobReader reader = new FastBlobReader(stateEngine);
/// get a stream from the snapshot file location
ByteArrayInputStream snapshotStream = new ByteArrayInputStream(snapshot);
/// get a stream from the delta file location
ByteArrayInputStream deltaStream = new ByteArrayInputStream(delta);
try {
/// first read the snapshot
reader.readSnapshot(snapshotStream);
/// then apply the delta
reader.readDelta(deltaStream);
} catch (IOException e) {
/// either of these methods throws an exception if the FastBlobReader
/// is unable to read from the provided stream.
} finally {
/// it is your responsibility to close the streams. The FastBlobReader will not do this.
try {
snapshotStream.close();
deltaStream.close();
} catch (IOException ignore) { }
}
return stateEngine;
}
public void createSnapshot() {
/// We add each of our object instances to the state engine. Note that for each call, we are
/// specifying the images to which we are adding the instance.
/// This operation is still thread safe and can be called from multiple processing threads.
stateEngine.add("A", getExampleA1(), new boolean[] { true, false });
stateEngine.add("A", getExampleA2(), new boolean[] { true, true });
stateEngine.add("A", getExampleA3(), new boolean[] { false, true });
/// The following lets the state engine know that we have finished adding all of our
/// objects to the state.
stateEngine.prepareForWrite();
/// Create a writer, which will be responsible for creating snapshot and/or delta blobs.
/// Note that we specify the index of the image we wish to write.
FastBlobWriter writer = new FastBlobWriter(stateEngine, 0);
image1Snapshot = writeSnapshot(writer);
image2Snapshot = writeSnapshot(new FastBlobWriter(stateEngine, 1));
}
private byte[] writeSnapshot(FastBlobWriter writer) {
/// Create an output stream to somewhere. This can be to a local file on disk
/// or directly to the blob destination. The VMS team writes this data directly
/// to disk, and then spawns a new thread to upload the data to S3.
/// We need to pass a DataOutputStream. Remember that DataOutputStream is not buffered,
/// so if you write to a FileOutputStream or other non-buffered source, you likely want to
/// make the DataOutputStream wrap a BufferedOutputStream
/// (e.g. new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile))))
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
/// write the snapshot to the output stream.
writer.writeSnapshot(outputStream);
} catch(IOException e) {
/// the FastBlobWriter throws an IOException if it is
/// unable to write to the provided OutputStream
} finally {
/// it is your responsibility to close the stream. The FastBlobWriter will not do this.
try {
outputStream.close();
} catch(IOException ignore) { }
}
byte snapshot[] = baos.toByteArray();
return snapshot;
}
public void createDelta() {
/// The following call informs the state engine that we have finished writing
/// all of our snapshot / delta files, and we are ready to begin adding fresh
/// object instances for the next cycle.
stateEngine.prepareForNextCycle();
// Again, we add each of our object instances to the state engine.
// This operation is still thread safe and can be called from multiple processing threads.
stateEngine.add("A", getExampleA1(), new boolean[] { true, false });
stateEngine.add("A", getExampleA2Prime(), new boolean[] { true, true });
stateEngine.add("A", getExampleA3(), new boolean[] { false, true });
/// We must again let the state engine know that we have finished adding all of our
/// objects to the state.
stateEngine.prepareForWrite();
/// Create a writer, which will be responsible for creating snapshot and/or delta blobs.
/// Again, note that we are specifying the index of image we wish to write.
FastBlobWriter writer = new FastBlobWriter(stateEngine, 0);
image1Delta = writeDelta(writer);
image2Delta = writeDelta(new FastBlobWriter(stateEngine, 1));
}
private byte[] writeDelta(FastBlobWriter writer) {
/// Again create an output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
/// This time write the delta file.
writer.writeDelta(outputStream);
} catch(IOException e) {
/// thrown if the FastBlobWriter was unable to write to the provided stream.
} finally {
try {
outputStream.close();
} catch(IOException ignore){ }
}
byte delta[] = baos.toByteArray();
return delta;
}
public A getExampleA1() {
B b1 = new B(1, "one");
B b2 = new B(2, "two");
List<B> bList = new ArrayList<B>();
bList.add(b1);
bList.add(b2);
C c = new C(Long.MAX_VALUE, new byte[] { 1, 2, 3, 4, 5 });
A a = new A(bList, c, 1);
return a;
}
public A getExampleA2() {
B b3 = new B(3, "three");
B b4 = new B(4, "four");
B b5 = new B(5, "five");
List<B> bList = new ArrayList<B>();
bList.add(b3);
bList.add(b4);
bList.add(b5);
C c = new C(Long.MAX_VALUE, new byte[] { 10, 9, 8, 7, 6 });
A a = new A(bList, c, 2);
return a;
}
public A getExampleA3() {
B b3 = new B(8, "eight");
List<B> bList = new ArrayList<B>();
bList.add(b3);
C c = new C(Long.MAX_VALUE, new byte[] { 20, 30, 40 });
A a = new A(bList, c, 3);
return a;
}
public A getExampleA2Prime() {
B c3 = new B(3, "three");
B c4 = new B(4, "four");
B c6 = new B(6, "six");
List<B> cList = new ArrayList<B>();
cList.add(c3);
cList.add(c4);
cList.add(c6);
C d = new C(Long.MAX_VALUE, new byte[] { 10, 9, 8, 7, 6 });
A a = new A(cList, d, 2);
return a;
}
}
| 8,242 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/framework/IntSumRecord.java | /*
*
* Copyright 2013 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.zeno.examples.framework;
import com.netflix.zeno.serializer.NFSerializationRecord;
/**
* When implementing a SerializationFramework, we need to create some kind of "serialization record".<p/>
*
* The role of the serialization record is to maintain some state while traversing an object instance.<p/>
*
* In our contrived example, this means we will have to keep track of a sum.<p/>
*
* A "serialization record" must implement NFSerializationRecord. This interface defines no methods and is only
* intended to indicate the role of the class.
*
* @author dkoszewnik
*
*/
public class IntSumRecord extends NFSerializationRecord {
private int sum;
public void addValue(int value) {
sum += value;
}
public int getSum() {
return sum;
}
}
| 8,243 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/framework/IntSumFramework.java | /*
*
* Copyright 2013 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.zeno.examples.framework;
import com.netflix.zeno.serializer.SerializationFramework;
import com.netflix.zeno.serializer.SerializerFactory;
/**
* An example framework which sums all of the integers contained in an object instance (anywhere in the
* hierarchy defined by the data model). <p/>
*
* Follow along in the documentation page <a href="https://github.com/Netflix/zeno/wiki/Creating-new-operations">creating new operations</a>
*
* @author dkoszewnik
*
*/
public class IntSumFramework extends SerializationFramework {
public IntSumFramework(SerializerFactory serializerFactory) {
super(serializerFactory);
this.frameworkSerializer = new IntSumFrameworkSerializer(this);
}
public <T> int getSum(String type, T obj) {
IntSumRecord record = new IntSumRecord();
getSum(type, obj, record);
return record.getSum();
}
<T> void getSum(String type, T obj, IntSumRecord record) {
getSerializer(type).serialize(obj, record);
}
}
| 8,244 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/framework/IntSumFrameworkExample.java | /*
*
* Copyright 2013 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.zeno.examples.framework;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.examples.serializers.ExampleSerializerFactory;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.Assert;
/**
* Example usage of the {@link IntSumFramework}.
*
* @author dkoszewnik
*
*/
public class IntSumFrameworkExample {
@Test
public void determineSumOfValues() {
IntSumFramework sumFramework = new IntSumFramework(new ExampleSerializerFactory());
B b1 = new B(12, "Twelve!"); /// sum = 12
B b2 = new B(25, "Plus Twenty Five!"); /// sum = 37
B b3 = new B(10, "Plus Ten!"); /// sum = 47
List<B> bList = Arrays.asList(b1, b2, b3);
C c = new C(20, new byte[] { 100, 101, 102 }); /// longs don't count. Still sum = 47.
A a = new A(bList, c, 100); /// sum = 147
int actualSum = sumFramework.getSum("A", a);
Assert.assertEquals(147, actualSum);
}
}
| 8,245 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/framework/IntSumFrameworkSerializer.java | /*
*
* Copyright 2013 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.zeno.examples.framework;
import com.netflix.zeno.serializer.FrameworkSerializer;
import com.netflix.zeno.serializer.SerializationFramework;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* After defining our "serialization record", we need to implement a "framework serializer".
*
* @author dkoszewnik
*
*/
public class IntSumFrameworkSerializer extends FrameworkSerializer<IntSumRecord> {
public IntSumFrameworkSerializer(SerializationFramework framework) {
super(framework);
}
/**
* We need to implement serializePrimitive to describe what happens when we encounter one of the following types:
* Integer, Long, Float, Double, Boolean, String.
*/
@Override
public void serializePrimitive(IntSumRecord rec, String fieldName, Object value) {
/// only interested in int values.
if(value instanceof Integer) {
rec.addValue(((Integer) value).intValue());
}
}
@Override
public void serializeObject(IntSumRecord rec, String fieldName, Object obj) {
String typeName = rec.getSchema().getObjectType(fieldName);
serializeObject(rec, fieldName, typeName, obj);
}
@Override
public void serializeObject(IntSumRecord rec, String fieldName, String typeName, Object obj) {
((IntSumFramework)framework).getSum(typeName, obj, rec);
}
@Override
public <T> void serializeList(IntSumRecord rec, String fieldName, String typeName, Collection<T> obj) {
serializeCollection(rec, obj, typeName);
}
@Override
public <T> void serializeSet(IntSumRecord rec, String fieldName, String typeName, Set<T> obj) {
serializeCollection(rec, obj, typeName);
}
@Override
public <K, V> void serializeMap(IntSumRecord rec, String fieldName, String keyTypeName, String valueTypeName, Map<K, V> obj) {
serializeCollection(rec, obj.keySet(), keyTypeName);
serializeCollection(rec, obj.values(), valueTypeName);
}
private <T> void serializeCollection(IntSumRecord rec, Collection<T> coll, String elementTypeName) {
for(T t : coll) {
((IntSumFramework)framework).getSum(elementTypeName, t, rec);
}
}
@Override
public void serializeBytes(IntSumRecord rec, String fieldName, byte[] value) {
// do nothing, not interested in byte[]
}
}
| 8,246 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/serializers/BWithStringReferenceSerializer.java | /*
*
* Copyright 2013 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.zeno.examples.serializers;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.StringSerializer;
import java.util.Collection;
public class BWithStringReferenceSerializer extends NFTypeSerializer<B> {
public BWithStringReferenceSerializer() {
super("B");
}
@Override
public void doSerialize(B value, NFSerializationRecord rec) {
serializePrimitive(rec, "bInt", value.getBInt());
serializeObject(rec, "bString", value.getBString());
}
@Override
protected B doDeserialize(NFDeserializationRecord rec) {
int bInt = deserializeInteger(rec, "bInt");
String bString = deserializeObject(rec, "bString");
return new B(bInt, bString);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("bInt", FieldType.INT),
field("bString", StringSerializer.NAME)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(
new StringSerializer()
);
}
}
| 8,247 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/serializers/ASerializer.java | /*
*
* Copyright 2013 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.zeno.examples.serializers;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.ListSerializer;
import java.util.Collection;
import java.util.List;
public class ASerializer extends NFTypeSerializer<A> {
public ASerializer() {
super("A");
}
@Override
public void doSerialize(A value, NFSerializationRecord rec) {
serializeObject(rec, "blist", value.getBList());
serializeObject(rec, "c", value.getCValue());
serializePrimitive(rec, "intVal", value.getIntValue());
}
@Override
protected A doDeserialize(NFDeserializationRecord rec) {
List<B> bList = deserializeObject(rec, "blist");
C c = deserializeObject(rec, "c");
int intValue = deserializeInteger(rec, "intVal");
return new A(bList, c, intValue);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("blist", "ListOfBs"),
field("c", "C"),
field("intVal", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(
new ListSerializer<B>("ListOfBs", new BSerializer()),
new CSerializer()
);
}
}
| 8,248 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/serializers/ExampleSerializerFactory.java | /*
*
* Copyright 2013 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.zeno.examples.serializers;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
/**
* An example SerializerFactory, which references the following types (classes / serializers):<p/>
*
* <ul>
* <li>A / ASerializer</li>
* <li>B / BSerializer</li>
* <li>C / CSerializer</li>
* </ul>
*
*/
public class ExampleSerializerFactory implements SerializerFactory {
public static final SerializerFactory INSTANCE = new ExampleSerializerFactory();
@Override
public NFTypeSerializer<?>[] createSerializers() {
NFTypeSerializer<A> serializer = new ASerializer();
// only ASerializer needs to be passed in the array.
// CSerializer and DSerializer will be available because they are referenced by the
// requiredSubSerializers() method of ASerializer.
return new NFTypeSerializer<?>[] { serializer };
}
}
| 8,249 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/serializers/CSerializer.java | /*
*
* Copyright 2013 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.zeno.examples.serializers;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
public class CSerializer extends NFTypeSerializer<C> {
public CSerializer() {
super("C");
}
@Override
public void doSerialize(C value, NFSerializationRecord rec) {
serializePrimitive(rec, "cLong", value.getCLong());
serializeBytes(rec, "cBytes", value.getCBytes());
}
@Override
protected C doDeserialize(NFDeserializationRecord rec) {
long cLong = deserializeLong(rec, "cLong");
byte cBytes[] = deserializeBytes(rec, "cBytes");
return new C(cLong, cBytes);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("cLong", FieldType.LONG),
field("cBytes", FieldType.BYTES)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptySet();
}
}
| 8,250 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/serializers/DSerializer.java | /*
*
* Copyright 2013 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.zeno.examples.serializers;
import com.netflix.zeno.examples.pojos.A;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.examples.pojos.C;
import com.netflix.zeno.examples.pojos.D;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.IntegerSerializer;
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.List;
import java.util.Map;
import java.util.Set;
public class DSerializer extends NFTypeSerializer<D> {
public DSerializer() {
super("D");
}
@Override
public void doSerialize(D value, NFSerializationRecord rec) {
serializeObject(rec, "aList", value.getList());
serializeObject(rec, "bSet", value.getSet());
serializeObject(rec, "cMap", value.getMap());
}
@Override
protected D doDeserialize(NFDeserializationRecord rec) {
List<A> aList = deserializeObject(rec, "aList");
Set<B> bSet = deserializeObject(rec, "bSet");
Map<Integer, C> cMap = deserializeObject(rec, "cMap");
return new D(aList, bSet, cMap);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("aList", "ListOfAs"),
field("bSet", "SetOfBs"),
field("cMap", "MapOfCs")
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(
new ListSerializer<A>("ListOfAs", new ASerializer()),
new SetSerializer<B>("SetOfBs", new BSerializer()),
new MapSerializer<Integer, C>("MapOfCs", new IntegerSerializer(), new CSerializer())
);
}
}
| 8,251 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/serializers/BSerializer.java | /*
*
* Copyright 2013 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.zeno.examples.serializers;
import com.netflix.zeno.examples.pojos.B;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
public class BSerializer extends NFTypeSerializer<B> {
public BSerializer() {
super("B");
}
@Override
public void doSerialize(B value, NFSerializationRecord rec) {
serializePrimitive(rec, "bInt", value.getBInt());
serializePrimitive(rec, "bString", value.getBString());
}
@Override
protected B doDeserialize(NFDeserializationRecord rec) {
int bInt = deserializeInteger(rec, "bInt");
String bString = deserializePrimitiveString(rec, "bString");
return new B(bInt, bString);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("bInt", FieldType.INT),
field("bString", FieldType.STRING)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptySet();
}
}
| 8,252 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/address/AddressSerializer.java | /*
*
* Copyright 2013 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.zeno.examples.address;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
* This class is here for demonstration purposes. It is a serializer for a less efficient representation of an Address
* object. Follow along with: https://github.com/Netflix/zeno/wiki/Designing-for-efficiency to see how
* to reason about how to make Zeno more effective at deduplicating your object model.
*
* @author dkoszewnik
*
*/
public class AddressSerializer extends NFTypeSerializer<Address> {
public AddressSerializer() {
super("Address");
}
@Override
public void doSerialize(Address value, NFSerializationRecord rec) {
serializePrimitive(rec, "street", value.getStreetAddress());
serializePrimitive(rec, "city", value.getCity());
serializePrimitive(rec, "state", value.getState());
serializePrimitive(rec, "postalCode", value.getPostalCode());
}
@Override
protected Address doDeserialize(NFDeserializationRecord rec) {
String streetAddress = deserializePrimitiveString(rec, "street");
String city = deserializePrimitiveString(rec, "city");
String state = deserializePrimitiveString(rec, "state");
String postalCode = deserializePrimitiveString(rec, "postalCode");
return new Address(streetAddress, city, state, postalCode);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("street", FieldType.STRING),
field("city", FieldType.STRING),
field("state", FieldType.STRING),
field("postalCode", FieldType.STRING)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,253 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/address/AddressRefactor.java | /*
*
* Copyright 2013 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.zeno.examples.address;
/**
* This class is here for demonstration purposes. It is a more efficient representation of an Address
* object. Follow along with: https://github.com/Netflix/zeno/wiki/Designing-for-efficiency to see how
* to reason about how to make Zeno more effective at deduplicating your object model.
*
* @author dkoszewnik
*
*/
public class AddressRefactor {
private final String streetAddress;
private final City city;
private final String postalCode;
public AddressRefactor(String streetAddress, City city, String postalCode) {
this.streetAddress = streetAddress;
this.city = city;
this.postalCode = postalCode;
}
public String getStreetAddress() {
return streetAddress;
}
public City getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
public static class City {
private final String city;
private final String state;
public City(String city, String state) {
this.city = city;
this.state = state;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
}
}
| 8,254 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/address/AddressRefactorSerializer.java | /*
*
* Copyright 2013 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.zeno.examples.address;
import com.netflix.zeno.examples.address.AddressRefactor.City;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.StringSerializer;
import java.util.Collection;
/**
* This class is here for demonstration purposes. It is a serializer for a more efficient representation of an Address
* object. Follow along with: https://github.com/Netflix/zeno/wiki/Designing-for-efficiency to see how
* to reason about how to make Zeno more effective at deduplicating your object model.
*
* @author dkoszewnik
*
*/
public class AddressRefactorSerializer extends NFTypeSerializer<AddressRefactor> {
public AddressRefactorSerializer() {
super("Address");
}
@Override
public void doSerialize(AddressRefactor value, NFSerializationRecord rec) {
serializePrimitive(rec, "street", value.getStreetAddress());
serializeObject(rec, "city", value.getCity());
serializeObject(rec, "postalCode", value.getPostalCode());
}
@Override
protected AddressRefactor doDeserialize(NFDeserializationRecord rec) {
String streetAddress = deserializePrimitiveString(rec, "street");
City city = deserializeObject(rec, "city");
String postalCode = deserializeObject(rec, "postalCode");
return new AddressRefactor(streetAddress, city, postalCode);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("street", FieldType.STRING),
field("city", "City"),
field("postalCode", "PostalCodeString")
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(
new CitySerializer(),
new StringSerializer("PostalCodeString")
);
}
}
| 8,255 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/address/Address.java | /*
*
* Copyright 2013 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.zeno.examples.address;
/**
* This class is here for demonstration purposes. It is a less efficient representation of an Address
* object. Follow along with: https://github.com/Netflix/zeno/wiki/Designing-for-efficiency to see how
* to reason about how to make Zeno more effective at deduplicating your object model.
*
* @author dkoszewnik
*
*/
public class Address {
private final String streetAddress;
private final String city;
private final String state;
private final String postalCode;
public Address(String streetAddress, String city, String state, String postalCode) {
this.streetAddress = streetAddress;
this.city = city;
this.state = state;
this.postalCode = postalCode;
}
public String getStreetAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public String getPostalCode() {
return postalCode;
}
}
| 8,256 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/address/CitySerializer.java | /*
*
* Copyright 2013 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.zeno.examples.address;
import com.netflix.zeno.examples.address.AddressRefactor.City;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.common.StringSerializer;
import java.util.Collection;
/**
* This class is here for demonstration purposes. It is a sub-serializer for the city
* component of a more efficient representation of an Address object. Follow along with:
* https://github.com/Netflix/zeno/wiki/Designing-for-efficiency to see how to reason about
* how to make Zeno more effective at deduplicating your object model.
*
* @author dkoszewnik
*
*/
public class CitySerializer extends NFTypeSerializer<City> {
public CitySerializer() {
super("City");
}
@Override
public void doSerialize(City value, NFSerializationRecord rec) {
serializePrimitive(rec, "city", value.getCity());
serializeObject(rec, "state", value.getState());
}
@Override
protected City doDeserialize(NFDeserializationRecord rec) {
String city = deserializePrimitiveString(rec, "city");
String state = deserializeObject(rec, "state");
return new City(city, state);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("city", FieldType.STRING),
field("state", "StateString")
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(
new StringSerializer("StateString")
);
}
}
| 8,257 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/pojos/B.java | /*
*
* Copyright 2013 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.zeno.examples.pojos;
public class B {
private final int bInt;
private final String bString;
public B(int bInt, String bString) {
this.bInt = bInt;
this.bString = bString;
}
public int getBInt() {
return bInt;
}
public String getBString() {
return bString;
}
}
| 8,258 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/pojos/C.java | /*
*
* Copyright 2013 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.zeno.examples.pojos;
public class C {
private final long cLong;
private final byte cBytes[];
public C(long cLong, byte cBytes[]) {
this.cLong = cLong;
this.cBytes = cBytes;
}
public long getCLong() {
return cLong;
}
public byte[] getCBytes() {
return cBytes;
}
}
| 8,259 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/pojos/D.java | /*
*
* Copyright 2013 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.zeno.examples.pojos;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class D {
private final List<A> list;
private final Set<B> set;
private final Map<Integer, C> map;
public D(List<A> list, Set<B> set, Map<Integer, C> map) {
this.list = list;
this.set = set;
this.map = map;
}
public List<A> getList() {
return list;
}
public Set<B> getSet() {
return set;
}
public Map<Integer, C> getMap() {
return map;
}
}
| 8,260 |
0 | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples | Create_ds/zeno/src/examples/java/com/netflix/zeno/examples/pojos/A.java | /*
*
* Copyright 2013 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.zeno.examples.pojos;
import java.util.List;
public class A {
private final List<B> bList;
private final C cValue;
private final int intValue;
public A(List<B> bList, C cValue, int intValue) {
this.bList = bList;
this.cValue = cValue;
this.intValue = intValue;
}
public List<B> getBList() {
return bList;
}
public C getCValue() {
return cValue;
}
public int getIntValue() {
return intValue;
}
}
| 8,261 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/genericobject/DiffHtmlGenerator.java | /*
*
* Copyright 2013 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.zeno.genericobject;
import com.netflix.zeno.genericobject.GenericObject.CollectionType;
import com.netflix.zeno.genericobject.GenericObject.Field;
import com.netflix.zeno.serializer.SerializerFactory;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* This class generates HTML describing the differences between two GenericObjects.
*
* @author dkoszewnik
*
*/
/*
* This is extremely messy code and is ripe for replacement.
*
* It is the result of an afternoon spike several months ago and has not yet needed any updates.
*/
public class DiffHtmlGenerator {
private final DiffHtmlCollectionLocker locker;
private final GenericObjectSerializationFramework genericObjectFramework;
private final boolean moreAtFromLevels[] = new boolean[1024];
private final boolean moreAtToLevels[] = new boolean[1024];
private int hierarchyLevel = 1;
/**
* Instantiate with the SerializerFactory describing an object model.
*/
public DiffHtmlGenerator(SerializerFactory factory) {
locker = new DiffHtmlCollectionLocker(factory);
genericObjectFramework = new GenericObjectSerializationFramework(factory);
}
/**
* Generate the HTML difference between two objects.
*
* @param objectType - The NFTypeSerializer name of the objects
* @param from - The first object to diff
* @param to - The second object to diff
* @return
*/
public String generateDiff(String objectType, Object from, Object to) {
GenericObject fromGenericObject = from == null ? null : genericObjectFramework.serialize(from, objectType);
GenericObject toGenericObject = to == null ? null : genericObjectFramework.serialize(to, objectType);
return generateDiff(fromGenericObject, toGenericObject);
}
/**
* Generate the HTML difference between two GenericObjects.
*
* @return
*/
public String generateDiff(GenericObject from, GenericObject to) {
StringBuilder builder = new StringBuilder();
builder.append("<table class=\"nomargin diff\">");
builder.append("<thead>");
builder.append("<tr>");
builder.append("<th/>");
builder.append("<th class=\"texttitle\">From</th>");
builder.append("<th/>");
builder.append("<th class=\"texttitle\">To</th>");
builder.append("</tr>");
builder.append("</thead>");
builder.append("<tbody>");
writeDiff(builder, from, to);
builder.append("</tbody>");
builder.append("</table>");
return builder.toString();
}
private void writeDiff(StringBuilder builder, GenericObject from, GenericObject to) {
if(from != null && to != null) {
writeDiffBothObjectsPresent(builder, from, to);
} else if(from != null || to != null) {
writeDiffOneObjectNull(builder, from, to);
}
}
private void writeDiffBothObjectsPresent(StringBuilder builder, GenericObject from, GenericObject to) {
if(from.getCollectionType() == CollectionType.COLLECTION) {
writeCollectionDiff(builder, from, to);
} else if(from.getCollectionType() == CollectionType.MAP) {
writeMapDiff(builder, from, to);
} else {
writeObjectDiff(builder, from, to);
}
}
private void writeCollectionDiff(StringBuilder builder, GenericObject from, GenericObject to) {
locker.lockCollectionFields(from, to);
/// both objects' fields length should be the same after the lockCollectionFields operation
for(int i=0;i<from.getFields().size();i++) {
Field fromField = from.getFields().get(i);
Field toField = to.getFields().get(i);
boolean moreFromFields = moreCollectionFields(from.getFields(), i);
boolean moreToFields = moreCollectionFields(to.getFields(), i);
appendField(builder, fromField, toField, moreFromFields, moreToFields);
}
}
private void writeMapDiff(StringBuilder builder, GenericObject from, GenericObject to) {
sortMapFieldsByKey(from);
sortMapFieldsByKey(to);
int fromCounter = 0;
int toCounter = 0;
while(fromCounter < from.getFields().size() || toCounter < to.getFields().size()) {
Field fromField = fromCounter < from.getFields().size() ? from.getFields().get(fromCounter) : null;
Field toField = toCounter < to.getFields().size() ? to.getFields().get(toCounter) : null;
int comparison = mapFieldComparator.compare(fromField, toField);
boolean moreFromFields = moreCollectionFields(from.getFields(), fromCounter);
boolean moreToFields = moreCollectionFields(to.getFields(), toCounter);
if(comparison == 0) {
appendField(builder, fromField, toField, moreFromFields, moreToFields);
fromCounter++;
toCounter++;
} else if(comparison < 0) {
appendField(builder, fromField, null, moreFromFields, toField != null);
fromCounter++;
} else {
appendField(builder, null, toField, fromField != null, moreToFields);
toCounter++;
}
}
}
private boolean moreCollectionFields(List<Field> fieldList, int position) {
if(position >= fieldList.size())
return false;
for(int i=position+1;i<fieldList.size();i++) {
if(fieldList.get(i) != null)
return true;
}
return false;
}
private void writeObjectDiff(StringBuilder builder, GenericObject from, GenericObject to) {
/// objects of the same type should always have the same number of fields.
for(int i=0;i<from.getFields().size();i++) {
Field fromField = from.getFields().get(i);
Field toField = to.getFields().get(i);
boolean moreFields = i != (from.getFields().size() - 1);
appendField(builder, fromField, toField, moreFields, moreFields);
}
}
private void sortMapFieldsByKey(GenericObject map) {
Collections.sort(map.getFields(), mapFieldComparator);
}
private void writeDiffOneObjectNull(StringBuilder builder, GenericObject from, GenericObject to) {
if(from != null) {
for(int i=0;i<from.getFields().size();i++) {
boolean moreFields = i != (from.getFields().size() - 1);
appendField(builder, from.getFields().get(i), null, moreFields, false);
}
} else {
for(int i=0;i<to.getFields().size();i++) {
boolean moreFields = i != (to.getFields().size() - 1);
appendField(builder, null, to.getFields().get(i), false, moreFields);
}
}
}
private void appendField(StringBuilder builder, Field fromField, Field toField, boolean moreAtFromLevel, boolean moreAtToLevel) {
moreAtFromLevels[hierarchyLevel] = moreAtFromLevel;
moreAtToLevels[hierarchyLevel] = moreAtToLevel;
Object nonNullValue = getNonNullValue(fromField, toField);
builder.append("<tr>");
if(fromField != null && fromField.getCollectionPosition() != 0)
builder.append("<th>").append(fromField.getCollectionPosition()).append("</th>");
else
builder.append("<th/>");
builder.append("<td class=\"").append(cssClass(fromField, toField, "delete")).append("\">");
if(fromField != null) {
if(nonNullValue instanceof GenericObject) {
openNewObject(builder, fromField.getFieldName(), ((GenericObject) nonNullValue).getObjectType(), moreAtFromLevel, true);
} else {
appendFieldValue(builder, fromField.getFieldName(), fromField.getValue(), moreAtFromLevel, true);
}
} else {
appendEmptyHierarchyLevel(builder, moreAtFromLevels);
}
builder.append("</td>");
if(toField != null && toField.getCollectionPosition() != 0)
builder.append("<th>").append(toField.getCollectionPosition()).append("</th>");
else
builder.append("<th/>");
builder.append("<td class=\"").append(cssClass(toField, fromField, "insert")).append("\">");
if(toField != null) {
if(nonNullValue instanceof GenericObject) {
openNewObject(builder, toField.getFieldName(), ((GenericObject) nonNullValue).getObjectType(), moreAtToLevel, false);
} else {
appendFieldValue(builder, toField.getFieldName(), toField.getValue(), moreAtToLevel, false);
}
} else {
appendEmptyHierarchyLevel(builder, moreAtToLevels);
}
builder.append("</td>");
builder.append("</tr>");
if(nonNullValue instanceof GenericObject) {
hierarchyLevel++;
writeDiff(builder, (GenericObject)fieldValue(fromField), (GenericObject)fieldValue(toField));
hierarchyLevel--;
}
moreAtFromLevels[hierarchyLevel] = false;
moreAtToLevels[hierarchyLevel] = false;
}
private Object fieldValue(Field field) {
if(field == null)
return null;
return field.getValue();
}
private Object getNonNullValue(Field fromField, Field toField) {
if(fromField != null && fromField.getValue() != null)
return fromField.getValue();
if(toField != null)
return toField.getValue();
return null;
}
private void openNewObject(StringBuilder builder, String fieldName, String typeName, boolean lastFieldAtLevel, boolean from) {
appendHierarchyLevel(builder, true, hierarchyLevel, lastFieldAtLevel, from);
builder.append(fieldName).append(": ").append("(").append(typeName).append(")\n");
}
private String cssClass(Field field1, Field field2, String missingCssClass) {
if(field1 == null)
return "empty";
if(field2 == null)
return missingCssClass;
if(field1.getValue() == null && field2.getValue() != null)
return "replace";
if(field1.getValue() == null && field2.getValue() == null)
return "equal";
if(field1.getValue() != null && field2.getValue() == null)
return "replace";
if(!(field1.getValue() instanceof GenericObject)) {
if(!field1.getValue().equals(field2.getValue()))
return "replace";
}
return "equal";
}
private void appendFieldValue(StringBuilder builder, String fieldName, Object value, boolean moreFieldsAtLevel, boolean from) {
appendHierarchyLevel(builder, false, hierarchyLevel, moreFieldsAtLevel, from);
builder.append(fieldName).append(": ").append(value).append("\n");
}
private void appendHierarchyLevel(StringBuilder builder, boolean objectField, int hierarchyLevel, boolean moreFieldsAtLevel, boolean from) {
boolean levelGuide[] = from ? moreAtFromLevels : moreAtToLevels;
for(int i=1;i<hierarchyLevel;i++) {
if(levelGuide[i]) {
builder.append(".│");
} else {
builder.append("..");
}
}
if(objectField) {
if(moreFieldsAtLevel)
builder.append(".┝━┯━>");
else
builder.append(".┕━┯━>");
} else {
if(moreFieldsAtLevel)
builder.append(".├───>");
else
builder.append(".└───>");
}
}
private void appendEmptyHierarchyLevel(StringBuilder builder, boolean[] levelGuide) {
for(int i=1;i<=hierarchyLevel;i++) {
if(levelGuide[i]) {
builder.append(" │");
} else {
for(int j=i;j<=hierarchyLevel;j++) {
if(levelGuide[j]) {
builder.append(" ");
break;
}
}
}
}
}
private static final Comparator<Field> mapFieldComparator = new Comparator<Field>() {
@SuppressWarnings({ "unchecked", "rawtypes" })
public int compare(Field o1, Field o2) {
if(o1 == null && o2 == null)
return 0;
if(o1 == null)
return 1;
if(o2 == null)
return -1;
Object key1 = getKey(o1);
Object key2 = getKey(o2);
if(key1 instanceof Comparable) {
return ((Comparable) key1).compareTo(key2);
}
return key1.hashCode() - key2.hashCode();
}
};
private static Object getKey(Field entryField) {
GenericObject entryObject = (GenericObject) entryField.getValue();
Field keyField = entryObject.getFields().get(0);
GenericObject keyObject = (GenericObject)keyField.getValue();
return keyObject.getActualObject();
}
}
| 8,262 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/genericobject/GenericObjectSerializationFramework.java | /*
*
* Copyright 2013 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.zeno.genericobject;
import com.netflix.zeno.serializer.SerializationFramework;
import com.netflix.zeno.serializer.SerializerFactory;
/**
* This framework is used to create a GenericObject representation of data.
*
* The GenericObject representation is used by the diff HTML generator.
*
* @author dkoszewnik
*
*/
public class GenericObjectSerializationFramework extends SerializationFramework {
public GenericObjectSerializationFramework(SerializerFactory factory) {
super(factory);
this.frameworkSerializer = new GenericObjectFrameworkSerializer(this);
}
public GenericObject serialize(Object obj, String serializerName) {
GenericObject diffObject = new GenericObject(serializerName, obj);
getSerializer(serializerName).serialize(obj, diffObject);
return diffObject;
}
}
| 8,263 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/genericobject/GenericObjectFrameworkSerializer.java | /*
*
* Copyright 2013 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.zeno.genericobject;
import com.netflix.zeno.genericobject.GenericObject.CollectionType;
import com.netflix.zeno.serializer.FrameworkSerializer;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializationFramework;
import com.netflix.zeno.util.PrimitiveObjectIdentifier;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
/**
* The GenericObject representation is used by the diff HTML generator.
*
* @author dkoszewnik
*
*/
public class GenericObjectFrameworkSerializer extends FrameworkSerializer<GenericObject> {
public GenericObjectFrameworkSerializer(SerializationFramework framework) {
super(framework);
}
@Override
public void serializePrimitive(GenericObject rec, String fieldName, Object value){
if(value != null){
if( value.getClass().isEnum()){
value = ((Enum<?>)value).name();
} else if(value instanceof Date) {
value = value.toString();
}
}
rec.add(fieldName, value);
}
@Override
public void serializeBytes(GenericObject rec, String fieldName, byte[] value) {
String str = null;
if(value != null){
byte encoded[] = Base64.encodeBase64(value, true);
try {
str = new String(encoded, "UTF-8");
} catch (UnsupportedEncodingException ignore) { }
}
rec.add(fieldName, str);
}
private static boolean isPrimitive(Class<?> type){
return type.isEnum() || PrimitiveObjectIdentifier.isPrimitiveOrWrapper(type);
}
/*
* @Deprecated instead use serializeObject(GenericObject rec, String fieldName, Object obj)
*
*/
@Deprecated
@Override
@SuppressWarnings("unchecked")
public void serializeObject(GenericObject rec, String fieldName, String typeName, Object obj) {
if( obj == null ){
rec.add(fieldName, null);
} else if (isPrimitive(obj.getClass())){
serializePrimitive(rec, fieldName, obj);
return;
} else {
GenericObject subObject = new GenericObject(typeName, obj);
getSerializer(typeName).serialize(obj, subObject);
rec.add(fieldName, subObject);
}
}
@Override
public void serializeObject(GenericObject rec, String fieldName, Object obj) {
serializeObject(rec, fieldName, rec.getObjectType(fieldName), obj);
}
@Override
public <T> void serializeList(GenericObject rec, String fieldName, String elementTypeName, Collection<T> obj) {
serializeCollection(rec, fieldName, "List", elementTypeName, obj);
}
@Override
public <T> void serializeSet(GenericObject rec, String fieldName, String elementTypeName, Set<T> obj) {
serializeCollection(rec, fieldName, "Set", elementTypeName, obj);
}
private <T> void serializeCollection(GenericObject rec, String fieldName, String collectionType, String elementTypeName, Collection<T> obj) {
if(obj == null) {
rec.add(fieldName, null);
} else {
GenericObject setObject = new GenericObject(collectionType, CollectionType.COLLECTION, obj);
serializeCollectionElements(setObject, elementTypeName, obj);
rec.add(fieldName, setObject);
}
}
@SuppressWarnings("unchecked")
private <T> void serializeCollectionElements(GenericObject record, String elementTypeName, Collection<T> obj) {
int counter = 0;
for(T element : obj) {
if(element == null) {
record.add("element", obj, ++counter);
} else {
NFTypeSerializer<Object> elementSerializer = getSerializer(elementTypeName);
GenericObject elementObject = new GenericObject(elementTypeName, element);
elementSerializer.serialize(element, elementObject);
record.add("element", elementObject, ++counter);
}
}
}
@Override
@SuppressWarnings("unchecked")
public <K, V> void serializeMap(GenericObject record, String fieldName, String keyTypeName, String valueTypeName, Map<K, V> map) {
if(map == null) {
record.add(fieldName, null);
}
GenericObject mapObject = new GenericObject("Map", CollectionType.MAP, map);
int counter = 0;
for(Map.Entry<K, V> entry : map.entrySet()) {
counter++;
GenericObject entryObject = new GenericObject("Map.Entry", entry);
NFTypeSerializer<Object> keySerializer = getSerializer(keyTypeName);
GenericObject keyObject = new GenericObject(keyTypeName, entry.getKey());
keySerializer.serialize(entry.getKey(), keyObject);
entryObject.add("key", keyObject);
if(entry.getValue() == null) {
entryObject.add("value", null);
} else {
NFTypeSerializer<Object> valueSerializer = getSerializer(valueTypeName);
GenericObject valueObject = new GenericObject(valueTypeName, entry.getValue());
valueSerializer.serialize(entry.getValue(), valueObject);
entryObject.add("value", valueObject);
}
mapObject.add("entry", entryObject, counter);
}
record.add(fieldName, mapObject);
}
}
| 8,264 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/genericobject/DiffHtmlCollectionLocker.java | /*
*
* Copyright 2013 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.zeno.genericobject;
import com.netflix.zeno.diff.DiffRecord;
import com.netflix.zeno.diff.DiffSerializationFramework;
import com.netflix.zeno.genericobject.GenericObject.Field;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* This class will line up two collections so that the most similar items are paired together.<p/>
*
* This helps to eyeball the differences between two objects with collections in their hierarchies, without
* requiring knowledge of the semantics of these objects.<p/>
*
* The similarity metric used here is the <a href="http://matpalm.com/resemblance/jaccard_coeff/">jaccard</a> distance.
*
* @author dkoszewnik
*
*/
public class DiffHtmlCollectionLocker {
private final DiffSerializationFramework diffFramework;
public DiffHtmlCollectionLocker(SerializerFactory factory) {
diffFramework = new DiffSerializationFramework(factory);
}
void lockCollectionFields(GenericObject from, GenericObject to) {
List<Field> lockedFromFields = new ArrayList<Field>();
List<Field> lockedToFields = new ArrayList<Field>();
List<DiffRecord> fromDiffRecords = createDiffRecordList(from);
List<DiffRecord> toDiffRecords = createDiffRecordList(to);
JaccardMatrixPairwiseMatcher matcher = new JaccardMatrixPairwiseMatcher(from.getFields(), fromDiffRecords, to.getFields(), toDiffRecords);
while (matcher.nextPair()) {
lockedFromFields.add(matcher.getX());
lockedToFields.add(matcher.getY());
}
from.setFields(lockedFromFields);
to.setFields(lockedToFields);
}
private List<DiffRecord> createDiffRecordList(GenericObject from) {
List<DiffRecord> diffRecords = new ArrayList<DiffRecord>();
for (int i = 0; i < from.getFields().size(); i++) {
Field field = from.getFields().get(i);
if (field != null && field.getValue() != null) {
DiffRecord rec = getDiffRecord(field);
diffRecords.add(rec);
} else {
DiffRecord rec = new DiffRecord();
rec.setSchema(from.getSchema());
diffRecords.add(rec);
}
}
return diffRecords;
}
private DiffRecord getDiffRecord(Field field) {
GenericObject fieldValue = (GenericObject) field.getValue();
DiffRecord rec = new DiffRecord();
rec.setSchema(fieldValue.getSchema());
if (field.getValue() instanceof GenericObject) {
rec.setTopLevelSerializerName(fieldValue.getObjectType());
((NFTypeSerializer<Object>) diffFramework.getSerializer(fieldValue.getObjectType())).serialize(fieldValue.getActualObject(), rec);
} else {
rec.setTopLevelSerializerName("primitive");
rec.serializePrimitive("value", field.getValue());
}
return rec;
}
}
| 8,265 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/genericobject/GenericObject.java | /*
*
* Copyright 2013 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.zeno.genericobject;
import com.netflix.zeno.serializer.NFSerializationRecord;
import java.util.ArrayList;
import java.util.List;
/**
* The GenericObject representation is used by the diff HTML generator.
*
* @author dkoszewnik
*
*/
public class GenericObject extends NFSerializationRecord {
private final String type;
private final CollectionType collectionType;
private final Object actualObject;
private int collectionPosition;
private List<Field> fields;
public GenericObject(String objectType, Object actualObject) {
this(objectType, CollectionType.NONE, actualObject);
}
public GenericObject(String objectType, CollectionType collectionType, Object actualObject) {
this.type = objectType;
this.collectionType = collectionType;
this.actualObject = actualObject;
this.fields = new ArrayList<Field>();
}
public void setCollectionPosition(int position) {
this.collectionPosition = position;
}
public int getCollectionPosition() {
return collectionPosition;
}
public void add(String fieldName, Object obj) {
fields.add(new Field(fieldName, obj));
}
public void add(String fieldName, Object obj, int collectionPosition) {
fields.add(new Field(fieldName, obj, collectionPosition));
}
public String getObjectType() {
return type;
}
public CollectionType getCollectionType() {
return collectionType;
}
public Object getActualObject() {
return actualObject;
}
public List<Field> getFields() {
return fields;
}
/// may be set after reordered by Jaccard Matrix pairwise matching for diff view
void setFields(List<Field> fields) {
this.fields = fields;
}
public static class Field {
private final String fieldName;
private final Object value;
private final int collectionPosition;
public Field(String fieldName, Object value) {
this(fieldName, value, 0);
}
public Field(String fieldName, Object value, int collectionPosition) {
this.fieldName = fieldName;
this.value = value;
this.collectionPosition = collectionPosition;
}
public String getFieldName() {
return fieldName;
}
public Object getValue() {
return value;
}
public int getCollectionPosition() {
return collectionPosition;
}
}
public static enum CollectionType {
NONE,
MAP,
COLLECTION
}
}
| 8,266 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/genericobject/JaccardMatrixPairwiseMatcher.java | /*
*
* Copyright 2013 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.zeno.genericobject;
import com.netflix.zeno.diff.DiffPropertyPath;
import com.netflix.zeno.diff.DiffRecord;
import com.netflix.zeno.diff.DiffRecordValueListMap;
import com.netflix.zeno.genericobject.GenericObject.Field;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
/**
* This class pulls out matches pairs of objects based on maximum jaccard similarity.<p/>
*
* For a good discussion of how jaccard similarity matrix works, see http://matpalm.com/resemblance/jaccard_distance/
*
* @author dkoszewnik
*
*/
public class JaccardMatrixPairwiseMatcher {
private final List<Field> objects1;
private final List<Field> objects2;
private final float matrix[][];
private int rowSize = 0;
private int columnSize = 0;
private final BitSet illegalColumns;
private final BitSet illegalRows;
private Field x;
private Field y;
public JaccardMatrixPairwiseMatcher(List<Field> objects1, List<DiffRecord> recs1, List<Field> objects2, List<DiffRecord> recs2) {
this.objects1 = objects1;
this.objects2 = objects2;
columnSize = objects1.size();
rowSize = objects2.size();
matrix = new float[recs1.size()][recs2.size()];
for(int i=0;i<columnSize;i++) {
for(int j=0;j<rowSize;j++) {
matrix[i][j] = calculateJaccardDistance(recs1.get(i), recs2.get(j));
}
}
illegalColumns = new BitSet(columnSize);
illegalRows = new BitSet();
}
private float calculateJaccardDistance(DiffRecord rec1, DiffRecord rec2) {
DiffRecordValueListMap map1 = rec1.getValueListMap();
DiffRecordValueListMap map2 = rec2.getValueListMap();
int xorCardinality = 0;
int unionCardinality = 0;
for(DiffPropertyPath key : map1.keySet()) {
List<Object> list1 = map1.getList(key);
List<Object> list2 = map2.getList(key);
if(list2 == null) {
xorCardinality += list1.size();
} else {
list2 = new ArrayList<Object>(list2);
for(Object o1 : list1) {
if(list2.contains(o1)) {
list2.remove(o1);
unionCardinality++;
} else {
xorCardinality++;
}
}
}
}
for(DiffPropertyPath key : map2.keySet()) {
List<Object> list1 = map1.getList(key);
if(list1 == null) {
List<Object> list2 = map2.getList(key);
xorCardinality += list2.size();
}
}
if(xorCardinality == 0 && unionCardinality == 0) {
return 0;
}
return ((float)xorCardinality) / ((float)(xorCardinality + unionCardinality));
}
public boolean nextPair() {
int minColumn = -1;
int minRow = -1;
float minDistance = 1.0F;
for(int i=0;i<columnSize;i++) {
if(!illegalColumns.get(i)) {
for(int j=0;j<rowSize;j++) {
if(!illegalRows.get(j)) {
if(matrix[i][j] < minDistance) {
minColumn = i;
minRow = j;
minDistance = matrix[i][j];
}
}
}
}
}
if(minDistance != 1.0F) {
illegalColumns.set(minColumn);
illegalRows.set(minRow);
x = objects1.get(minColumn);
y = objects2.get(minRow);
return true;
}
for(int i=0;i<columnSize;i++) {
if(!illegalColumns.get(i)) {
illegalColumns.set(i);
x = objects1.get(i);
y = null;
return true;
}
}
for(int j=0;j<rowSize;j++) {
if(!illegalRows.get(j)) {
illegalRows.set(j);
x = null;
y = objects2.get(j);
return true;
}
}
x = null;
y = null;
return false;
}
public Field getX() {
return x;
}
public Field getY() {
return y;
}
}
| 8,267 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/FrameworkSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
/**
*
* A framework serializer allows for the definition of operations to be performed during traversal of POJOs in order to accomplish
* some task without requiring knowledge of the structure or semantics of the data.<p/>
*
* For each "Zeno native" element type, some action can be defined.<p/>
*
* The FrameworkSerializer will define the method of traversal of the Objects during serialization <i>from</i> POJOs via the specification of
* the serializeObject, serializeList, serializeSet, and serializeMap interfaces.<p/>
*
* @author dkoszewnik
* @author tvaliulin
*
*/
public abstract class FrameworkSerializer<S extends NFSerializationRecord> {
protected final SerializationFramework framework;
protected FrameworkSerializer(SerializationFramework framework){
this.framework = framework;
}
@SuppressWarnings("rawtypes")
public NFTypeSerializer getSerializer(String typeName){
NFTypeSerializer serializer = framework.getSerializer(typeName);
if( serializer == null){
throw new RuntimeException("Serializer " + typeName + " is not found");
}
return serializer;
}
/**
* Serializing java primitive
* @param rec
* @param fieldName
* @param value
*/
abstract public void serializePrimitive(S rec, String fieldName, Object value);
/**
* Can be overridden to avoid boxing an int where appropriate
*/
public void serializePrimitive(S rec, String fieldName, int value) {
serializePrimitive(rec, fieldName, Integer.valueOf(value));
}
/**
* Can be overridden to avoid boxing a long where appropriate
*/
public void serializePrimitive(S rec, String fieldName, long value) {
serializePrimitive(rec, fieldName, Long.valueOf(value));
}
/**
* Can be overridden to avoid boxing a float where appropriate
*/
public void serializePrimitive(S rec, String fieldName, float value) {
serializePrimitive(rec, fieldName, Float.valueOf(value));
}
/**
* Can be overridden to avoid boxing a double where appropriate
*/
public void serializePrimitive(S rec, String fieldName, double value) {
serializePrimitive(rec, fieldName, Double.valueOf(value));
}
/**
* Can be overridden to avoid boxing an int where appropriate
*/
public void serializePrimitive(S rec, String fieldName, boolean value) {
serializePrimitive(rec, fieldName, Boolean.valueOf(value));
}
/**
* Serializing java array
* @param rec
* @param fieldName
* @param value
*/
abstract public void serializeBytes(S rec, String fieldName, byte[] value);
/**
* @deprecated instead use serializeObject(S rec, String fieldName, Object obj)
*
* Serializing class object
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
@Deprecated
abstract public void serializeObject(S rec, String fieldName, String typeName, Object obj);
/**
* Serializing class object
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
abstract public void serializeObject(S rec, String fieldName, Object obj);
/**
* Serializing list
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
abstract public <T> void serializeList(S rec, String fieldName, String typeName, Collection<T> obj);
/**
* Serializing set
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
abstract public <T> void serializeSet(S rec, String fieldName, String typeName, Set<T> obj);
/**
* Serializing map
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
abstract public <K, V> void serializeMap(S rec, String fieldName, String keyTypeName, String valueTypeName, Map<K, V> obj);
/**
* Serialize sorted map
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
public <K, V> void serializeSortedMap(S rec, String fieldName, String keyTypeName, String valueTypeName, SortedMap<K, V> obj) {
serializeMap(rec, fieldName, keyTypeName, valueTypeName, obj);
}
}
| 8,268 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/NFTypeSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.fastblob.record.schema.FieldDefinition;
import com.netflix.zeno.fastblob.record.schema.MapFieldDefinition;
import com.netflix.zeno.fastblob.record.schema.TypedFieldDefinition;
/**
* The NFTypeSerializer is used to represent a hierarchy of Objects contained in a POJO Object model.<p/>
*
* Using a set of NFTypeSerializers to define an Object hierarchy allows for the definition of
* semantically and structurally independent operations over that data.
*
* Check out the <a href="https://github.com/Netflix/zeno/wiki">Zeno documentation</a> section
* <a href="https://github.com/Netflix/zeno/wiki/Defining-an-object-model">defining an object model</a> for details about how
* to define your data model with NFTypeSerializers.
*
* @param <T> - The type of object this serializer serializes
*/
public abstract class NFTypeSerializer<T> {
private final String schemaName;
private FastBlobSchema schema;
protected SerializationFramework serializationFramework;
public NFTypeSerializer(String schemaName) {
this.schemaName = schemaName;
}
public void serialize(T value, NFSerializationRecord rec) {
/// automatically track the schemas.
FastBlobSchema existingSchema = rec.getSchema();
rec.setSchema(getFastBlobSchema());
doSerialize(value, rec);
rec.setSchema(existingSchema);
}
public T deserialize(NFDeserializationRecord rec) {
return doDeserialize(rec);
}
protected abstract void doSerialize(T value, NFSerializationRecord rec);
protected abstract T doDeserialize(NFDeserializationRecord rec);
protected abstract FastBlobSchema createSchema();
public abstract Collection<NFTypeSerializer<?>> requiredSubSerializers();
public Collection<NFTypeSerializer<?>> requiredSubSerializers(FastBlobSchemaField[] fields) {
Collection<NFTypeSerializer<?>> requiredSubSerializers = new HashSet<NFTypeSerializer<?>>();
for(FastBlobSchemaField field : fields) {
if(field.typeSerializer != null) {
requiredSubSerializers.add(field.typeSerializer);
}
}
return requiredSubSerializers;
}
@SuppressWarnings("unchecked")
protected void serializePrimitive(NFSerializationRecord rec, String fieldName, Object value) {
serializationFramework.getFrameworkSerializer().serializePrimitive(rec, fieldName, value);
}
@SuppressWarnings("unchecked")
protected void serializeBytes(NFSerializationRecord rec, String fieldName, byte[] value) {
serializationFramework.getFrameworkSerializer().serializeBytes(rec, fieldName, value);
}
/**
* @Deprecated instead use serializeObject(NFSerializationRecord rec, String fieldName, Object obj)
*/
@Deprecated
@SuppressWarnings("unchecked")
protected void serializeObject(NFSerializationRecord rec, String fieldName, String typeName, Object obj) {
serializationFramework.getFrameworkSerializer().serializeObject(rec, fieldName, typeName, obj);
}
@SuppressWarnings("unchecked")
protected void serializeObject(NFSerializationRecord rec, String fieldName, Object obj) {
serializationFramework.getFrameworkSerializer().serializeObject(rec, fieldName, obj);
}
/**
* @deprecated use instead deserializeObject(NFDeserializationRecord rec, String fieldName);
*/
@Deprecated
@SuppressWarnings("unchecked")
protected <X> X deserializeObject(NFDeserializationRecord rec, String typeName, String fieldName) {
return (X) serializationFramework.getFrameworkDeserializer().deserializeObject(rec, fieldName, typeName, null);
}
@SuppressWarnings("unchecked")
protected <X> X deserializeObject(NFDeserializationRecord rec, String fieldName) {
return (X) serializationFramework.getFrameworkDeserializer().deserializeObject(rec, fieldName, null);
}
public FastBlobSchema getFastBlobSchema() {
if(schema == null)
schema = createSchema();
return schema;
}
public String getName() {
return schemaName;
}
public void setSerializationFramework(SerializationFramework framework) {
if(serializationFramework != null && serializationFramework != framework) {
throw new RuntimeException("Should not be replacing an existing SerializationFramework with a different one! This can cause bugs which are difficult to track down!");
}
this.serializationFramework = framework;
}
/**
* @deprecated use instead field(String name, String objectType);
*/
@Deprecated
protected FastBlobSchemaField field(String name) {
return field(name, FieldType.OBJECT);
}
protected FastBlobSchemaField field(String name, String objectType) {
FastBlobSchemaField field = new FastBlobSchemaField();
field.name = name;
field.type = new TypedFieldDefinition(FieldType.OBJECT, objectType);
return field;
}
protected FastBlobSchemaField field(String name, NFTypeSerializer<?> typeSerializer) {
FastBlobSchemaField field = new FastBlobSchemaField();
field.name = name;
field.type = new TypedFieldDefinition(FieldType.OBJECT, typeSerializer.getName());
field.typeSerializer = typeSerializer;
return field;
}
protected FastBlobSchemaField field(String name, FieldType fieldType) {
FastBlobSchemaField field = new FastBlobSchemaField();
field.name = name;
field.type = new FieldDefinition(fieldType);
return field;
}
protected FastBlobSchemaField listField(String name, String elementType) {
FastBlobSchemaField field = new FastBlobSchemaField();
field.name = name;
field.type = new TypedFieldDefinition(FieldType.LIST, elementType);
return field;
}
protected FastBlobSchemaField setField(String name, String elementType) {
FastBlobSchemaField field = new FastBlobSchemaField();
field.name = name;
field.type = new TypedFieldDefinition(FieldType.SET, elementType);
return field;
}
protected FastBlobSchemaField mapField(String name, String keyType, String valueType) {
FastBlobSchemaField field = new FastBlobSchemaField();
field.name = name;
field.type = new MapFieldDefinition(keyType, valueType);
return field;
}
protected FastBlobSchema schema(FastBlobSchemaField... fields) {
FastBlobSchema schema = new FastBlobSchema(schemaName, fields.length);
for(FastBlobSchemaField field : fields) {
schema.addField(field.name, field.type);
}
return schema;
}
protected List<NFTypeSerializer<?>> serializers(NFTypeSerializer<?>... serializers) {
List<NFTypeSerializer<?>> list = new ArrayList<NFTypeSerializer<?>>();
for (NFTypeSerializer<?> s : serializers) {
list.add(s);
}
return list;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected boolean deserializeBoolean(NFDeserializationRecord rec, String field) {
FrameworkDeserializer frameworkSerializer = serializationFramework.getFrameworkDeserializer();
return frameworkSerializer.deserializePrimitiveBoolean(rec, field);
}
@SuppressWarnings("unchecked")
protected boolean deserializeBoolean(NFDeserializationRecord rec, String field, boolean defaultVal) {
Boolean recObj = serializationFramework.getFrameworkDeserializer().deserializeBoolean(rec, field);
if (recObj == null)
return defaultVal;
return recObj.booleanValue();
}
@SuppressWarnings("unchecked")
protected Integer deserializeInteger(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializeInteger(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected int deserializePrimitiveInt(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializePrimitiveInt(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected Long deserializeLong(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializeLong(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected long deserializePrimitiveLong(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializePrimitiveLong(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected Float deserializeFloat(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializeFloat(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected float deserializePrimitiveFloat(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializePrimitiveFloat(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected Double deserializeDouble(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializeDouble(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected double deserializePrimitiveDouble(NFDeserializationRecord rec, String fieldName) {
return serializationFramework.getFrameworkDeserializer().deserializePrimitiveDouble(rec, fieldName);
}
@SuppressWarnings("unchecked")
protected String deserializePrimitiveString(NFDeserializationRecord rec, String field) {
return serializationFramework.getFrameworkDeserializer().deserializeString(rec, field);
}
@SuppressWarnings("unchecked")
protected byte[] deserializeBytes(NFDeserializationRecord rec, String field) {
return serializationFramework.getFrameworkDeserializer().deserializeBytes(rec, field);
}
public SerializationFramework getSerializationFramework() {
return serializationFramework;
}
public static class FastBlobSchemaField {
public String name;
public FieldDefinition type;
public NFTypeSerializer<?> typeSerializer;
}
}
| 8,269 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/SerializationFramework.java | /*
*
* Copyright 2013 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.zeno.serializer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An implementation of the abstract class SerializationFramework will describe some operation
* that can be performed on data in a semantically and structurally agnostic way.<p/>
*
* For a given POJO model, a set of {@link NFTypeSerializer} implementations must be created to describe their
* structure. A set of serializers, identified by a SerializerFactory, is passed into the constructor
* of this Object.<p/>
*
* The SerializationFramework implementation will traverse this hierarchy of serializers in order to
* perform its operation.<p/>
*
* Example implementations of SerializationFramework are:<p/>
*
* HashSerializationFramework: Calculates an MD5 sum for POJOs conforming to the NFTypeSerializers.<br/>
* JsonSerializationFramework: Translates POJOs to json (and vice versa)<br/>
* FastBlobSerializationFramework: Creates binary dumps of data states represented by POJOs<br/>
*
* By maintaining a clean separation of data semantics / structure and the operations which can be performed
* on the data, we avoid multiplying the work required to maintain our data model by the number of operations
* we can perform.<p/>
*
* Supporting new functionality is easy; we can define a new SerializationFramework. Adding to the data model
* is easy; we simply create / modify {@link NFTypeSerializer}s
*
* For details about how to create new SerializationFramework implementations, check out the section
* <a href="https://github.com/Netflix/zeno/wiki/Creating-new-operations">creating new operations</a> in the
* Zeno documentation.
*
* @author dkoszewnik
*
*/
public abstract class SerializationFramework {
protected FrameworkSerializer<?> frameworkSerializer;
protected FrameworkDeserializer<?> frameworkDeserializer;
protected NFTypeSerializer<?>[] topLevelSerializers;
private final Map<String, NFTypeSerializer<?>> serializers = new HashMap<String, NFTypeSerializer<?>>();
/// The NFTypeSerializers, ordered such that all dependencies come *before* their dependents
private final List<NFTypeSerializer<?>> orderedSerializers = new ArrayList<NFTypeSerializer<?>>();
public SerializationFramework(SerializerFactory serializerFactory) {
this.topLevelSerializers = serializerFactory.createSerializers();
addSerializerTree(topLevelSerializers);
}
private void addSerializerTree(NFTypeSerializer<?>... topLevelSerializers) {
Set<String> alreadyAddedSerializers = new HashSet<String>();
for(NFTypeSerializer<?> serializer : topLevelSerializers) {
addSerializer(serializer, alreadyAddedSerializers, true);
}
}
private void addSerializer(NFTypeSerializer<?> serializer, Set<String>alreadyAddedSerializers, boolean topLevelSerializer) {
if(firstTimeSeeingSerializer(serializer, alreadyAddedSerializers)) {
for(NFTypeSerializer<?> subSerializer : serializer.requiredSubSerializers()) {
addSerializer(subSerializer, alreadyAddedSerializers, false);
}
serializer.setSerializationFramework(this);
serializers.put(serializer.getName(), serializer);
orderedSerializers.add(serializer);
}
}
private boolean firstTimeSeeingSerializer(NFTypeSerializer<?> serializer, Set<String>alreadyAddedSerializers) {
if(!alreadyAddedSerializers.contains(serializer.getName())) {
alreadyAddedSerializers.add(serializer.getName());
return true;
}
return false;
}
@SuppressWarnings("rawtypes")
public FrameworkSerializer getFrameworkSerializer() {
return frameworkSerializer;
}
@SuppressWarnings("rawtypes")
public FrameworkDeserializer getFrameworkDeserializer() {
return frameworkDeserializer;
}
/**
* @return the NFTypeSerializers ordered such that dependencies come *before* their dependents.
*/
public List<NFTypeSerializer<?>> getOrderedSerializers() {
return orderedSerializers;
}
@SuppressWarnings("unchecked")
public <T> NFTypeSerializer<T> getSerializer(String typeName) {
return (NFTypeSerializer<T>) serializers.get(typeName);
}
public NFTypeSerializer<?>[] getTopLevelSerializers() {
return topLevelSerializers;
}
}
| 8,270 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/NFDeserializationRecord.java | /*
*
* Copyright 2013 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.zeno.serializer;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
/**
* an NFDeserializationRecord is a record used to track state during traversal of an object's serialized representation via a FrameworkDeserializer.
*
* The minimum state to track is a FastBlobSchema for each level in the hierarchy, so that sub-object type names may be interrogated for each field.
*/
public abstract class NFDeserializationRecord {
private final FastBlobSchema schema;
public NFDeserializationRecord(FastBlobSchema schema) {
this.schema = schema;
}
public FastBlobSchema getSchema() {
return schema;
}
public String getObjectType(String fieldName) {
return schema.getObjectType(fieldName);
}
}
| 8,271 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/FrameworkDeserializer.java | /*
*
* Copyright 2013 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.zeno.serializer;
import com.netflix.zeno.hash.HashFrameworkSerializer;
import com.netflix.zeno.hash.HashSerializationFramework;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
/**
* Mirroring the FrameworkSerializer, FrameworkDeserializer will define the actions which must be taken to decode individual "Zeno native" elements during deserialization
* of objects. It will also define the method of traversal of serialized representations of Objects for deserialization
* via the specification of deserializeObject, deserializeList, deserializeSet, and deserializeMap methods.<p/>
*
* There may or may not be a "deserialization", which corresponds to every "serialization". For example, one operation which ships with
* the zeno framework is a calculation of a hash of a given Object (see {@link HashSerializationFramework}). This is a one-way operation and therefore has no corresponding
* "deserialization". In this case, the {@link HashFrameworkSerializer} does not have a corresponding deserializer.
*
* @author dkoszewnik
*
* @param <D>
*/
public abstract class FrameworkDeserializer <D extends NFDeserializationRecord> {
protected final SerializationFramework framework;
protected FrameworkDeserializer(SerializationFramework framework){
this.framework = framework;
}
/**
* Deserializing java boolean
* @param rec
* @param fieldName
* @param value
*/
abstract public Boolean deserializeBoolean(D rec, String fieldName);
/**
* Can be overridden to avoid boxing an int where appropriate
*/
public boolean deserializePrimitiveBoolean(D rec, String fieldName) {
return deserializeBoolean(rec, fieldName).booleanValue();
}
/**
* Deserializing java integer
* @param rec
* @param fieldName
* @param value
*/
abstract public Integer deserializeInteger(D rec, String fieldName);
/**
* Can be overridden to avoid boxing an int where appropriate
*/
public int deserializePrimitiveInt(D rec, String fieldName) {
return deserializeInteger(rec, fieldName).intValue();
}
/**
* Deserializing java long
* @param rec
* @param fieldName
* @param value
*/
abstract public Long deserializeLong(D rec, String fieldName);
/**
* Can be overridden to avoid boxing a long where appropriate
*/
public long deserializePrimitiveLong(D rec, String fieldName) {
return deserializeLong(rec, fieldName).longValue();
}
/**
* Deserializing java float
* @param rec
* @param fieldName
* @param value
*/
abstract public Float deserializeFloat(D rec, String fieldName);
/**
* Can be overridden to avoid boxing a float where appropriate
*/
public float deserializePrimitiveFloat(D rec, String fieldName) {
return deserializeFloat(rec, fieldName).floatValue();
}
/**
* Deserializing java double
* @param rec
* @param fieldName
* @param value
*/
abstract public Double deserializeDouble(D rec, String fieldName);
/**
* Can be overridden to avoid boxing a double where appropriate
*/
public double deserializePrimitiveDouble(D rec, String fieldName) {
return deserializeDouble(rec, fieldName).doubleValue();
}
/**
* Deserializing java string
* @param rec
* @param fieldName
* @param value
*/
abstract public String deserializeString(D rec, String fieldName);
/**
* Deserializing byte array
* @param rec
* @param fieldName
* @param value
*/
abstract public byte[] deserializeBytes(D rec, String fieldName);
/**
* @Deprecated instead use deserializeObject(D rec, String fieldName, Class<T> clazz)
*
* Deserializing class object
* @param rec
* @param fieldName
* @param typeName
* @param clazz
* @param obj
*/
@Deprecated
abstract public <T> T deserializeObject(D rec, String fieldName, String typeName, Class<T> clazz);
/**
* Deserializing class object
* @param rec
* @param fieldName
* @param clazz
* @param obj
*/
abstract public <T> T deserializeObject(D rec, String fieldName, Class<T> clazz);
/**
* Deserializing list
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
abstract public <T> List<T> deserializeList(D rec, String fieldName, NFTypeSerializer<T> itemSerializer);
/**
* Deserializing set
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
abstract public <T> Set<T> deserializeSet(D rec, String fieldName, NFTypeSerializer<T> itemSerializer);
/**
* Deserializing map
* @param rec
* @param fieldName
* @param typeName
* @param obj
*/
abstract public <K, V> Map<K, V> deserializeMap(D rec, String fieldName, NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer);
/**
* Deserialize sorted map
* @param rec
* @param fieldName
* @param keySerializer
* @param valueSerializer
*/
abstract public <K,V> SortedMap<K,V> deserializeSortedMap(D rec, String fieldName, NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer);
}
| 8,272 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/NFSerializationRecord.java | /*
*
* Copyright 2013 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.zeno.serializer;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
/**
* An NFSerializationRecord is responsible for tracking state during traversal via a FrameworkSerializer.
*
* The minimum state to track is a FastBlobSchema for each level in the hierarchy, so that sub-object type names may be interrogated for each field.
*/
public abstract class NFSerializationRecord {
private FastBlobSchema schema;
public void setSchema(FastBlobSchema schema) {
this.schema = schema;
}
public FastBlobSchema getSchema() {
return schema;
}
public String getObjectType(String schemaField) {
return schema.getObjectType(schemaField);
}
}
| 8,273 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/SerializerFactory.java | /*
*
* Copyright 2013 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.zeno.serializer;
/**
* The interface that the using code should implement in order make serializers
* available for frameworks to use.<p/>
*
* Each call to createSerializers() should return a unique array containing
* unique instances of the top level serializers which define an Object model.
*
* Check out the <a href="https://github.com/Netflix/zeno/wiki">Zeno documentation</a> section
* <a href="https://github.com/Netflix/zeno/wiki/Defining-an-object-model">defining an object model</a> for details about how
* to define your data model, and then reference it with a SerializerFactory.
*
*/
public interface SerializerFactory {
/**
* Creates the serializers
*
* @return
*/
NFTypeSerializer<?>[] createSerializers();
}
| 8,274 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/ListSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import java.util.List;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializationFramework;
/**
*
* A default NFTypeSerializer implementation for List objects.
*
*/
public class ListSerializer<E> extends CollectionSerializer<E, List<E>> {
public ListSerializer(String name, NFTypeSerializer<E> elementSerializer) {
super(name, elementSerializer);
}
public ListSerializer(NFTypeSerializer<E> elementSerializer) {
this("ListOf" + elementSerializer.getName(), elementSerializer);
}
@Override
@SuppressWarnings("unchecked")
protected List<E> doDeserialize(NFDeserializationRecord rec) {
return serializationFramework.getFrameworkDeserializer().deserializeList(rec, ORDINALS_FIELD_NAME, elementSerializer);
}
@Override
public void setSerializationFramework(SerializationFramework framework) {
this.serializationFramework = framework;
this.elementSerializer.setSerializationFramework(framework);
}
@Override
protected FastBlobSchema createSchema() {
return schema(listField(ORDINALS_FIELD_NAME, elementSerializer.getName()));
}
}
| 8,275 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/BooleanSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for Boolean objects.
*
*/
public class BooleanSerializer extends NFTypeSerializer<Boolean> {
public static final String NAME = "Boolean";
public BooleanSerializer() {
super(NAME);
}
@Override
public void doSerialize(Boolean value, NFSerializationRecord rec) {
serializePrimitive(rec, "val", value);
}
@Override
protected Boolean doDeserialize(NFDeserializationRecord rec) {
return deserializeBoolean(rec, ("val"));
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val", FieldType.BOOLEAN)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptySet();
}
}
| 8,276 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/ByteArraySerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for byte arrays.
*
*/
public class ByteArraySerializer extends NFTypeSerializer<byte[]> {
public static final String NAME = "ByteArray";
public ByteArraySerializer() {
super(NAME);
}
@Override
public void doSerialize(byte[] value, NFSerializationRecord rec) {
serializeBytes(rec, "val", value);
}
@Override
protected byte[] doDeserialize(NFDeserializationRecord rec) {
return deserializeBytes(rec, ("val"));
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val", FieldType.BYTES)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptySet();
}
}
| 8,277 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/FloatSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for Float objects.
*
*/
public class FloatSerializer extends NFTypeSerializer<Float> {
public static final String NAME = "Float";
public FloatSerializer() {
super(NAME);
}
@Override
public void doSerialize(Float value, NFSerializationRecord rec) {
serializePrimitive(rec, "val", value);
}
@Override
protected Float doDeserialize(NFDeserializationRecord rec) {
return deserializeFloat(rec, "val");
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val", FieldType.FLOAT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
} | 8,278 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/LongSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for Long objects.
*
*/
public class LongSerializer extends NFTypeSerializer<Long>{
public static final String NAME = "Long";
public LongSerializer() {
super(NAME);
}
@Override
public void doSerialize(Long value, NFSerializationRecord rec) {
serializePrimitive(rec, "val", value);
}
@Override
protected Long doDeserialize(NFDeserializationRecord rec) {
return deserializeLong(rec, "val");
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val", FieldType.LONG)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,279 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/MapSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import java.util.Collection;
import java.util.Map;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializationFramework;
/**
*
* A default NFTypeSerializer implementation for Map objects.
*
*/
public class MapSerializer<K, V> extends NFTypeSerializer<Map<K, V>> {
private final NFTypeSerializer<K> keySerializer;
private final NFTypeSerializer<V> valueSerializer;
public MapSerializer(String schemaName, NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer) {
super(schemaName);
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
}
public MapSerializer(NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer) {
this("MapOf" + keySerializer.getName() + "To" + valueSerializer.getName(), keySerializer, valueSerializer);
}
@Override
@SuppressWarnings("unchecked")
public void doSerialize(Map<K, V> map, NFSerializationRecord rec) {
serializationFramework.getFrameworkSerializer().serializeMap(rec, "map", keySerializer.getName(), valueSerializer.getName(), map);
}
@Override
@SuppressWarnings("unchecked")
protected Map<K, V> doDeserialize(NFDeserializationRecord rec) {
return serializationFramework.getFrameworkDeserializer().deserializeMap(rec, "map", keySerializer, valueSerializer);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
mapField("map", keySerializer.getName(), valueSerializer.getName())
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(
keySerializer,
valueSerializer
);
}
@Override
public void setSerializationFramework(SerializationFramework framework) {
this.serializationFramework = framework;
keySerializer.setSerializationFramework(framework);
valueSerializer.setSerializationFramework(framework);
}
}
| 8,280 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/CollectionSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import java.util.Collection;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
/**
*
* A default NFTypeSerializer implementation for Collection objects.
*
* This is an abstract class, implemented by {@link ListSerializer} and {@link SetSerializer}
*
*/
public abstract class CollectionSerializer<E, T extends Collection<E>> extends NFTypeSerializer<T> {
protected static final String ORDINALS_FIELD_NAME = "ordinals";
protected final NFTypeSerializer<E> elementSerializer;
@SuppressWarnings({ "unchecked" })
@Override
public void doSerialize(T list, NFSerializationRecord rec) {
serializationFramework.getFrameworkSerializer().serializeList(rec, ORDINALS_FIELD_NAME, elementSerializer.getName(), list);
}
public CollectionSerializer(String schemaName, NFTypeSerializer<E> elementSerializer) {
super(schemaName);
this.elementSerializer = elementSerializer;
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(elementSerializer);
}
}
| 8,281 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/StringSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for String objects.
*
*/
public class StringSerializer extends NFTypeSerializer<String> {
public static final String NAME = "Strings";
public StringSerializer() {
super(NAME);
}
public StringSerializer(String typeName) {
super(typeName);
}
@Override
public void doSerialize(String value, NFSerializationRecord rec) {
serializePrimitive( rec, "value", value);
}
@Override
protected String doDeserialize(NFDeserializationRecord rec) {
return deserializePrimitiveString(rec, "value");
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("value", FieldType.STRING)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,282 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/IntegerSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for Integer objects.
*
*/
public class IntegerSerializer extends NFTypeSerializer<Integer>{
public static final String NAME = "Integer";
public IntegerSerializer() {
super(NAME);
}
@Override
public void doSerialize(Integer value, NFSerializationRecord rec) {
serializePrimitive(rec, "val", value);
}
@Override
protected Integer doDeserialize(NFDeserializationRecord rec) {
return deserializeInteger(rec, "val");
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val", FieldType.INT)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,283 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/SortedMapSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import java.util.Collection;
import java.util.SortedMap;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializationFramework;
/**
*
* A default NFTypeSerializer implementation for SortedMap objects.
*
*/
public class SortedMapSerializer<K, V> extends NFTypeSerializer<SortedMap<K, V>> {
private final NFTypeSerializer<K> keySerializer;
private final NFTypeSerializer<V> valueSerializer;
public SortedMapSerializer(String schemaName, NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer) {
super(schemaName);
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
}
public SortedMapSerializer(NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer) {
this("SortedMapOf" + keySerializer.getName() + "To" + valueSerializer.getName(), keySerializer, valueSerializer);
}
@Override
@SuppressWarnings("unchecked")
public void doSerialize(SortedMap<K, V> map, NFSerializationRecord rec) {
serializationFramework.getFrameworkSerializer().serializeSortedMap(rec, "map", keySerializer.getName(), valueSerializer.getName(), map);
}
@Override
@SuppressWarnings("unchecked")
protected SortedMap<K, V> doDeserialize(NFDeserializationRecord rec) {
return serializationFramework.getFrameworkDeserializer().deserializeSortedMap(rec, "map", keySerializer, valueSerializer);
}
@Override
protected FastBlobSchema createSchema() {
return schema(
mapField("map", keySerializer.getName(), valueSerializer.getName())
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return serializers(
keySerializer,
valueSerializer
);
}
@Override
public void setSerializationFramework(final SerializationFramework framework) {
this.serializationFramework = framework;
keySerializer.setSerializationFramework(framework);
valueSerializer.setSerializationFramework(framework);
}
}
| 8,284 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/DateSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
/**
*
* A default NFTypeSerializer implementation for Date objects.
*
*/
public class DateSerializer extends NFTypeSerializer<Date>{
public static final String NAME = "Date";
public DateSerializer() {
super(NAME);
}
@Override
public void doSerialize(Date value, NFSerializationRecord rec) {
serializePrimitive(rec, "val", value.getTime());
}
@Override
protected Date doDeserialize(NFDeserializationRecord rec) {
return new Date(deserializePrimitiveLong(rec, "val"));
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val", FieldType.LONG)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
}
| 8,285 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/DoubleSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for Double objects.
*
*/
public class DoubleSerializer extends NFTypeSerializer<Double>{
public static final String NAME = "Double";
public DoubleSerializer() {
super(NAME);
}
@Override
public void doSerialize(Double value, NFSerializationRecord rec) {
serializePrimitive(rec, "val", value);
}
@Override
protected Double doDeserialize(NFDeserializationRecord rec) {
return deserializeDouble(rec, "val");
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("val", FieldType.DOUBLE)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
} | 8,286 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/EnumSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema.FieldType;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.Collection;
import java.util.Collections;
/**
*
* A default NFTypeSerializer implementation for Enums.<p/>
*
* NOTE: Including enum types in your data model may cause issues. The enum is serialized as a String, which is the Enum name.
* If the Enum does not exist during deserialization, null will be returned during deserialization.
*
*/
@SuppressWarnings("rawtypes")
public class EnumSerializer<T extends Enum> extends NFTypeSerializer<T> {
private final Class<T> enumClazz;
public EnumSerializer(Class<T> enumClazz) {
super(unqualifiedClassName(enumClazz));
this.enumClazz = enumClazz;
}
@Override
public void doSerialize(T value, NFSerializationRecord rec) {
serializePrimitive(rec, "value", value == null ? null : value.name());
}
@Override
@SuppressWarnings("unchecked")
protected T doDeserialize(NFDeserializationRecord rec) {
String value = deserializePrimitiveString(rec, "value");
try {
return (T) Enum.valueOf(enumClazz, value);
} catch (Exception ignore) { }
return null;
}
@Override
protected FastBlobSchema createSchema() {
return schema(
field("value", FieldType.STRING)
);
}
@Override
public Collection<NFTypeSerializer<?>> requiredSubSerializers() {
return Collections.emptyList();
}
private static String unqualifiedClassName(Class<?>clazz) {
String qualifiedName = clazz.getCanonicalName();
if(qualifiedName.indexOf('.') < 0)
return qualifiedName;
return qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1);
}
}
| 8,287 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer | Create_ds/zeno/src/main/java/com/netflix/zeno/serializer/common/SetSerializer.java | /*
*
* Copyright 2013 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.zeno.serializer.common;
import java.util.Set;
import com.netflix.zeno.fastblob.record.schema.FastBlobSchema;
import com.netflix.zeno.serializer.NFDeserializationRecord;
import com.netflix.zeno.serializer.NFSerializationRecord;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.serializer.SerializationFramework;
/**
*
* A default NFTypeSerializer implementation for Set objects.
*
*/
public class SetSerializer<E> extends CollectionSerializer<E, Set<E>> {
public SetSerializer(String schemaName, NFTypeSerializer<E> elementSerializer) {
super(schemaName, elementSerializer);
}
public SetSerializer(NFTypeSerializer<E> elementSerializer) {
this("SetOf" + elementSerializer.getName(), elementSerializer);
}
@Override
@SuppressWarnings("unchecked")
public void doSerialize(Set<E> list, NFSerializationRecord rec) {
serializationFramework.getFrameworkSerializer().serializeSet(rec, ORDINALS_FIELD_NAME, elementSerializer.getName(), list);
}
@Override
@SuppressWarnings("unchecked")
protected Set<E> doDeserialize(NFDeserializationRecord rec) {
return serializationFramework.getFrameworkDeserializer().deserializeSet(rec, ORDINALS_FIELD_NAME, elementSerializer);
}
@Override
public void setSerializationFramework(SerializationFramework framework) {
this.serializationFramework = framework;
this.elementSerializer.setSerializationFramework(framework);
}
@Override
protected FastBlobSchema createSchema() {
return schema(setField(ORDINALS_FIELD_NAME, elementSerializer.getName()));
}
}
| 8,288 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/util/EnsureSuccessSimultaneousExecutor.java | /*
*
* Copyright 2013 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.zeno.util;
import java.util.concurrent.ExecutionException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableFuture;
/**
* A {@link SimultaneousExecutor} which throws an Exception on awaitUniterruptibly(), if
* any of the tasks did not finish.
*
* @author dsu
*
*/
public class EnsureSuccessSimultaneousExecutor extends SimultaneousExecutor {
private final List<Future<?>> futures = new ArrayList<Future<?>>();
public EnsureSuccessSimultaneousExecutor() {
}
public EnsureSuccessSimultaneousExecutor(double threadsPerCpu) {
super(threadsPerCpu);
}
public EnsureSuccessSimultaneousExecutor(double threadsPerCpu, String threadName) {
super(threadsPerCpu, threadName);
}
public EnsureSuccessSimultaneousExecutor(int numThreads) {
super(numThreads);
}
public EnsureSuccessSimultaneousExecutor(int numThreads, String threadName) {
super(numThreads, threadName);
}
@Override
protected final <T> RunnableFuture<T> newTaskFor(final Runnable runnable, final T value) {
final RunnableFuture<T> task = super.newTaskFor(runnable, value);
futures.add(task);
return task;
}
@Override
protected final <T> RunnableFuture<T> newTaskFor(final Callable<T> callable) {
final RunnableFuture<T> task = super.newTaskFor(callable);
futures.add(task);
return task;
}
/**
* Await successful completion of all tasks. throw exception for the first task that fails.
* @throws ExecutionException
* @throws InterruptedException
* @throws Exception
*/
public void awaitSuccessfulCompletion() throws InterruptedException, ExecutionException {
awaitUninterruptibly();
for(final Future<?> f:futures) {
f.get();
}
}
}
| 8,289 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/util/SimultaneousExecutor.java | /*
*
* Copyright 2013 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.zeno.util;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
*
* A convenience wrapper around ThreadPoolExecutor. Provides sane defaults to constructor arguments and
* allows for awaitUninterruptibly().
*
* @author dkoszewnik
*
*/
public class SimultaneousExecutor extends ThreadPoolExecutor {
private static final String DEFAULT_THREAD_NAME = "zeno-simultaneous-executor";
public SimultaneousExecutor() {
this(2.5d);
}
public SimultaneousExecutor(double threadsPerCpu) {
this(threadsPerCpu, DEFAULT_THREAD_NAME);
}
public SimultaneousExecutor(double threadsPerCpu, String threadName) {
this((int)((double)Runtime.getRuntime().availableProcessors() * threadsPerCpu), threadName);
}
public SimultaneousExecutor(int numThreads) {
this(numThreads, DEFAULT_THREAD_NAME);
}
public SimultaneousExecutor(int numThreads, final String threadName) {
super(numThreads, numThreads, numThreads, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t = new Thread(r, threadName);
t.setDaemon(true);
return t;
}
});
}
public void awaitUninterruptibly() {
shutdown();
while(!isTerminated()) {
try {
awaitTermination(1, TimeUnit.DAYS);
} catch (final InterruptedException e) { }
}
}
}
| 8,290 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/util/CollectionUnwrapper.java | /*
*
* Copyright 2013 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.zeno.util;
import com.netflix.zeno.util.collections.MinimizedUnmodifiableCollections;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
/**
*
* Unwraps collections, which have been wrapped with Unmodifiable wrappers.<p/>
*
* If comparing two Collections for "sameness" (==), it is useful to compare the "unwrapped" instances
* of these Objects, to avoid false negatives when comparing a wrapped vs an unwrapped instance.
*
* @author dkoszewnik
*
*/
public class CollectionUnwrapper {
private static final Class<?> unmodifiableCollectionClass = getInnerClass(Collections.class, "UnmodifiableCollection");
private static final Field unmodifiableCollectionField = getField(unmodifiableCollectionClass, "c");
private static final Class<?> unmodifiableMapClass = getInnerClass(Collections.class, "UnmodifiableMap");
private static final Field unmodifiableMapField = getField(unmodifiableMapClass, "m");
private static Class<?> getInnerClass(Class<?> fromClass, String className) {
for(Class<?> c : fromClass.getDeclaredClasses()) {
if(c.getSimpleName().equals(className)) {
return c;
}
}
return null;
}
private static Field getField(Class<?> fromClass, String fieldName) {
try {
Field f = fromClass.getDeclaredField(fieldName);
f.setAccessible(true);
return f;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static <T> T unwrap(Object obj) {
if(obj instanceof Collection) {
if(((Collection<?>)obj).isEmpty()) {
if(obj instanceof List)
return (T) Collections.EMPTY_LIST;
if(obj instanceof Set)
return (T) Collections.EMPTY_SET;
}
if(unmodifiableCollectionClass.isInstance(obj)) {
return unwrap(obj, unmodifiableCollectionClass, unmodifiableCollectionField);
}
} else if(obj instanceof Map) {
if(((Map<?,?>)obj).isEmpty()) {
if(obj instanceof SortedMap)
return (T) MinimizedUnmodifiableCollections.EMPTY_SORTED_MAP;
return (T) Collections.EMPTY_MAP;
}
if(unmodifiableMapClass.isInstance(obj)) {
return unwrap(obj, unmodifiableMapClass, unmodifiableMapField);
}
}
return (T) obj;
}
@SuppressWarnings("unchecked")
private static <T> T unwrap(Object obj, Class<?> clazz, Field field) {
try {
do {
obj = field.get(obj);
} while(clazz.isInstance(obj));
return (T) obj;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 8,291 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno | Create_ds/zeno/src/main/java/com/netflix/zeno/util/PrimitiveObjectIdentifier.java | /*
*
* Copyright 2013 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.zeno.util;
import java.util.HashMap;
import java.util.Map;
/**
*
* Utility to identify primitives.
*
* @author tvaliulin
*
*/
public class PrimitiveObjectIdentifier {
/**
* Map with primitive wrapper type as key and corresponding primitive
* type as value, for example: Integer.class -> int.class.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new HashMap<Class<?>, Class<?>>(8);
static {
primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
primitiveWrapperTypeMap.put(Byte.class, byte.class);
primitiveWrapperTypeMap.put(Character.class, char.class);
primitiveWrapperTypeMap.put(Double.class, double.class);
primitiveWrapperTypeMap.put(Float.class, float.class);
primitiveWrapperTypeMap.put(Integer.class, int.class);
primitiveWrapperTypeMap.put(Long.class, long.class);
primitiveWrapperTypeMap.put(Short.class, short.class);
}
/**
* Check if the given class represents a primitive wrapper,
* i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.
* @param clazz the class to check
* @return whether the given class is a primitive wrapper class
*/
public static boolean isPrimitiveWrapper(Class<?> clazz) {
return primitiveWrapperTypeMap.containsKey(clazz);
}
/**
* Check if the given class represents a primitive (i.e. boolean, byte,
* char, short, int, long, float, or double) or a primitive wrapper
* (i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double).
* @param clazz the class to check
* @return whether the given class is a primitive or primitive wrapper class
*/
public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
}
}
| 8,292 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/util | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections/MinimizedUnmodifiableCollections.java | /*
*
* Copyright 2013 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.zeno.util.collections;
import com.netflix.zeno.util.collections.builder.Builders;
import com.netflix.zeno.util.collections.builder.ListBuilder;
import com.netflix.zeno.util.collections.builder.MapBuilder;
import com.netflix.zeno.util.collections.builder.SetBuilder;
import com.netflix.zeno.util.collections.impl.BinarySearchArrayHashMap;
import com.netflix.zeno.util.collections.impl.BinarySearchArrayIndexedHashMap;
import com.netflix.zeno.util.collections.impl.BinarySearchArrayIndexedSet;
import com.netflix.zeno.util.collections.impl.BinarySearchArrayMap;
import com.netflix.zeno.util.collections.impl.BinarySearchArraySet;
import com.netflix.zeno.util.collections.impl.ImmutableArrayList;
import com.netflix.zeno.util.collections.impl.NetflixCollections;
import com.netflix.zeno.util.collections.impl.OpenAddressingArraySet;
import com.netflix.zeno.util.collections.impl.OpenAddressingHashMap;
import com.netflix.zeno.util.collections.impl.OpenAddressingSortedHashMap;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class MinimizedUnmodifiableCollections {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static final SortedMap EMPTY_SORTED_MAP = Collections.unmodifiableSortedMap(new TreeMap());
private final CollectionImplementation implementation;
public MinimizedUnmodifiableCollections(CollectionImplementation implementation) {
this.implementation = implementation;
}
@SuppressWarnings("unchecked")
public <K, V> SortedMap<K, V> emptySortedMap() {
return (SortedMap<K, V>) EMPTY_SORTED_MAP;
}
public <K, V> Map<K, V> minimizeMap(Map<K, V> map) {
if (map.isEmpty()) {
return Collections.emptyMap();
}
if (map.size() == 1) {
Map.Entry<K, V> entry = map.entrySet().iterator().next();
return Collections.singletonMap(entry.getKey(), entry.getValue());
}
return map;
}
public <K, V> SortedMap<K, V> minimizeSortedMap(SortedMap<K, V> map) {
if (map.isEmpty()) {
return NetflixCollections.emptySortedMap();
}
if (map.size() == 1) {
Map.Entry<K, V> entry = map.entrySet().iterator().next();
return NetflixCollections.singletonSortedMap(entry.getKey(), entry.getValue());
}
return map;
}
public <E> Set<E> minimizeSet(Set<E> set) {
if (set.isEmpty()) {
return Collections.emptySet();
}
if (set.size() == 1) {
return Collections.singleton(set.iterator().next());
}
return set;
}
public <E> List<E> minimizeList(List<E> list) {
if (list.isEmpty()) {
return Collections.emptyList();
}
if (list.size() == 1) {
return Collections.singletonList(list.iterator().next());
}
return list;
}
public <E> ListBuilder<E> createListBuilder() {
switch (implementation) {
case COMPACT_BINARYSEARCH:
case COMPACT_BINARYSEARCH_INDEXED:
case COMPACT_OPENADDRESS:
return new ImmutableArrayList<E>();
case JAVA_UTIL:
default:
return new Builders.ArrayListBuilder<E>();
}
}
public <E> SetBuilder<E> createSetBuilder() {
switch (implementation) {
case COMPACT_BINARYSEARCH:
return new BinarySearchArraySet<E>();
case COMPACT_BINARYSEARCH_INDEXED:
return new BinarySearchArrayIndexedSet<E>();
case COMPACT_OPENADDRESS:
return new OpenAddressingArraySet<E>();
case JAVA_UTIL:
default:
return new Builders.HashSetBuilder<E>();
}
}
public <K, V> MapBuilder<K, V> createMapBuilder() {
switch (implementation) {
case COMPACT_BINARYSEARCH:
return new BinarySearchArrayHashMap<K, V>();
case COMPACT_BINARYSEARCH_INDEXED:
return new BinarySearchArrayIndexedHashMap<K, V>();
case COMPACT_OPENADDRESS:
return new OpenAddressingHashMap<K, V>();
case JAVA_UTIL:
default:
return new Builders.HashMapBuilder<K, V>();
}
}
public <K, V> MapBuilder<K, V> createSortedMapBuilder() {
switch (implementation) {
case COMPACT_BINARYSEARCH:
case COMPACT_BINARYSEARCH_INDEXED:
return new BinarySearchArrayMap<K, V>();
case COMPACT_OPENADDRESS:
return new OpenAddressingSortedHashMap<K, V>();
case JAVA_UTIL:
default:
return new Builders.TreeMapBuilder<K, V>();
}
}
}
| 8,293 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/util | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections/CollectionImplementation.java | /*
*
* Copyright 2013 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.zeno.util.collections;
public enum CollectionImplementation {
COMPACT_BINARYSEARCH,
COMPACT_BINARYSEARCH_INDEXED,
COMPACT_OPENADDRESS,
JAVA_UTIL
}
| 8,294 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/util | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections/Comparators.java | /*
*
* Copyright 2013 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.zeno.util.collections;
import java.util.Comparator;
/**
* Registry of comparators being used in the library
*
* @author tvaliulin
*
*/
public class Comparators {
private static final Comparator<Object> hashCodeComparator = new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
if (o1 == o2) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
int hash1 = o1.hashCode();
int hash2 = o2.hashCode();
return hash1 < hash2 ? -1 : (hash1 > hash2 ? 1 : 0);
}
};
@SuppressWarnings("unchecked")
public static <K> Comparator<K> hashCodeComparator() {
return (Comparator<K>) hashCodeComparator;
}
private static final Comparator<?> comparableComparator = new Comparator<Object>() {
@Override
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
if (o1 == o2) {
return 0;
}
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
return ((Comparable<Object>) o1).compareTo(o2);
}
};
@SuppressWarnings("unchecked")
public static <K> Comparator<K> comparableComparator() {
return (Comparator<K>) comparableComparator;
}
}
| 8,295 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections/impl/AbstractArrayMap.java | /*
*
* Copyright 2013 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.zeno.util.collections.impl;
import com.netflix.zeno.util.collections.builder.MapBuilder;
import java.util.AbstractCollection;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* Abstract class which helps people to write Array based immutable
* implementations of the Map interface
*
* @author tvaliulin
*
* @param <K>
* @param <V>
*/
public abstract class AbstractArrayMap<K, V> implements Map<K, V>, MapBuilder<K, V> {
protected static final Object undefined = new Object();
public AbstractArrayMap() {
}
public AbstractArrayMap(AbstractArrayMap<K, V> map, int start, int end) {
builderInit(end - start);
for (int i = start; i < end; i++) {
builderPut(i - start, map.key(i), map.value(i));
}
builderFinish();
}
public abstract Object getUndefined(Object key);
@Override
public abstract int size();
protected abstract K key(int index);
protected abstract V value(int index);
@Override
public abstract void builderInit(int size);
@Override
public abstract void builderPut(int index, K key, V value);
@Override
public abstract Map<K, V> builderFinish();
public void setMap(Map<K, V> map) {
builderInit(map.size());
int i = 0;
for (Map.Entry<K, V> entry : map.entrySet()) {
builderPut(i++, entry.getKey(), entry.getValue());
}
builderFinish();
}
public void setMap(Map.Entry<K, V>[] entries) {
builderInit(entries.length);
int i = 0;
for (Map.Entry<K, V> entry : entries) {
builderPut(i++, entry.getKey(), entry.getValue());
}
builderFinish();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
Object result = getUndefined(key);
if (result == undefined) {
return null;
} else {
return (V) result;
}
}
@Override
public boolean containsKey(Object key) {
return undefined != getUndefined(key);
}
@Override
public boolean containsValue(Object value) {
for (int i = 0; i < size(); i++) {
if (value(i) == value) {
return true;
}
if (value != null && value.equals(value(i))) {
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K, V> m = (Map<K, V>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K, V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K, V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key) == null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
@Override
public int hashCode() {
int h = 0;
Iterator<Entry<K, V>> i = entrySet().iterator();
while (i.hasNext())
h += i.next().hashCode();
return h;
}
@Override
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Set<K> keySet() {
return new KeySet<K>();
}
@Override
public Collection<V> values() {
return new ValueCollection<V>();
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
return new EntrySet();
}
private class KeyValueIterator<E> implements Iterator<E> {
boolean key;
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
public KeyValueIterator(boolean key) {
this.key = key;
}
@Override
public boolean hasNext() {
return cursor != AbstractArrayMap.this.size();
}
@SuppressWarnings("unchecked")
@Override
public E next() {
int i = cursor;
if (i >= AbstractArrayMap.this.size())
throw new NoSuchElementException();
cursor = i + 1;
lastRet = i;
return key ? (E) AbstractArrayMap.this.key(lastRet) : (E) AbstractArrayMap.this.value(lastRet);
}
@Override
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
try {
AbstractArrayMap.this.remove(key(lastRet));
cursor = lastRet;
lastRet = -1;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
private class KeySet<E> extends AbstractSet<E> {
@Override
public Iterator<E> iterator() {
return new KeyValueIterator<E>(true);
}
@Override
public boolean contains(Object o) {
return AbstractArrayMap.this.containsKey(o);
}
@Override
public int size() {
return AbstractArrayMap.this.size();
}
}
private class ValueCollection<E> extends AbstractCollection<E> {
@Override
public Iterator<E> iterator() {
return new KeyValueIterator<E>(false);
}
@Override
public int size() {
return AbstractArrayMap.this.size();
}
}
private class EntryIterator implements Iterator<java.util.Map.Entry<K, V>> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
@Override
public boolean hasNext() {
return cursor != AbstractArrayMap.this.size();
}
@Override
public Entry<K, V> next() {
int i = cursor;
if (i >= AbstractArrayMap.this.size())
throw new NoSuchElementException();
cursor = i + 1;
lastRet = i;
return new SimpleImmutableEntry<K, V>(key(lastRet), value(lastRet));
}
@Override
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
try {
AbstractArrayMap.this.remove(key(lastRet));
cursor = lastRet;
lastRet = -1;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
private class EntrySet extends AbstractSet<java.util.Map.Entry<K, V>> {
@Override
public Iterator<java.util.Map.Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public int size() {
return AbstractArrayMap.this.size();
}
}
protected int hashCode(Object o) {
return o == null ? 0 : rehash(o.hashCode());
}
protected int rehash(int hash) {
return hash;
}
}
| 8,296 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections/impl/OpenAddressingArraySet.java | /*
*
* Copyright 2013 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.zeno.util.collections.impl;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
/**
* Open addressing hash set immutable implementation of the Set interface
*
* @author dkoszevnik
* @author tvaliulin
*
* @param <E>
*/
public class OpenAddressingArraySet<E> extends AbstractArraySet<E> {
private Object hashTable;
private Object elements[];
private int size;
public OpenAddressingArraySet() {
super();
}
public OpenAddressingArraySet(Collection<E> from) {
super(from);
}
@Override
public int size() {
return size;
}
// 70% load factor
public float loadFactor() {
return 0.7f;
}
@Override
public boolean contains(Object o) {
// / Math.abs(x % n) is the same as (x & n-1) when n is a power of 2
int hashModMask = OpenAddressing.hashTableLength(hashTable) - 1;
int hash = hashCode(o);
int bucket = hash & hashModMask;
int hashEntry = OpenAddressing.getHashEntry(hashTable, bucket);
// We found an entry at this hash position
while (hashEntry >= 0) {
if (Utils.equal(elements[hashEntry], o)) {
return true;
}
// linear probing resolves collisions.
bucket = (bucket + 1) & hashModMask;
hashEntry = OpenAddressing.getHashEntry(hashTable, bucket);
}
return false;
}
@SuppressWarnings("unchecked")
@Override
protected E element(int index) {
return (E) elements[index];
}
@Override
public void builderInit(int numEntries) {
hashTable = OpenAddressing.newHashTable(numEntries, loadFactor());
elements = new Object[numEntries];
}
@Override
public void builderSet(int index, E element) {
elements[size++] = element;
}
@Override
public Set<E> builderFinish() {
if(elements.length > size)
elements = Arrays.copyOf(elements, size);
// Math.abs(x % n) is the same as (x & n-1) when n is a power of 2
int hashModMask = OpenAddressing.hashTableLength(hashTable) - 1;
for (int i = 0; i < elements.length; i++) {
int hash = hashCode(elements[i]);
int bucket = hash & hashModMask;
// / linear probing resolves collisions
while (OpenAddressing.getHashEntry(hashTable, bucket) != -1) {
bucket = (bucket + 1) & hashModMask;
}
OpenAddressing.setHashEntry(hashTable, bucket, i);
}
return this;
}
@Override
protected int rehash(int hash) {
return OpenAddressing.rehash(hash);
}
}
| 8,297 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections/impl/BinarySearchArrayMap.java | /*
*
* Copyright 2013 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.zeno.util.collections.impl;
import com.netflix.zeno.util.collections.Comparators;
import com.netflix.zeno.util.collections.algorithms.ArrayQuickSort;
import com.netflix.zeno.util.collections.algorithms.BinarySearch;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedMap;
/**
* Implementation of the Binary Search map with the natural comparator. This
* implementation requires keys to be comparable.
*
* @author tvaliulin
*
* @param <K>
* @param <V>
*/
public class BinarySearchArrayMap<K, V> extends AbstractArraySortedMap<K, V> {
protected Object[] keysAndValues;
public BinarySearchArrayMap() {
setMap(Collections.<K, V> emptyMap());
}
public BinarySearchArrayMap(Map<K, V> map) {
setMap(map);
}
public BinarySearchArrayMap(Map.Entry<K, V>[] entries) {
setMap(entries);
}
private BinarySearchArrayMap(AbstractArrayMap<K, V> map, int start, int end) {
super(map, start, end);
}
@Override
public AbstractArraySortedMap<K, V> newMap(int start, int end) {
return new BinarySearchArrayMap<K, V>(this, start, end);
}
@Override
public void builderInit(int size) {
keysAndValues = new Object[size * 2];
}
@Override
public void builderPut(int i, K key, V value) {
keysAndValues[i * 2] = key;
keysAndValues[i * 2 + 1] = value;
}
@Override
public SortedMap<K, V> builderFinish() {
ArrayQuickSort.sort(this, comparator());
return this;
}
@Override
public K at(int index) {
return key(index);
}
@Override
public void swap(int x, int y) {
Utils.Array.swap(keysAndValues, x, y);
}
@Override
public int size() {
return keysAndValues.length / 2;
}
@SuppressWarnings("unchecked")
@Override
protected K key(int index) {
int realIndex = index * 2;
if (realIndex < 0 || realIndex >= keysAndValues.length) {
throw new ArrayIndexOutOfBoundsException();
}
return (K) keysAndValues[realIndex];
}
@SuppressWarnings("unchecked")
@Override
protected V value(int index) {
int realIndex = index * 2 + 1;
if (realIndex < 0 || realIndex >= keysAndValues.length) {
throw new ArrayIndexOutOfBoundsException();
}
return (V) keysAndValues[realIndex];
}
@SuppressWarnings("unchecked")
@Override
public Object getUndefined(Object key) {
int index = BinarySearch.binarySearch(this, (K) key, comparator());
if (index < 0) {
return AbstractArrayMap.undefined;
}
// going upward
for (int i = index; i >= 0 && (comparator().compare(key(i), (K) key) == 0); i--) {
if (Utils.equal(key, key(i))) {
return value(i);
}
}
// going downward
for (int i = index + 1; i < size() && (comparator().compare(key(i), (K) key) == 0); i++) {
if (Utils.equal(key, key(i))) {
return value(i);
}
}
return AbstractArrayMap.undefined;
}
@Override
public Comparator<K> comparator() {
return Comparators.comparableComparator();
}
}
| 8,298 |
0 | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections | Create_ds/zeno/src/main/java/com/netflix/zeno/util/collections/impl/NetflixCollections.java | /*
*
* Copyright 2013 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.zeno.util.collections.impl;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Utility class
*
* @author tvaliulin
*
*/
public class NetflixCollections {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static final SortedMap<?, ?> EMPTY_SORTED_MAP = Collections.unmodifiableSortedMap(new TreeMap());
@SuppressWarnings("unchecked")
public static <K, V> SortedMap<K, V> emptySortedMap() {
return (SortedMap<K, V>) EMPTY_SORTED_MAP;
}
public static <K, V> SortedMap<K, V> singletonSortedMap(K key, V value) {
return new SingletonSortedMap<K, V>(key, value);
}
}
| 8,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.