Permalink
Browse files

Initial commit.

  • Loading branch information...
0 parents commit 08759da035cd32e218bc04ff3226f9fa2cb705b3 @asmyczek asmyczek committed Apr 13, 2011
2 .gitignore
@@ -0,0 +1,2 @@
+lib
+classes
177 LICENSE
@@ -0,0 +1,177 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
48 README.md
@@ -0,0 +1,48 @@
+# simple-avro
+Clojure wrapper around Avro schema and serialization.
+
+## Quick Start
+
+### Schema definition
+
+ (defavro-enum State
+ "AL" "AK" "AS" "AZ" "AR" "CA" "CO" ; ...
+ )
+
+ (defavro-record Address
+ :street avro-string
+ :city avro-string
+ :state State
+ :zip avro-int
+ :country avro-string)
+
+ (defavro-record Contact
+ :first avro-string
+ :last avro-string
+ :address Address
+ :email avro-string
+ :phone (avro-union avro-string avro-null))
+
+_simple-avro_ implements all types defined in [Avro schema specification](http://avro.apache.org/docs/1.5.0/spec.html).
+Just prepend _avro-_ to the type name or use plain string names. _defavro-_ macros defined for all named types
+(_defavro-record_, _defavro_enum_ and _defavro-fixed) create var objects convenient for hierarchical schema composition.
+Parameters namespace, aliases and doc can by provided in an optional argument map.
+Use string names for type references to define recursive types, for example:
+
+ (defavro-record IntList
+ "value" avro-int
+ "next" (avro-union "IntList" avro-null))
+
+### Data serialization
+
+ (def contact {:first "Mike" :last ...})
+ (def packed (pack Contact contact <optional encoder>))
+ (assert (= contact (unpack Contact packed <optional decoder>)))
+
+_pack_ serializes objects into generic Avro objects. For json or binary serialization provide an optional _json-encoder_ or _binary-encoder_.
+Use equivalent decoder to de-serialize objects using _unpack_.
+
+For more details, see examples and unit tests.
+
+Found a bug? Have a question? Drop me an email at adam.smyczek \_at\_ gmail.com.
+
12 project.clj
@@ -0,0 +1,12 @@
+(defproject simple-avro "0.0.2"
+ :description "Clojure wrapper around Avro schema and serialization."
+ :dependencies [[org.clojure/clojure "1.2.0"]
+ [org.clojure/clojure-contrib "1.2.0"]
+ [org.apache.avro/avro "1.5.0"]]
+ :disable-deps-clean false
+ :warn-on-reflection true
+ :source-path "src"
+ :test-path "test"
+ :license {:name "Apache License - Version 2.0"
+ :url "http://www.apache.org/licenses/"})
+
58 src/examples/address_book.clj
@@ -0,0 +1,58 @@
+(ns examples.address-book
+ (:use (simple-avro schema core)))
+
+; Schema
+
+(defavro-enum Country
+ "USA" "Germany" "France" ; ...
+ )
+
+(defavro-enum State
+ "AL" "AK" "AS" "AZ" "AR" "CA" "CO" ; ...
+ )
+
+(defavro-record Address
+ :street avro-string
+ :city avro-string
+ :state State
+ :zip avro-int
+ :country Country)
+
+(defavro-record Person
+ :first avro-string
+ :last avro-string
+ :address Address
+ :email avro-string
+ :phone (avro-union avro-string avro-null))
+
+(defavro-record Company
+ :name avro-string
+ :address Address
+ :contact Person)
+
+(def Contact
+ (avro-union Person Company))
+
+(def AddressBook
+ (avro-array Contact))
+
+
+; Sample records
+
+(def address-book
+ [{"first" "Mike"
+ "last" "Foster"
+ "address" {"street" "South Park Str. 14"
+ "city" "Wasco"
+ "state" "CA"
+ "zip" 95171
+ "country" "USA"}
+ "email" "mike@home.com"
+ "phone" nil}])
+
+; Serialization
+
+(let [packed-address-book (pack AddressBook address-book)
+ unpacked-address-book (unpack AddressBook packed-address-book)]
+ (assert (= address-book unpacked-address-book)))
+
252 src/simple_avro/core.clj
@@ -0,0 +1,252 @@
+(ns simple-avro.core
+ {:doc "Core namespace defines serialization/de-serialization functions."}
+ (:require (clojure.contrib [json :as json]))
+ (:import (java.io FileOutputStream ByteArrayOutputStream)
+ (org.apache.avro Schema Schema$Type Schema$Field)
+ (org.apache.avro.generic GenericData$EnumSymbol
+ GenericData$Fixed
+ GenericData$Array
+ GenericData$Record
+ GenericDatumWriter
+ GenericDatumReader)
+ (org.apache.avro.io EncoderFactory DecoderFactory)
+ (org.apache.avro.util Utf8)))
+
+
+;
+; Encoding
+;
+
+(declare pack avro-schema)
+
+(defmacro throw-with-log
+ "Throw exception and log helper."
+ {:private true}
+ [ & msg ]
+ `(let [l# ~(last msg)]
+ (if (instance? Exception l#)
+ (throw (Exception. (apply str ~(vec (butlast msg))) l#))
+ (throw (Exception. (str ~@msg))))))
+
+(def #^{:private true}
+ *packers*
+ {Schema$Type/NULL (fn [#^Schema schema obj] nil)
+ Schema$Type/BOOLEAN (fn [#^Schema schema obj] (boolean obj))
+ Schema$Type/INT (fn [#^Schema schema obj] (int obj))
+ Schema$Type/LONG (fn [#^Schema schema obj] (long obj))
+ Schema$Type/FLOAT (fn [#^Schema schema obj] (float obj))
+ Schema$Type/DOUBLE (fn [#^Schema schema obj] (double obj))
+ Schema$Type/BYTES (fn [#^Schema schema obj] (bytes obj))
+
+ Schema$Type/STRING (fn [#^Schema schema obj] (if (string? obj)
+ (Utf8. (str obj))
+ (throw (Exception. (str "'" obj "' is not a string.")))))
+ Schema$Type/FIXED (fn [#^Schema schema obj] (GenericData$Fixed. schema obj))
+
+ Schema$Type/ENUM (fn [#^Schema schema obj]
+ (if-let [enum (some #{obj} (.getEnumSymbols schema))]
+ (GenericData$EnumSymbol. schema enum)
+ (throw-with-log "Enum does not define '" obj "'.")))
+
+ Schema$Type/UNION (fn [#^Schema schema obj]
+ (loop [schemas (.getTypes schema)]
+ (if (empty? schemas)
+ (throw-with-log "No union type defined for object '" obj "'.")
+ (let [rec (try
+ (pack (first schemas) obj)
+ (catch Exception e :not-matching-untion-type))]
+ (if (not= rec :not-matching-untion-type)
+ rec
+ (recur (next schemas)))))))
+
+ Schema$Type/ARRAY (fn [#^Schema schema obj]
+ (let [type-schema (.getElementType schema)
+ array (GenericData$Array. (count obj) schema)]
+ (doseq [e obj] (.add array (pack type-schema e)))
+ array))
+
+ Schema$Type/MAP (fn [#^Schema schema obj]
+ (let [type-schema (.getValueType schema)]
+ (reduce (fn [m [k v]] (assoc m k (pack type-schema v))) {} obj)))
+
+ Schema$Type/RECORD (fn [#^Schema schema obj]
+ (if-let [ks (keys obj)]
+ (let [record (GenericData$Record. schema)]
+ (doseq [#^String k ks]
+ (let [field (.getField schema k)]
+ (.put record k (pack (.schema field) (obj k)))))
+ record)))
+
+ })
+
+(defn- encode-to
+ [#^Schema schema obj encoder result]
+ (let [stream (ByteArrayOutputStream.)
+ writer (GenericDatumWriter. schema)
+ #^java.io.Flushable encoder (encoder schema stream)]
+ (.write writer obj encoder)
+ (.flush encoder)
+ (result stream)))
+
+(defn pack
+ [schema obj & [encoder]]
+ (let [#^Schema schema (avro-schema schema)
+ type (.getType schema)
+ encode (or encoder (fn [_ obj] obj))
+ packer (*packers* type)]
+ (if packer
+ (try
+ (encode schema (packer schema obj))
+ (catch Exception e
+ (throw-with-log "Exception reading object '" obj "' for schema '" schema "'." e)))
+ (throw-with-log "No pack defined for type '" type "'."))))
+
+(def json-encoder
+ (fn [#^Schema schema obj]
+ (encode-to schema obj
+ (fn [#^Schema schema #^ByteArrayOutputStream stream]
+ (.jsonEncoder (EncoderFactory/get) schema stream))
+ (fn [#^ByteArrayOutputStream stream]
+ (.. stream toString)))))
+
+(def binary-encoder
+ (fn [#^Schema schema obj]
+ (encode-to schema obj
+ (fn [#^Schema schema #^ByteArrayOutputStream stream]
+ (.binaryEncoder (EncoderFactory/get) stream nil))
+ (fn [#^ByteArrayOutputStream stream]
+ (.. stream toString getBytes)))))
+
+;
+; Decoding
+;
+
+(declare unpack)
+
+(def #^{:private true}
+ *unpackers*
+ {Schema$Type/NULL (fn [#^Schema schema obj] nil)
+ Schema$Type/BOOLEAN (fn [#^Schema schema obj] (boolean obj))
+ Schema$Type/INT (fn [#^Schema schema obj] (int obj))
+ Schema$Type/LONG (fn [#^Schema schema obj] (long obj))
+ Schema$Type/FLOAT (fn [#^Schema schema obj] (float obj))
+ Schema$Type/DOUBLE (fn [#^Schema schema obj] (double obj))
+ Schema$Type/BYTES (fn [#^Schema schema obj] (bytes obj))
+ Schema$Type/FIXED (fn [#^Schema schema #^GenericData$Fixed obj] (.bytes obj))
+ Schema$Type/ENUM (fn [#^Schema schema obj] (str obj))
+
+ Schema$Type/STRING (fn [#^Schema schema obj] (if (instance? Utf8 obj)
+ (str obj)
+ (throw (Exception. (str "Object '" obj "' is not a Utf8.")))))
+
+ Schema$Type/UNION (fn [#^Schema schema obj]
+ (loop [schemas (.getTypes schema)]
+ (if (empty? schemas)
+ (throw-with-log "No union type defined for object '" obj "'.")
+ (let [rec (try
+ (unpack (first schemas) obj)
+ (catch Exception e :not-matching-untion-type))]
+ (if (not= rec :not-matching-untion-type)
+ rec
+ (recur (next schemas)))))))
+
+ Schema$Type/ARRAY (fn [#^Schema schema obj]
+ (let [type-schema (.getElementType schema)]
+ (vec (map #(unpack type-schema %) obj))))
+
+ Schema$Type/MAP (fn [#^Schema schema obj]
+ (let [type-schema (.getValueType schema)]
+ (reduce (fn [m [k v]] (assoc m (str k) (unpack type-schema v))) {} obj)))
+
+ Schema$Type/RECORD (fn [#^Schema schema #^GenericData$Record obj]
+ (reduce (fn [m #^Schema$Field f]
+ (let [k (.name f)]
+ (assoc m k (unpack (.schema f) (.get obj k)))))
+ {} (.getFields schema)))
+ })
+
+(defn- decode-from
+ [schema obj decoder]
+ (let [stream (ByteArrayOutputStream.)
+ reader (GenericDatumReader. schema)
+ decoder (decoder schema obj)]
+ (.read reader nil decoder)))
+
+(defn unpack
+ [schema obj & [decoder]]
+ (let [#^Schema schema (avro-schema schema)
+ type (.getType schema)
+ decode (or decoder (fn [_ obj] obj))
+ unpacker (*unpackers* type)
+ obj (decode schema obj)]
+ (if unpacker
+ (try
+ (unpacker schema obj)
+ (catch Exception e
+ (throw-with-log "Exception unpacking object '" obj "' for schema '" schema "'." e)))
+ (throw-with-log "No unpack defined for type '" type "'."))))
+
+(def json-decoder
+ (fn [#^Schema schema obj]
+ (decode-from schema obj
+ (fn [#^Schema schema #^String obj]
+ (.jsonDecoder (DecoderFactory/get) schema obj)))))
+
+(def binary-decoder
+ (fn [#^Schema schema obj]
+ (decode-from schema obj
+ (fn [#^Schema schema #^bytes obj]
+ (.binaryDecoder (DecoderFactory/get) obj nil)))))
+
+;
+; Avro schema generation
+;
+
+(def named-types nil)
+
+(defn- traverse-schema
+ "Traverse types of a schema."
+ [schema f]
+ (cond
+ (vector? schema)
+ (vec (map #(f %) schema))
+
+ (map? schema)
+ (case (:type schema)
+ "array" (assoc schema :items (f (:items schema)))
+ "map" (assoc schema :values (f (:values schema)))
+ "record" (assoc schema :fields (vec (map #(assoc % :type (f (:type %))) (:fields schema))))
+ schema)
+ :else schema))
+
+(defn- flatten-named-types
+ "Ensures a named type is only defined once."
+ [schema]
+ (if-let [name (:name schema)]
+ (if (some @named-types [name])
+ name
+ (let [schema (traverse-schema schema flatten-named-types)]
+ (swap! named-types conj name)
+ schema))
+ (traverse-schema schema flatten-named-types)))
+
+(defn avro-schema
+ "Convert a simple-avro or json string schema to Avro schema object."
+ [schema]
+ (cond
+ (instance? Schema schema)
+ schema
+ (string? schema)
+ (Schema/parse #^String schema)
+ :else
+ (let [schema (binding [named-types (atom #{})]
+ (flatten-named-types schema))]
+ (Schema/parse #^String (json/json-str schema)))))
+
+(defn json-schema
+ "Print schema to a json string. Provide optional parameter {:pretty bool}
+ for pretty printing. Default is false."
+ [schema & [opts]]
+ (let [pretty (or (:pretty opts) false)]
+ (.toString #^Schema (avro-schema schema) pretty)))
+
101 src/simple_avro/schema.clj
@@ -0,0 +1,101 @@
+(ns simple-avro.schema
+ {:doc "Avro 1.5 schema specification.
+ See http://avro.apache.org/docs/1.5.0/spec.html for details."}
+ (:use (clojure.contrib [string :only (as-str)]
+ [json :only (json-str)])))
+
+(defmacro avro-type
+ "Standard type declaration."
+ [type]
+ `{:type ~type})
+
+; Primitive types
+
+(defmacro avro-prim
+ "Primitive types declaration helper."
+ {:private true}
+ [type]
+ `(def ~(symbol (str "avro-" type))
+ (avro-type ~(str type))))
+
+; Primitive types
+(avro-prim null)
+(avro-prim boolean)
+(avro-prim int)
+(avro-prim long)
+(avro-prim float)
+(avro-prim double)
+(avro-prim bytes)
+(avro-prim string)
+
+; Complex types
+
+(defn avro-array
+ [type]
+ {:type "array" :items type})
+
+(defn avro-map
+ [type]
+ {:type "map" :values type})
+
+(defn avro-union
+ [ & types]
+ (vec types))
+
+; Named types
+
+(defn avro-record
+ [name & decl]
+ (let [schema {:type "record"
+ :name name}
+ [schema decl] (if (map? (first decl))
+ [(merge (first decl) schema) (next decl)]
+ [schema decl])]
+ (assoc schema :fields
+ (loop [d decl fields []]
+ (if (empty? d)
+ fields
+ (let [[field d] [{:name (as-str (first d))
+ :type (first (next d))}
+ (drop 2 d)]
+ [field d] (if (map? (first d))
+ [(merge (first d) field) (next d)]
+ [field d])]
+ (recur d (conj fields field))))))))
+
+(defn avro-enum
+ [name & decl]
+ (let [schema {:type "enum"
+ :name name}
+ [schema decl] (if (map? (first decl))
+ [(merge (first decl) schema) (next decl)]
+ [schema decl])]
+ (assoc schema :symbols (vec (clojure.core/map as-str decl)))))
+
+(defn avro-fixed
+ [name size & [opts]]
+ (let [schema {:type "fixed"
+ :size size
+ :name name}]
+ (if opts
+ (merge opts schema)
+ schema)))
+
+; Convenient named type declaration macros
+
+(defmacro defavro-record
+ [name & decl]
+ `(def ~name
+ (avro-record ~(str name) ~@decl)))
+
+(defmacro defavro-enum
+ [name & decl]
+ `(def ~name
+ (avro-enum ~(str name) ~@decl)))
+
+
+(defmacro defavro-fixed
+ [name size & [opts]]
+ `(def ~name
+ (avro-fixed ~(str name) ~size ~opts)))
+
66 src/simple_avro/utils.clj
@@ -0,0 +1,66 @@
+(ns simple-avro.utils
+ {:doc "General utils."}
+ (:use (simple-avro core))
+ (:require (clojure.contrib [json :as json]))
+ (:import (org.apache.avro Schema Schema$Type)
+ (org.apache.avro.file CodecFactory
+ DataFileWriter
+ DataFileReader)
+ (org.apache.avro.generic GenericDatumWriter
+ GenericDatumReader)
+ (java.io File)
+ (java.net URI URL)
+ (java.util NoSuchElementException)))
+
+(defmulti #^{:private true}
+ file class)
+
+(defmethod file File [f]
+ f)
+
+(defmethod file String [f]
+ (File. f))
+
+(defmethod file URL [f]
+ (file (.getPath f)))
+
+(defmethod file URI [f]
+ (file (.toURL f)))
+
+(defn write-file
+ "Write to Avro data file."
+ [f schema objs & [meta]]
+ (let [schema (avro-schema schema)
+ writer (DataFileWriter. (GenericDatumWriter. schema))]
+ (try
+ (.setCodec writer (CodecFactory/deflateCodec 6))
+ (doseq [[k v] meta]
+ (.setMeta writer (str k) (str v)))
+ (.create writer schema (file f))
+ (doseq [o objs]
+ (.append writer (pack schema o)))
+ (finally
+ (.close writer)))))
+
+(defn read-file
+ "Read data from Avro data file."
+ [f]
+ (let [reader (DataFileReader. (file f) (GenericDatumReader.))
+ schema (.getSchema reader)
+ read-next (fn read-next [reader]
+ (try
+ (cons (unpack schema (.next reader)) (read-next reader))
+ (catch Exception e nil)
+ (finally
+ (.close reader))))]
+ (read-next reader)))
+
+(defn read-meta
+ "Read meta from Avro data file."
+ [f]
+ (let [reader (DataFileReader. (file f) (GenericDatumReader.))]
+ (loop [[k & ks] (.getMetaKeys reader) mta {}]
+ (if (nil? k)
+ mta
+ (recur ks (assoc mta k (String. (.getMeta reader k) "UTF-8")))))))
+
83 test/simple_avro/core_tests.clj
@@ -0,0 +1,83 @@
+(ns simple-avro.core-tests
+ (:use (simple-avro schema core)
+ (clojure test)))
+
+(deftest test-prim-types
+ (is (= (pack avro-null nil) nil))
+ (is (= (pack avro-null 5) nil))
+ (is (= (pack avro-boolean true) true))
+ (is (= (pack avro-boolean nil) false))
+ (is (= (pack avro-int 5) 5))
+ (is (= (pack avro-long 10) (long 10)))
+ (is (= (pack avro-long (long 10)) (long 10)))
+ (is (= (pack avro-float 2.5) (float 2.5)))
+ (is (= (pack avro-float (float 2.5)) (float 2.5)))
+ (is (= (pack avro-double 2.5) (double 2.5)))
+ (is (= (pack avro-double (double 2.5)) (double 2.5)))
+ (is (= (str (pack avro-string "test")) "test")))
+
+; Some types
+(def bool-array (avro-array avro-boolean))
+(def int-map (avro-map avro-int))
+(def a-union (avro-union avro-string avro-int avro-null))
+
+(defavro-fixed MyFixed 2)
+
+(defavro-enum MyEnum "A" "B" "C")
+
+(defavro-record MyRecord
+ "f1" avro-int
+ "f2" avro-string)
+
+(defavro-record MyNestedRecord
+ "f1" avro-int
+ "f2" avro-string)
+
+(defavro-record List
+ "value" avro-int
+ "next" (avro-union "List" avro-null))
+
+(def recursive
+ {"value" 1
+ "next" {"value" 2
+ "next" {"value" 3
+ "next" nil}}})
+
+(defmacro test-pack-unpack
+ [name encoder decoder]
+ `(deftest ~name
+ (is (= (unpack avro-null (pack avro-null nil ~encoder) ~decoder) nil))
+ (is (= (unpack avro-null (pack avro-null 5 ~encoder) ~decoder) nil))
+ (is (= (unpack avro-boolean (pack avro-boolean true ~encoder) ~decoder) true))
+ (is (= (unpack avro-int (pack avro-int 5 ~encoder) ~decoder) 5))
+ (is (= (unpack avro-long (pack avro-long 10 ~encoder) ~decoder) (long 10)))
+ (is (= (unpack avro-float (pack avro-float 2.5 ~encoder) ~decoder) (float 2.5)))
+ (is (= (unpack avro-double (pack avro-double 2.5 ~encoder) ~decoder) (double 2.5)))
+ (is (= (str (unpack avro-string (pack avro-string "test" ~encoder) ~decoder)) "test"))
+
+ (is (= (unpack bool-array (pack bool-array [true false false] ~encoder) ~decoder) [true false false]))
+ (is (= (unpack int-map (pack int-map {"a" 1 "b" 2} ~encoder) ~decoder) {"a" 1 "b" 2}))
+
+ (is (= (unpack a-union (pack a-union "test" ~encoder) ~decoder) "test"))
+ (is (= (unpack a-union (pack a-union 10 ~encoder) ~decoder) 10))
+
+ (let [pu# (unpack MyFixed (pack MyFixed (byte-array [(byte 1) (byte 2)]) ~encoder) ~decoder)]
+ (is (= (nth pu# 0) 1))
+ (is (= (nth pu# 1) 2)))
+
+ (is (= (unpack MyEnum (pack MyEnum "A" ~encoder) ~decoder) "A"))
+ (is (= (unpack MyEnum (pack MyEnum "B" ~encoder) ~decoder) "B"))
+ (is (= (unpack MyEnum (pack MyEnum "C" ~encoder) ~decoder) "C"))
+
+ (let [pu# (unpack MyRecord (pack MyRecord {"f1" 6 "f2" "test"} ~encoder) ~decoder)]
+ (is (= (pu# "f1") 6))
+ (is (= (pu# "f2") "test")))
+
+ (is (= (unpack List (pack List recursive ~encoder) ~decoder) recursive))
+
+ ))
+
+(test-pack-unpack test-prim-types-pack-unpack-no-decoder nil nil)
+(test-pack-unpack test-prim-types-pack-unpack-json json-encoder json-decoder)
+(test-pack-unpack test-prim-types-pack-unpack-binary binary-encoder binary-decoder)
+
65 test/simple_avro/schema_tests.clj
@@ -0,0 +1,65 @@
+(ns simple-avro.schema-tests
+ (:use (simple-avro schema core)
+ (clojure test)))
+
+(deftest test-prim-types
+ (is (= avro-null {:type "null"}))
+ (is (= avro-boolean {:type "boolean"}))
+ (is (= avro-int {:type "int"}))
+ (is (= avro-long {:type "long"}))
+ (is (= avro-float {:type "float"}))
+ (is (= avro-double {:type "double"}))
+ (is (= avro-bytes {:type "bytes"}))
+ (is (= avro-string {:type "string"})))
+
+(deftest test-complex-types
+ (is (= (avro-array avro-int) {:type "array" :items {:type "int"}}))
+ (is (= (avro-map avro-string) {:type "map" :values {:type "string"}}))
+ (is (= (avro-union avro-string avro-int avro-null)
+ [{:type "string"} {:type "int"} {:type "null"}])))
+
+(deftest test-named-types
+ (is (= (avro-fixed "MyFixed" 16)
+ {:type "fixed" :size 16 :name "MyFixed"}))
+ (is (= (avro-enum "MyEnum" "A" "B" "C")
+ {:type "enum" :symbols ["A" "B" "C"] :name "MyEnum"}))
+ (is (= (avro-record "MyRecord"
+ "f1" avro-int
+ "f2" avro-string)
+ {:type "record"
+ :name "MyRecord"
+ :fields [{:name "f1" :type {:type "int"}}
+ {:name "f2" :type {:type "string"}}]})))
+
+(defavro-fixed MyDefFixed 16)
+
+(defavro-enum MyDefEnum "A" "B" "C")
+
+(defavro-record MyDefRecord
+ "f1" avro-int
+ "f2" avro-string)
+
+(deftest test-defavro
+ (is (= MyDefFixed {:type "fixed" :size 16 :name "MyDefFixed"}))
+ (is (= MyDefEnum {:type "enum" :symbols ["A" "B" "C"] :name "MyDefEnum"}))
+ (is (= MyDefRecord
+ {:type "record"
+ :name "MyDefRecord"
+ :fields [{:name "f1" :type {:type "int"}}
+ {:name "f2" :type {:type "string"}}]})))
+
+
+(deftest test-opts
+ (is (= (avro-fixed "MyFixed" 16 {:namespace "test-namespace"})
+ {:type "fixed" :size 16 :name "MyFixed" :namespace "test-namespace"}))
+ (is (= (avro-enum "MyEnum" {:namespace "test-namespace"} "A" "B" "C")
+ {:type "enum" :symbols ["A" "B" "C"] :name "MyEnum" :namespace "test-namespace"}))
+ (is (= (avro-record "MyRecord" {:namespace "test-namespace"}
+ "f1" avro-int
+ "f2" avro-string)
+ {:type "record"
+ :name "MyRecord"
+ :namespace "test-namespace"
+ :fields [{:name "f1" :type {:type "int"}}
+ {:name "f2" :type {:type "string"}}]})))
+
23 test/simple_avro/utils_tests.clj
@@ -0,0 +1,23 @@
+(ns simple-avro.utils-tests
+ (:use (simple-avro schema core utils)
+ (clojure test)))
+
+(defavro-record Test
+ "field1" avro-string
+ "field2" avro-int)
+
+(def test-records
+ [{"field1" "record1" "field2" 10}
+ {"field1" "record2" "field2" 20}
+ {"field1" "record3" "field2" 30}
+ {"field1" "record4" "field2" 40}])
+
+(deftest read-write-test
+ (let [file (java.io.File/createTempFile "avro-test-data", ".tmp")
+ _ (write-file file Test test-records {"m1" "test1" "m2" "test2"})
+ content (read-file file)
+ meta (read-meta file)]
+ (is (= content test-records))
+ (is (= (meta "m1") "test1"))
+ (is (= (meta "m2") "test2"))))
+

0 comments on commit 08759da

Please sign in to comment.