package carbonite;

import clojure.lang.RT;
import clojure.lang.Var;
import com.esotericsoftware.kryo.Kryo;

public class JavaBridge {
    static final Var require = RT.var("clojure.core", "require");
    static final Var symbol = RT.var("clojure.core", "symbol");

    static Var defaultReg;
    static Var regSerializers;
    static Var cljPrimitives;
    static Var javaPrimitives;
    static Var cljCollections;

    public static void initialize() {
        try {
            require.invoke(symbol.invoke("carbonite.api"));
            requireCarbonite();
        } catch (Exception e) {
            e.printStackTrace();
        }

        defaultReg = RT.var("carbonite.api", "default-registry");
        regSerializers = RT.var("carbonite.api", "register-serializers");
        cljPrimitives  = RT.var("carbonite.serializer", "clojure-primitives");
        javaPrimitives = RT.var("carbonite.serializer", "java-primitives");
        cljCollections = RT.var("carbonite.serializer", "clojure-collections");
    }

    public static void registerPrimitives(Kryo registry) throws Exception {
        initialize();
        regSerializers.invoke(registry, cljPrimitives.deref());
    }

    public static void registerCollections(Kryo registry) throws Exception {
        initialize();
        regSerializers.invoke(registry, cljCollections.deref());
    }

    public static void registerJavaPrimitives(Kryo registry) throws Exception {
        initialize();
        regSerializers.invoke(registry, javaPrimitives.deref());
    }

    public static Kryo defaultRegistry() throws Exception {
        initialize();
        return (Kryo) defaultReg.invoke();
    }

    public static void requireCarbonite () {
        require.invoke(symbol.invoke("carbonite.serializer"));
    }

    public static void enhanceRegistry(Kryo registry) throws Exception {
        registerPrimitives(registry);
        registerJavaPrimitives(registry);
        registerCollections(registry);
    }
}

@@ -410,16 +410,62 @@
 tions;%0A%0A
+    static boolean registryEnhanced = false;%0A%0A
     publ
@@ -1833,24 +1833,37 @@
 blic static 
+synchronized 
 void enhance
@@ -1897,32 +1897,68 @@
 ows Exception %7B%0A
+        if(!registryEnhanced) %7B%0A    
         register
@@ -1979,32 +1979,36 @@
 istry);%0A        
+   
+ 
 registerJavaPrim
@@ -2025,32 +2025,36 @@
 istry);%0A        
+    
 registerCollecti
@@ -2064,20 +2064,67 @@
 (registry);%0A
+            registryEnhanced = true;%0A        %7D%0A
     %7D%0A%7D%0A

synchronize enhanceRegistry method