/data/test/clojure/b9c742da3658522f78ebcb09d377eff511c0c613protocol.clj

https://github.com/aliostad/deep-learning-lang-detection · Clojure · 63 lines · 46 code · 10 blank · 7 comment · 0 complexity · 8481c8e593710f2db062e37a8c15fc40 MD5 · raw file

  1. (ns ribbit.protocol
  2. (:import (org.bouncycastle.asn1 ASN1InputStream ASN1Sequence DERUTF8String DERInteger DERObject)
  3. (java.io InputStream)
  4. (java.lang.ClassCastException)))
  5. ;; Oh boy here we go: the Clojure RIBBIT protocol decoder.
  6. ;; Check out this cool RFC on the RIBBIT protocol: http://frog.tips/api/1/
  7. (defn- create-tip
  8. "Create a FROG tip. Croaks are represented as a sequence of tips."
  9. [number tip]
  10. {:number number
  11. :tip tip})
  12. (defn- object-from-stream
  13. "Create a DERObject from a stream. This object may or may not be iterable."
  14. [^InputStream stream]
  15. (.readObject (ASN1InputStream. stream)))
  16. (defn- object-seq-from-object
  17. "Treat the DERObject as iterable and convert it a sequence of DERObjects."
  18. [^DERObject der]
  19. (enumeration-seq
  20. (.getObjects (cast ASN1Sequence der))))
  21. (defn- decode-from-stream
  22. "Decode a part of the RIBBIT protocol from a stream."
  23. [decoder-func stream]
  24. (try
  25. (-> stream
  26. object-from-stream
  27. object-seq-from-object
  28. decoder-func)
  29. ; These shouldn't bubble up
  30. (catch ClassCastException _ nil)))
  31. (defn- decode-tip
  32. "Decode a RIBBIT tip from a sequence of ASN.1 objects."
  33. [der-objects]
  34. (let [[first second] der-objects
  35. number (.getValue (cast DERInteger first))
  36. tip (.getString (cast DERUTF8String second))]
  37. (create-tip number tip)))
  38. (defn- decode-croak
  39. "Decode an entire RIBBIT croak from a sequence of ASN.1 objects."
  40. [der-objects]
  41. ; Force this to evaluate now and throw any exceptions.
  42. ; There's probably a more idiomatic way to handle this.
  43. (doall (map #(decode-tip (object-seq-from-object %1)) der-objects)))
  44. ;; RIBBIT decoder functions that operate on streams.
  45. ;; These return nil on any decoding error to keep things idomatic - I think?
  46. (defn decode-tip-from-stream
  47. "Decode a RIBBIT tip"
  48. [stream]
  49. (decode-from-stream decode-tip stream))
  50. (defn decode-croak-from-stream
  51. "Decode a RIBBIT croak"
  52. [stream]
  53. (decode-from-stream decode-croak stream))