org.aksw.jenax.io.kryo.jena.GenericCollectionSerializer Maven / Gradle / Ivy
package org.aksw.jenax.io.kryo.jena;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Riot-based serializer for Models.
*
* @author Claus Stadler
*/
public class GenericCollectionSerializer
extends Serializer
{
protected Class collectionClass;
protected Class itemClass;
protected Function> colToIter;
protected Supplier colCtor;
protected BiConsumer addItem;
public GenericCollectionSerializer(
Class collectionClass,
Class itemClass,
// Function toBackend,
Function> colToIter,
Supplier colCtor,
BiConsumer addItem) {
super();
this.collectionClass = collectionClass;
this.itemClass = itemClass;
this.colToIter = colToIter;
this.colCtor = colCtor;
this.addItem = addItem;
}
public static GenericCollectionSerializer create(Class collectionClass, Class itemClass, Function> colToIter, Supplier colCtor, BiConsumer addItem) {
return new GenericCollectionSerializer<>(collectionClass, itemClass, colToIter, colCtor, addItem);
}
@Override
public void write(Kryo kryo, Output output, C col) {
try (Stream stream = colToIter.apply(col)) {
stream.forEach(item -> {
if (item == null) {
throw new IllegalStateException("Unexpected null item");
}
kryo.writeObjectOrNull(output, item, itemClass);
});
kryo.writeObjectOrNull(output, null, itemClass);
}
}
@Override
public C read(Kryo kryo, Input input, Class objClass) {
C result = colCtor.get();
T item;
while ((item = kryo.readObjectOrNull(input, itemClass)) != null) {
addItem.accept(result, item);
}
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy