1 | ;; simple wrappers for jakarta's ftp client |
2 |
|
3 | ;; TODO: keep checking reply codes, throw exception if not OK |
4 |
|
5 | (ns com.github.kyleburton.sandbox.ftp |
6 | (:import (org.apache.commons.net.ftp FTP FTPClient) |
7 | (java.net URL)) |
8 | (:use [ clojure.contrib.str-utils :as str])) |
9 |
|
10 | (defmulti open "Open an ftp connection." class) |
11 |
|
12 | (defmethod open String [s] |
13 | (open (java.net.URL. s))) |
14 |
|
15 | (defmethod open URL [url] |
16 | (let [client (FTPClient.)] |
17 | (.connect client |
18 | (.getHost url) |
19 | (if (= -1 (.getPort url)) |
20 | (.getDefaultPort url) |
21 | (.getPort url))) |
22 | client)) |
23 |
|
24 | (defmacro with-ftp [[client url & extra-bindings] & body] |
25 | `(let [u# (URL. ~url) |
26 | ~client (open u#) |
27 | res# (atom nil) |
28 | ~@extra-bindings] |
29 | (if (.getUserInfo u#) |
30 | (let [[uname# pass#] (.split (.getUserInfo u#) ":" 2)] |
31 | (.login ~client uname# pass#))) |
32 | (.changeWorkingDirectory ~client (.getPath u#)) |
33 | (.setFileType ~client FTP/BINARY_FILE_TYPE) |
34 | (reset! res# |
35 | (do |
36 | ~@body)) |
37 | (.disconnect ~client) |
38 | @res#)) |
39 |
|
40 | (defn list-all [url] |
41 | (with-ftp [client url] |
42 | (map #(.getName %) (.listFiles client)))) |
43 |
|
44 | (defn list-files [url] |
45 | (with-ftp [client url] |
46 | (map #(.getName %) (filter #(.isFile %) (.listFiles client))))) |
47 |
|
48 | (defn list-directories [url] |
49 | (with-ftp [client url] |
50 | (map #(.getName %) (filter #(.isDirectory %) (.listFiles client))))) |
51 |
|
52 | (defn retrieve-file [url fname & [local-file]] |
53 | (with-ftp [client url] |
54 | (if local-file |
55 | (with-open [outstream (java.io.FileOutputStream. local-file)] |
56 | (.retrieveFile client fname outstream)) |
57 | (.retrieveFile client fname)))) |
58 |
|
59 | ;; (retrieve-file "ftp://anonymous:user%40host.com@ftp2.census.gov/geo/tiger/TIGER2008/42_PENNSYLVANIA/" "tl_2008_42_place.zip" "/home/mortis/tl_2008_42_place.zip") |
60 | ;; (list-files "ftp://anonymous:user%40host.com@ftp2.census.gov/geo/tiger/TIGER2008/42_PENNSYLVANIA/") |