forked from ari4java/ari4java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathari4java.clj
More file actions
701 lines (542 loc) · 18.2 KB
/
ari4java.clj
File metadata and controls
701 lines (542 loc) · 18.2 KB
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
(ns codegen3.ari4java
(:require [codegen3.javagen :as jg]
[clojure.spec.alpha :as s]
[orchestra.spec.test :as st]
[codegen3.signatures :as sgn]))
;; This namespace runs the translation of
;; a swagger database (e.g. sample_db.clj) as read in core
;; into an array of Java class definitions that will
;; then be written by javagen.clj
;; LOGIC
;; We distinguish two kinds of objects:
;; - Actions: these are the actual objects that
;; are used to perform actions. When you run A4j
;; you use an interface, but the runtime object
;; is bound to the version you specified.
;; They are named e.g. "ActionApplications" and the
;; runtime version will be "ActionApplication_impl_{ariVer}"
;; - Models: these are data containers coming from Asterisk.
;; They are "only" data continers, so have no meaningful
;; method on themselves. We add .toString, .equals and
;; .hashCode just in case.
;; Method Permutations
;; ....
;; INTERFACES
;; .a4j.generated
;;
;; Actions: -
;;
;; Models:
;; e.g. (-> DB :ari_1_0_0 :applications :models :Application)
;; At the interface level, we make it a map
;; {"field" "swaggerType"}
;; To actually generate the model, we also need:
;; - All the ARI version(s) it is present in
;; - The description, as taken from most recent version
;;
;; A fixed set of models extend EventSource (for tagging)
;;
;; \TODO which models are "extends EventSource"?
(def IMPORTS_GENERATED_MODELS [
"ch.loway.oss.ari4java.generated.*"
"com.fasterxml.jackson.databind.annotation.JsonDeserialize"
"java.util.Date"
"java.util.List"
"java.util.Map" ])
(def IMPORTS_INTERFACES_MODELS [
"java.util.Date"
"java.util.List"
"java.util.Map"
"java.util.ArrayList"
"ch.loway.oss.ari4java.tools.RestException"
"ch.loway.oss.ari4java.tools.AriCallback"
"ch.loway.oss.ari4java.tools.tags.*"
])
(defn eventSources
"At the moment the list of EventSources is fixed.
But it would be better to read it from the DB."
[]
#{ :Bridge :Channel :Endpoint :DeviceState })
(defn isEvtSource
"A set can be looked-up as a function of its members"
[model]
(some? ((eventSources) model)))
(defn models-for
"A list of models for an ARI version.
Models are held in:
-> DB :ari_1_0_0 :applications :models
-> DB :ari_1_0_0 :events :models
Returns a map of models indexed by model name.
"
[DB version]
(let [entries (-> DB version keys)]
(reduce into {}
(for [entry entries]
(-> DB version entry :models)))))
(defn model-names-for
[DB version]
(keys (models-for DB version)))
(defn all-ari-versions [db]
(keys db))
(defn all-possible-model-names
"Returns a list of all possible model names across all ARI versions"
[DB]
(reduce into #{}
(map (partial model-names-for DB)
(all-ari-versions DB))))
(defn get-model- [DB version name]
"Reads a model given a version and a name.
Annotates the ARI model with whether it's an event and
the ARI version it comes from"
(let [am (-> DB version :applications :models name)
em (-> DB version :events :models name)]
(cond
(and (nil? em) (nil? am))
nil
(nil? em)
(into {:cljid name :ver version :isevt false} am)
:else
(into {:cljid name :ver version :isevt true} em))))
(defn get-model [DB version name]
"Reads a model given a version and a name.
Annotates the ARI model with whether it's an event and
the ARI version it comes from"
(let [entries (-> DB version keys)
lzModels (map #(-> DB version % :models name) entries)
found (first (filter some? lzModels))]
(cond
(nil? found) nil
:else (into {:cljid name :ver version :isevt false} found)
)))
(defn merge-property
"Derives an annotated property from an existing annotated
property p1 + a non-annotated property and a version.
An annotated property has a name and
a list of versions it applies to.
"
[ap1 p2 name version]
;(prn "mergeprop" ap1 p2 name version)
(cond
(nil? ap1)
(into {:versions [version] :name name} p2)
:else
(cond
(= (:type ap1) (:type p2))
(into ap1 {:versions (conj (:versions ap1) version)})
:else-exception
(throw (IllegalArgumentException.
(str "Different type in version: " version " for ap1:" ap1 " p2:" p2 ))))
))
(defn props-set
"Given a list of models and a prop to extract,
gets us the property."
[vModels prop]
(let [allprops (map
(fn [model]
{:ver (:ver model)
:name prop
:prop (get-in model [:properties prop])})
vModels)
; a prop might not exist
allexistingprops (filter #(some? (:prop %)) allprops)
]
(reduce (fn [a v] (merge-property a (:prop v) prop (:ver v)))
nil
allexistingprops)
)
)
(defn model-info
"What do we know about this model across our entire database?
"
[DB name]
(let [models (map #(get-model DB % name) (all-ari-versions DB))
found (filter some? models)
versions (map :ver found)
lastmod (last found)
allpropnames (keys (reduce into {} (map :properties found)))
allprops (map (partial props-set found) allpropnames)
]
{:model name
:versions (vec versions)
:dscr (:description lastmod)
:evt (:isevt lastmod)
:properties (vec allprops)
;:_fnd found
}
))
(defn get-property-description [prop]
(str (:description prop)
"\n"
"\n"
"Supported versions: " (:versions prop)
)
)
(defn get-model-description [prop]
(str (:dscr prop)
"\n"
"\n"
"Supported versions: " (:versions prop)
"\n"
"DEBUG:" prop "\n"
)
)
(defn generate-model-concrete
[model]
(jg/mkDataClass
"ch.loway.oss.ari4java.generated"
(name (:model model))
(get-model-description model)
(mapv
(fn [prop]
{:type (jg/swagger->java
(:type prop) "")
:name (name (:name prop))
:comment (get-property-description prop)})
(:properties model)
)))
(defn generate-model-interface
[model]
(let [modelName (:model model)]
(jg/mkDataClassInterface
"ch.loway.oss.ari4java.generated"
(name modelName)
(if (isEvtSource modelName) " EventSource " nil ) ;; extends
[] ;; implements
IMPORTS_INTERFACES_MODELS
(get-model-description model)
(mapv
(fn [prop]
{:type (jg/swagger->java
(:type prop) "")
:name (name (:name prop))
:comment (get-property-description prop)
:interfaceonly true })
(:properties model)
))
)
)
(defn generate-model-interfaces
"Builds all model interfaces.
"
[DB]
(let [models (map (partial model-info DB) (all-possible-model-names DB) )]
(map generate-model-interface models)))
(defn generate-model-implementation
"An implementaion is like an interface, but:
- if a field is not supported, it should throw
an error
- it has toString and hashCode methods added in
"
[model ari]
(jg/mkDataClass
;(vec [
(str "ch.loway.oss.ari4java.generated." (name ari) ".models")
(str (name (:model model)) "_impl_" (name ari))
nil ;; extends
[ (name (:model model)) ] ;; implements
IMPORTS_GENERATED_MODELS
(get-model-description model)
(mapv
(fn [prop]
{:type (jg/swagger->java
(:type prop) "")
:name (name (:name prop))
:comment (get-property-description prop)
:notimplemented (not (some #{ari} (:versions prop) )) }
)
(:properties model))
; ]
))
(defn generate-model-implementations [DB]
(let [allaris (all-ari-versions DB)
allmodels (all-possible-model-names DB)
models (map (partial model-info DB) allmodels)]
(for [m models a allaris]
(generate-model-implementation m a)
;allaris
)))
;; ACTIONS
;; In order to work on actions, we first transform the Actions database
;; so that it is a large list of Operations
;; enriched with:
;; :op_path
;; :op_description
;; :op_version :ari_0_0_1
;; :op_type :bridges
(defn dbDescr
"Loads a description of the DB in terms of aris and entities"
[DB]
(let [allaris (all-ari-versions DB)
allentities (reduce into #{}
(map #(-> DB % keys) allaris)) ]
{:aris (vec (sort allaris))
:ents (vec (sort allentities))} ))
(defn opsDb
"Loads a flat operations DB that can be easily filtered"
[DB]
(let [{aris :aris ents :ents} (dbDescr DB)]
(vec
(flatten
(for [ari aris
ent ents]
(let [apis (-> DB ari ent :apis)]
(for [api apis]
(let [path (:path api)
descr (:description api)
ops (:operations api)]
(map
(fn [op] (into {:op_path path
:op_description descr
:op_version ari
:op_action ent} op))
ops)))))))))
;; Here we have a litte tool to understand the contents of our DB
;; (aj/findParams (aj/opsDb DB) #(= "operation" (:name %) ) )
(defn findParams
[odb pred]
(filter
#(pos? (count (filter pred (:parameters %)) ) )
odb
))
(defn viewMethod [odb ari name]
(let [predAri (cond
(nil? ari) #(= 1 1)
:else #(= ari (:op_version %)))
predName #(= name (:nickname %))
]
(filter
#(and (predAri %) (predName %))
odb
)))
; How many methods have multiple parameters? just a few
;
;(map #(vec [(:op_action %) (:nickname %)])
; (aj/findParams
; (filter #(= :ari_1_8_0 (:op_version %)) (aj/opsDb DB))
; #(= true (:allowMultiple %) ) ))
;
; ([:applications "subscribe"]
; [:applications "unsubscribe"]
; [:asterisk "getInfo"]
; [:bridges "addChannel"]
; [:bridges "removeChannel"]
; [:events "eventWebsocket"]
; [:events "userEvent"])
; How many methods have enums?
;(map #(vec [(:op_action %) (:nickname %)])
; (aj/findParams
; (filter #(= :ari_1_8_0 (:op_version %)) (aj/opsDb DB))
; #(= "LIST" (-> % :allowableValues :valueType) ) ))
;
; ([:asterisk "getInfo"]
; [:bridges "record"]
; [:channels "hangup"]
; [:channels "mute"]
; [:channels "unmute"]
; [:channels "record"]
; [:channels "snoopChannel"]
; [:channels "snoopChannelWithId"]
; [:deviceStates "update"]
; [:playbacks "control"])
;; ---------- Enums ---------
; Enums have a name that matches the field they go in.
; If multiple enums have the same name, their fields are coalesced.
;
; To find enums, we scan all fields for ":allowableValues :valueType" = "LIST"
; Enums are produced as a map of arrays:
; {e1 [v1 v2 v3], e2 [v1 v2 v3]}
(defn find-enums
[odb]
(let [parms (flatten (map :parameters odb))
wEnum (filter #(= "LIST" (-> % :allowableValues :valueType) ) parms)
tuples (map (fn [p] [(:name p) (set (-> p :allowableValues :values)) ]) wEnum)
groups (group-by first tuples)
mapk (map (fn [[k v]] [k (reduce into #{} (map second v)) ] ) groups)
]
(into {} mapk)))
(defn generate-enum-classes [odb]
(let [ens (find-enums odb)]
(map
(fn [[k v]]
(jg/mkEnum "ch.loway.oss.ari4java.generated.enums" k "-" v))
ens
)))
; ==================
; ARIBUILDERS and such things
(defn generate-ari-builder-interface
"public abstract ActionApplications actionApplications();"
[allmods allactions]
(let [allObj (sort (into allmods allactions))]
{
:isInterface true
:classname "AriBuilder"
:package "ch.loway.app.oss.ari4java.generated"
:imports [ "ch.loway.oss.ari4java.ARI" ]
:notes ""
:stanzas (into
["public abstract ARI.ClassFactory getClassFactory();"]
(map #(str "public abstract "
(jg/className (name %))
" "
(jg/lcName (name %))
"();")
allObj))
}))
(defn generate-ari-builder-impl
"public abstract ActionApplications actionApplications();"
[version DB allmods allactions]
(let [allObj (sort (into allmods allactions))
ver (name version)
pkg (str "ch.loway.app.oss.ari4java.generated." ver)
knownModels (set (model-names-for DB version))
]
{
:classname (str "AriBuilder_impl_" (name version))
:package pkg
:imports [ (str pkg ".models.*;")
(str pkg ".actions.*;")
"ch.loway.oss.ari4java.generated.*"
"ch.loway.oss.ari4java.ARI" ]
:implements "AriBuilder"
:notes ""
:functions (map (fn [x]
{:method (jg/lcName (name x))
:returns (jg/className (name x))
:body (cond
(knownModels x)
(str "return new "
(jg/className (name x))
"_impl_"
ver
"();")
:else
"throw new UnsupportedOperationException();")
})
allObj)
:stanzas (str "public ARI.ClassFactory getClassFactory() {\n"
"return new ClassTranslator_impl_" ver "();\n};\n")
}))
(defn generate-class-translator-impl
""
[version DB allmods allactions]
(let [allObj (sort (into allmods allactions))
ver (name version)
pkg (str "ch.loway.app.oss.ari4java.generated." ver)
knownModels (set (model-names-for DB version))
]
{
:classname (str "ClassTranslator_impl_" (name version))
:package pkg
:imports [ (str pkg ".models.*;")
(str pkg ".actions.*;")
"ch.loway.oss.ari4java.generated.*"
"ch.loway.oss.ari4java.ARI" ]
:implements "ARI.ClassFactory"
:notes ""
:stanzas (str "@Override\n"
"public Class getImplementationFor(Class interfaceClass) { \n"
(apply str (map (fn [o] (str "if ( interfaceClass.equals("
(name o) ".class) ) {\n"
"return (" (name o) "_impl_" ver ".class);\n"
"} else \n")) allObj))
"{\n return null;\n } }"
)
}))
(defn generate-ari-builders
"We generate a generic AriBuilder interface for
all models plus an implementor for each ARI version."
[DB]
(let [allaris (all-ari-versions DB)
allmods (all-possible-model-names DB)
allacts [] ]
(flatten
[(generate-ari-builder-interface allmods allacts)
(map #(generate-ari-builder-impl % DB allmods allacts) allaris)
(map #(generate-class-translator-impl % DB allmods allacts) allaris)]
)))
; =================================================================
; ACTIONS
; Generation of all actions is based on an opsDb
; when testing, you can:
; (def ODB (opsDb (codegen3.core/readAll)))
; (allSignaturesForAction ODB :applications)
(s/def ::odb_entry
(s/keys :req-un [::op_path
::op_description
::op_version
::op_action
::httpMethod
::summary
::nickname
::responseClass
;::parameters
]))
(s/def ::odb
(s/coll-of ::odb_entry :kind sequential? ))
(defn allActions [ODB]
(->> ODB
(map :op_action)
set
sort
vec ))
(s/fdef allActions
:args (s/cat :odb ::odb)
:ret vector?)
; op_entity -> op_action
(s/fdef signature
:args (s/cat :dbe ::odb_entry))
(defn signature
"Gets a signature tuple. [{:nick....} :ari_0]
As :parameters might not exist, we read it through a get
so we can put a default."
[dbe]
(let [p (get dbe :parameters [])]
[{:nickname (:nickname dbe)
:parms (sgn/explode-parms-permutations p)
:responseClass (:responseClass dbe)
}
(:op_version dbe)]
))
(s/def ::tuple
(s/and vector?
#(= 2 (count %)) ))
(s/fdef groupTuples
:args (s/cat :tuples (s/coll-of ::tuple ))
:ret map?)
(defn groupTuples
"Translates a sequence of [ [item tag]...]
into a map {item [tag...]}
"
[sTuples]
(into {}
(map
(fn [[k v]] [k (mapv second v)] )
(group-by first sTuples))))
(s/fdef allSignaturesForAction
:args (s/cat :dbe ::odb
:action keyword?))
(defn allSignaturesForAction
[ODB action]
(let [odb (filter #(= action (:op_action %)) ODB)]
(groupTuples (mapv signature odb))))
; =================================================================
; Try everything once.
(defn process
"Turns a database into a set of interfaces and classes."
[database]
(let [mif (generate-model-interfaces database)
mci (generate-model-implementations database)
odb (opsDb database)
enm (generate-enum-classes odb)
bld (generate-ari-builders database)
all (-> []
(into mif)
(into mci)
(into enm)
(into bld)
)
]
(map jg/writeOutKlass all)
))
; Orchestra instrumentation is active automagically
(st/instrument)