четверг, 12 июня 2014 г.

call clojure code from java


Since clojure 1.6 there is no more special dances inside clojure code: special declarations or wrappers or something else. it is possible call clojure code from jar file like this. Clojure code (jar file) and clojure-1.6.jar should be in a class-path.

import clojure.java.api.Clojure;
import clojure.lang.IFn;

        IFn require = Clojure.var("clojure.core", "require");
        require.invoke(Clojure.read("my-clj-project.core"));

        IFn myf0 = Clojure.var("my-clj-project.core", "my-clojure-func0");
        myf0.invoke();

or  myf0.invoke(param1, param2);

среда, 11 июня 2014 г.

How to break JCE crypto policy limit when using bouncycastle

    //this code allows to break limit if client jdk/jre has no unlimited policy files for JCE.
    //it should be run once. So this static section is always execute during the class loading process.
//this code is useful when working with Bouncycastle library.
    static {
        try {
            Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
            field.setAccessible(true);
            field.set(null, java.lang.Boolean.FALSE);
        } catch (Exception ex) {
        }
    }

or clojure variant of this function

(defn break-jce-policy-limit
  "This function breaks JCE crypto limits. Should be run once, primarily at the begining of the program
  to avoid JCE policy limit if JDK/JRE runtime has no installed files for break crypto limit. Returns nil."
  []
  (safe (let [field (-> (Class/forName "javax.crypto.JceSecurity")
                      (.getDeclaredField "isRestricted"))]
          (.setAccessible field true)
          (.set field nil java.lang.Boolean/FALSE))))

(defmacro safe [bindings? & forms]
  "This macro is used to execute any function inside try-catch block."
  (let [bindings (if (and (even? (count bindings?)) (vector? bindings?))
                   bindings? nil)
        forms (if bindings forms (cons bindings? forms))
        except `(catch Exception e# e#
                  (println (.getMessage e#) e#))]
    (if bindings
      `(let ~bindings (try ~@forms ~except))
      `(try ~@forms ~except))))