Skip to content

Instantly share code, notes, and snippets.

@kommen
Last active December 20, 2017 18:42
Show Gist options
  • Save kommen/4d57c92c16373180443cbde09b005f26 to your computer and use it in GitHub Desktop.
Save kommen/4d57c92c16373180443cbde09b005f26 to your computer and use it in GitHub Desktop.
#!/bin/bash
abs_bin_dir="$(cd "$(dirname "$0")" && pwd)"
FILE="${abs_bin_dir}/zprint-filter-0.4.4"
# check if zprint server port is reachable
ncat -z 127.0.0.1 7877
if [ $? == 0 ]; then
ncat 127.0.0.1 7877 <&0
else
if [ -f $FILE ]; then
java -Xbootclasspath/a:$FILE zprint.main '{:style :community}' <&0
else
curl --location --silent --output $FILE "https://github.com/kkinnear/zprint/releases/download/0.4.4/zprint-filter-0.4.4"
java -Xbootclasspath/a:$FILE zprint.main '{:style :community}' <&0
fi
fi
(ns server.zprint-server
(:require [zprint.core :as zprint]
[clojure.java.io :as io])
(:import [java.net InetAddress Socket ServerSocket SocketException]))
(defmacro ^:private thread
[^String name daemon & body]
`(doto (Thread. (fn [] ~@body) ~name)
(.setDaemon ~daemon)
(.start)))
(defn- read-all-lines [in]
(let [sw (java.io.StringWriter.)]
(io/copy in sw)
(.toString sw)))
(defn- accept-connection
"Start accept function, to be invoked on a client thread, given:
conn - client socket
in - in stream
out - out stream
err - err stream"
[^Socket conn in out err]
(let [contents (read-all-lines in)]
(try (spit out (zprint/zprint-file-str contents "<stdin>"))
(catch clojure.lang.ExceptionInfo e (spit out contents))
(catch SocketException _disconnect)
(finally (.close conn)))))
(defn start-server
"Start a zprint server given the specified opts:
:address Host or address, string, defaults to loopback address
:port Port, integer, required
:bind-err Bind *err* to socket out stream?, defaults to true
Returns a socket."
[opts]
(let [{:keys [address port bind-err]
:or {bind-err true}} opts
address (InetAddress/getByName address) ;; nil returns loopback
socket (ServerSocket. port 0 address)]
(thread
(str "zprint Server ")
true
(try
(loop [client-counter 1]
(when (not (.isClosed socket))
(try
(let [conn (.accept socket)
in (.getInputStream conn)
out (java.io.BufferedWriter. (java.io.OutputStreamWriter. (.getOutputStream conn)))
client-id (str client-counter)]
(thread
(str "zprint client " client-counter)
true
(accept-connection conn in out (if bind-err out *err*))))
(catch SocketException _disconnect))
(recur (inc client-counter))))))
socket))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment