Skip to content

Instantly share code, notes, and snippets.

@joeatwork
Created February 16, 2012 16:57
Show Gist options
  • Save joeatwork/1846438 to your computer and use it in GitHub Desktop.
Save joeatwork/1846438 to your computer and use it in GitHub Desktop.
I needed mmencode but didn't have it. Clojure nubware over Apache Geronimo to encode plain text as quoted-printable.
(ns workstationClojure.quoted-printable
(:require [clojure.java.io :as jio])
(:import [java.io ByteArrayOutputStream ByteArrayInputStream]
[org.apache.geronimo.mail.util QuotedPrintableEncoder]))
;; http://geronimo.apache.org/maven/specs/geronimo-javamail_1.4_spec/1.6/apidocs/org/apache/geronimo/mail/util/QuotedPrintableEncoder.html
;; In project.clj,
;; [geronimo/geronimo-mail "1.1"]
;; Geronimo's API is asymmetric, and in somewhat weasily ways, so we
;; need two differently shaped driver loops. In particular,
;; QuotedPrintableEncoder.decode(buffer, offset, len, out)
;; requires the entire message to be in buffer, which defeats
;; the streaminess of these guys.
(defn qp-streams! [instream outstream]
(let [buffer (byte-array 1024)
encoder (QuotedPrintableEncoder.)]
(loop [bytes-read (. instream read buffer)
bytes-wrote 0]
(if (= -1 bytes-read)
(inc bytes-wrote)
(do
(. encoder encode buffer 0 bytes-read outstream)
(recur (. instream read buffer) (+ bytes-read bytes-wrote)))))))
(defn unqp-streams! [instream outstream]
(let [decoder (QuotedPrintableEncoder.)]
(loop [byte-decoded (decoder instream)
bytes-wrote 0]
(if (= -1 byte-decoded)
bytes-wrote
(do
(outstream write byte-decoded)
(recur (decoder instream) (inc bytes-wrote)))))))
(defn- shovel-bytes-from-string [ ^String instring ^String encoding processor!]
(let [inbytes (ByteArrayInputStream. (. instring getBytes))
outbytes (ByteArrayOutputStream.)]
(processor! inbytes outbytes)
(. outbytes toString encoding)))
(defn- shovel-files [infile outfile processor!]
(with-open [ins (jio/input-stream infile)]
(with-open [outs (jio/output-stream outfile )]
(processor! ins outs))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn qp-files! [infile outfile]
(shovel-files infile outfile qp-streams!))
(defn unqp-files! [infile outfile]
(shovel-files infile outfile unqp-streams!))
(defn qp [instring]
(shovel-bytes-from-string instring "US-ASCII" qp-streams!))
(defn unqp [instring & encoding]
(shovel-bytes-from-string instring encoding unqp-streams!))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment