-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentityController.go
2038 lines (1819 loc) · 59.9 KB
/
entityController.go
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
package controllers
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"p3/models"
u "p3/utils"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func getObjID(x string) (primitive.ObjectID, error) {
objID, err := primitive.ObjectIDFromHex(x)
if err != nil {
return objID, err
}
return objID, nil
}
// This function is useful for debugging
// purposes. It displays any JSON
func viewJson(r *http.Request) {
var updateData map[string]interface{}
json.NewDecoder(r.Body).Decode(&updateData)
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(updateData); err != nil {
log.Fatal(err)
}
}
func Disp(x map[string]interface{}) {
jx, _ := json.Marshal(x)
println("JSON: ", string(jx))
}
// 'Flattens' the map[string]interface{}
// for PATCH requests
func Flatten(prefix string, src map[string]interface{}, dest map[string]interface{}) {
if len(prefix) > 0 {
prefix += "."
}
for k, v := range src {
switch child := v.(type) {
case map[string]interface{}:
Flatten(prefix+k, child, dest)
// case []interface{}:
// for i := 0; i < len(child); i++ {
// dest[prefix+k+"."+strconv.Itoa(i)] = child[i]
// }
default:
dest[prefix+k] = v
}
}
}
func DispRequestMetaData(r *http.Request) {
fmt.Println("URL:", r.URL.String())
fmt.Println("IP-ADDR: ", r.RemoteAddr)
fmt.Println(time.Now().Format("2006-Jan-02 Monday 03:04:05 PM MST -07:00"))
}
var decoder = schema.NewDecoder()
func getFiltersFromQueryParams(r *http.Request) u.RequestFilters {
var filters u.RequestFilters
decoder.Decode(&filters, r.URL.Query())
return filters
}
// swagger:operation POST /api/{obj} objects CreateObject
// Creates an object in the system.
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Indicates the Object. Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "acs", "panels",
// "cabinets", "groups", "corridors",
// "room-templates", "obj-templates", "bldg-templates","sensors", "stray-devices",
// "stray-sensors" are acceptable'
// required: true
// type: string
// default: "sites"
// - name: Name
// in: query
// description: Name of object
// required: true
// type: string
// default: "Object A"
// - name: Category
// in: query
// description: Category of Object (ex. Consumer Electronics, Medical)
// required: true
// type: string
// default: "Research"
// - name: Domain
// description: 'Domain of Object'
// required: true
// type: string
// default: 999
// - name: ParentID
// description: 'All objects are linked to a
// parent with the exception of Tenant since it has no parent'
// required: true
// type: int
// default: 999
// - name: Description
// in: query
// description: Description of Object
// required: false
// type: string[]
// default: ["Some abandoned object in Grenoble"]
// - name: Attributes
// in: query
// description: 'Any other object attributes can be added.
// They are required depending on the obj type.'
// required: true
// type: json
// responses:
// '201':
// description: 'Created. A response body will be returned with
// a meaningful message.'
// '400':
// description: 'Bad request. A response body with an error
// message will be returned.'
var CreateEntity = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: CreateEntity ")
fmt.Println("******************************************************")
DispRequestMetaData(r)
var e string
var resp map[string]interface{}
entity := map[string]interface{}{}
err := json.NewDecoder(r.Body).Decode(&entity)
entStr, e1 := mux.Vars(r)["entity"]
if !e1 {
w.WriteHeader(http.StatusBadRequest)
u.Respond(w, u.Message(false, "Error while parsing path params"))
u.ErrLog("Error while parsing path params", "CREATE "+entStr, "", r)
return
}
entUpper := strings.ToUpper(entStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
u.Respond(w, u.Message(false, "Error while decoding request body"))
u.ErrLog("Error while decoding request body", "CREATE "+entStr, "", r)
return
}
//If creating templates, format them
entStr = strings.Replace(entStr, "-", "_", 1)
i := u.EntityStrToInt(entStr)
println("ENT: ", entStr)
println("ENUM VAL: ", i)
//Prevents Mongo from creating a new unidentified collection
if i < 0 {
w.WriteHeader(http.StatusBadRequest)
u.Respond(w, u.Message(false, "Invalid entity in URL: '"+mux.Vars(r)["entity"]+"' Please provide a valid object"))
u.ErrLog("Cannot create invalid object", "CREATE "+mux.Vars(r)["entity"], "", r)
return
}
//Check if category and endpoint match, except for templates and strays
if i < u.ROOMTMPL {
if entity["category"] != entStr {
w.WriteHeader(http.StatusBadRequest)
u.Respond(w, u.Message(false, "Category in request body does not correspond with desired object in endpoint"))
u.ErrLog("Cannot create invalid object", "CREATE "+mux.Vars(r)["entity"], "", r)
return
}
}
//Clean the data of 'id' attribute if present
delete(entity, "id")
resp, e = models.CreateEntity(i, entity)
switch e {
case "validate", "duplicate":
w.WriteHeader(http.StatusBadRequest)
u.ErrLog("Error while creating "+entStr, "CREATE "+entUpper, e, r)
case "":
w.WriteHeader(http.StatusCreated)
default:
if strings.Split(e, " ")[1] == "duplicate" {
w.WriteHeader(http.StatusBadRequest)
u.ErrLog("Error: Duplicate "+entStr+" is forbidden",
"CREATE "+entUpper, e, r)
} else {
w.WriteHeader(http.StatusInternalServerError)
u.ErrLog("Error while creating "+entStr, "CREATE "+entUpper, e, r)
}
}
u.Respond(w, resp)
}
// swagger:operation GET /api/objects/{name} objects GetObject
// Gets an Object from the system.
// The hierarchyName must be provided in the URL parameter
// ---
// produces:
// - application/json
// parameters:
// - name: name
// in: query
// description: 'hierarchyName of the object'
//
// responses:
//
// '200':
// description: 'Found. A response body will be returned with
// a meaningful message.'
// '404':
// description: Not Found. An error message will be returned.
// swagger:operation OPTIONS /api/objects/{name} objects ObjectOptions
// Displays possible operations for the resource in response header.
// ---
// produces:
// - application/json
// parameters:
// - name: name
// in: query
// description: 'hierarchyName of the object'
//
// responses:
//
// '200':
// description: 'Found. A response header will be returned with
// possible operations.'
// '400':
// description: Bad request. An error message will be returned.
// '404':
// description: Not Found. An error message will be returned.
var GetGenericObject = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: GetGenericObject ")
fmt.Println("******************************************************")
DispRequestMetaData(r)
var data map[string]interface{}
var e1 string
var resp map[string]interface{}
name, e := mux.Vars(r)["name"]
filters := getFiltersFromQueryParams(r)
if e {
data, e1 = models.GetObjectByName(name, filters)
} else {
u.Respond(w, u.Message(false, "Error while parsing path parameters"))
u.ErrLog("Error while parsing path parameters", "GET ENTITY", "", r)
return
}
if data == nil {
resp = u.Message(false, "Error while getting "+name+": "+e1)
u.ErrLog("Error while getting "+name, "GET GENERIC", "", r)
w.WriteHeader(http.StatusNotFound)
} else {
resp = u.Message(true, "successfully got object")
}
if r.Method == "OPTIONS" && data != nil {
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Allow", "GET, DELETE, OPTIONS, PATCH, PUT")
} else {
resp["data"] = data
u.Respond(w, resp)
}
}
// swagger:operation GET /api/{objs}/{id} objects GetObject
// Gets an Object from the system.
// The ID must be provided in the URL parameter
// The name can be used instead of ID if the obj is tenant
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Indicates the location. Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "room-templates",
// "obj-templates", "bldg-templates","acs", "panels","cabinets", "groups",
// "corridors","sensors","stray-devices", "stray-sensors" are acceptable'
// required: true
// type: string
// default: "sites"
// - name: ID
// in: path
// description: 'ID of desired object or Name of Tenant.
// For templates the slug is the ID. For stray-devices the name is the ID'
// required: true
// type: int
// default: 999
// responses:
// '200':
// description: 'Found. A response body will be returned with
// a meaningful message.'
// '400':
// description: Bad request. An error message will be returned.
// '404':
// description: Not Found. An error message will be returned.
// swagger:operation OPTIONS /api/{objs}/{id} objects ObjectOptions
// Displays possible operations for the resource in response header.
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "room-templates",
// "obj-templates", "bldg-templates","acs", "panels","cabinets", "groups",
// "corridors","sensors","stray-devices","stray-sensors", are acceptable'
// - name: id
// in: query
// description: 'ID of the object or name of Tenant.
// For templates the slug is the ID. For stray-devices the name is the ID'
//
// responses:
//
// '200':
// description: 'Found. A response header will be returned with
// possible operations.'
// '400':
// description: Bad request. An error message will be returned.
// '404':
// description: Not Found. An error message will be returned.
var GetEntity = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: GetEntity ")
fmt.Println("******************************************************")
DispRequestMetaData(r)
var data map[string]interface{}
var id, e1 string
var x primitive.ObjectID
var e bool
var e2 error
var resp map[string]interface{}
entityStr := mux.Vars(r)["entity"]
filters := getFiltersFromQueryParams(r)
//If templates, format them
entityStr = strings.Replace(entityStr, "-", "_", 1)
//GET By ID
if id, e = mux.Vars(r)["id"]; e {
x, e2 = getObjID(id)
if e2 != nil {
u.Respond(w, u.Message(false, "Error while converting ID to ObjectID"))
u.ErrLog("Error while converting ID to ObjectID", "GET ENTITY", "", r)
return
}
//Prevents API from creating a new unidentified collection
if i := u.EntityStrToInt(entityStr); i < 0 {
w.WriteHeader(http.StatusNotFound)
u.Respond(w, u.Message(false, "Invalid object in URL: '"+mux.Vars(r)["entity"]+"' Please provide a valid object"))
u.ErrLog("Cannot get invalid object", "GET "+mux.Vars(r)["entity"], "", r)
return
}
data, e1 = models.GetEntity(bson.M{"_id": x}, entityStr, filters)
} else if id, e = mux.Vars(r)["name"]; e { //GET By String
if entityStr == "tenant" {
data, e1 = models.GetEntity(bson.M{"name": id}, entityStr, filters) //GET By Name
} else if strings.Contains(entityStr, "template") {
data, e1 = models.GetEntity(bson.M{"slug": id}, entityStr, filters) //GET By Slug (template)
} else {
println(id)
data, e1 = models.GetEntity(bson.M{"hierarchyName": id}, entityStr, filters) // GET By hierarchyName
}
}
if !e {
u.Respond(w, u.Message(false, "Error while parsing path parameters"))
u.ErrLog("Error while parsing path parameters", "GET ENTITY", "", r)
return
}
if data == nil {
resp = u.Message(false, "Error while getting "+entityStr+": "+e1)
u.ErrLog("Error while getting "+entityStr, "GET "+strings.ToUpper(entityStr), "", r)
switch e1 {
case "record not found":
w.WriteHeader(http.StatusNotFound)
case "mongo: no documents in result":
resp = u.Message(false, "Error while getting :"+entityStr+", No Objects Found!")
w.WriteHeader(http.StatusNotFound)
case "invalid request":
w.WriteHeader(http.StatusBadRequest)
default:
w.WriteHeader(http.StatusNotFound) //For now
}
} else {
message := ""
switch u.EntityStrToInt(entityStr) {
case u.ROOMTMPL:
message = "successfully got room_template"
case u.OBJTMPL:
message = "successfully got obj_template"
case u.BLDGTMPL:
message = "successfully got building_template"
default:
message = "successfully got object"
}
resp = u.Message(true, message)
}
if r.Method == "OPTIONS" && data != nil {
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Allow", "GET, DELETE, OPTIONS, PATCH, PUT")
} else {
resp["data"] = data
u.Respond(w, resp)
}
}
// swagger:operation GET /api/{objs} objects GetAllObjects
// Gets all present objects for specified category in the system.
// Returns JSON body with all specified objects of type and their IDs
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Indicates the location. Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "room-templates",
// "obj-templates","acs", "panels", "cabinets", "groups",
// "corridors", "sensors", "stray-devices", "stray-sensors" are acceptable'
// required: true
// type: string
// default: "sites"
//
// responses:
//
// '200':
// description: 'Found. A response body will be returned with
// a meaningful message.'
// '404':
// description: Nothing Found. An error message will be returned.
var GetAllEntities = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: GetAllEntities ")
fmt.Println("******************************************************")
DispRequestMetaData(r)
var data []map[string]interface{}
var e, entStr string
//Main hierarchy objects
entStr = mux.Vars(r)["entity"]
println("ENTSTR: ", entStr)
//If templates, format them
entStr = strings.Replace(entStr, "-", "_", 1)
//Prevents Mongo from creating a new unidentified collection
if i := u.EntityStrToInt(entStr); i < 0 {
w.WriteHeader(http.StatusNotFound)
u.Respond(w, u.Message(false, "Invalid object in URL: '"+mux.Vars(r)["entity"]+"' Please provide a valid object"))
u.ErrLog("Cannot get invalid object", "GET "+mux.Vars(r)["entity"], "", r)
return
}
data, e = models.GetManyEntities(entStr, bson.M{}, u.RequestFilters{})
var resp map[string]interface{}
if len(data) == 0 {
resp = u.Message(false, "Error while getting "+entStr+": "+e)
u.ErrLog("Error while getting "+entStr+"s", "GET ALL "+strings.ToUpper(entStr), e, r)
switch e {
case "":
resp = u.Message(false,
"Error while getting "+entStr+"s: No Records Found")
w.WriteHeader(http.StatusNotFound)
default:
}
} else {
message := ""
switch u.EntityStrToInt(entStr) {
case u.ROOMTMPL:
message = "successfully got all room_templates"
case u.OBJTMPL:
message = "successfully got all obj_templates"
default:
message = "successfully got all objects "
}
resp = u.Message(true, message)
}
resp["data"] = map[string]interface{}{"objects": data}
u.Respond(w, resp)
}
// swagger:operation DELETE /api/{objs}/{id} objects DeleteObject
// Deletes an Object in the system.
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Indicates the location. Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "room-templates",
// "obj-templates","acs", "panels",
// "cabinets", "groups", "corridors","sensors", "stray-devices"
// "stray-sensors" are acceptable'
// required: true
// type: string
// default: "sites"
// - name: ID
// in: path
// description: 'ID of the object or name of Tenant.
// For templates the slug is the ID. For stray-devices the name is the ID'
// required: true
// type: int
// default: 999
//
// responses:
//
// '204':
// description: 'Successfully deleted object.
// No response body will be returned'
// '404':
// description: Not found. An error message will be returned
var DeleteEntity = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: DeleteEntity ")
fmt.Println("******************************************************")
DispRequestMetaData(r)
var v map[string]interface{}
id, e := mux.Vars(r)["id"]
name, e2 := mux.Vars(r)["name"]
//Get entity from URL
entity := mux.Vars(r)["entity"]
//If templates, format them
entity = strings.Replace(entity, "-", "_", 1)
//Prevents Mongo from creating a new unidentified collection
if u.EntityStrToInt(entity) < 0 {
w.WriteHeader(http.StatusNotFound)
u.Respond(w, u.Message(false, "Invalid object in URL: '"+mux.Vars(r)["entity"]+"' Please provide a valid object"))
u.ErrLog("Cannot delete invalid object", "DELETE "+mux.Vars(r)["entity"], "", r)
return
}
switch {
case e2 && !e: // DELETE by name
if strings.Contains(entity, "template") {
v, _ = models.DeleteEntityManual(entity, bson.M{"slug": name})
} else {
//use hierarchyName
v = models.DeleteEntityByName(entity, name)
}
case e && !e2: // DELETE by id
objID, err := primitive.ObjectIDFromHex(id)
if err != nil {
u.Respond(w, u.Message(false, "Error while converting ID to ObjectID"))
u.ErrLog("Error while converting ID to ObjectID", "DELETE ENTITY", "", r)
return
}
if entity == "device" {
v, _ = models.DeleteDeviceF(objID)
} else {
v, _ = models.DeleteEntity(entity, objID)
}
default:
u.Respond(w, u.Message(false, "Error while parsing path parameters"))
u.ErrLog("Error while parsing path parameters", "DELETE ENTITY", "", r)
return
}
if v["status"] == false {
w.WriteHeader(http.StatusNotFound)
v["message"] = "No Records Found!"
u.ErrLog("Error while deleting entity", "DELETE ENTITY", "Not Found", r)
} else {
w.WriteHeader(http.StatusNoContent)
}
u.Respond(w, v)
}
// swagger:operation PATCH /api/{objs}/{id} objects PartialUpdateObject
// Partially update data in the system.
// This is the preferred method for modifying data in the system.
// If you want to do a full data replace, please use PUT instead.
// If the operation succeeds, the data result will be returned.
// If no new or any information is provided
// an OK will still be returned
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Indicates the location. Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "room-templates",
// "obj-templates", "bldg-templates","rooms", "acs", "panels", "cabinets", "groups",
// "corridors", "sensors", "stray-devices", "stray-sensors" are acceptable'
// required: true
// type: string
// default: "sites"
// - name: ID
// in: path
// description: 'ID of the object or name of Tenant.
// For templates the slug is the ID. For stray-devices the name is the ID'
// required: true
// type: int
// default: 999
// - name: Name
// in: query
// description: Name of Object
// required: false
// type: string
// default: "INFINITI"
// - name: Category
// in: query
// description: Category of Object (ex. Consumer Electronics, Medical)
// required: false
// type: string
// default: "Auto"
// - name: Description
// in: query
// description: Description of Object
// required: false
// type: string[]
// default: "High End Worldwide automotive company"
// - name: Domain
// description: 'Domain of the Object'
// required: false
// type: string
// default: "High End Auto"
// - name: Attributes
// in: query
// description: Any other object attributes can be updated
// required: false
// type: json
// responses:
// '200':
// description: 'Updated. A response body will be returned with
// a meaningful message.'
// '400':
// description: Bad request. An error message will be returned.
// '404':
// description: Not Found. An error message will be returned.
// swagger:operation PUT /api/{objs}/{id} objects UpdateObject
// Changes Object data in the system.
// This method will replace the existing data with the JSON
// received, thus fully replacing the data. If you do not
// want to do this, please use PATCH.
// If the operation succeeds, the data result will be returned.
// If no new or any information is provided
// an OK will still be returned
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Indicates the location. Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "room-templates",
// "obj-templates", "bldg-templates","rooms","acs", "panels", "cabinets", "groups",
// "corridors","sensors", "stray-devices", "stray-sensors" are acceptable'
// required: true
// type: string
// default: "sites"
// - name: ID
// in: path
// description: 'ID of the object or name of Tenant.
// For templates the slug is the ID. For stray-devices the name is the ID'
// required: true
// type: int
// default: 999
// - name: Name
// in: query
// description: Name of Object
// required: false
// type: string
// default: "INFINITI"
// - name: Category
// in: query
// description: Category of Object (ex. Consumer Electronics, Medical)
// required: false
// type: string
// default: "Auto"
// - name: Description
// in: query
// description: Description of Object
// required: false
// type: string[]
// default: "High End Worldwide automotive company"
// - name: Domain
// description: 'Domain of the Object'
// required: false
// type: string
// default: "High End Auto"
// - name: Attributes
// in: query
// description: Any other object attributes can be updated
// required: false
// type: json
// responses:
// '200':
// description: 'Updated. A response body will be returned with
// a meaningful message.'
// '400':
// description: Bad request. An error message will be returned.
// '404':
// description: Not Found. An error message will be returned.
var UpdateEntity = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: UpdateEntity ")
fmt.Println("******************************************************")
DispRequestMetaData(r)
var v map[string]interface{}
var e3 string
var entity string
updateData := map[string]interface{}{}
id, e := mux.Vars(r)["id"]
name, e2 := mux.Vars(r)["name"]
isPatch := false
if r.Method == "PATCH" {
isPatch = true
}
println(r.Method)
err := json.NewDecoder(r.Body).Decode(&updateData)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
u.Respond(w, u.Message(false, "Error while decoding request body"))
u.ErrLog("Error while decoding request body", "UPDATE ENTITY", "", r)
return
}
//Get entity from URL and strip trailing 's'
entity = mux.Vars(r)["entity"]
//If templates, format them
entity = strings.Replace(entity, "-", "_", 1)
//Prevents Mongo from creating a new unidentified collection
if u.EntityStrToInt(entity) < 0 {
w.WriteHeader(http.StatusNotFound)
u.Respond(w, u.Message(false, "Invalid object in URL: '"+mux.Vars(r)["entity"]+"' Please provide a valid object"))
u.ErrLog("Cannot update invalid object", "UPDATE "+mux.Vars(r)["entity"], "", r)
return
}
//Flatten updateData if we have
//a PATCH request
if isPatch {
newUpdateData := map[string]interface{}{}
Flatten("", updateData, newUpdateData)
updateData = newUpdateData
}
switch {
case e2: // Update with slug/hierarchyName
var req bson.M
if strings.Contains(entity, "template") {
req = bson.M{"slug": name}
} else if entity == "tenant" {
req = bson.M{"name": name}
} else {
req = bson.M{"hierarchyName": name}
}
v, e3 = models.UpdateEntity(entity, req, &updateData, isPatch)
case e: // Update with id
objID, err := primitive.ObjectIDFromHex(id)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
u.Respond(w, u.Message(false, "Error while converting ID to ObjectID"))
u.ErrLog("Error while converting ID to ObjectID", "UPDATE ENTITY", "", r)
return
}
println("OBJID:", objID.Hex())
println("Entity;", entity)
v, e3 = models.UpdateEntity(entity, bson.M{"_id": objID}, &updateData, isPatch)
default:
w.WriteHeader(http.StatusBadRequest)
u.Respond(w, u.Message(false, "Error while extracting from path parameters"))
u.ErrLog("Error while extracting from path parameters", "UPDATE ENTITY", "", r)
return
}
switch e3 {
case "validate", "Invalid ParentID", "Need ParentID", "invalid":
w.WriteHeader(http.StatusBadRequest)
u.ErrLog("Error while updating "+entity, "UPDATE "+strings.ToUpper(entity), e3, r)
case "internal":
w.WriteHeader(http.StatusInternalServerError)
u.ErrLog("Error while updating "+entity, "UPDATE "+strings.ToUpper(entity), e3, r)
case "mongo: no documents in result", "parent not found":
w.WriteHeader(http.StatusNotFound)
u.ErrLog("Error while updating "+entity, "UPDATE "+strings.ToUpper(entity), e3, r)
default:
}
u.Respond(w, v)
}
// swagger:operation GET /api/{objs}? objects GetObject
// Gets an Object using any attribute (with the exception of description)
// via query in the system
// The attributes are in the form {attr}=xyz&{attr1}=abc
// And any combination can be used given that at least 1 is provided.
// ---
// produces:
// - application/json
// parameters:
// - name: objs
// in: query
// description: 'Indicates the object. Only values of "tenants", "sites",
// "buildings", "rooms", "racks", "devices", "room-templates",
// "obj-templates","acs","panels", "groups", "corridors",
// "sensors", "stray-devices" and "stray-sensors" are acceptable'
// required: true
// type: string
// default: "sites"
// - name: Name
// in: query
// description: Name of tenant
// required: false
// type: string
// default: "INFINITI"
// - name: Category
// in: query
// description: Category of Tenant (ex. Consumer Electronics, Medical)
// required: false
// type: string
// default: "Auto"
// - name: Domain
// description: 'Domain of the Tenant'
// required: false
// type: string
// default: "High End Auto"
// - name: Attributes
// in: query
// description: Any other object attributes can be queried
// required: false
// type: json
//
// responses:
//
// '204':
// description: 'Found. A response body will be returned with
// a meaningful message.'
// '404':
// description: Not found. An error message will be returned.
var GetEntityByQuery = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: GetEntityByQuery ")
fmt.Println("******************************************************")
DispRequestMetaData(r)
var data []map[string]interface{}
var resp map[string]interface{}
var bsonMap bson.M
var e, entStr string
entStr = r.URL.Path[5 : len(r.URL.Path)-1]
filters := getFiltersFromQueryParams(r)
//If templates, format them
entStr = strings.Replace(entStr, "-", "_", 1)
query := u.ParamsParse(r.URL, u.EntityStrToInt(entStr))
js, _ := json.Marshal(query)
json.Unmarshal(js, &bsonMap)
//Prevents Mongo from creating a new unidentified collection
if u.EntityStrToInt(entStr) < 0 {
w.WriteHeader(http.StatusNotFound)
u.Respond(w, u.Message(false, "Invalid object in URL: '"+entStr+"' Please provide a valid object"))
u.ErrLog("Cannot get invalid object", "GET ENTITYQUERY"+entStr, "", r)
return
}
data, e = models.GetManyEntities(entStr, bsonMap, filters)
if len(data) == 0 {
resp = u.Message(false, "Error: "+e)
u.ErrLog("Error while getting "+entStr, "GET ENTITYQUERY", e, r)
switch e {
case "record not found":
w.WriteHeader(http.StatusNotFound)
case "":
resp = u.Message(false, "Error: No Records Found")
w.WriteHeader(http.StatusNotFound)
default:
resp = u.Message(false, "Error: No Records Found")
w.WriteHeader(http.StatusNotFound)
}
} else {
message := ""
switch u.EntityStrToInt(entStr) {
case u.ROOMTMPL:
message = "successfully got query for room_template"
case u.OBJTMPL:
message = "successfully got query for obj_template"
default:
message = "successfully got query for object"
}
resp = u.Message(true, message)
}
resp["data"] = map[string]interface{}{"objects": data}
u.Respond(w, resp)
}
// swagger:operation GET /api/tempunits/{id} tempunits GetTempUnit
// Gets the temperatureUnit attribute of the parent site of given object.
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: query
// description: 'ID of any object.'
// required: true
// responses:
// '200':
// description: 'Found. A response body will be returned with
// a meaningful message.'
// '404':
// description: 'Nothing Found. An error message will be returned.'
// swagger:operation OPTIONS /api/tempunits/{id} tempunits GetTempUnit
// Gets the possible operations of the parent site tempunit of given object.
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: query
// description: 'ID or hierarchyName of any object.'
// required: true
// responses:
// '200':
// description: 'Found. A response body will be returned with
// a meaningful message.'
// '404':
// description: 'Nothing Found. An error message will be returned.'
var GetTempUnit = func(w http.ResponseWriter, r *http.Request) {
fmt.Println("******************************************************")
fmt.Println("FUNCTION CALL: GetTempUnit ")