-
Notifications
You must be signed in to change notification settings - Fork 202
/
core.clj
1119 lines (1017 loc) · 38.7 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns amazonica.core
"Amazon AWS functions."
(:use [clojure.algo.generic.functor :only (fmap)])
(:require [clojure.string :as str]
[clojure.java.io :as io])
(:import clojure.lang.Reflector
[com.amazonaws
AmazonServiceException
ClientConfiguration]
[com.amazonaws.auth
AWSCredentials
AWSCredentialsProvider
AWSStaticCredentialsProvider
BasicAWSCredentials
BasicSessionCredentials
DefaultAWSCredentialsProviderChain]
[com.amazonaws.util
AwsHostNameUtils]
com.amazonaws.auth.profile.ProfileCredentialsProvider
[com.amazonaws.regions
Region
Regions
DefaultAwsRegionProviderChain]
com.amazonaws.client.builder.AwsClientBuilder
com.amazonaws.client.builder.AwsClientBuilder$EndpointConfiguration
org.joda.time.DateTime
org.joda.time.base.AbstractInstant
java.io.File
java.io.PrintWriter
java.io.StringWriter
java.lang.reflect.InvocationTargetException
java.lang.reflect.ParameterizedType
java.lang.reflect.Method
java.lang.reflect.Modifier
java.lang.reflect.Constructor
java.lang.reflect.Parameter
java.math.BigDecimal
java.math.BigInteger
java.nio.ByteBuffer
java.text.ParsePosition
java.text.SimpleDateFormat
java.util.Date))
(defonce ^:private credential (atom {}))
(defonce ^:private client-config (atom {}))
(def ^:dynamic ^:private *credentials* nil)
(def ^:dynamic ^:private *client-config* nil)
(def ^:dynamic ^:private *client-class* nil)
(def ^:private date-format (atom "yyyy-MM-dd"))
(def ^:private root-unwrapping (atom false))
(defn- invoke-constructor
[class-name arg-vec]
(Reflector/invokeConstructor
(Class/forName class-name)
(into-array Object arg-vec)))
(defn set-root-unwrapping!
"Enables JSON-like root unwrapping of singly keyed
top level maps.
{:root {:key 'foo' :name 'bar'}}
would become
{:key 'foo' :name 'bar'}"
[b]
(reset! root-unwrapping b))
(defn set-date-format!
"Sets the java.text.SimpleDateFormat pattern to use
for transparent coercion of Strings passed as
arguments where java.util.Dates are required by the
AWS api."
[df]
(reset! date-format df))
(defn stack->string
"Converts a Java stacktrace to String representation."
[^Throwable ex]
(let [sw (StringWriter.)
pw (PrintWriter. sw)
_ (.printStackTrace ex pw)]
(.toString sw)))
(defn ex->map
"Converts a com.amazonaws.AmazonServiceException to a
Clojure map with keys:
:error-code
:error-type
:status-code
:request-id
:service-name
:message
:stack-trace"
[^AmazonServiceException e]
{:error-code (.getErrorCode e)
:error-type (.toString (.getErrorType e))
:status-code (.getStatusCode e)
:request-id (.getRequestId e)
:service-name (.getServiceName e)
:message (.getMessage e)
:stack-trace (stack->string e)})
(defn keys->cred
[access-key secret-key & [endpoint]]
(let [credential {:access-key access-key
:secret-key secret-key}]
(if-not (empty? endpoint)
(merge credential {:endpoint endpoint})
credential)))
(defn defcredential
"Specify the AWS access key, secret key and optional
endpoint to use on subsequent requests."
([cred]
(reset! credential cred))
([access-key secret-key & [endpoint]]
(defcredential (keys->cred access-key secret-key endpoint))))
(defn defclientconfig
"Specify the default Client configuration to use on
subsequent requests."
[config]
(reset! client-config config))
(defmacro with-credential
"Per invocation binding of credentials for ad-hoc
service calls using alternate user/password combos
(and endpoints)."
[cred & body]
`(binding [*credentials*
(let [cred# ~cred]
(if (sequential? cred#)
(apply keys->cred cred#)
cred#))]
(do ~@body)))
(defmacro with-client-config
"Per invocation binding of client-config for ad-hoc
service calls using alternate client configuration."
[config & body]
`(binding [*client-config* ~config]
(do ~@body)))
(defn- get-default-region
"Get the AWS region
Takes AWS_DEFAULT_REGION as the first priority to match old behaviour. Otherwise, see
https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#default-region-provider-chain
for region selection order."
[]
(or
(System/getenv "AWS_DEFAULT_REGION")
(-> (DefaultAwsRegionProviderChain.)
(.getRegion))))
(defn- builder ^AwsClientBuilder [^Class clazz]
(let [^Method method (.getMethod clazz "builder" (make-array Class 0))]
(.invoke method clazz (make-array Object 0))))
(declare set-fields)
(defn- build-client [^Class clazz credentials configuration raw-creds options]
(let [default-region (get-default-region)
builder (builder clazz)
_ (set-fields builder options)
builder (if credentials (.withCredentials builder credentials) builder)
builder (if configuration (.withClientConfiguration builder configuration) builder)
^String endpoint (or (:endpoint raw-creds) default-region)
builder (if endpoint
(if (.startsWith endpoint "http")
(.withEndpointConfiguration
builder
(AwsClientBuilder$EndpointConfiguration. endpoint (or (AwsHostNameUtils/parseRegion endpoint nil) default-region)))
(.withRegion builder endpoint))
builder)]
(.build builder)))
(defn- create-client
[^Class clazz credentials configuration raw-creds options]
(if (= (.getSimpleName clazz) "TransferManager")
(invoke-constructor
"com.amazonaws.services.s3.transfer.TransferManager"
[(create-client (Class/forName "com.amazonaws.services.s3.AmazonS3Client")
credentials
configuration
raw-creds {})])
(build-client clazz credentials configuration raw-creds options)))
(defn get-credentials ^AWSCredentialsProvider
[credentials]
(cond
(instance? AWSCredentialsProvider credentials)
credentials
(instance? AWSCredentials credentials)
(AWSStaticCredentialsProvider. credentials)
(and (associative? credentials)
(contains? credentials :session-token))
(AWSStaticCredentialsProvider.
(BasicSessionCredentials.
(:access-key credentials)
(:secret-key credentials)
(:session-token credentials)))
(and (associative? credentials)
(contains? credentials :access-key))
(AWSStaticCredentialsProvider.
(BasicAWSCredentials.
(:access-key credentials)
(:secret-key credentials)))
(and (associative? credentials)
(contains? credentials :profile))
(ProfileCredentialsProvider.
(:profile credentials))
(and (associative? credentials)
(instance? AWSCredentialsProvider (:cred credentials)))
(:cred credentials)
:else
(DefaultAWSCredentialsProviderChain/getInstance)))
(defn parse-args
"Legacy support means credentials may or may not be passed
as the first argument."
[cred args]
(if (and (instance? AWSCredentialsProvider (get-credentials cred))
(not (instance? AWSCredentialsProvider cred))
(nil? (:endpoint cred))
(nil? (:profile cred)))
{:args (conj args cred)}
{:args args :cred cred}))
(declare create-bean)
(defn- get-client-configuration
[configuration]
(when (associative? configuration)
(create-bean ClientConfiguration configuration)))
(defn- get-region ^Regions
[credentials]
(when-let [endpoint (or (:endpoint credentials)
(get-default-region))]
(if (contains? (fmap #(-> % str/upper-case (str/replace "_" ""))
(apply hash-set (seq (Regions/values))))
(-> (str/upper-case endpoint)
(str/replace "-" "")))
(try
(->> (-> (str/upper-case endpoint)
(str/replace "-" "_"))
Regions/valueOf)
(catch NoSuchMethodException e
(println e))))))
(defn encryption-client*
[encryption credentials configuration]
(let [creds (get-credentials credentials)
config (get-client-configuration configuration)
key (or (:secret-key encryption)
(:key-pair encryption)
(:kms-customer-master-key encryption))
crypto (invoke-constructor
"com.amazonaws.services.s3.model.CryptoConfiguration" [])
_ (when (:kms-customer-master-key encryption)
(.setAwsKmsRegion crypto (Region/getRegion (get-region {:endpoint (:region key)})) ))
em (when-not (:kms-customer-master-key encryption)
(invoke-constructor "com.amazonaws.services.s3.model.EncryptionMaterials"
[key]))
materials (if (:kms-customer-master-key encryption)
(invoke-constructor "com.amazonaws.services.s3.model.KMSEncryptionMaterialsProvider"
[(:id key)])
(invoke-constructor
"com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider"
[em]))
_ (if-let [provider (:provider encryption)]
(.withCryptoProvider crypto provider))
client (if config
(invoke-constructor
"com.amazonaws.services.s3.AmazonS3EncryptionClient"
[creds materials config crypto])
(invoke-constructor
"com.amazonaws.services.s3.AmazonS3EncryptionClient"
[creds materials crypto]))]
client))
(swap! client-config assoc :encryption-client-fn (memoize encryption-client*))
(defn amazon-client*
[clazz credentials configuration]
(let [aws-creds (get-credentials credentials)
aws-config (get-client-configuration configuration)
client (create-client clazz aws-creds aws-config credentials configuration)]
client))
(swap! client-config assoc :amazon-client-fn (memoize amazon-client*))
(defn- keyword-converter
"Given something that tokenizes a string into parts, turn it into
a :kebab-case-keyword."
[separator-regex]
(fn [s]
(->> (str/split s separator-regex)
(map str/lower-case)
(interpose \-)
str/join
keyword)))
(def ^:private camel->keyword
"from Emerick, Grande, Carper 2012 p.70"
(keyword-converter #"(?<=[a-z])(?=[A-Z])"))
(def ^:private camel->keyword2
"Like [[camel->keyword]], but smarter about acronyms and concepts like iSCSI
and OpenID which should be treated as a single concept."
(comp
(keyword-converter #"(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")
#(str/replace % #"(?i)iscsi" "ISCSI")
#(str/replace % #"(?i)openid" "OPENID")))
(defn- ^String keyword->camel
[kw]
(let [n (name kw)
m (.replace n "?" "")]
(->> (str/split m #"\-")
(fmap str/capitalize)
str/join)))
(defn- aws-package?
[^Class clazz]
(->> (.getName clazz)
(re-find #"com\.amazonaws\.services")
some?))
(defn to-date
[date]
(cond
(instance? java.util.Date date) date
(instance? AbstractInstant date) (.toDate ^AbstractInstant date)
(integer? date) (java.util.Date. (long date))
true (.. (SimpleDateFormat. @date-format)
(parse (str date) (ParsePosition. 0)))))
(defn to-file
[file]
(if (instance? File file)
file
(if (string? file)
(File. ^String file))))
(defn to-enum
"Case-insensitive resolution of Enum types by String."
^java.lang.Enum [^Class type value]
(some
(fn [^java.lang.Enum en]
(if (and
(not (nil? (.toString en))) ; some aws enums return nil!
(= (str/upper-case value)
(str/upper-case (.toString en))))
en))
(-> type
(.getDeclaredMethod "values" (make-array Class 0))
(.invoke type (make-array Object 0)))))
; assoc java Class to Clojure cast functions
(defonce ^:private coercions
(->> [:String :Integer :Long :Double :Float]
(reduce
(fn [m e]
(let [arr (str "[Ljava.lang." (name e) ";")
clazz (Class/forName arr)]
(assoc m clazz into-array))) {})
(merge {
String str
Integer int
Long long
Boolean boolean
Double double
Float float
BigDecimal bigdec
BigInteger bigint
Date to-date
File to-file
Region #(Region/getRegion (Regions/fromName %))
ByteBuffer #(-> % str .getBytes ByteBuffer/wrap)
"int" int
"long" long
"double" double
"float" float
"boolean" boolean})
atom))
(defn register-coercions
"Accepts key/value pairs of class/function, which defines
how data will be converted to the appropriate type
required by the AWS Amazon*Client Java method."
[& {:as coercion}]
(swap! coercions merge coercion))
(defn coerce-value
"Coerces the supplied stringvalue to the required type as
defined by the AWS method signature. String or keyword
conversion to Enum types (e.g. via valueOf()) is supported."
[value ^Class type]
(let [value (if (keyword? value) (name value) value)]
(if-not (instance? type value)
(if (= java.lang.Enum (.getSuperclass type))
(to-enum type value)
(if-let [coercion (@coercions (if (.isPrimitive type)
(str type)
type))]
(coercion value)
(throw (IllegalArgumentException.
(format "No coercion is available to turn %s into an object of type %s"
value type)))))
value)))
(defn- default-value
[class-name]
(get
{"boolean" false
"double" (double 0.0)
"float" (float 0.0)
"long" 0
"int" (int 0)}
class-name))
(defn- constructor-args
[^Constructor ctor]
(let [types (.getParameterTypes ctor)]
(if (= 0 (count types))
(make-array Object 0)
(into-array Object
(map
(comp default-value str)
(seq types))))))
(defn best-constructor
"Prefer no-arg ctor if one exists, else the first found."
^Constructor [^Class clazz]
{:pre [clazz]}
(let [ctors (.getConstructors clazz)]
(or
(some
(fn [^Constructor ctor]
(when (= 0 (count (.getParameterTypes ctor))) ctor))
ctors)
(first (sort-by
(fn [^Constructor ctor]
(some aws-package? (.getParameterTypes ctor)))
ctors)))))
(defn- new-instance
"Create a new instance of a Java bean. S3 neccessitates
the check for contructor args here, as the rest of the
AWS api contains strictly no-arg ctor JavaBeans."
[clazz]
{:pre [clazz]}
(let [ctor (best-constructor clazz)
arr (constructor-args ctor)]
(.newInstance ctor arr)))
(defn- unwind-types
[depth param]
(if (instance? ParameterizedType param)
(let [f (partial unwind-types (inc depth))
types (-> ^ParameterizedType param .getActualTypeArguments)
t (-> types last f)]
(if (and (instance? ParameterizedType (last types))
(.contains (-> types last str) "java.util")
(.contains (-> types last str) "java.lang"))
{:type [(-> types ^ParameterizedType last .getRawType)]
:depth depth}
t))
{:type [param]
:depth depth}))
(defn- paramter-types
[^Method method]
(let [types (seq (.getGenericParameterTypes method))
param (last types)
rval {:generic types}]
(if (instance? ParameterizedType param)
(let [t (unwind-types 1 param)]
(merge rval
{:actual (:type t)
:depth (:depth t)}))
rval)))
(defn- normalized-name
[^String method-name]
(-> method-name
(.replaceFirst
(case (.substring method-name 0 3)
"get" "get"
"set" "set"
"default")
"")
(.toLowerCase)))
(defn- matches?
"We exclude any mutators of the bean which
expect a java.util.Map$Entry as the first
argument, as we won't be dealing in these
from Clojure. Specifically, this is meant
to address the various setKey() methods
in the DynamoDBV2Client.
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/model/DeleteItemRequest.html#setKey(java.util.Map.Entry, java.util.Map.Entry)
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/model/GetItemRequest.html#setKey(java.util.Map.Entry, java.util.Map.Entry)"
[^Method method name value]
(let [args (.getParameterTypes method)
n (count args)
^Class clazz (first args)]
(and (= name (normalized-name (.getName method)))
(if (empty? value)
(= 0 n)
(and (< 0 n)
(or (= n (count (flatten value)))
(and (coll? value)
(= 1 n)
(or (contains? @coercions clazz)
(.isArray clazz)
(and (.getPackage clazz)
(.startsWith
(.getName (.getPackage clazz))
"java.util")))))
(not (and (= 2 n)
(every? (partial = java.util.Map$Entry)
args))))))))
(defn- accessor-methods
[class-methods name value]
(reduce
#(if (matches? %2 name value)
(conj %1 %2)
%1)
[]
class-methods))
(defn- find-methods
[^Object pojo k & v]
(-> (.getClass pojo)
(.getMethods)
(accessor-methods
(.toLowerCase (keyword->camel k))
v)))
(defn to-java-coll
"Need this only because S3 methods actually try to
mutate (e.g. sort) collections passed to them."
[col]
(cond
(map? col)
(doto
(java.util.HashMap.)
(.putAll col))
(set? col)
(java.util.HashSet. ^java.util.Set col)
(or (list? col) (vector? col))
(java.util.ArrayList. ^java.util.Collection col)))
(defn- invoke
[pojo ^Method method v]
(.invoke method pojo
(into-array
;; misbehaving S3Client mutates the coll
(if (and (coll? v)
(not (nil? *client-class*))
(= "AmazonS3Client" (.getSimpleName ^Class *client-class*)))
(if (and (> (count (.getParameterTypes method)) 1)
(sequential? v))
(to-java-coll v)
[(to-java-coll v)])
[v])))
true)
(defn kw->str [k]
(if (keyword? k) (name k) k))
(defn- populate
[types key props]
(let [type (-> types key last)]
(assert type (str "Bad data type - there is no " key " in " types))
(if (contains? @coercions type)
(coerce-value props type)
(set-fields (new-instance type) props))))
(defn- unmarshall
"Transform Clojure data to the required Java objects."
[types col]
(let [^Class type (last (or (:actual types)
(:generic types)))
pp (partial populate types :actual)]
(try
(if (aws-package? type)
(if (map? col)
(if (contains? types :actual)
(if (empty? col)
{} ; assoc doesn't like being called to do nothing
(if (< (:depth types) 3)
(apply assoc {}
(interleave (fmap kw->str (apply vector (keys col)))
(fmap pp (apply vector (vals col)))))
(apply assoc {}
(interleave (fmap kw->str (apply vector (keys col)))
[(fmap #(populate {:generic [type]}
:generic
%)
(first (apply vector (vals col))))]))))
(populate types :generic col))
(if (and (contains? types :actual)
(= (:depth types) 3))
(fmap #(fmap pp %) col)
(fmap pp col)))
(if (and (contains? types :actual)
(aws-package? type))
(fmap pp col)
(fmap #(coerce-value % type) col)))
(catch Throwable e
(throw (RuntimeException. (str
"Failed to create an instance of "
(.getName type)
" from " col
" due to " e
". Make sure the data matches an existing constructor and setters.")))))))
(defn- invoke-method
[pojo v method]
(let [f (partial invoke pojo method)
types (paramter-types method)
generic (last (:generic types))]
(if (and
(coll? v)
(not (contains? @coercions generic)))
(f (unmarshall types v))
(if (instance? generic v)
(f v)
(f (coerce-value v generic))))))
(defn set-fields
"Returns the populated AWS *Request bean with 'args' as
the values. args is a map with keywords as keys and any
type values. Complex values will be recursively resolved
to the corresponding method calls on the object graph."
[pojo args]
(doseq [[k v] args]
(try
(->> (find-methods pojo k v)
(some (partial invoke-method pojo v)))
(catch Throwable e
(throw (ex-info
(str "Error setting " k ": " (.getMessage e) ". Perhaps the value isn't compatible with the setter?")
{:property k, :value v}
e)))))
pojo)
(defn- create-bean
[clazz args]
(-> clazz new-instance (set-fields args)))
(defn- create-request-bean
"Create a new instance of an AWS *Request style Java
bean passed as the argument to a method call on the
Amazon*Client class. (Note that we assume all AWS
service calls take at most a single argument.)"
[^Method method args]
(let [clazz (first (.getParameterTypes method))]
(if (contains? @coercions clazz)
(coerce-value (into {} args) clazz)
(create-bean clazz args))))
(defprotocol IMarshall
"Defines the contract for converting Java types to Clojure
data. All return values from AWS service calls are
marshalled. As such, the AWS service-specific namespaces
will frequently need to implement this protocol in order
to provide convenient data representations. See also the
register-coercions function for coercing Clojure data to
Java types."
(marshall [obj]))
(defn- getter?
[^Method method]
(let [name (.getName method)
type (.getName (.getReturnType method))]
(or (and
(.startsWith name "get")
(= 0 (count (.getParameterTypes method))))
(and
(.startsWith name "is")
(= "boolean" type)))))
(defn accessors
"Returns a vector of getters or setters for the class."
[^Class clazz getters?]
(reduce
(fn [acc ^Method m]
(if (or
(and getters? (getter? m))
(and (not getters?)
(.startsWith (.getName m) "set")))
(conj acc m)
acc))
[]
(.getDeclaredMethods clazz)))
(defn- prop->name
[^Method method]
(let [name (.getName method)]
(if (.startsWith name "is")
(str (.substring name 2) "?")
(.substring name 3))))
(defn get-fields
"Returns a map of all non-null values returned by
invoking all public getters on the specified object."
[obj]
(let [no-arg (make-array Object 0)]
(into {}
(for [^Method m (accessors (class obj) true)]
(let [r (marshall (.invoke m obj no-arg))]
(if-not (nil? r)
(hash-map
(camel->keyword (prop->name m))
r)))))))
(extend-protocol IMarshall
nil
(marshall [obj] nil)
java.util.Map
(marshall [obj]
(if-not (empty? obj)
(apply assoc {}
(interleave
(fmap #(if (string? %) (keyword %) %)
(apply vector (keys obj)))
(fmap marshall
(apply vector (vals obj)))))))
java.util.Collection
(marshall [obj]
(if (instance? clojure.lang.IPersistentSet obj)
obj
(fmap marshall (apply vector obj))))
java.util.Date
(marshall [obj] (DateTime. (.getTime obj)))
; `false` boolean objects (i.e. (Boolean. false)) come out of e.g.
; .doesBucketExist, which wreak havoc on Clojure truthiness
Boolean
(marshall [obj] (when-not (nil? obj) (.booleanValue obj)))
Object
(marshall [obj]
(if (aws-package? (class obj))
(get-fields obj)
obj)))
(defn- use-aws-request-bean?
[^Method method args]
(let [types (.getParameterTypes method)]
(and (or (map? args) (< 1 (count args)) (nil? args))
(< 0 (count types))
(or (nil? args)
(map? args)
(and
(or (and
(even? (count args))
(not= java.io.File (last types)))
(and
(odd? (count args))
(= java.io.File (last types)))) ; s3 getObject() support
(some keyword? args)))
(or (aws-package? (first types))
(and (aws-package? (last types))
(not (< (count types) (count args))))))))
(defn- prepare-args
[^Method method args]
(let [types (.getParameterTypes method)
num (count types)]
(if (and (empty? args) (= 0 num))
(into-array Object args)
(if (= num (count args))
(into-array Object
(map (fn [arg ^Class clazz]
(if (and (aws-package? clazz) (seq (.getConstructors clazz)))
; must be a concrete, instantiatable class
(if (contains? @coercions clazz)
(coerce-value arg clazz)
(create-bean clazz arg))
(coerce-value arg clazz)))
(vec args)
types))
(if (use-aws-request-bean? method args)
(cond
(= 1 num)
(into-array Object
[(create-request-bean
method
(seq (apply hash-map args)))])
(and (aws-package? (first types))
(= 2 num)
(= File (last types)))
(into-array Object
[(create-request-bean
method
(seq (apply hash-map (butlast args))))
(last args)])))))))
(defn- args-from
"Function arguments take an optional first parameter map
of AWS credentials. Addtional parameters are either a map,
or seq of keys and values."
[arg-seq]
(let [args (first arg-seq)]
(cond
(or (and (or (map? args)
(map? (first args)))
(or (contains? (first args) :access-key)
(contains? (first args) :endpoint)
(contains? (first args) :profile)
(contains? (first args) :client-config)))
(instance? AWSCredentialsProvider (first args))
(instance? AWSCredentials (first args)))
{:args (if (-> args rest first map?)
(if (-> args rest first empty?)
{}
(mapcat identity (-> args rest args-from :args)))
(rest args))
:credential (if (map? (first args))
(dissoc (first args) :client-config)
(first args))
:client-config (:client-config (first args))}
(map? (first args))
{:args (let [m (mapcat identity (first args))]
(if (seq m) m {}))}
:default {:args args})))
(defn transfer-manager*
[credential client-config crypto]
(let [encryption-client (:encryption-client-fn client-config)
amazon-client (:amazon-client-fn client-config)]
(invoke-constructor
"com.amazonaws.services.s3.transfer.TransferManager"
(if crypto
[(encryption-client crypto credential client-config)]
[(amazon-client (Class/forName "com.amazonaws.services.s3.AmazonS3Client")
credential
client-config)]))))
(swap! client-config assoc :transfer-manager-fn (memoize transfer-manager*))
(defn candidate-client
[^Class clazz args]
(let [cred-bound (or *credentials* (:credential args))
credential (if (map? cred-bound)
(merge @credential cred-bound)
(or cred-bound @credential))
config-bound (or *client-config* (:client-config args))
client-config (merge @client-config config-bound)
encryption-client (:encryption-client-fn client-config)
amazon-client (:amazon-client-fn client-config)
transfer-manager (:transfer-manager-fn client-config)
crypto (if (even? (count (:args args)))
(:encryption (apply hash-map (:args args))))
client (if (and crypto (or (= (.getSimpleName clazz) "AmazonS3Client")
(= (.getSimpleName clazz) "TransferManager")))
(delay (encryption-client crypto credential client-config))
(delay (amazon-client clazz credential client-config)))]
(if (= (.getSimpleName clazz) "TransferManager")
(transfer-manager credential client-config crypto)
@client)))
(defn- fn-call
"Returns a function that reflectively invokes method on
clazz with supplied args (if any). The 'method' here is
the Java method on the Amazon*Client class."
[clazz ^Method method & arg]
(binding [*client-class* clazz]
(let [args (args-from arg)
arg-arr (prepare-args method (:args args))
client (delay (candidate-client clazz args))]
(fn []
(try
(let [java (.invoke method @client arg-arr)
cloj (marshall java)]
(if (and
@root-unwrapping
(map? cloj)
(= 1 (count (keys cloj))))
(-> cloj first second)
cloj))
(catch InvocationTargetException ite
(throw (.getTargetException ite))))))))
(defn- types-match-args
[args ^Method method]
(let [types (.getParameterTypes method)]
(if (and (= (count types) (count args))
(every? identity (map instance? types args)))
method)))
(defn- coercible? [type]
(and (contains? @coercions type)
(not (re-find #"java\.lang" (str type)))))
(defn- choose-from [possible]
(if (= 1 (count possible))
(first possible)
(first
(sort-by
(fn [^Method method]
(let [types (.getParameterTypes method)]
(cond
(some coercible? types) 1
(some #(= java.lang.Enum (.getSuperclass ^Class %)) types) 2
:else 3)))
possible))))
(defn possible-methods
[methods args]
(filter
(fn [^Method method]
(let [types (.getParameterTypes method)
num (count types)]
(if (or
(and (empty? args) (= 0 num))
(use-aws-request-bean? method args)
(and
(= num (count args))
(not (keyword? (first args)))
(not (aws-package? (first types)))))
method
false)))
methods))
(defn- best-method
"Finds the appropriate method to invoke in cases where
the Amazon*Client has overloaded methods by arity or type."
[methods & arg]
(let [args (:args (args-from arg))]
(or (some (partial types-match-args args) methods)
(choose-from (possible-methods methods args)))))
(defn- clojure-case
"Similar to \"kabob case\" but the returned string is suitable for
reading a single symbol with `read-string`."
[string]
(-> string
;; Replace the space between a non-upper-case letter and an
;; upper-case letter with a dash.
(str/replace #"(?<=[^A-Z])(?=[A-Z])" "-")
;; Remove anything that a Clojure reader would not accept in a
;; symbol.
(str/replace #"[\\'\"\[\]\(\){}\s]" "")
(str/lower-case)))
(defn- type-clojure-name
"Given a `java.lang.Class` return it's name in kabob case"
[^Class type]
(let [type-name (last (.. type getName (split "\\.")))
type-name (if-let [;; Check for a type name like "[C" etc.
[_ name] (re-matches #"\[([A-Z]+)$" type-name)]
name
type-name)]
(clojure-case type-name)))
(defn- parameter-clojure-name
"Given a `java.lang.reflect.Parameter` return it's name in kabob
case."
[^Parameter parameter]
(if (. parameter isNamePresent)
(clojure-case (. parameter getName))
;; The name will be synthesized so instead we'll derive
;; it from it's type.
(type-clojure-name (. parameter getType))))
(def ^{:arglists '([method])
:private true}
parameter-names
"Given a `java.lang.reflect.Method` return a list of it's parameter
names."
;; The regular expression here will only match against version
;; numbers that are 1.7.X and below.
(if (re-matches #"[^2-9]\.[1-7]\..+" (System/getProperty "java.version"))
;; Java 1.7 and below.
(fn [^Method method]
(map type-clojure-name (. method getParameterTypes)))
;; Java 1.8 and above.
(fn [^Method method]
(map parameter-clojure-name (. method getParameters)))))