package org.eclipse.jetty.nosql.kvs.session.kryo;

import org.eclipse.jetty.nosql.kvs.session.ISerializationTranscoder;
import org.eclipse.jetty.nosql.kvs.session.TranscoderException;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class KryoTranscoder implements ISerializationTranscoder {
  private final int initialBufferSize = 8192; // FIXME: how much is enough?
  private Kryo kryo = null;

  public KryoTranscoder() {
    this(Thread.currentThread().getContextClassLoader());
  }

  public KryoTranscoder(ClassLoader cl) {
    kryo = new Kryo();
    kryo.setRegistrationRequired(false);
    kryo.setClassLoader(cl);
  }

  public byte[] encode(Object obj) throws TranscoderException {
    byte[] raw = null;
    try {
      Output output = new Output(initialBufferSize, -1);
      kryo.writeObject(output, obj);
      output.close();
      raw = output.getBuffer();
    } catch (Exception error) {
      throw(new TranscoderException(error));
    }
    return raw;
  }

  public <T> T decode(byte[] raw, Class<T> klass) throws TranscoderException {
    T obj = null;
    try {
      Input input = new Input(raw);
      obj = kryo.readObject(input, klass);
    } catch (Exception error) {
      throw(new TranscoderException(error));
    }
    return obj;
  }
}

@@ -44,16 +44,92 @@
 .kryo;%0A%0A
+import java.io.ByteArrayInputStream;%0Aimport java.io.ByteArrayOutputStream;%0A%0A
 import o
@@ -189,16 +189,16 @@
 scoder;%0A
-
 import o
@@ -451,84 +451,8 @@
 r %7B%0A
-  private final int initialBufferSize = 8192; // FIXME: how much is enough?%0A
   pr
@@ -800,24 +800,90 @@
 ;%0A    try %7B%0A
+      ByteArrayOutputStream stream = new ByteArrayOutputStream();%0A
       Output
@@ -907,29 +907,14 @@
 put(
-initialBufferSize, -1
+stream
 );%0A 
@@ -987,24 +987,26 @@
 w = 
-output.getBuffer
+stream.toByteArray
 ();%0A
@@ -1212,24 +1212,91 @@
 ;%0A    try %7B%0A
+      ByteArrayInputStream stream = new ByteArrayInputStream(raw);%0A
       Input 
@@ -1313,19 +1313,22 @@
 w Input(
-raw
+stream
 );%0A     

use ByteArrayOutputStream during serialization to remove embeded value of initialBufferSize