package com.datatorrent.lib.codec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.google.common.base.Preconditions;

import com.datatorrent.api.StreamCodec;

import com.datatorrent.common.util.Slice;

/**
 * This codec is used for serializing the objects of class which are Kryo serializable.
 * It is needed when custom static partitioning is required.
 *
 * @param <T> Type of the object which gets serialized/deserialized using this codec.
 * @since 0.9.0
 */
public class KryoSerializableStreamCodec<T> implements StreamCodec<T>, Serializable
{
  protected transient final Kryo kryo;

  public KryoSerializableStreamCodec()
  {
    this.kryo = new Kryo();
    this.kryo.setClassLoader(Thread.currentThread().getContextClassLoader());
  }

  /**
   * Registers a class with kryo. If the class of the tuple and its fields are registered then kryo serialization is more efficient.
   *
   * @param clazz class to register with Kryo.
   */
  public void register(Class<?> clazz)
  {
    this.kryo.register(clazz);
  }

  /**
   * Register a class with specified id.
   *
   * @param clazz class to register with Kryo.
   * @param id    int ID of the class.
   */
  public void register(Class<?> clazz, int id)
  {
    Preconditions.checkArgument(id > 0, "invalid id");
    this.kryo.register(clazz, id);
  }

  @Override
  public Object fromByteArray(Slice fragment)
  {
    ByteArrayInputStream is = new ByteArrayInputStream(fragment.buffer, fragment.offset, fragment.length);
    Input input = new Input(is);
    return kryo.readClassAndObject(input);
  }

  @Override
  public Slice toByteArray(T info)
  {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Output output = new Output(os);
    kryo.writeClassAndObject(output, info);
    output.flush();
    return new Slice(os.toByteArray(), 0, os.toByteArray().length);
  }

  @Override
  public int getPartition(T t)
  {
    return t.hashCode();
  }

  private static final long serialVersionUID = 201411031402L;
}

@@ -96,32 +96,94 @@
 ayOutputStream;%0A
+import java.io.IOException;%0Aimport java.io.ObjectInputStream;%0A
 import java.io.S
@@ -195,16 +195,16 @@
 izable;%0A
-
 %0Aimport 
@@ -367,17 +367,16 @@
 itions;%0A
-%0A
 import c
@@ -403,25 +403,24 @@
 treamCodec;%0A
-%0A
 import com.d
@@ -820,22 +820,16 @@
 ansient 
-final 
 Kryo kry
@@ -871,16 +871,16 @@
 Codec()%0A
-
   %7B%0A    
@@ -978,32 +978,266 @@
 Loader());%0A  %7D%0A%0A
+  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException%0A  %7B%0A    in.defaultReadObject();%0A    this.kryo = new Kryo();%0A    this.kryo.setClassLoader(Thread.currentThread().getContextClassLoader());%0A  %7D%0A%0A
   /**%0A   * Regis
@@ -2179,24 +2179,25 @@
 Output(os);%0A
+%0A
     kryo.wri

Fix KryoSerializableStreamCodec deserialization.