Java Code Examples for com.esotericsoftware.kryo.Kryo#setInstantiatorStrategy()

The following examples show how to use com.esotericsoftware.kryo.Kryo#setInstantiatorStrategy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SerializationTest.java    From rtree-3d with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testSerializationRoundTrip() throws FileNotFoundException {
    // this test to see if can use kryo to serialize RTree instance
    List<Entry<Object, Point>> entries = GreekEarthquakes.entriesList();
    int maxChildren = 8;
    RTree<Object, Point> tree = RTree.maxChildren(maxChildren).<Object, Point> create()
            .add(entries);

    File file = new File("target/greek-serialized.kryo");
    file.delete();

    Kryo kryo = new Kryo();
    Output output = new Output(new FileOutputStream(file));
    kryo.writeObject(output, tree);
    output.close();

    Input input = new Input(new FileInputStream(file));
    kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
    @SuppressWarnings("unchecked")
    RTree<Object, Point> tree2 = kryo.readObject(input, RTree.class);
    assertNotNull(tree2);

}
 
Example 2
Source File: DbStoragePlainFile.java    From Iron with Apache License 2.0 6 votes vote down vote up
private Kryo createKryoInstance() {
    Kryo kryo = new Kryo();

    kryo.register(IronTable.class);
    kryo.setDefaultSerializer(CompatibleFieldSerializer.class);
    kryo.setReferences(false);

    // Serialize Arrays$ArrayList
    //noinspection ArraysAsListWithZeroOrOneArgument
    kryo.register(Arrays.asList("").getClass(), new ArraysAsListSerializer());
    UnmodifiableCollectionsSerializer.registerSerializers(kryo);
    SynchronizedCollectionsSerializer.registerSerializers(kryo);
    // Serialize inner AbstractList$SubAbstractListRandomAccess
    kryo.addDefaultSerializer(new ArrayList<>().subList(0, 0).getClass(),
            new NoArgCollectionSerializer());
    // Serialize AbstractList$SubAbstractList
    kryo.addDefaultSerializer(new LinkedList<>().subList(0, 0).getClass(),
            new NoArgCollectionSerializer());
    // To keep backward compatibility don't change the order of serializers above

    kryo.setInstantiatorStrategy(
            new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
    return kryo;
}
 
Example 3
Source File: KryoFactory.java    From vertexium with Apache License 2.0 6 votes vote down vote up
public Kryo createKryo() {
    Kryo kryo = new Kryo(new DefaultClassResolver(), new MapReferenceResolver() {
        @Override
        public boolean useReferences(Class type) {
            // avoid calling System.identityHashCode
            if (type == String.class || type == Date.class) {
                return false;
            }
            return super.useReferences(type);
        }
    });
    registerClasses(kryo);

    kryo.setAutoReset(true);
    kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));

    return kryo;
}
 
Example 4
Source File: KryoSerialization.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Object deserializeFrom(final String filename)
		throws SerializationException {
	LOGGER.info("Deserializing object from " + filename);
	try {
		final Kryo kryo = new Kryo();
		final Input input = new Input(new FileInputStream(filename));

		kryo.setInstantiatorStrategy(new SerializingInstantiatorStrategy());

		final Object obj = kryo.readClassAndObject(input);
		input.close();
		return obj;
	} catch (final FileNotFoundException e) {
		throw new ISerializationStrategy.SerializationException(e);
	}
}
 
Example 5
Source File: TestKryoUpgrade.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testSchemaPathUpgrade() throws Exception {
  /*
    Pre-4.2 serialized SchemaPath.  Generated by this code:

    final PathSegment.NameSegment nameSegment = new PathSegment.NameSegment("path");
    final SchemaPath schemaPath = new SchemaPath(nameSegment);

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final Output output = new Output(outputStream);

    final Kryo kryo = new Kryo();
    kryo.writeObject(output, schemaPath);

    FileUtils.writeByteArrayToFile(new File("schemapath.kryo"), output.getBuffer());
  */
  final URL resource = Resources.getResource("kryo/schemapath.kryo");
  final byte[] bytes = Files.readAllBytes(Paths.get(resource.getPath()));

  final Kryo kryo = new Kryo();
  kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));

  final SchemaPath schemaPath = kryo.readObject(new Input(bytes), SchemaPath.class);
  assertEquals("path", schemaPath.getAsUnescapedPath());
}
 
Example 6
Source File: KryoSerialization.java    From JPPF with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Kryo instance, with its instantiator strategy and a set of
 * common serializers (from kryo-serializers project) initialized.
 * @return an instance of {@link Kryo}.
 */
private static Kryo createKryo() {
  final Kryo kryo = new Kryo(new CustomClassResolver(), new MapReferenceResolver());
  kryo.setAutoReset(true);
  kryo.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));

  kryo.register(ObjectName.class, new ObjectNameSerializer());
  kryo.register(OffloadableNotification.class, new GenericObjectSerializer());
  kryo.register(TaskExecutionNotification.class, new GenericObjectSerializer());
  kryo.register(TaskGraph.class, new JobTaskGraphSerializer());
  kryo.register(Collection.class, new CollectionSerializer());
  kryo.register(Arrays.asList( "" ).getClass(), new ArraysAsListSerializer() );
  kryo.register(Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer() );
  kryo.register(Collections.EMPTY_MAP.getClass(), new CollectionsEmptyMapSerializer() );
  kryo.register(Collections.EMPTY_SET.getClass(), new CollectionsEmptySetSerializer() );
  kryo.register(Collections.singletonList( "" ).getClass(), new CollectionsSingletonListSerializer() );
  kryo.register(Collections.singleton( "" ).getClass(), new CollectionsSingletonSetSerializer() );
  kryo.register(Collections.singletonMap( "", "" ).getClass(), new CollectionsSingletonMapSerializer() );
  kryo.register(GregorianCalendar.class, new GregorianCalendarSerializer());
  kryo.register(InvocationHandler.class, new JdkProxySerializer());
  UnmodifiableCollectionsSerializer.registerSerializers(kryo);
  SynchronizedCollectionsSerializer.registerSerializers(kryo);
  kryo.register(EnumMap.class, new EnumMapSerializer());
  kryo.register(EnumSet.class, new EnumSetSerializer());
  return kryo;
}
 
Example 7
Source File: SerDeUtils.java    From metron with Apache License 2.0 5 votes vote down vote up
@Override
    protected Kryo initialValue() {
      Kryo ret = new Kryo();
      ret.setReferences(true);
      ret.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));

      ret.register(Arrays.asList("").getClass(), new ArraysAsListSerializer());
      ret.register(Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer());
      ret.register(Collections.EMPTY_MAP.getClass(), new CollectionsEmptyMapSerializer());
      ret.register(Collections.EMPTY_SET.getClass(), new CollectionsEmptySetSerializer());
      ret.register(Collections.singletonList("").getClass(), new CollectionsSingletonListSerializer());
      ret.register(Collections.singleton("").getClass(), new CollectionsSingletonSetSerializer());
      ret.register(Collections.singletonMap("", "").getClass(), new CollectionsSingletonMapSerializer());
      ret.register(GregorianCalendar.class, new GregorianCalendarSerializer());
      ret.register(InvocationHandler.class, new JdkProxySerializer());
      UnmodifiableCollectionsSerializer.registerSerializers(ret);
      SynchronizedCollectionsSerializer.registerSerializers(ret);

// custom serializers for non-jdk libs

// register CGLibProxySerializer, works in combination with the appropriate action in handleUnregisteredClass (see below)
      ret.register(CGLibProxySerializer.CGLibProxyMarker.class, new CGLibProxySerializer());
// joda DateTime, LocalDate and LocalDateTime
      ret.register(LocalDate.class, new JodaLocalDateSerializer());
      ret.register(LocalDateTime.class, new JodaLocalDateTimeSerializer());
// guava ImmutableList, ImmutableSet, ImmutableMap, ImmutableMultimap, UnmodifiableNavigableSet
      ImmutableListSerializer.registerSerializers(ret);
      ImmutableSetSerializer.registerSerializers(ret);
      ImmutableMapSerializer.registerSerializers(ret);
      ImmutableMultimapSerializer.registerSerializers(ret);
      return ret;
    }
 
Example 8
Source File: KryoSerializer.java    From mango with Apache License 2.0 5 votes vote down vote up
@Override
protected Kryo initialValue() {

    Kryo kryo = new Kryo();
    kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
    return kryo;
}
 
Example 9
Source File: TreeSerializationTest.java    From swblocks-decisiontree with Apache License 2.0 5 votes vote down vote up
@Test
public void treeNode() {
    final Result<DecisionTreeRuleSet> result = (new CommisionRuleSetSupplier()).get();
    EhSupport.ensure(result.isSuccess(), "Could not create decision tree");
    final DecisionTreeRuleSet ruleSet = result.getData();

    final TreeNode node = DecisionTreeFactory.constructDecisionTree(ruleSet, DecisionTreeType.SINGLE);

    final Kryo kryo = new Kryo();
    // no default no-arg constructors
    kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());

    final InstantiatorStrategy defaultInstantiatorStrategy = new Kryo.DefaultInstantiatorStrategy();
    kryo.getRegistration(ArrayList.class)
            .setInstantiator(defaultInstantiatorStrategy.newInstantiatorOf(ArrayList.class));
    kryo.getRegistration(HashSet.class)
            .setInstantiator(defaultInstantiatorStrategy.newInstantiatorOf(HashSet.class));
    UnmodifiableCollectionsSerializer.registerSerializers(kryo);

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Output output = new Output(out);
    kryo.writeObject(output, node);
    output.flush();
    output.close();

    final ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray());
    final Input kryoInput = new Input(inputStream);
    final TreeNode tree = kryo.readObject(kryoInput, BaseTreeNode.class);

    final SingleDecisionTreeFactoryTest test = new SingleDecisionTreeFactoryTest();
    test.checkTreeNode(tree, ruleSet);

    assertEquals(node, tree);
}
 
Example 10
Source File: KryoSerializer.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Chill Kryo Serializer which is implicitly added to the classpath via flink-runtime.
 * Falls back to the default Kryo serializer if it can't be found.
 * @return The Kryo serializer instance.
 */
private Kryo getKryoInstance() {

	try {
		// check if ScalaKryoInstantiator is in class path (coming from Twitter's Chill library).
		// This will be true if Flink's Scala API is used.
		Class<?> chillInstantiatorClazz =
				Class.forName("org.apache.flink.runtime.types.FlinkScalaKryoInstantiator");
		Object chillInstantiator = chillInstantiatorClazz.newInstance();

		// obtain a Kryo instance through Twitter Chill
		Method m = chillInstantiatorClazz.getMethod("newKryo");

		return (Kryo) m.invoke(chillInstantiator);
	} catch (ClassNotFoundException | InstantiationException | NoSuchMethodException |
		IllegalAccessException | InvocationTargetException e) {

		LOG.warn("Falling back to default Kryo serializer because Chill serializer couldn't be found.", e);

		Kryo.DefaultInstantiatorStrategy initStrategy = new Kryo.DefaultInstantiatorStrategy();
		initStrategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy());

		Kryo kryo = new Kryo();
		kryo.setInstantiatorStrategy(initStrategy);

		return kryo;
	}
}
 
Example 11
Source File: KryoSerializer.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of Kryo serializer, for use with the given object type.
 * <p/>
 * Note: this method is public to allow end-users to validate compatibility of their POJOs,
 * with the Kryo serializer as used by CQEngine.
 *
 * @param objectType The type of object which the instance of Kryo will serialize
 * @return a new instance of Kryo serializer
 */
@SuppressWarnings({"ArraysAsListWithZeroOrOneArgument", "WeakerAccess"})
protected Kryo createKryo(Class<?> objectType) {
    Kryo kryo = new Kryo();
    // Instantiate serialized objects via a no-arg constructor when possible, falling back to Objenesis...
    kryo.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
    // Register the object which this index will persist...
    kryo.register(objectType);
    kryo.setRegistrationRequired(false);
    // Register additional serializers which are not built-in to Kryo 3.0...
    kryo.register(Arrays.asList().getClass(), new ArraysAsListSerializer());
    UnmodifiableCollectionsSerializer.registerSerializers(kryo);
    SynchronizedCollectionsSerializer.registerSerializers(kryo);
    return kryo;
}
 
Example 12
Source File: Namespace.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Kryo instance.
 *
 * @return Kryo instance
 */
@Override
public Kryo create() {
  LOGGER.trace("Creating Kryo instance for {}", this);
  Kryo kryo = new Kryo();
  kryo.setClassLoader(classLoader);
  kryo.setRegistrationRequired(registrationRequired);

  // If compatible serialization is enabled, override the default serializer.
  if (compatible) {
    kryo.setDefaultSerializer(CompatibleFieldSerializer::new);
  }

  // TODO rethink whether we want to use StdInstantiatorStrategy
  kryo.setInstantiatorStrategy(
      new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));

  for (RegistrationBlock block : registeredBlocks) {
    int id = block.begin();
    if (id == FLOATING_ID) {
      id = kryo.getNextRegistrationId();
    }
    for (Pair<Class<?>[], Serializer<?>> entry : block.types()) {
      register(kryo, entry.getLeft(), entry.getRight(), id++);
    }
  }
  return kryo;
}
 
Example 13
Source File: AbstractConfig.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
public static <T extends AbstractConfig<?>> T fromFile(final String path, final Class<T> clazz) throws FileNotFoundException {
	final Kryo kryo = new Kryo();
	kryo.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
    try (final Input input = new Input(new FileInputStream(path))) {
		final T bc = kryo.readObject(input, clazz);
		return bc;
	}
}
 
Example 14
Source File: KryoPoolFactory.java    From AvatarMQ with Apache License 2.0 5 votes vote down vote up
public Kryo create() {
    Kryo kryo = new Kryo();
    kryo.setReferences(false);
    kryo.register(RequestMessage.class);
    kryo.register(ResponseMessage.class);
    kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
    return kryo;
}
 
Example 15
Source File: KryoUtils.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static Kryo getKryo() {
    if (_Kryo.get() == null) {
        Kryo kryo = new Kryo();
        kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
        kryo.register(BitSet.class, new BitSetSerializer());
        _Kryo.set(kryo);
    }

    return _Kryo.get();
}
 
Example 16
Source File: KryoSerializer.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
@Override
protected Kryo initialValue() throws Exception {
    Kryo kryo = new Kryo();
    for (Class<?> type : useJavaSerializerTypes) {
        kryo.addDefaultSerializer(type, JavaSerializer.class);
    }
    kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
    kryo.setRegistrationRequired(false);
    kryo.setReferences(false);
    return kryo;
}
 
Example 17
Source File: KryoSerializer.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Chill Kryo Serializer which is implicitly added to the classpath via flink-runtime.
 * Falls back to the default Kryo serializer if it can't be found.
 * @return The Kryo serializer instance.
 */
private Kryo getKryoInstance() {

	try {
		// check if ScalaKryoInstantiator is in class path (coming from Twitter's Chill library).
		// This will be true if Flink's Scala API is used.
		Class<?> chillInstantiatorClazz =
				Class.forName("org.apache.flink.runtime.types.FlinkScalaKryoInstantiator");
		Object chillInstantiator = chillInstantiatorClazz.newInstance();

		// obtain a Kryo instance through Twitter Chill
		Method m = chillInstantiatorClazz.getMethod("newKryo");

		return (Kryo) m.invoke(chillInstantiator);
	} catch (ClassNotFoundException | InstantiationException | NoSuchMethodException |
		IllegalAccessException | InvocationTargetException e) {

		LOG.warn("Falling back to default Kryo serializer because Chill serializer couldn't be found.", e);

		Kryo.DefaultInstantiatorStrategy initStrategy = new Kryo.DefaultInstantiatorStrategy();
		initStrategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy());

		Kryo kryo = new Kryo();
		kryo.setInstantiatorStrategy(initStrategy);

		return kryo;
	}
}
 
Example 18
Source File: SerializeUtils.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Kryo create() {
	Kryo kryo = new Kryo();
	kryo.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new SerializingInstantiatorStrategy()));
	return kryo;
}
 
Example 19
Source File: KryoSerializer.java    From jstorm with Apache License 2.0 4 votes vote down vote up
public KryoSerializer() {
    kryo = new Kryo();
    kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
    output = new Output(200, 2000000000);
    input = new Input(1);
}
 
Example 20
Source File: KryoCodec.java    From jvm-serializer with Apache License 2.0 4 votes vote down vote up
protected Kryo initialValue() {
    Kryo kryo = new Kryo();

    kryo.register(byte[].class);
    kryo.register(char[].class);
    kryo.register(short[].class);
    kryo.register(int[].class);
    kryo.register(long[].class);
    kryo.register(float[].class);
    kryo.register(double[].class);
    kryo.register(boolean[].class);
    kryo.register(String[].class);
    kryo.register(Object[].class);
    kryo.register(KryoSerializable.class);
    kryo.register(BigInteger.class);
    kryo.register(BigDecimal.class);
    kryo.register(Class.class);
    kryo.register(Date.class);
    //kryo.register(Enum.class);
    kryo.register(EnumSet.class);
    kryo.register(Currency.class);
    kryo.register(StringBuffer.class);
    kryo.register(StringBuilder.class);
    kryo.register(Collections.EMPTY_LIST.getClass());
    kryo.register(Collections.EMPTY_MAP.getClass());
    kryo.register(Collections.EMPTY_SET.getClass());
    kryo.register(Collections.singletonList(null).getClass());
    kryo.register(Collections.singletonMap(null, null).getClass());
    kryo.register(Collections.singleton(null).getClass());
    kryo.register(TreeSet.class);
    kryo.register(Collection.class);
    kryo.register(TreeMap.class);
    kryo.register(Map.class);
    try {
        kryo.register(Class.forName("sun.util.calendar.ZoneInfo"));
    } catch (ClassNotFoundException e) {
        //Noop
    }
    kryo.register(Calendar.class);
    kryo.register(Locale.class);

    kryo.register(BitSet.class);
    kryo.register(HashMap.class);
    kryo.register(Timestamp.class);
    kryo.register(ArrayList.class);

    int size = idList.size();
    for (int i = 0; i < size; i++) {
        kryo.register(classList
                        .get(i),
                serializerList
                        .get(i),
                idList.get(i));
    }
    kryo.setRegistrationRequired(true);
    kryo.setReferences(false);
    kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
    return kryo;
}