-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdataverselib.go
More file actions
1672 lines (1477 loc) · 54 KB
/
Copy pathdataverselib.go
File metadata and controls
1672 lines (1477 loc) · 54 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
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 dataverselib
import (
"archive/zip"
"bytes"
"cmp"
"encoding/json"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"slices"
"strconv"
"strings"
"time"
)
// GetVersionOfDataset get a specific version of a dataverse dataset.
// It uses Dataverse API https://guides.dataverse.org/en/latest/api/native-api.html#get-version-of-a-dataset
// "$SERVER_URL/api/datasets/:persistentId/versions/{version}"
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - parameters: map[string]interface{} - request parameters (e.g., persistentId, excludeFiles, etc)
// - version: string - version identifier (e.g., ":latest", ":draft", "1", etc)
//
// Returns:
// - DatasetVersion struct
// - error if the request fail
func GetVersionOfDataset(apiClient *ApiClient, parameters map[string]interface{}, version string) (DatasetVersion, error) {
//curl "https://borealisdata.ca/api/datasets/:persistentId/versions/:latest?excludeFiles=true&persistentId=doi:10.5683/SP3/IXWUWU"
dv := DatasetVersion{}
r := RequestResponse{}
client := apiClient.HttpClient
u := apiClient.BaseUrl + "/api/datasets/:persistentId/versions/" + version
headers := map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
resp, err := GetRequest(parameters, u, headers, client)
defer resp.Body.Close()
if err != nil {
log.Printf("Error making request: %s %s\n", parameters["persistentId"], err)
return dv, err
}
if resp.StatusCode != http.StatusOK {
log.Printf("Error non-OK HTTP status: %s %s\n", parameters["persistentId"], resp.Status)
return dv, fmt.Errorf("failed to get dataset version: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
log.Printf("Error decoding response for dataset version: %s %s\n", parameters["persistentId"], err)
return dv, err
}
if r.Status == "OK" {
json.Unmarshal(r.Data, &dv)
} else {
return dv, fmt.Errorf("Error from server getting dataset version: %s %s", parameters["persistentId"], r.Message)
}
return dv, nil
}
// GetContentOfDataverse get content of specific dataverse collection.
// It uses Dataverse API https://guides.dataverse.org/en/latest/api/native-api.html#show-contents-of-a-dataverse-collection
// "$SERVER_URL/api/dataverses/$ID/contents"
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - dataverseAlias: string - alias of the dataverse collection (e.g., "root", "international", etc)
//
// Returns:
// - array that contains ItemInDataverse elements
// - error if the request fail
func GetContentOfDataverse(apiClient *ApiClient, dataverseAlias string) ([]ItemInDataverse, error) {
//curl -H "X-Dataverse-key:$API_TOKEN" "$SERVER_URL/api/dataverses/$ID/contents"
r := RequestResponse{}
c := []ItemInDataverse{}
u := apiClient.BaseUrl + "/api/dataverses/" + dataverseAlias + "/contents"
headers := map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
resp, err := GetRequest(nil, u, headers, apiClient.HttpClient)
defer resp.Body.Close()
if err != nil {
log.Printf("Error making request: %s %s\n", dataverseAlias, err)
return c, err
}
if resp.StatusCode != http.StatusOK {
log.Printf("Error non-OK HTTP status: %s %s\n", dataverseAlias, resp.Status)
return c, fmt.Errorf("Error to get dataverse contents: %s", resp.Status)
}
// Process response as needed
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
log.Printf("Error decoding response for dataverse content: %s %s\n", dataverseAlias, err)
return c, err
}
if r.Status == "OK" {
json.Unmarshal(r.Data, &c)
} else {
return c, fmt.Errorf(r.Message)
}
return c, nil
}
// GetAllDatasetsInDataverseAndSubdataverses get pids and ids of all datasets in specific dataverse collection and its subdataverses.
// It is a recursive function that calls itself for each dataverse collection in the content of the dataverse collection until it reaches the dataset level.
// It uses GetContentOfDataverse(apiClient *ApiClient) ([]ItemInDataverse, error) function
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - dataverseAlias: string - alias of the dataverse collection (e.g., "root", "international", etc)
// - datasets: *[]MinimalDataset - pointer to an array that contains MinimalDataset elements (id and pid of dataset)
//
// Returns:
// - error if the request fail
func GetAllDatasetsInDataverseAndSubdataverses(apiClient *ApiClient, dataverseAlias string, datasets *[]MinimalDataset) error {
c, err := GetContentOfDataverse(apiClient, dataverseAlias)
if err != nil {
return err
}
for _, item := range c {
if item.Type == "dataverse" {
err := GetAllDatasetsInDataverseAndSubdataverses(apiClient, strconv.Itoa(item.Id), datasets)
if err != nil {
return err
}
} else if item.Type == "dataset" {
pid := item.Protocol + ":" + item.Authority + item.Separator + item.Identifier
(*datasets) = append((*datasets), MinimalDataset{Id: item.Id, Pid: pid})
}
}
return nil
}
// GetTotalCount get total count of a search dataverse API.
// It uses dataverse search API, documentation https://guides.dataverse.org/en/latest/api/search.html#
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - parameters: map[string]interface{} - request parameters for search (e.g., q, type, metadata_fields, subtree, etc)
//
// Returns:
// - total count of the search result
// - error if the request fail
func GetTotalCount(apiClient *ApiClient, parameters map[string]interface{}) (int, error) {
parameters["start"] = "0"
u := apiClient.BaseUrl + "/api/search"
r := RequestResponse{}
s := SearchResult{}
headers := map[string]interface{}{}
if apiClient.ApiToken != "" {
headers = map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
}
resp, err := GetRequest(parameters, u, headers, apiClient.HttpClient)
defer resp.Body.Close()
if err != nil {
return 0, err
}
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("Error to get search: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return 0, err
}
if r.Status == "OK" {
json.Unmarshal(r.Data, &s)
} else {
return 0, fmt.Errorf("Error from server getting search: %s ", r.Message)
}
return s.TotalCount, nil
}
func getAllMetadataStartEndSearch(apiClient *ApiClient, parameters map[string]interface{}, jobs <-chan int, results chan<- []SearchItem) {
log.Println("Starting getAllMetadataStartEndSearch")
for start := range jobs {
r := RequestResponse{}
s := SearchResult{}
fmt.Println(start)
parameters["start"] = strconv.Itoa(start)
u := apiClient.BaseUrl + "/api/search"
headers := map[string]interface{}{}
if apiClient.ApiToken != "" {
headers = map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
}
resp, err := GetRequest(parameters, u, headers, apiClient.HttpClient)
defer resp.Body.Close()
if err != nil {
log.Printf("Error getting request for start:%d, %s\n", start, err)
return
}
log.Println("good")
if resp.StatusCode != http.StatusOK {
log.Printf("Error in request status for start:%d, %d\n", start, resp.StatusCode)
return
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
log.Printf("Error decoding request for start:%d, %s\n", start, err)
return
}
log.Println(r.Status)
if r.Status == "OK" {
json.Unmarshal(r.Data, &s)
} else {
log.Printf("Error status decoder for start:%d, %s\n", start, r.Status)
return
}
results <- s.Items
}
}
// GetAllMetadataOfDatasetsInDataverseSearchParallel get datasets metadata from specific dataverse.
// It uses dataverse search API, documentation https://guides.dataverse.org/en/latest/api/search.html#
// It is a parallel version of GetAllMetadataOfDatasetsInDataverseSearch(apiClient *ApiClient, mbList []string) ([]SearchItem, error) function that uses goroutines to get metadata of datasets in parallel. It divides the total count of the search result into batches (numInBatch) and assigns each batch to a goroutine to get the metadata. The results are collected in a channel and combined at the end. The number of goroutines can be controlled by the numOfWorkers parameter.
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - dataverseAlias: string - alias of the dataverse collection (e.g., "root", "international", etc)
// - mbList: []string - list of metadata blocks to be included in the search
// - numOfWorkers: int - limit the number of goroutines for parallel processing
// - numInBatch: int - number of per page in search (e.g., 300)
//
// Returns:
// - Search result is an array that contains SearchItem elements, which include global_id, identifier_of_dataverse, and metadata_blocks of each dataset in the search result
// - error if the request fail
func GetAllMetadataOfDatasetsInDataverseSearchParallel(apiClient *ApiClient, dataverseAlias string, mbList []string, numOfWorkers int, numInBatch int) ([]SearchItem, error) {
allItems := make([]SearchItem, 0)
mbListPar := make([]string, 0)
for _, mb := range mbList {
mbField := mb + ":*"
mbListPar = append(mbListPar, mbField)
}
parameters := map[string]interface{}{
"q": "*",
"type": "dataset",
"metadata_fields": mbListPar,
"subtree": dataverseAlias,
"per_page": "1",
}
totalCount, err := GetTotalCount(apiClient, parameters)
log.Println(totalCount)
if err != nil {
return nil, err
}
numbOfRoutines := totalCount / numInBatch
log.Println("number of routines:", numbOfRoutines)
if numInBatch*numbOfRoutines < totalCount {
numbOfRoutines = numbOfRoutines + 1
}
log.Println("number of routines:", numbOfRoutines)
numOfJobs := numbOfRoutines
jobs := make(chan int, numOfJobs)
results := make(chan []SearchItem, numOfJobs)
//limiter := time.Tick(20 * time.Second)
log.Println("Number of workers:", numOfWorkers)
for batch := 0; batch < numOfWorkers; batch++ {
start := batch * numInBatch
log.Println(totalCount - numInBatch)
if start > totalCount-numInBatch && batch != 0 {
log.Println("finish break ", start)
break
}
parameters = map[string]interface{}{
"q": "*",
"type": "dataset",
"metadata_fields": mbListPar,
"subtree": dataverseAlias,
"per_page": strconv.Itoa(numInBatch),
"start": strconv.Itoa(start),
}
go getAllMetadataStartEndSearch(apiClient, parameters, jobs, results)
}
log.Println("number of Jobs:", numOfJobs)
// send jobs
for j := 0; j < numOfJobs; j++ {
jobs <- j * numInBatch
}
close(jobs)
// collect results
for a := 0; a < numOfJobs; a++ {
items := <-results
allItems = append(allItems, items...)
}
log.Println("Total length:", len(allItems))
return allItems, nil
}
// GetSpecificMetadataOfDatasetsInDataverseSearchParallel get datasets metadata from specific dataverse with search string.
// It uses dataverse search API, documentation https://guides.dataverse.org/en/latest/api/search.html#
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - dataverseAlias: string - alias of the dataverse collection (e.g., "root", "international", etc)
// - mbList: []string - list of metadata blocks to be included in the search
// - numOfWorkers: int - limit the number of goroutines for parallel processing
// - numInBatch: int - number of per page in search (e.g., 300)
// - searchStr: string - search string for the search query (e.g., "title:water")
//
// Returns:
// - Search result is an array that contains SearchItem elements, which include global_id, identifier_of_dataverse, and metadata_blocks of each dataset in the search result
// - error if the request fail
func GetSpecificMetadataOfDatasetsInDataverseSearchParallel(apiClient *ApiClient, dataverseAlias string, mbListPar []string, numOfWorkers int, numInBatch int, searchStr string) ([]SearchItem, error) {
log.Printf("Start getting metadata with search string: %s\n", searchStr)
allItems := make([]SearchItem, 0)
parameters := map[string]interface{}{
"q": searchStr,
"type": "dataset",
"metadata_fields": mbListPar,
"subtree": dataverseAlias,
"per_page": "1",
}
totalCount, err := GetTotalCount(apiClient, parameters)
if err != nil {
return nil, err
}
if totalCount <= numInBatch {
numInBatch = totalCount
}
numbOfRoutines := totalCount / numInBatch
if numInBatch*numbOfRoutines < totalCount {
numbOfRoutines = numbOfRoutines + 1
}
log.Println("number of routines", numbOfRoutines)
log.Println("number of workers", numOfWorkers)
n := math.Min(float64(numOfWorkers), float64(numbOfRoutines))
numOfWorkers = int(n)
log.Println("New number of workers", numOfWorkers)
numOfJobs := numbOfRoutines
jobs := make(chan int, numOfJobs)
results := make(chan []SearchItem, numOfJobs)
//limiter := time.Tick(20 * time.Second)
for batch := 0; batch < numOfWorkers; batch++ {
start := batch * numInBatch
log.Println("Start:", start)
if start > totalCount-numInBatch {
log.Println("finish break")
break
}
parameters = map[string]interface{}{
"q": searchStr,
"type": "dataset",
"metadata_fields": mbListPar,
"subtree": dataverseAlias,
"per_page": strconv.Itoa(numInBatch),
"start": strconv.Itoa(start),
}
go getAllMetadataStartEndSearch(apiClient, parameters, jobs, results)
}
// send jobs
for j := 0; j < numOfJobs; j++ {
jobs <- j * 300
}
close(jobs)
// collect results
for a := 0; a < numOfJobs; a++ {
items := <-results
allItems = append(allItems, items...)
}
log.Println("Total length:", len(allItems))
return allItems, nil
}
// GetAllMetadataOfDatasetsInDataverseSearch get datasets metadata from specific dataverse.
// It uses dataverse search API, documentation https://guides.dataverse.org/en/latest/api/search.html#
// It is a not parallel version of GetAllMetadataOfDatasetsInDataverseSearchParallel(apiClient *ApiClient, mbList []string, numOfWorkers int, numInBatch int) ([]SearchItem, error) function that gets metadata of datasets sequentially by iterating through the search result with start and numInBatch parameters until it reaches the end of the search result. It is simpler than the parallel version but may take longer time to get the metadata if the search result is large.
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - dataverseAlias: string - alias of the dataverse collection (e.g., "root", "international", etc)
// - mbList: []string - list of metadata blocks to be included in the search
// - numInBatch: int - number of per page in search (e.g., 300). maximum is 1000 according to dataverse API documentation.
//
// Returns:
// - Search result is an array that contains SearchItem elements, which include global_id, identifier_of_dataverse, and metadata_blocks of each dataset in the search result
// - error if the request fail
func GetAllMetadataOfDatasetsInDataverseSearch(apiClient *ApiClient, dataverseAlias string, mbList []string, numInBatch int) ([]SearchItem, error) {
// curl "https://borealisdata.ca/api/search?q=*&type=dataset&metadata_fields=geospatial:*&metadata_fields=citation:*&subtree=international"
r := RequestResponse{}
s := SearchResult{}
allItems := make([]SearchItem, 0)
mbListPar := make([]string, 0)
for _, mb := range mbList {
mbField := mb + ":*"
mbListPar = append(mbListPar, mbField)
}
start := 0
for {
parameters := map[string]interface{}{
"q": "*",
"type": "dataset",
"metadata_fields": mbListPar,
"subtree": dataverseAlias,
"per_page": strconv.Itoa(numInBatch),
"start": strconv.Itoa(start),
}
u := apiClient.BaseUrl + "/api/search"
headers := map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
resp, err := GetRequest(parameters, u, headers, apiClient.HttpClient)
defer resp.Body.Close()
if err != nil {
return allItems, err
}
if resp.StatusCode != http.StatusOK {
return allItems, fmt.Errorf("Error to get search: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return allItems, err
}
if r.Status == "OK" {
json.Unmarshal(r.Data, &s)
} else {
return allItems, fmt.Errorf("Error from server getting search: %s ", r.Message)
}
for _, v := range s.Items {
allItems = append(allItems, v)
}
start = start + len(s.Items)
if start >= s.TotalCount {
break
}
}
return allItems, nil
}
func GetDatasetFromSearch(apiClient *ApiClient, q string, dvType string) ([]SearchItem, error) {
r := RequestResponse{}
s := SearchResult{}
parameters := map[string]interface{}{
"q": q,
"type": dvType,
}
u := apiClient.BaseUrl + "/api/search"
headers := map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
resp, err := GetRequest(parameters, u, headers, apiClient.HttpClient)
defer resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
fmt.Errorf("Error to get search: %s", resp.Status)
return nil, fmt.Errorf("Error to get search: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return nil, err
}
if r.Status == "OK" {
json.Unmarshal(r.Data, &s)
}
log.Println(s)
if len(s.Items) > 1 {
return s.Items, fmt.Errorf("Error more than 1 result found for query: %s", q)
}
if len(s.Items) == 0 {
return s.Items, fmt.Errorf("Error no result found for query: %s", q)
}
return s.Items, nil
}
// GetListOfMetadataBlocksOfDataverse get list of all metadatablocks for specific dataverse.
// It uses dataverse native API, documentation https://guides.dataverse.org/en/latest/api/native-api.html#list-metadata-blocks-defined-on-a-dataverse-collection
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - dataverseAlias: string - alias of the dataverse collection (e.g., "root", "international", etc)
// - parameters: map[string]interface{} - request parameters for the API (e.g., returnDatasetFieldTypes, onlyDisplayedOnCreate, datasetType, etc)
//
// Returns:
// - list of metadata blocks defined on the dataverse collection, which can be used in the search API to get specific metadata of datasets in the dataverse collection
// - a dictionary that maps display name of metadata block to its name, which can be used to get the name of metadata block from its display name in the dataverse collection
// - error if the request fail
func GetListOfMetadataBlocksOfDataverse(apiClient *ApiClient, dataverseAlias string, parameters map[string]interface{}) ([]string, map[string]string, error) {
//curl -H "X-Dataverse-key:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" "https://demo.dataverse.org/api/dataverses/root/metadatablocks?returnDatasetFieldTypes=true&onlyDisplayedOnCreate=true&datasetType=software"
client := apiClient.HttpClient
r := RequestResponse{}
metadatablocks := []string{}
metaBlocsDict := make(map[string]string)
u := apiClient.BaseUrl + "/api/dataverses/" + dataverseAlias + "/metadatablocks"
headers := map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
resp, err := GetRequest(parameters, u, headers, client)
if err != nil {
return metadatablocks, metaBlocsDict, err
}
defer resp.Body.Close()
if err != nil {
return metadatablocks, metaBlocsDict, err
}
if resp.StatusCode != http.StatusOK {
return metadatablocks, metaBlocsDict, fmt.Errorf("Error to get search: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return metadatablocks, metaBlocsDict, err
}
mbList := make([]MetadataBlockItem, 0)
if r.Status == "OK" {
json.Unmarshal(r.Data, &mbList)
} else {
return metadatablocks, metaBlocsDict, fmt.Errorf("Error from server getting list of metadatablocks: %s ", r.Message)
}
for _, v := range mbList {
metadatablocks = append(metadatablocks, v.Name)
metaBlocsDict[v.DisplayName] = v.Name
}
return metadatablocks, metaBlocsDict, nil
}
// GetExportMetadataOfDataset exports metadata in provided format.
// It uses dataverse Native API, documentation https://guides.dataverse.org/en/latest/api/native-api.html#export-metadata-of-a-dataset-in-various-formats
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - persistentId: string - persistent identifier of the dataset (e.g., "doi:10.5072/FK2/J8SJZB")
// - exporterFormat: string - format to export metadata (e.g., "ddi", "json", etc)
// - published: bool - whether to export published version or draft version of the dataset. If true, it will export published version; if false, it will export draft version.
//
// Returns:
// - exported metadata in bytes, which can be saved as a file or processed further
// - error if the request fail
func GetExportMetadataOfDataset(apiClient *ApiClient, persistentId string, exporterFormat string, published bool) ([]byte, error) {
//curl -H "X-Dataverse-key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" "https://demo.dataverse.org/api/datasets/export?exporter=ddi&persistentId=doi:10.5072/FK2/J8SJZB&version=:draft"
var requestParameters map[string]interface{}
url := apiClient.BaseUrl + "/api/datasets/export?exporter=" + exporterFormat + "&persistentId=" + persistentId
if !published {
url = url + "&version=:draft"
}
headers := map[string]interface{}{}
if apiClient.ApiToken != "" {
headers = map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
}
resp, err := GetRequest(requestParameters, url, headers, apiClient.HttpClient)
defer resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Error to export metadata: %s", resp.Status)
}
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bodyBytes, nil
}
func flatCompoundClass(c map[string]interface{}, column string, columnsMap *map[string]int, headers *[]string) string {
var flatValues string = ""
var currentFieldInCompound int = 0
for _, raw := range c {
if inner, ok := raw.(map[string]interface{}); ok {
if typeName, ok := inner["typeName"]; ok {
columnIndx, ok := (*columnsMap)[column]
if !ok {
columnIndx = len(*columnsMap)
(*columnsMap)[column] = columnIndx
*headers = append(*headers, column)
}
if currentFieldInCompound == 0 {
flatValues += fmt.Sprintf("{")
}
flatValues += fmt.Sprintf("'%s':'%s'", typeName, inner["value"].(string))
if currentFieldInCompound < len(c)-1 {
flatValues += fmt.Sprintf(",")
}
if currentFieldInCompound == len(c)-1 {
flatValues += fmt.Sprintf("}")
}
currentFieldInCompound++
}
}
}
return flatValues
}
// ConvertMetadataToCSVFormat converts and flattens search metadata into csv, one dataset - one line.
//
// Parameters:
// - datasets: []SearchItem - array that contains SearchItem elements with metadata blocks of each dataset
// - mbDict: map[string]string - dictionary that maps display name of metadata block to its name, which can be used to get the name of metadata block from its display name in the dataverse collection
//
// Returns:
// - Search result is an array that contains map of column name and value for each dataset, which can be used to create a csv file with columns of metadata fields and rows of datasets
// - array of column names for the csv file, which can be used as header of the csv file
func ConvertMetadataToCSVFormat(datasets []SearchItem, mbDict map[string]string) ([]map[string]string, []string) {
var columnsMap map[string]int = make(map[string]int) //columns of csv file
var records []map[string]string = make([]map[string]string, 0)
var headers []string = make([]string, 0)
headers = append(headers, "persistentId") // first column is always persistentId
for _, ds := range datasets {
var record map[string]string = make(map[string]string)
//fmt.Println(ds.GlobalId)
record["persistentId"] = ds.GlobalId
metadata := ds.MetadataBlocks
for _, mb := range metadata { // for each metadata block
fields := mb.Fields
for _, field := range fields {
//fmt.Printf("Field TypeName: %s, Value: %+v, Multiple: %t, TypeClass: %s\n", field.TypeName, field.Value, field.Multiple, field.TypeClass)
if mbDict != nil {
mb.Name = mbDict[mb.DisplayName]
}
column := mb.Name + ":" + field.TypeName
if field.TypeClass == "primitive" || field.TypeClass == "controlledVocabulary" {
columnIndx, ok := columnsMap[column]
flatValues := ""
if field.Multiple {
for indx, v := range field.Value.([]interface{}) {
if indx > 0 {
flatValues += "|"
}
flatValues += fmt.Sprintf("%s", v)
}
} else {
flatValues = fmt.Sprintf("%s", field.Value)
}
if ok {
record[column] = flatValues
} else {
columnIndx = len(columnsMap)
columnsMap[column] = columnIndx
headers = append(headers, column)
record[column] = flatValues
}
} else if field.TypeClass == "compound" {
flatValues := ""
if field.Multiple {
entry, ok := field.Value.([]interface{}) // it is an array of values
if ok {
for indx, v := range entry { // for each value in the array
c, _ := v.(map[string]interface{}) // value is string: class
if indx > 0 {
flatValues += "|"
}
flatValues += flatCompoundClass(c, column, &columnsMap, &headers)
}
} else {
log.Printf(" Unexpected type for single compound field: %T\n", field.Value)
}
} else {
c, ok := field.Value.(map[string]interface{}) // it is a single compound class
if ok {
flatValues += flatCompoundClass(c, column, &columnsMap, &headers)
}
}
record[column] = flatValues
}
}
}
records = append(records, record)
}
return records, headers
}
// GetMetadataBlockField gets metadatablock fields for specific metadatablock.
// It uses dataverse native API, documentation https://guides.dataverse.org/en/latest/api/native-api.html#show-info-about-single-metadata-block
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - metadataBlockName: string - name of the metadata block (e.g., "geospatial", "citation", etc)
//
// Returns:
// - MetadataBlockInfo struct, which contains name of the metadata block and its fields, which can be used to get the metadata fields of the metadata block for further processing
// - error if the request fail
func GetMetadataBlockFields(apiClient *ApiClient, metadataBlockName string) (MetadataBlockInfo, error) {
//$SERVER/api/metadatablocks/geospatial
log.Println("Start getting metadata block fields for:", metadataBlockName)
client := apiClient.HttpClient
r := RequestResponse{}
mb := MetadataBlockInfo{}
u := apiClient.BaseUrl + "/api/metadatablocks/" + metadataBlockName
log.Println(u)
headers := map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
}
resp, err := GetRequest(nil, u, headers, client)
if err != nil {
log.Printf("Error making request: %s\n", err)
return mb, err
}
defer resp.Body.Close()
if err != nil {
return mb, err
}
log.Println(resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return mb, fmt.Errorf("Error to get search: %s", resp.Status)
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return mb, err
}
if r.Status == "OK" {
json.Unmarshal(r.Data, &mb)
} else {
return mb, fmt.Errorf("Error from server getting search: %s ", r.Message)
}
log.Println(mb.Fields)
return mb, nil
}
// CreateHeadersCSVMetadata creates an array of column names for the csv file, which can be used as header of the csv file, based on the metadata blocks and their fields defined in the dataverse collection.
//
// Parameters:
// - apiClient: *ApiClient - Dataverse API client (BaseUrl, ApiToken, HttpClient)
// - dataverseAlias: string - alias of the dataverse collection (e.g., "root", "international", etc)
//
// Returns:
// - MetadataBlockInfo struct, which contains name of the metadata block and its fields, which can be used to get the metadata fields of the metadata block for further processing
// - error if the request fail
func CreateHeadersCSVMetadata(apiClient *ApiClient, dataverseAlias string) ([]string, error) {
headers := []string{}
mbList, _, err := GetListOfMetadataBlocksOfDataverse(apiClient, dataverseAlias, nil)
if err != nil {
log.Printf("Error getting metadata blocks for dataverse %s: %s\n", dataverseAlias, err)
return headers, err
}
for _, mb := range mbList {
fmt.Println(mb)
mbInfo, err := GetMetadataBlockFields(apiClient, mb)
if err != nil {
log.Printf("Error getting metadata block fields for metadata block %s: %s\n", mb, err)
return headers, err
}
for _, field := range mbInfo.Fields {
column := mb + ":" + field.Name
headers = append(headers, column)
}
}
return headers, nil
}
func CreateDatasetWithJson(apiClient *ApiClient, dataverseAlias string, parameters map[string]interface{}, jsonData []byte) (MinimalDataset, error) {
// curl -H "X-Dataverse-key:$API_TOKEN" -X POST "$SERVER_URL/api/dataverses/$PARENT/datasets?doNotValidate=true" --upload-file dataset-incomplete.json -H 'Content-type:application/json'
r := RequestResponse{}
dataset := MinimalDataset{}
url := apiClient.BaseUrl + "/api/dataverses/" + dataverseAlias + "/datasets"
headers := map[string]interface{}{
"X-Dataverse-key": apiClient.ApiToken,
"Content-type": "application/json",
}
fmt.Printf("%s\n", string(jsonData))
resp, err := PostRequest(parameters, url, headers, apiClient.HttpClient, jsonData)
if err != nil {
log.Println(err)
return dataset, err
}
defer resp.Body.Close()
if err != nil {
return dataset, err
}
fmt.Println(resp.StatusCode)
if resp.StatusCode != 201 {
bodyBytes, err := io.ReadAll(resp.Body)
fmt.Println("Status:", resp.Status)
fmt.Println("Response:", string(bodyBytes))
if err != nil {
return dataset, err
}
return dataset, fmt.Errorf("Error CreateDatasetWithJson: %s, %d\n", string(bodyBytes), resp.StatusCode)
}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return dataset, err
}
if r.Status == "OK" {
json.Unmarshal(r.Data, &dataset)
} else {
return dataset, fmt.Errorf("Error from server getting versions of dataset: %s ", r.Message)
}
log.Println(r)
log.Println("++++++++++++")
log.Println(dataset)
return dataset, nil
}
func FindRequiredFields(metaFields []MetadataBlockInfo) (map[string][]string, error) {
requiredFields := make(map[string][]string)
for _, mb := range metaFields {
for _, field := range mb.Fields {
if field.IsRequired {
requiredFields[mb.Name+":"+field.Name] = make([]string, 0)
if field.ChildFields != nil {
for _, child := range field.ChildFields {
if child.IsRequired {
requiredFields[mb.Name+":"+field.Name] = append(requiredFields[mb.Name+":"+field.Name], child.Name)
}
}
}
}
}
}
return requiredFields, nil
}
func CheckMandatoryFieldsInHeaders(metaFields []MetadataBlockInfo, headers []string) ([]string, error) {
requiredFieldsMissing := make([]string, 0)
requiredFields, err := FindRequiredFields(metaFields)
if err != nil {
return requiredFieldsMissing, err
}
set := make(map[string]struct{})
// make set from headers
for _, element := range headers {
set[element] = struct{}{}
}
for field, _ := range requiredFields {
if _, exists := set[field]; !exists {
requiredFieldsMissing = append(requiredFieldsMissing, field)
}
}
return requiredFieldsMissing, nil
}
func CreateMapBlockFields(metaFields []MetadataBlockInfo) (map[string]map[string]MetadataFieldItem, error) {
blockFields := make(map[string]map[string]MetadataFieldItem)
for _, mb := range metaFields {
blockFields[mb.Name] = mb.Fields
}
return blockFields, nil
}
func CreateDataverseDatasetVersionStruct(metaFields []MetadataBlockInfo, headers []string, row []string) (DatasetVersion, error) {
datasetVersion := DatasetVersion{}
datasetVersion.MetadataBlocks = make(map[string]MetadataBlock)
mainMissingMandatoryFields, err := CheckMandatoryFieldsInHeaders(metaFields, headers)
if err != nil {
return datasetVersion, err
}
if len(mainMissingMandatoryFields) > 0 {
return datasetVersion, fmt.Errorf("Missing mandatory fields in headers: %v", mainMissingMandatoryFields)
}
blockFields, _ := CreateMapBlockFields(metaFields)
metadataBlocksNames := make(map[string]struct{})
var metadatablock MetadataBlock
for i, column := range headers {
value := row[i]
split := strings.Split(column, ":")
if len(split) != 2 {
return datasetVersion, fmt.Errorf("Invalid column name: %s", column)
}
if _, ok := metadataBlocksNames[split[0]]; !ok {
metadataBlocksNames[split[0]] = struct{}{}
metadatablock = MetadataBlock{
Name: split[0],
Fields: make([]MetadataField, 0),
}
//datasetVersion.MetadataBlocks[split[0]] = metadatablock
}
if fields, ok := blockFields[split[0]]; ok {
if field, ok := fields[split[1]]; ok {
mf := MetadataField{
TypeName: field.Name,
TypeClass: field.TypeClass,
Multiple: field.Multiple,
Value: nil,
}
if field.TypeClass == "primitive" || field.TypeClass == "controlledVocabulary" {
if field.Multiple {
finalValueStringArray := strings.Split(value, "|")
mf.Value = finalValueStringArray
//metadatablock.Fields = append(metadatablock.Fields, mf)
} else {
mf.Value = value
//metadatablock.Fields = append(metadatablock.Fields, mf)
}
} else if field.TypeClass == "compound" {
if field.Multiple {
valueClassArray := make([]map[string]interface{}, 0)
elements := strings.Split(value, "|")
for _, element := range elements {
m := make(map[string]string)
err := json.Unmarshal([]byte(element), &m)
if err != nil {
return datasetVersion, fmt.Errorf("Error unmarshalling compound field value: %s", err)
}
var valueClassMult map[string]interface{} = make(map[string]interface{})
for key, _ := range m {
if _, ok := field.ChildFields[key]; !ok {
return datasetVersion, fmt.Errorf("Child field %s not found in metadata block %s for compound field %s", key, split[0], split[1])
} else {
childField := MetadataField{
TypeName: key,
TypeClass: field.ChildFields[key].TypeClass,
Multiple: field.ChildFields[key].Multiple,
Value: m[key],